Skip to content
Snippets Groups Projects
jsexec.c 28 KiB
Newer Older
/* Execute a Synchronet JavaScript module from the command-line */

/* $Id$ */

/****************************************************************************
 * @format.tab-size 4		(Plain Text/Source Code File Header)			*
 * @format.use-tabs true	(see http://www.synchro.net/ptsc_hdr.html)		*
 *																			*
 * Copyright 2011 Rob Swindell - http://www.synchro.net/copyright.html		*
 *																			*
 * This program is free software; you can redistribute it and/or			*
 * modify it under the terms of the GNU General Public License				*
 * as published by the Free Software Foundation; either version 2			*
 * of the License, or (at your option) any later version.					*
 * See the GNU General Public License for more details: gpl.txt or			*
 * http://www.fsf.org/copyleft/gpl.html										*
 *																			*
 * Anonymous FTP access to the most recent released source is available at	*
 * ftp://vert.synchro.net, ftp://cvs.synchro.net and ftp://ftp.synchro.net	*
 *																			*
 * Anonymous CVS access to the development source and modification history	*
 * is available at cvs.synchro.net:/cvsroot/sbbs, example:					*
 * cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs login			*
 *     (just hit return, no password is necessary)							*
 * cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs checkout src		*
 *																			*
 * For Synchronet coding style and modification guidelines, see				*
 * http://www.synchro.net/source.html										*
 *																			*
 * You are encouraged to submit any modifications (preferably in Unix diff	*
 * format) via e-mail to mods@synchro.net									*
 *																			*
 * Note: If this box doesn't appear square, then you need to fix your tabs.	*
 ****************************************************************************/

rswindell's avatar
rswindell committed
#ifndef JAVASCRIPT
rswindell's avatar
rswindell committed
#endif
#ifdef __unix__
#include <signal.h>
#endif

#define DEFAULT_LOG_LEVEL	LOG_DEBUG	/* Display all LOG levels */
#define DEFAULT_ERR_LOG_LVL	LOG_WARNING
JSRuntime*	js_runtime;
JSContext*	js_cx;
JSObject*	js_glob;
scfg_t		scfg;
ulong		js_max_bytes=JAVASCRIPT_MAX_BYTES;
ulong		js_cx_stack=JAVASCRIPT_CONTEXT_STACK;
ulong		stack_limit=JAVASCRIPT_THREAD_STACK;
rswindell's avatar
rswindell committed
FILE*		confp;
FILE*		errfp;
FILE*		statfp;
char*		host_name=NULL;
char		host_name_buf[128];
char*		load_path_list=JAVASCRIPT_LOAD_PATH;
BOOL		pause_on_exit=FALSE;
BOOL		pause_on_error=FALSE;
BOOL		terminated=FALSE;
int			log_level=DEFAULT_LOG_LEVEL;
#if defined(__unix__)
BOOL		daemonize=FALSE;
#endif
void banner(FILE* fp)
{
	fprintf(fp,"\nJSexec v%s%c-%s (rev %s)%s - "
		"Execute Synchronet JavaScript Module\n"
		,VERSION,REVISION
		,PLATFORM_DESC
		,revision

	fprintf(fp, "Compiled %s %s with %s\n"
		,__DATE__, __TIME__, compiler);
void usage(FILE* fp)
{
	fprintf(fp,"\nusage: jsexec [-opts] [path]module[.js] [args]\n"
		"\navailable opts:\n\n"
		"\t-c<ctrl_dir>   specify path to Synchronet CTRL directory\n"
#if defined(__unix__)
		"\t-d             run in background (daemonize)\n"
#endif
		"\t-m<bytes>      set maximum heap size (default=%u bytes)\n"
		"\t-s<bytes>      set context stack size (default=%u bytes)\n"
		"\t-S<bytes>      set thread stack limit (default=%u, 0=unlimited)\n"
		"\t-b<limit>      set branch limit (default=%u, 0=unlimited)\n"
		"\t-y<interval>   set yield interval (default=%u, 0=never)\n"
		"\t-g<interval>   set garbage collection interval (default=%u, 0=never)\n"
		"\t-h[hostname]   use local or specified host name (instead of SCFG value)\n"
		"\t-u<mask>       set file creation permissions mask (in octal)\n"
		"\t-L<level>      set log level (default=%u)\n"
		"\t-E<level>      set error log level threshold (default=%u)\n"
		"\t-i<path_list>  set load() comma-sep search path list (default=\"%s\")\n"
		"\t-f             use non-buffered stream for console messages\n"
		"\t-a             append instead of overwriting message output files\n"
		"\t-e<filename>   send error messages to file in addition to stderr\n"
		"\t-o<filename>   send console messages to file instead of stdout\n"
		"\t-n             send status messages to %s instead of stderr\n"
		"\t-q             send console messages to %s instead of stdout\n"
		"\t-v             display version details and exit\n"
		"\t-x             disable auto-termination on local abort signal\n"
		"\t-l             loop until intentionally terminated\n"
		"\t-p             wait for keypress (pause) on exit\n"
		"\t-!             wait for keypress (pause) on error\n"
		,JAVASCRIPT_MAX_BYTES
		,JAVASCRIPT_CONTEXT_STACK
		,JAVASCRIPT_THREAD_STACK
		,JAVASCRIPT_YIELD_INTERVAL
		,JAVASCRIPT_GC_INTERVAL
		,load_path_list
		,_PATH_DEVNULL
int mfprintf(FILE* fp, char *fmt, ...)
{
	va_list argptr;
	char sbuf[1024];
	int ret=0;

    va_start(argptr,fmt);
    ret=vsnprintf(sbuf,sizeof(sbuf),fmt,argptr);
	sbuf[sizeof(sbuf)-1]=0;
    va_end(argptr);

	/* Mutex-protect stdout/stderr */
	pthread_mutex_lock(&output_mutex);

	ret = fprintf(fp, "%s\n", sbuf);

	pthread_mutex_unlock(&output_mutex);
    return(ret);
}

int lprintf(int level, const char *fmt, ...)
deuce's avatar
deuce committed
	int ret=0;
    ret=vsnprintf(sbuf,sizeof(sbuf),fmt,argptr);
#if defined(__unix__)
	if(daemonize) {

	/* Mutex-protect stdout/stderr */
	pthread_mutex_lock(&output_mutex);

		ret=fprintf(errfp,"%s\n",sbuf);
		if(errfp!=stderr && confp!=stdout)
			ret=fprintf(statfp,"%s\n",sbuf);
	}
	if(level>err_level || errfp!=stderr)
		ret=fprintf(confp,"%s\n",sbuf);
#if defined(__unix__) && defined(NEEDS_DAEMON)
/****************************************************************************/
/* Daemonizes the process                                                   */
/****************************************************************************/
int
daemon(int nochdir, int noclose)
{
    int fd;

    switch (fork()) {
    case -1:
        return (-1);
    case 0:
        break;
    default:
        _exit(0);
    }

    if (setsid() == -1)
        return (-1);

    if (!nochdir)
        (void)chdir("/");

    if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
        (void)dup2(fd, STDIN_FILENO);
        (void)dup2(fd, STDOUT_FILENO);
        (void)dup2(fd, STDERR_FILENO);
        if (fd > 2)
            (void)close(fd);
    }
    return (0);
}
#endif

#if defined(_WINSOCKAPI_)
#define SOCKLIB_DESC WSAData.szDescription
static BOOL WSAInitialized=FALSE;

static BOOL winsock_startup(void)
{
	int		status;             /* Status Code */

    if((status = WSAStartup(MAKEWORD(1,1), &WSAData))==0) {
/*		fprintf(statfp,"%s %s\n",WSAData.szDescription, WSAData.szSystemStatus); */
    lprintf(LOG_CRIT,"!WinSock startup ERROR %d", status);
#define winsock_startup()	(TRUE)
#define SOCKLIB_DESC NULL
static int do_bail(int code)
#if defined(_WINSOCKAPI_)
	if(WSAInitialized && WSACleanup()!=0) 
		lprintf(LOG_ERR,"!WSACleanup ERROR %d",ERROR_VALUE);
	if(pause_on_exit || (code && pause_on_error)) {
		fprintf(statfp,"\nHit enter to continue...");

	if(code)
		fprintf(statfp,"\nReturning error code: %d\n",code);
	return(code);
}

void bail(int code)
{
	exit(do_bail(code));
js_log(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
deuce's avatar
deuce committed
	jsrefcount	rc;
deuce's avatar
deuce committed
	char		*logstr;
	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

	if(argc > 1 && JSVAL_IS_NUMBER(argv[i]))
	for(; i<argc; i++) {
		if((str=JS_ValueToString(cx, argv[i]))==NULL)
			return(JS_FALSE);
		JSSTRING_TO_STRING(cx, str, logstr, NULL);
deuce's avatar
deuce committed
		if(logstr==NULL)
			return(JS_FALSE);
deuce's avatar
deuce committed
		lprintf(level,"%s",logstr);
deuce's avatar
deuce committed
	if(logstr==NULL)
		JS_SET_RVAL(cx, arglist, JSVAL_VOID);
		JS_SET_RVAL(cx, arglist, STRING_TO_JSVAL(str));
js_read(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
	char*	buf;
	int		rd;
	int32	len=128;
deuce's avatar
deuce committed
	jsrefcount	rc;
	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

	if(argc)
		JS_ValueToInt32(cx,argv[0],&len);
	if((buf=alloca(len))==NULL)
	rd=fread(buf,sizeof(char),len,stdin);
		JS_SET_RVAL(cx, arglist, STRING_TO_JSVAL(JS_NewStringCopyN(cx,buf,rd)));
js_readln(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
	char*	buf;
	char*	p;
	int32	len=128;
deuce's avatar
deuce committed
	jsrefcount	rc;
	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

	if(argc)
		JS_ValueToInt32(cx,argv[0],&len);
	if((buf=alloca(len+1))==NULL)
	p=fgets(buf,len+1,stdin);
		JS_SET_RVAL(cx, arglist, STRING_TO_JSVAL(JS_NewStringCopyZ(cx,truncnl(p))));
js_write(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
deuce's avatar
deuce committed
	jsrefcount	rc;
deuce's avatar
deuce committed
	char		*line;
	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

deuce's avatar
deuce committed
		if((str=JS_ValueToString(cx, argv[0]))==NULL)
		JSSTRING_TO_STRING(cx, str, line, NULL);
deuce's avatar
deuce committed
		if(line==NULL)
			return(JS_FALSE);
deuce's avatar
deuce committed
		fprintf(confp,"%s",line);
		JS_SET_RVAL(cx, arglist, JSVAL_VOID);
		JS_SET_RVAL(cx, arglist, STRING_TO_JSVAL(str));
js_writeln(JSContext *cx, uintN argc, jsval *arglist)
deuce's avatar
deuce committed
	jsrefcount	rc;

	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

deuce's avatar
deuce committed
	if(!js_write(cx,argc,arglist))
js_printf(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
deuce's avatar
deuce committed
	jsrefcount	rc;
	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

	if((p = js_sprintf(cx, 0, argc, argv))==NULL) {
		JS_ReportError(cx,"js_sprintf failed");
	JS_SET_RVAL(cx, arglist, STRING_TO_JSVAL(JS_NewStringCopyZ(cx, p)));
js_alert(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
deuce's avatar
deuce committed
	jsrefcount	rc;
deuce's avatar
deuce committed
	char		*line;
	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

	JSVALUE_TO_STRING(cx, argv[0], line, NULL);
deuce's avatar
deuce committed
	if(line==NULL)
deuce's avatar
deuce committed
	fprintf(confp,"!%s\n",line);
	JS_SET_RVAL(cx, arglist, argv[0]);
js_confirm(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
deuce's avatar
deuce committed
	char	 *	cstr;
deuce's avatar
deuce committed
	jsrefcount	rc;
	char		instr[81]="y";
	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

	if((str=JS_ValueToString(cx, argv[0]))==NULL)
	    return(JS_FALSE);

	JSSTRING_TO_STRING(cx, str, cstr, NULL);
	printf("%s (Y/n)? ", cstr);
	fgets(instr,sizeof(instr),stdin);
	p=instr;
	SKIP_WHITESPACE(p);
	JS_SET_RVAL(cx, arglist, BOOLEAN_TO_JSVAL(tolower(*p)!='n'));
	return(JS_TRUE);
}

static JSBool
js_deny(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
    JSString *	str;
	char	 *	cstr;
	char     *	p;
	jsrefcount	rc;
	char		instr[81];

	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

	if((str=JS_ValueToString(cx, argv[0]))==NULL)
	    return(JS_FALSE);

	JSSTRING_TO_STRING(cx, str, cstr, NULL);
	printf("%s (N/y)? ", cstr);
	rc=JS_SUSPENDREQUEST(cx);
	fgets(instr,sizeof(instr),stdin);
	JS_RESUMEREQUEST(cx, rc);

	p=instr;
	SKIP_WHITESPACE(p);
	JS_SET_RVAL(cx, arglist, BOOLEAN_TO_JSVAL(tolower(*p)!='y'));
js_prompt(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
deuce's avatar
deuce committed
	jsrefcount	rc;
deuce's avatar
deuce committed
	char		*prstr;
	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

	if(argc>0 && !JSVAL_IS_VOID(argv[0])) {
		JSVALUE_TO_STRING(cx, argv[0], prstr, NULL);
deuce's avatar
deuce committed
		fprintf(confp,"%s: ",prstr);
		JSVALUE_TO_STRING(cx, argv[1], prstr, NULL);
deuce's avatar
deuce committed
		SAFECOPY(instr,prstr);
	if(!fgets(instr,sizeof(instr),stdin)) {
		JS_RESUMEREQUEST(cx, rc);
	if((str=JS_NewStringCopyZ(cx, truncnl(instr)))==NULL)
	JS_SET_RVAL(cx, arglist, STRING_TO_JSVAL(str));
static JSBool
js_chdir(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
	char*		p;
deuce's avatar
deuce committed
	jsrefcount	rc;
	JSVALUE_TO_STRING(cx, argv[0], p, NULL);
deuce's avatar
deuce committed
	if(p==NULL) {
		JS_SET_RVAL(cx, arglist, INT_TO_JSVAL(-1));
		return(JS_TRUE);
	}

	JS_SET_RVAL(cx, arglist, BOOLEAN_TO_JSVAL(chdir(p)==0));
	return(JS_TRUE);
}

static JSBool
js_putenv(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
	if(argc)
		JSVALUE_TO_STRING(cx, argv[0], p, NULL);
deuce's avatar
deuce committed
	if(p==NULL) {
		JS_SET_RVAL(cx, arglist, INT_TO_JSVAL(-1));
		return(JS_TRUE);
	}

	JS_SET_RVAL(cx, arglist, BOOLEAN_TO_JSVAL(putenv(strdup(p))==0));
	return(JS_TRUE);
}

static jsSyncMethodSpec js_global_functions[] = {
	{"read",			js_read,            1},
	{"readln",			js_readln,          1},
    {"writeln",         js_writeln,         0},
    {"print",           js_writeln,         0},
    {"printf",          js_printf,          1},	
	{"alert",			js_alert,			1},
	{"prompt",			js_prompt,			1},
	{"confirm",			js_confirm,			1},
	{"deny",			js_deny,			1},
	{"chdir",			js_chdir,			1},
	{"putenv",			js_putenv,			1},
    {0}
};

static void
js_ErrorReporter(JSContext *cx, const char *message, JSErrorReport *report)
{
	char	line[64];
	char	file[MAX_PATH+1];
	const char*	warning;
deuce's avatar
deuce committed
	jsrefcount	rc;
		lprintf(LOG_ERR,"!JavaScript: %s", message);
		return;
    }

	if(report->filename)
		sprintf(file," %s",report->filename);
	else
		file[0]=0;

	if(report->lineno)
		sprintf(line," line %d",report->lineno);
	else
		line[0]=0;

	if(JSREPORT_IS_WARNING(report->flags)) {
		if(JSREPORT_IS_STRICT(report->flags))
			warning="strict warning";
		else
			warning="warning";
		log_level=LOG_WARNING;
	} else {
		log_level=LOG_ERR;
	lprintf(log_level,"!JavaScript %s%s%s: %s",warning,file,line,message);
js_BranchCallback(JSContext *cx, JSObject *script)
    return(js_CommonBranchCallback(cx,&branch));
#if JS_VERSION>180
static JSBool
js_OperationCallback(JSContext *cx)
{
	JSBool	ret;

	JS_SetOperationCallback(cx, NULL);
	ret=js_BranchCallback(cx, NULL);
	JS_SetOperationCallback(cx, js_OperationCallback);
	return ret;
}
#endif

static BOOL js_CreateEnvObject(JSContext* cx, JSObject* glob, char** env)
{
	char		name[256];
	char*		val;
	uint		i;
	JSObject*	js_env;

	if((js_env=JS_NewObject(js_cx, NULL, NULL, glob))==NULL)
		return(FALSE);

	if(!JS_DefineProperty(cx, glob, "env", OBJECT_TO_JSVAL(js_env)
		,NULL,NULL,JSPROP_READONLY|JSPROP_ENUMERATE))
		return(FALSE);

	for(i=0;env[i]!=NULL;i++) {
		SAFECOPY(name,env[i]);
		truncstr(name,"=");
		val=strchr(env[i],'=');
		if(val==NULL)
			val="";
		else
			val++;
		if(!JS_DefineProperty(cx, js_env, name, STRING_TO_JSVAL(JS_NewStringCopyZ(cx,val))
			,NULL,NULL,JSPROP_READONLY|JSPROP_ENUMERATE))
			return(FALSE);
	}

	return(TRUE);
}

rswindell's avatar
rswindell committed
static BOOL js_init(char** environ)
	js_startup_t	startup;

	memset(&startup,0,sizeof(startup));
	SAFECOPY(startup.load_path, load_path_list);
	fprintf(statfp,"%s\n",(char *)JS_GetImplementationVersion());

	fprintf(statfp,"JavaScript: Creating runtime: %lu bytes\n"
	if((js_runtime = jsrt_GetNew(js_max_bytes, 5000, __FILE__, __LINE__))==NULL)
	fprintf(statfp,"JavaScript: Initializing context (stack: %lu bytes)\n"
    if((js_cx = JS_NewContext(js_runtime, js_cx_stack))==NULL)
	if(stack_limit)
		fprintf(statfp,"JavaScript: Thread stack limit: %lu bytes\n"
			,stack_limit);

	JS_SetErrorReporter(js_cx, js_ErrorReporter);

	/* Global Object */
	if((js_glob=js_CreateCommonObjects(js_cx, &scfg, NULL, js_global_functions
		,time(NULL), host_name, SOCKLIB_DESC	/* system */
		,&branch,&startup						/* js */
		,NULL,INVALID_SOCKET					/* client */
		))==NULL) {
	/* Environment Object (associative array) */
	if(!js_CreateEnvObject(js_cx, js_glob, environ)) {
		return(FALSE);
	if(js_CreateUifcObject(js_cx, js_glob)==NULL) {
	if(js_CreateConioObject(js_cx, js_glob)==NULL) {
		return(FALSE);
static const char* js_ext(const char* fname)
{
	if(strchr(fname,'.')==NULL)
		return(".js");
	return("");
}

long js_exec(const char *fname, char** args)
{
	char*		js_buf=NULL;
	size_t		js_buflen;
	jsval		rval=JSVAL_VOID;
	int32		result=0;
	long double	start;
	long double	diff;
		if(isfullpath(fname)) {
			SAFECOPY(path,fname);
		}
		else {
			SAFEPRINTF3(path,"%s%s%s",orig_cwd,fname,js_ext(fname));
			if(!fexistcase(path)) {
				SAFEPRINTF3(path,"%s%s%s",scfg.mods_dir,fname,js_ext(fname));
				if(scfg.mods_dir[0]==0 || !fexistcase(path))
					SAFEPRINTF3(path,"%s%s%s",scfg.exec_dir,fname,js_ext(fname));
			}
			lprintf(LOG_ERR,"!Module file (%s) doesn't exist",path);
			lprintf(LOG_ERR,"!Error %d (%s) opening %s",errno,STRERROR(errno),path);
	if(stack_limit) {
#if JS_STACK_GROWTH_DIRECTION > 0
		stack_frame=((ulong)&stack_frame)+stack_limit;
#else
		stack_frame=((ulong)&stack_frame)-stack_limit;
#endif
		JS_SetThreadStackLimit(js_cx, stack_frame);
	}
	JS_DefineProperty(js_cx, js_glob, "argv", OBJECT_TO_JSVAL(argv)
		,NULL,NULL,JSPROP_READONLY|JSPROP_ENUMERATE);

	for(argc=0;args[argc];argc++) {
		arg = JS_NewStringCopyZ(js_cx, args[argc]);
		if(arg==NULL)
			break;
		val=STRING_TO_JSVAL(arg);
		if(!JS_SetElement(js_cx, argv, argc, &val))
			break;
	}
	JS_DefineProperty(js_cx, js_glob, "argc", INT_TO_JSVAL(argc)
		,NULL,NULL,JSPROP_READONLY|JSPROP_ENUMERATE);

	JS_DefineProperty(js_cx, js_glob, "jsexec_revision"
		,STRING_TO_JSVAL(JS_NewStringCopyZ(js_cx,revision))
		,NULL,NULL,JSPROP_READONLY|JSPROP_ENUMERATE);

	sprintf(rev_detail,"JSexec %s%s  "
		"Compiled %s %s with %s"
		,revision
#ifdef _DEBUG
		," Debug"
#else
		,""
#endif
		,__DATE__, __TIME__, compiler
		);

	JS_DefineProperty(js_cx, js_glob, "jsexec_revision_detail"
		,STRING_TO_JSVAL(JS_NewStringCopyZ(js_cx,rev_detail))
		,NULL,NULL,JSPROP_READONLY|JSPROP_ENUMERATE);

#if JS_VERSION>180
	JS_SetOperationCallback(js_cx, js_OperationCallback);
#else
	JS_SetBranchCallback(js_cx, js_BranchCallback);
	if(fp==stdin) 	 /* Using stdin for script source */
	fprintf(statfp,"Reading script from %s\n",path);
	line_no=0;
	js_buflen=0;
	while(!feof(fp)) {
		if(!fgets(line,sizeof(line),fp))
#if defined(__unix__)	/* Support Unix Shell Scripts that start with #!/path/to/jsexec */
		if(line_no==1 && strncmp(line,"#!",2)==0)
			strcpy(line,"\n");	/* To keep line count correct */
		len=strlen(line);
		if((js_buf=realloc(js_buf,js_buflen+len))==NULL) {
			lprintf(LOG_ERR,"!Error allocating %u bytes of memory"
		memcpy(js_buf+js_buflen,line,len);
		js_buflen+=len;
	if(fp!=NULL && fp!=stdin)
		fclose(fp);

	if((js_script=JS_CompileScript(js_cx, js_glob, js_buf, js_buflen, fname==NULL ? NULL : path, 1))==NULL) {
		lprintf(LOG_ERR,"!Error compiling script from %s",path);
	if((diff=xp_timer()-start) > 0)
		mfprintf(statfp,"%s compiled in %.2Lf seconds"
	js_PrepareToExecute(js_cx, js_glob, fname==NULL ? NULL : path, orig_cwd);
	JS_ExecuteScript(js_cx, js_glob, js_script, &rval);
	JS_GetProperty(js_cx, js_glob, "exit_code", &rval);
	if(rval!=JSVAL_VOID && JSVAL_IS_NUMBER(rval)) {
deuce's avatar
deuce committed
		char	*p;

		JSVALUE_TO_STRING(js_cx, rval, p, NULL);
deuce's avatar
deuce committed
		mfprintf(statfp,"Using JavaScript exit_code: %s",p);
		JS_ValueToInt32(js_cx,rval,&result);
	}
	js_EvalOnExit(js_cx, js_glob, &branch);

	JS_ReportPendingException(js_cx);

	if((diff=xp_timer()-start) > 0)
		mfprintf(statfp,"%s executed in %.2Lf seconds"
	return(result);
void break_handler(int type)
	lprintf(LOG_NOTICE,"\n-> Terminated Locally (signal: %d)",type);
	lprintf(LOG_NOTICE,"\n-> Recycled Locally (signal: %d)",type);
#if defined(_WIN32)
deuce's avatar
deuce committed
BOOL WINAPI ControlHandler(unsigned long CtrlType)
	break_handler((int)CtrlType);
int parseLogLevel(const char* p)
{
	str_list_t logLevelStringList=iniLogLevelStringList();
	int i;

	if(isdigit(*p))
		return strtol(p,NULL,0);

	/* Exact match */
	for(i=0;logLevelStringList[i]!=NULL;i++) {
		if(stricmp(logLevelStringList[i],p)==0)
			return i;
	}
	/* Partial match */
	for(i=0;logLevelStringList[i]!=NULL;i++) {
		if(strnicmp(logLevelStringList[i],p,strlen(p))==0)
			return i;
	}
	return DEFAULT_LOG_LEVEL;
}


/*********************/
/* Entry point (duh) */
/*********************/
rswindell's avatar
rswindell committed
int main(int argc, char **argv, char** environ)
	char	error[512];
	char*	module=NULL;
	char*	p;
	char*	omode="w";
	int		argn;
	BOOL	nonbuffered_con=FALSE;
rswindell's avatar
rswindell committed
	confp=stdout;
	errfp=stderr;
	if((nulfp=fopen(_PATH_DEVNULL,"w+"))==NULL) {
		perror(_PATH_DEVNULL);
		return(do_bail(-1));
	if(isatty(fileno(stderr)))
		statfp=stderr;
	else	/* if redirected, don't send status messages to stderr */
		statfp=nulfp;