/* * Initialize the applications's window */ static int initWindow(Mpr *mpr) { WNDCLASS wc; int rc; wc.style = CS_HREDRAW | CS_VREDRAW; wc.hbrBackground = (HBRUSH) (COLOR_WINDOW+1); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = (HINSTANCE) appInst; wc.hIcon = NULL; wc.lpfnWndProc = (WNDPROC) msgProc; wc.lpszMenuName = wc.lpszClassName = mprGetAppName(mpr); rc = RegisterClass(&wc); if (rc == 0) { mprError(mpr, "Can't register windows class"); return -1; } appHwnd = CreateWindow(mprGetAppName(mpr), mprGetAppTitle(mpr), WS_OVERLAPPED, CW_USEDEFAULT, 0, 0, 0, NULL, NULL, 0, NULL); if (! appHwnd) { mprError(mpr, "Can't create window"); return -1; } if (taskBarIcon > 0) { ShowWindow(appHwnd, SW_MINIMIZE); UpdateWindow(appHwnd); } return 0; }
static int initialize(cchar *ip, int port) { if ((app->appweb = maCreateAppweb()) == 0) { mprUserError("Can't create HTTP service for %s", mprGetAppName()); return MPR_ERR_CANT_CREATE; } MPR->appwebService = app->appweb; if ((app->server = maCreateServer(app->appweb, "default")) == 0) { mprUserError("Can't create HTTP server for %s", mprGetAppName()); return MPR_ERR_CANT_CREATE; } if (maConfigureServer(app->server, app->configFile, app->home, app->documents, ip, port) < 0) { /* mprUserError("Can't configure the server, exiting."); */ return MPR_ERR_CANT_CREATE; } if (app->workers >= 0) { mprSetMaxWorkers(app->workers); } #if BLD_WIN_LIKE writePort(app->server); #elif BLD_UNIX_LIKE app->traceToggle = mprAddSignalHandler(SIGUSR2, traceHandler, 0, 0, MPR_SIGNAL_AFTER); #endif return 0; }
void mprWriteToOsLog(MprCtx ctx, cchar *message, int flags, int level) { HKEY hkey; void *event; long errorType; ulong exists; char buf[MPR_MAX_STRING], logName[MPR_MAX_STRING], *lines[9], *cp, *value; int type; static int once = 0; mprStrcpy(buf, sizeof(buf), message); cp = &buf[strlen(buf) - 1]; while (*cp == '\n' && cp > buf) { *cp-- = '\0'; } type = EVENTLOG_ERROR_TYPE; lines[0] = buf; lines[1] = 0; lines[2] = lines[3] = lines[4] = lines[5] = 0; lines[6] = lines[7] = lines[8] = 0; if (once == 0) { /* Initialize the registry */ once = 1; mprSprintf(logName, sizeof(logName), "SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\%s", mprGetAppName(ctx)); hkey = 0; if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, logName, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hkey, &exists) == ERROR_SUCCESS) { value = "%SystemRoot%\\System32\\netmsg.dll"; if (RegSetValueEx(hkey, "EventMessageFile", 0, REG_EXPAND_SZ, (uchar*) value, (int) strlen(value) + 1) != ERROR_SUCCESS) { RegCloseKey(hkey); return; } errorType = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE; if (RegSetValueEx(hkey, "TypesSupported", 0, REG_DWORD, (uchar*) &errorType, sizeof(DWORD)) != ERROR_SUCCESS) { RegCloseKey(hkey); return; } RegCloseKey(hkey); } } event = RegisterEventSource(0, mprGetAppName(ctx)); if (event) { /* * 3299 is the event number for the generic message in netmsg.dll. * "%1 %2 %3 %4 %5 %6 %7 %8 %9" -- thanks Apache for the tip */ ReportEvent(event, EVENTLOG_ERROR_TYPE, 0, 3299, NULL, sizeof(lines) / sizeof(char*), 0, (LPCSTR*) lines, 0); DeregisterEventSource(event); } }
static void stopMonitor() { HWND hwnd; hwnd = FindWindow(mprGetAppName(), mprGetAppName()); if (hwnd) { PostMessage(hwnd, WM_QUIT, 0, 0L); } }
static int createEndpoints(int argc, char **argv) { cchar *endpoint; char *ip; int argind, port, secure; ip = 0; port = -1; endpoint = 0; argind = 0; if ((app->appweb = maCreateAppweb()) == 0) { mprError("Cannot create HTTP service for %s", mprGetAppName()); return MPR_ERR_CANT_CREATE; } if ((app->server = maCreateServer(app->appweb, "default")) == 0) { mprError("Cannot create HTTP server for %s", mprGetAppName()); return MPR_ERR_CANT_CREATE; } loadStaticModules(); if (argc > argind) { app->documents = sclone(argv[argind++]); mprLog(2, "Documents %s", app->documents); } if (argind == argc) { if (maParseConfig(app->server, app->configFile, 0) < 0) { return MPR_ERR_CANT_CREATE; } } else { while (argind < argc) { endpoint = argv[argind++]; mprParseSocketAddress(endpoint, &ip, &port, &secure, 80); if (maConfigureServer(app->server, NULL, app->home, app->documents, ip, port) < 0) { return MPR_ERR_CANT_CREATE; } } } if (app->workers >= 0) { mprSetMaxWorkers(app->workers); } /* Call any ESP initializers from slink.c */ appwebStaticInitialize(); #if BIT_WIN_LIKE writePort(app->server); #elif BIT_UNIX_LIKE addSignals(); #endif return 0; }
PUBLIC int mprStartOsService() { /* Open a syslog connection */ #if SOLARIS openlog(mprGetAppName(), LOG_LOCAL0); #else openlog(mprGetAppName(), 0, LOG_LOCAL0); #endif return 0; }
/* See if an instance of this product is already running */ static int findInstance() { HWND hwnd; hwnd = FindWindow(mprGetAppName(), mprGetAppName()); if (hwnd) { if (IsIconic(hwnd)) { ShowWindow(hwnd, SW_RESTORE); } SetForegroundWindow(hwnd); return 1; } return 0; }
static void usageError(Mpr *mpr) { cchar *name; name = mprGetAppName(); mprEprintf("\n%s Usage:\n\n" " %s [options]\n" " %s [options] documents ip[:port] ...\n\n" " Without [documents ip:port], %s will read the appweb.conf configuration file.\n\n" " Options:\n" " --config configFile # Use named config file instead appweb.conf\n" " --chroot directory # Change root directory to run more securely (Unix)\n" " --debugger # Disable timeouts to make debugging easier\n" " --exe path # Set path to Appweb executable on Vxworks\n" " --home directory # Change to directory to run\n" " --log logFile:level # Log to file at verbosity level (0-5)\n" " --name uniqueName # Unique name for this instance\n" " --show # Show route table\n" " --trace traceFile:level # Trace to file at verbosity level (0-5)\n" " --verbose # Same as --log stderr:2\n" " --version # Output version information\n" " --DIGIT # Same as --log stderr:DIGIT\n\n", mprGetAppTitle(), name, name, name); exit(10); }
/* If ME_CONFIG_FILE is defined, use that as the base name for appweb.conf. Otherwise, use "programName.conf". Search order is: "."/BASE ME_SERVER_ROOT/BASE EXE/../BASE EXE/../appweb.conf */ static int findAppwebConf() { char *base, *filename; if (ME_CONFIG_FILE) { base = sclone(ME_CONFIG_FILE); } else { base = mprJoinPathExt(mprGetAppName(), ".conf"); } #if !ME_ROM filename = base; if (!mprPathExists(filename, R_OK)) { filename = mprJoinPath(app->home, base); if (!mprPathExists(filename, R_OK)) { filename = mprJoinPath(mprGetPathParent(mprGetAppDir()), base); if (!mprPathExists(filename, R_OK)) { filename = mprJoinPath(mprGetPathParent(mprGetAppDir()), "appweb.conf"); if (!mprPathExists(filename, R_OK)) { mprError("Cannot find config file %s", base); return MPR_ERR_CANT_OPEN; } } } } #endif app->configFile = filename; return 0; }
static void setAppDefaults() { app->appName = mprGetAppName(); app->serviceProgram = sjoin(mprGetAppDir(), "/", BLD_PRODUCT, ".exe", NULL); app->serviceName = sclone(BLD_COMPANY "-" BLD_PRODUCT); app->serviceHome = mprGetNativePath(SERVICE_HOME); app->serviceTitle = sclone(BLD_NAME); app->serviceStopped = 0; }
/* Move into a chroot jail */ static int changeRoot(cchar *jail) { #if BLD_UNIX_LIKE if (chdir(app->home) < 0) { mprError("%s: Can't change directory to %s", mprGetAppName(), app->home); return MPR_ERR_CANT_INITIALIZE; } if (chroot(jail) < 0) { if (errno == EPERM) { mprError("%s: Must be super user to use the --chroot option", mprGetAppName()); } else { mprError("%s: Can't change change root directory to %s, errno %d", mprGetAppName(), jail, errno); } return MPR_ERR_CANT_INITIALIZE; } #endif return 0; }
MAIN(benchMpr, int argc, char **argv, char **envp) { MprThread *thread; Mpr *mpr; char *argp; int err, nextArg; if ((mpr = mprCreate(argc, argv, MPR_USER_EVENTS_THREAD)) == 0) { return MPR_ERR_MEMORY; } if ((app = mprAllocObj(App, manageApp)) == 0) { return MPR_ERR_MEMORY; } mprAddRoot(app); app->mutex = mprCreateLock(mpr); app->complete = mprCreateCond(); app->iterations = 5; err = 0; for (nextArg = 1; nextArg < argc; nextArg++) { argp = argv[nextArg]; if (*argp != '-') { break; } if (strcmp(argp, "--iterations") == 0 || strcmp(argp, "-i") == 0) { if (nextArg >= argc) { err++; } else { app->iterations = atoi(argv[++nextArg]); } } else if (strcmp(argp, "--alloc") == 0 || strcmp(argp, "-a") == 0) { app->testAllocOnly++; } else { err++; } } if (err) { mprEprintf("usage: bench [-a] [-i iterations]\n"); mprEprintf("usage: %s [options]\n" " -a # Alloc test only\n" " --iterations count # Number of iterations to run the test\n", mprGetAppName(mpr)); exit(2); } mprStart(mpr); thread = mprCreateThread("bench", (MprThreadProc) doBenchmark, (void*) MPR, 0); mprStartThread(thread); while (!testComplete) { mprServiceEvents(250, 0); } mprPrintMem("Memory Report", 0); mprDestroy(); return 0; }
/* Create the listening endoints */ static int createEndpoints(int argc, char **argv) { cchar *endpoint; char *ip; int argind, port, secure; ip = 0; port = -1; endpoint = 0; argind = 0; if ((app->appweb = maCreateAppweb()) == 0) { mprError("Cannot create HTTP service for %s", mprGetAppName()); return MPR_ERR_CANT_CREATE; } if ((app->server = maCreateServer(app->appweb, "default")) == 0) { mprError("Cannot create HTTP server for %s", mprGetAppName()); return MPR_ERR_CANT_CREATE; } loadStaticModules(); if (argc > argind) { app->documents = sclone(argv[argind++]); mprLog(2, "Documents %s", app->documents); } if (argind == argc) { if (maParseConfig(app->server, app->configFile, 0) < 0) { return MPR_ERR_CANT_CREATE; } } else { while (argind < argc) { endpoint = argv[argind++]; mprParseSocketAddress(endpoint, &ip, &port, &secure, 80); if (maConfigureServer(app->server, NULL, app->home, app->documents, ip, port) < 0) { return MPR_ERR_CANT_CREATE; } } } return 0; }
/* Find the appweb.conf file */ static int findAppwebConf() { cchar *userPath; userPath = app->configFile; if (app->configFile == 0) { app->configFile = mprJoinPathExt(mprGetAppName(), ".conf"); } if (!mprPathExists(app->configFile, R_OK)) { if (!userPath) { app->configFile = mprJoinPath(app->home, "appweb.conf"); if (!mprPathExists(app->configFile, R_OK)) { app->configFile = mprJoinPath(mprGetAppDir(), sfmt("%s.conf", mprGetAppName())); } } if (!mprPathExists(app->configFile, R_OK)) { mprError("Cannot open config file \"%s\"", app->configFile); return MPR_ERR_CANT_OPEN; } } return 0; }
int main(int argc, char *argv[]) { Mpr *mpr; int rc; mpr = mprCreate(argc, argv, MPR_USER_EVENTS_THREAD); mprAddStandardSignals(); app = mprAllocObj(App, manageApp); mprAddRoot(app); app->host = sclone("127.0.0.1"); app->port = 4100; if ((ts = mprCreateTestService(mpr)) == 0) { mprLog("appweb test", 0, "Cannot create test service"); exit(2); } if (mprParseTestArgs(ts, argc, argv, parseArgs) < 0) { mprEprintf("\n" " Commands specifically for %s\n" " --host ip:port # Set the default host address for testing\n\n", mprGetAppName(mpr)); exit(3); } if (mprAddTestGroup(ts, &master) == 0) { exit(4); } #if BIT_PACK_SSL if (mprLoadSsl(0) < 0) { return 0; } #endif /* Need a background event thread as we use the main thread to run the tests. */ if (mprStart(mpr)) { mprLog("appweb test", 0, "Cannot start mpr services"); exit(5); } /* Run the tests and return zero if 100% success */ rc = mprRunTests(ts); mprReportTestResults(ts); mprDestroy(); return (rc == 0) ? 0 : -1; }
static int showUsage() { mprEprintf("usage: %s [options] [files] url\n" " Options:\n" " --auth basic|digest # Set authentication type.\n" " --benchmark # Compute benchmark results.\n" " --ca file # Certificate bundle to use when validating the server certificate.\n" " --cert file # Certificate to send to the server to identify the client.\n" " --chunk size # Request response data to use this chunk size.\n" " --ciphers cipher,... # List of suitable ciphers.\n" " --continue # Continue on errors.\n" " --cookie CookieString # Define a cookie header. Multiple uses okay.\n" " --data bodyData # Body data to send with PUT or POST.\n" " --debugger # Disable timeouts to make running in a debugger easier.\n" " --delete # Use the DELETE method. Shortcut for --method DELETE..\n" " --form string # Form data. Must already be form-www-urlencoded.\n" " --header 'key: value' # Add a custom request header.\n" " --host hostName # Host name or IP address for unqualified URLs.\n" " --iterations count # Number of times to fetch the URLs per thread (default 1).\n" " --key file # Private key file.\n" " --log logFile:level # Log to the file at the verbosity level.\n" " --method KIND # HTTP request method GET|OPTIONS|POST|PUT|TRACE (default GET).\n" " --nofollow # Don't automatically follow redirects.\n" " --noout # Don't output files to stdout.\n" " --out file # Send output to file.\n" " --password pass # Password for authentication.\n" " --post # Use POST method. Shortcut for --method POST.\n" " --printable # Make binary output printable.\n" " --protocol PROTO # Set HTTP protocol to HTTP/1.0 or HTTP/1.1 .\n" " --put # Use PUT method. Shortcut for --method PUT.\n" " --range byteRanges # Request a subset range of the document.\n" " --retries count # Number of times to retry failing requests.\n" " --sequence # Sequence requests with a custom header.\n" " --showHeaders # Output response headers.\n" " --showStatus # Output the Http response status code.\n" " --single # Single step. Pause for input between requests.\n" " --threads count # Number of thread instances to spawn.\n" " --timeout secs # Request timeout period in seconds.\n" " --upload # Use multipart mime upload.\n" " --user name # User name for authentication.\n" " --verify # Validate server certificates when using SSL.\n" " --verbose # Verbose operation. Trace progress.\n" " --workers count # Set maximum worker threads.\n" " --zero # Exit with zero status for any valid HTTP response.\n" , mprGetAppName()); return MPR_ERR_BAD_ARGS; }
static void setAppDefaults() { app->appName = mprGetAppName(); app->serviceProgram = sclone(SERVICE_PROGRAM); app->serviceName = sclone(SERVICE_NAME); app->serviceHome = mprGetNativePath(SERVICE_HOME); app->retries = RESTART_MAX; app->signal = SIGTERM; if (mprPathExists("/var/run", X_OK) && getuid() == 0) { app->pidDir = sclone("/var/run"); } else if (mprPathExists("/tmp", X_OK)) { app->pidDir = sclone("/tmp"); } else if (mprPathExists("/Temp", X_OK)) { app->pidDir = sclone("/Temp"); } else { app->pidDir = sclone("."); } }
static void usageError() { cchar *name; name = mprGetAppName(); mprEprintf("\n%s Usage:\n\n" " %s [options]\n" " Options:\n" " --config configFile # Use named config file instead http.json\n" " --debugger # Disable timeouts to make debugging easier\n" " --log logFile:level # Log to file at verbosity level (0-5)\n" " --name uniqueName # Unique name for this instance\n" " --show # Show route table\n" " --trace traceFile:level # Trace to file at verbosity level (0-5)\n" " --verbose # Same as --log stderr:2\n" " --version # Output version information\n" " --DIGIT # Same as --log stderr:DIGIT\n\n", mprGetAppTitle(), name); exit(7); }
/* Create a default window if the application has not already created one. */ PUBLIC int mprInitWindow() { MprWaitService *ws; WNDCLASS wc; HWND hwnd; wchar *name, *title; int rc; ws = MPR->waitService; if (ws->hwnd) { return 0; } name = (wchar*) wide(mprGetAppName()); title = (wchar*) wide(mprGetAppTitle()); wc.style = CS_HREDRAW | CS_VREDRAW; wc.hbrBackground = (HBRUSH) (COLOR_WINDOW+1); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = 0; wc.hIcon = NULL; wc.lpfnWndProc = (WNDPROC) msgProc; wc.lpszMenuName = wc.lpszClassName = name; rc = RegisterClass(&wc); if (rc == 0) { mprError("Cannot register windows class"); return MPR_ERR_CANT_INITIALIZE; } hwnd = CreateWindow(name, title, WS_OVERLAPPED, CW_USEDEFAULT, 0, 0, 0, NULL, NULL, 0, NULL); if (!hwnd) { mprError("Cannot create window"); return -1; } ws->hwnd = hwnd; ws->socketMessage = MPR_SOCKET_MESSAGE; return 0; }
static void showUsage(Mpr *mpr) { mprPrintfError(mpr, "usage: %s [options] [files] url\n" " Options:\n" " --benchmark # Compute benchmark results.\n" " --chunk size # Request response data to use this chunk size.\n" " --continue # Continue on errors.\n" " --cookie CookieString # Define a cookie header. Multiple uses okay.\n" " --debug # Run in debug mode. No timeouts.\n" " --delete # Use the DELETE method. Shortcut for --method DELETE..\n" " --form string # Form data. Must already be form-www-urlencoded.\n" " --header 'key: value' # Add a custom request header.\n" " --host hostName # Host name or IP address for unqualified URLs.\n" " --http 0|1 # HTTP version. 0 for HTTP 1.0, 1 for HTTP 1.1.\n" " --iterations count # Number of times to fetch the urls (default 1).\n" " --log logFile:level # Log to the file at the verbosity level.\n" " --method KIND # HTTP request method GET|OPTIONS|POST|PUT|TRACE (default GET).\n" " --nofollow # Don't automatically follow redirects.\n" " --noout # Don't output files to stdout.\n" " --password pass # Password for authentication.\n" " --post # Use POST method. Shortcut for --method POST.\n" " --printable # Make binary output printable.\n" " --put # Use PUT method. Shortcut for --method PUT.\n" " --range byteRanges # Request a subset range of the document.\n" " --retries count # Number of times to retry failing requests.\n" " --sequence # Sequence requests with a custom header.\n" " --showCode # Output the Http response code.\n" " --showHeaders # Output response headers.\n" " --single # Single step. Pause for input between requests.\n" " --timeout secs # Request timeout period in seconds.\n" " --threads count # Number of thread instances to spawn.\n" " --upload # Use multipart mime upload.\n" " --user name # User name for authentication.\n" " --verbose # Verbose operation. Trace progress.\n" " --workers count # Set maximum worker threads.\n", mprGetAppName(mpr)); }
/* * Display the program command line usage */ static int printUsage(Mpr *mpr) { cchar *name; name = mprGetAppName(mpr); mprPrintfError(mpr, "\n\n%s Usage:\n\n" " %s [options]\n" " %s [options] [IPaddress][:port] [documentRoot] \n\n" " Options:\n" " --config configFile # Use named config file instead appweb.conf\n" " --chroot directory # Change root directory to run more securely (Unix)\n" " --debug # Run in debug mode\n" " --ejs appSpec # Create an ejs application at the path\n" " --home directory # Change to directory to run\n" " --name uniqueName # Unique name for this instance\n" " --log logFile:level # Log to file file at verbosity level\n" " --threads maxThreads # Set maximum worker threads\n" " --version # Output version information\n\n" " Without IPaddress, %s will read the appweb.conf configuration file.\n\n", name, name, name, name, name); return MPR_ERR; }
static void usageError(Mpr *mpr) { cchar *name; name = mprGetAppName(); mprPrintfError("\n%s Usage:\n\n" " %s [options] [IPaddress][:port] [documents]\n\n" " Options:\n" " --config configFile # Use named config file instead appweb.conf\n" " --chroot directory # Change root directory to run more securely (Unix)\n" " --debugger # Disable timeouts to make debugging easier\n" " --exe path # Set path to Appweb executable on Vxworks\n" " --home directory # Change to directory to run\n" " --log logFile:level # Log to file file at verbosity level\n" " --name uniqueName # Unique name for this instance\n" " --threads maxThreads # Set maximum worker threads\n" " --verbose # Same as --log stderr:2\n" " --version # Output version information\n\n" " Without IPaddress, %s will read the appweb.conf configuration file.\n\n", mprGetAppTitle(), name, name, name, name); exit(10); }
void ecErrorv(EcCompiler *cp, cchar *severity, EcLocation *loc, cchar *fmt, va_list args) { cchar *appName; char *pointer, *errorMsg, *msg; appName = mprGetAppName(cp); msg = sfmtv(fmt, args); if (loc) { if (loc->source) { pointer = makeHighlight(cp, loc->source, loc->column); errorMsg = sfmt("%s: %s: %s: %d: %s\n %w \n %s", appName, severity, loc->filename, loc->lineNumber, msg, loc->source, pointer); } else if (loc->lineNumber >= 0) { errorMsg = sfmt("%s: %s: %s: %d: %s", appName, severity, loc->filename, loc->lineNumber, msg); } else { errorMsg = sfmt("%s: %s: %s: 0: %s", appName, severity, loc->filename, msg); } } else { errorMsg = sfmt("%s: %s: %s", appName, severity, msg); } cp->errorMsg = srejoin(cp->errorMsg, errorMsg, NULL); mprBreakpoint(); }
MAIN(ejsMain, int argc, char **argv, char **envp) { Mpr *mpr; EcCompiler *cp; Ejs *ejs; cchar *cmd, *className, *method, *homeDir; char *argp, *searchPath, *modules, *name, *tok, *extraFiles; int nextArg, err, ecFlags, stats, merge, bind, noout, debug, optimizeLevel, warnLevel, strict, i, next; /* Initialize Multithreaded Portable Runtime (MPR) */ mpr = mprCreate(argc, argv, 0); app = mprAllocObj(App, manageApp); mprAddRoot(app); mprAddStandardSignals(); if (mprStart(mpr) < 0) { mprError("Cannot start mpr services"); return EJS_ERR; } err = 0; className = 0; cmd = 0; method = 0; searchPath = 0; stats = 0; merge = 0; bind = 1; noout = 1; debug = 1; warnLevel = 1; optimizeLevel = 9; strict = 0; app->files = mprCreateList(-1, 0); app->iterations = 1; argc = mpr->argc; argv = (char**) mpr->argv; for (nextArg = 1; nextArg < argc; nextArg++) { argp = argv[nextArg]; if (*argp != '-') { break; } if (smatch(argp, "--bind")) { bind = 1; } else if (smatch(argp, "--class")) { if (nextArg >= argc) { err++; } else { className = argv[++nextArg]; } } else if (smatch(argp, "--chdir") || smatch(argp, "--home") || smatch(argp, "-C")) { if (nextArg >= argc) { err++; } else { homeDir = argv[++nextArg]; if (chdir((char*) homeDir) < 0) { mprError("Cannot change directory to %s", homeDir); } } #if BIT_UNIX_LIKE } else if (smatch(argp, "--chroot")) { /* Not documented or supported */ if (nextArg >= argc) { err++; } else { homeDir = mprGetAbsPath(argv[++nextArg]); if (chroot(homeDir) < 0) { if (errno == EPERM) { mprPrintfError("%s: Must be super user to use the --chroot option", mprGetAppName(mpr)); } else { mprPrintfError("%s: Cannot change change root directory to %s, errno %d", mprGetAppName(), homeDir, errno); } return 4; } } #endif } else if (smatch(argp, "--cmd") || smatch(argp, "-c")) { if (nextArg >= argc) { err++; } else { cmd = argv[++nextArg]; } #if BIT_WIN_LIKE } else if (smatch(argp, "--cygroot")) { if (nextArg >= argc) { err++; } else { app->cygroot = sclone(argv[++nextArg]); } #endif } else if (smatch(argp, "--debug")) { debug = 1; } else if (smatch(argp, "--debugger") || smatch(argp, "-D")) { mprSetDebugMode(1); } else if (smatch(argp, "--files") || smatch(argp, "-f")) { /* Compatibility with mozilla shell */ if (nextArg >= argc) { err++; } else { extraFiles = sclone(argv[++nextArg]); name = stok(extraFiles, " \t", &tok); while (name != NULL) { mprAddItem(app->files, sclone(name)); name = stok(NULL, " \t", &tok); } } } else if (smatch(argp, "--iterations") || smatch(argp, "-i")) { if (nextArg >= argc) { err++; } else { app->iterations = atoi(argv[++nextArg]); } } else if (smatch(argp, "--log")) { if (nextArg >= argc) { err++; } else { mprStartLogging(argv[++nextArg], 0); mprSetCmdlineLogging(1); } } else if (smatch(argp, "--method")) { if (nextArg >= argc) { err++; } else { method = argv[++nextArg]; } } else if (smatch(argp, "--name")) { /* Just ignore. Used to tag commands with a unique command line */ nextArg++; } else if (smatch(argp, "--nobind")) { bind = 0; } else if (smatch(argp, "--nodebug")) { debug = 0; } else if (smatch(argp, "--optimize")) { if (nextArg >= argc) { err++; } else { optimizeLevel = atoi(argv[++nextArg]); } } else if (smatch(argp, "-s")) { /* Compatibility with mozilla shell. Just ignore */ } else if (smatch(argp, "--search") || smatch(argp, "--searchpath")) { if (nextArg >= argc) { err++; } else { searchPath = argv[++nextArg]; } } else if (smatch(argp, "--standard")) { strict = 0; } else if (smatch(argp, "--stats")) { stats = 1; } else if (smatch(argp, "--strict")) { strict = 1; } else if (smatch(argp, "--require")) { if (nextArg >= argc) { err++; } else { if (app->modules == 0) { app->modules = mprCreateList(-1, 0); } modules = sclone(argv[++nextArg]); name = stok(modules, " \t", &tok); while (name != NULL) { require(name); name = stok(NULL, " \t", &tok); } } } else if (smatch(argp, "--verbose") || smatch(argp, "-v")) { mprStartLogging("stderr:2", 0); mprSetCmdlineLogging(1); } else if (smatch(argp, "--version") || smatch(argp, "-V")) { mprPrintf("%s-%s\n", BIT_VERSION, BIT_BUILD_NUMBER); return 0; } else if (smatch(argp, "--warn")) { if (nextArg >= argc) { err++; } else { warnLevel = atoi(argv[++nextArg]); } } else { err++; break; } } if (err) { /* If --method or --class is specified, then the named class.method will be run (method defaults to "main", class defaults to first class with a "main"). Examples: ejs ejs script.es arg1 arg2 arg3 ejs --class "Customer" --method "start" --files "script1.es script2.es" main.es */ mprPrintfError("Usage: %s [options] script.es [arguments] ...\n" " Ejscript shell program options:\n" " --class className # Name of class containing method to run\n" " --cmd ejscriptCode # Literal ejscript statements to execute\n" " --cygroot path # Set cygwin root for resolving script paths\n" " --debug # Use symbolic debugging information (default)\n" " --debugger # Disable timeouts to make using a debugger easier\n" " --files \"files..\" # Extra source to compile\n" " --log logSpec # Internal compiler diagnostics logging\n" " --method methodName # Name of method to run. Defaults to main\n" " --nodebug # Omit symbolic debugging information\n" " --optimize level # Set the optimization level (0-9 default is 9)\n" " --require 'module,...' # Required list of modules to pre-load\n" " --search ejsPath # Module search path\n" " --standard # Default compilation mode to standard (default)\n" " --stats # Print memory stats on exit\n" " --strict # Default compilation mode to strict\n" " --verbose | -v # Same as --log stderr:2 \n" " --version # Emit the compiler version information\n" " --warn level # Set the warning message level (0-9 default is 0)\n\n", mpr->name); return -1; } if ((ejs = ejsCreateVM(argc - nextArg, (cchar **) &argv[nextArg], 0)) == 0) { return MPR_ERR_MEMORY; } app->ejs = ejs; if (ejsLoadModules(ejs, searchPath, app->modules) < 0) { return MPR_ERR_CANT_READ; } ecFlags = 0; ecFlags |= (merge) ? EC_FLAGS_MERGE: 0; ecFlags |= (bind) ? EC_FLAGS_BIND: 0; ecFlags |= (noout) ? EC_FLAGS_NO_OUT: 0; ecFlags |= (debug) ? EC_FLAGS_DEBUG: 0; cp = app->compiler = ecCreateCompiler(ejs, ecFlags); if (cp == 0) { return MPR_ERR_MEMORY; } ecSetRequire(cp, app->modules); ecSetOptimizeLevel(cp, optimizeLevel); ecSetWarnLevel(cp, warnLevel); ecSetStrictMode(cp, strict); if (nextArg < argc) { mprAddItem(app->files, sclone(argv[nextArg])); } if (app->cygroot) { /* When cygwin invokes a script with shebang, it passes a cygwin path to the script The ejs --cygroot option permits ejscript to conver this to a native path */ for (next = 0; (name = mprGetNextItem(app->files, &next)) != 0; ) { if (*name == '/' || *name == '\\') { mprSetItem(app->files, next - 1, sjoin(app->cygroot, name, NULL)); } } } for (i = 0; !err && i < app->iterations; i++) { if (cmd) { if (interpretCommands(cp, cmd) < 0) { err++; } } else if (mprGetListLength(app->files) > 0) { if (interpretFiles(cp, app->files, argc - nextArg, &argv[nextArg], className, method) < 0) { err++; } } else { /* No args - run as an interactive shell */ if (interpretCommands(cp, NULL) < 0) { err++; } } } if (stats) { #if BIT_DEBUG mprSetLogLevel(1); mprPrintMem("Memory Usage", 1); #endif } if (!err) { err = mpr->exitStatus; } app->ejs = 0; mprTerminate(MPR_EXIT_DEFAULT, err); ejsDestroyVM(ejs); mprDestroy(MPR_EXIT_DEFAULT); return err; }
int APIENTRY WinMain(HINSTANCE inst, HINSTANCE junk, char *args, int junk2) { char **argv, *argp; int argc, err, nextArg, manage, stop; mpr = mprCreate(0, NULL, NULL); err = 0; manage = 0; appInst = inst; stop = 0; serviceName = BLD_COMPANY "-" BLD_PRODUCT; serviceTitle = BLD_NAME; serviceWindowName = BLD_PRODUCT "Angel"; serviceWindowTitle = BLD_NAME "Angel"; mprSetAppName(mpr, BLD_PRODUCT "Monitor", BLD_NAME " Monitor", BLD_VERSION); appName = mprGetAppName(mpr); appTitle = mprGetAppTitle(mpr); mprSetLogHandler(mpr, logHandler, NULL); chdir(mprGetAppDir(mpr)); /* * Parse command line arguments */ if (mprMakeArgv(mpr, "", args, &argc, &argv) < 0) { return FALSE; } for (nextArg = 1; nextArg < argc; nextArg++) { argp = argv[nextArg]; if (*argp != '-') { break; } if (strcmp(argp, "--manage") == 0) { manage++; } else if (strcmp(argp, "--stop") == 0) { stop++; } else { err++; } if (err) { mprUserError(mpr, "Bad command line: %s\n" " Usage: %s [options]\n" " Switches:\n" " --manage # Launch browser to manage", " --stop # Stop a running monitor", args, appName); return -1; } } if (stop) { stopMonitor(); return 0; } if (findInstance(mpr)) { mprUserError(mpr, "Application %s is already active.", mprGetAppTitle(mpr)); return MPR_ERR_BUSY; } /* * Create the window */ if (initWindow(mpr) < 0) { mprUserError(mpr, "Can't initialize application Window"); return MPR_ERR_CANT_INITIALIZE; } if (manage) { /* * Launch the browser */ runBrowser("/index.html"); } else { if (openMonitorIcon() < 0) { mprUserError(mpr, "Can't open %s tray", appName); } else { eventLoop(); closeMonitorIcon(); } } // mprFree(mpr); return 0; }
APIENTRY WinMain(HINSTANCE inst, HINSTANCE junk, char *command, int junk2) { char *argv[MPR_MAX_ARGC], *argp; int argc, err, nextArg, manage, stop; argc = mprParseArgs(command, &argv[1], MPR_MAX_ARGC - 1) + 1; if (mprCreate(argc, argv, MPR_USER_EVENTS_THREAD | MPR_NO_WINDOW) == NULL) { exit(1); } if ((app = mprAllocObj(App, manageApp)) == NULL) { exit(2); } mprAddRoot(app); err = 0; stop = 0; manage = 0; app->appInst = inst; app->serviceName = sclone(BIT_COMPANY "-" BIT_PRODUCT); app->serviceTitle = sclone(BIT_TITLE); app->serviceWindowName = sclone(BIT_PRODUCT "Angel"); app->serviceWindowTitle = sclone(BIT_TITLE "Angel"); mprSetAppName(BIT_PRODUCT "Monitor", BIT_TITLE " Monitor", BIT_VERSION); mprSetLogHandler(logHandler); chdir(mprGetAppDir()); /* Parse command line arguments */ for (nextArg = 1; nextArg < argc; nextArg++) { argp = argv[nextArg]; if (*argp != '-') { break; } if (strcmp(argp, "--manage") == 0) { manage++; } else if (strcmp(argp, "--stop") == 0) { stop++; } else { err++; } if (err) { mprUserError("Bad command line: %s\n" " Usage: %s [options]\n" " Switches:\n" " --manage # Launch browser to manage", " --stop # Stop a running monitor", command, mprGetAppName()); return -1; } } if (stop) { stopMonitor(); return 0; } if (findInstance()) { mprUserError("Application %s is already active.", mprGetAppTitle()); return MPR_ERR_BUSY; } if (mprInitWindow() < 0) { mprUserError("Can't initialize application Window"); return MPR_ERR_CANT_INITIALIZE; } app->appHwnd = mprGetHwnd(); mprSetWinMsgCallback(msgProc); if (app->taskBarIcon > 0) { ShowWindow(app->appHwnd, SW_MINIMIZE); UpdateWindow(app->appHwnd); } if (manage) { /* Launch the browser */ runBrowser("/index.html"); } else { if (openMonitorIcon() < 0) { mprUserError("Can't open %s tray", mprGetAppName()); } else { eventLoop(); closeMonitorIcon(); } } return 0; }
MAIN(appweb, int argc, char **argv, char **envp) { Mpr *mpr; cchar *ipAddrPort, *argp, *jail; char *ip, *logSpec; int argind, port, status, verbose; ipAddrPort = 0; ip = 0; jail = 0; port = -1; verbose = 0; logSpec = 0; argv[0] = BLD_APPWEB_PATH; if ((mpr = mprCreate(argc, argv, MPR_USER_EVENTS_THREAD)) == NULL) { exit(1); } mprSetAppName(BLD_PRODUCT, BLD_NAME, BLD_VERSION); if ((app = mprAllocObj(App, manageApp)) == NULL) { exit(2); } mprAddRoot(app); mprAddStandardSignals(); #if BLD_FEATURE_ROMFS extern MprRomInode romFiles[]; mprSetRomFileSystem(romFiles); #endif app->mpr = mpr; app->workers = -1; app->configFile = BLD_CONFIG_FILE; app->home = BLD_SERVER_ROOT; app->documents = app->home; argc = mpr->argc; argv = mpr->argv; for (argind = 1; argind < argc; argind++) { argp = argv[argind]; if (*argp != '-') { break; } if (smatch(argp, "--config") || smatch(argp, "--conf")) { if (argind >= argc) { usageError(); } app->configFile = sclone(argv[++argind]); #if BLD_UNIX_LIKE } else if (smatch(argp, "--chroot")) { if (argind >= argc) { usageError(); } jail = mprGetAbsPath(argv[++argind]); #endif } else if (smatch(argp, "--debugger") || smatch(argp, "-D")) { mprSetDebugMode(1); } else if (smatch(argp, "--exe")) { if (argind >= argc) { usageError(); } mpr->argv[0] = mprGetAbsPath(argv[++argind]); mprSetAppPath(mpr->argv[0]); mprSetModuleSearchPath(NULL); } else if (smatch(argp, "--home")) { if (argind >= argc) { usageError(); } app->home = mprGetAbsPath(argv[++argind]); #if UNUSED && KEEP if (chdir(app->home) < 0) { mprError("%s: Can't change directory to %s", mprGetAppName(), app->home); exit(4); } #endif } else if (smatch(argp, "--log") || smatch(argp, "-l")) { if (argind >= argc) { usageError(); } logSpec = argv[++argind]; } else if (smatch(argp, "--name") || smatch(argp, "-n")) { if (argind >= argc) { usageError(); } mprSetAppName(argv[++argind], 0, 0); } else if (smatch(argp, "--threads")) { if (argind >= argc) { usageError(); } app->workers = atoi(argv[++argind]); } else if (smatch(argp, "--verbose") || smatch(argp, "-v")) { verbose++; } else if (smatch(argp, "--version") || smatch(argp, "-V")) { mprPrintf("%s %s-%s\n", mprGetAppTitle(), BLD_VERSION, BLD_NUMBER); exit(0); } else { mprError("Unknown switch \"%s\"", argp); usageError(); exit(5); } } if (logSpec) { mprStartLogging(logSpec, 1); mprSetCmdlineLogging(1); } else if (verbose) { mprStartLogging(sfmt("stderr:%d", verbose + 1), 1); mprSetCmdlineLogging(1); } if (mprStart() < 0) { mprUserError("Can't start MPR for %s", mprGetAppName()); mprDestroy(MPR_EXIT_DEFAULT); return MPR_ERR_CANT_INITIALIZE; } if (checkEnvironment(argv[0]) < 0) { exit(6); } if (argc > argind) { if (argc > (argind + 2)) { usageError(); } ipAddrPort = argv[argind++]; if (argc > argind) { app->documents = sclone(argv[argind++]); } mprParseSocketAddress(ipAddrPort, &ip, &port, HTTP_DEFAULT_PORT); } else if (findConfigFile() < 0) { exit(7); } if (jail && changeRoot(jail) < 0) { exit(8); } if (initialize(ip, port) < 0) { return MPR_ERR_CANT_INITIALIZE; } if (maStartAppweb(app->appweb) < 0) { mprUserError("Can't start HTTP service, exiting."); exit(9); } /* Service I/O events until instructed to exit */ while (!mprIsStopping()) { mprServiceEvents(-1, 0); } status = mprGetExitStatus(); mprLog(1, "Stopping Appweb ..."); maStopAppweb(app->appweb); mprDestroy(MPR_EXIT_DEFAULT); return status; }
MAIN(appweb, int argc, char **argv) { Mpr *mpr; MaHttp *http; cchar *ipAddrPort, *documentRoot, *argp, *logSpec; char *configFile, *ipAddr, *homeDir, *timeText, *ejsPrefix, *ejsPath, *changeRoot; int workers, outputVersion, argind, port; documentRoot = 0; changeRoot = ejsPrefix = ejsPath = 0; ipAddrPort = 0; ipAddr = 0; port = -1; logSpec = 0; server = 0; outputVersion = 0; workers = -1; configFile = BLD_FEATURE_CONFIG_FILE; homeDir = BLD_FEATURE_SERVER_ROOT; mpr = mprCreate(argc, argv, memoryFailure); argc = mpr->argc; argv = mpr->argv; #if BLD_FEATURE_ROMFS extern MprRomInode romFiles[]; mprSetRomFileSystem(mpr, romFiles); #endif if (osInit(mpr) < 0) { exit(2); } if (mprStart(mpr, 0) < 0) { mprUserError(mpr, "Can't start MPR for %s", mprGetAppName(mpr)); mprFree(mpr); return MPR_ERR_CANT_INITIALIZE; } for (argind = 1; argind < argc; argind++) { argp = argv[argind]; if (*argp != '-') { break; } if (strcmp(argp, "--config") == 0) { if (argind >= argc) { return printUsage(mpr); } configFile = argv[++argind]; #if BLD_UNIX_LIKE } else if (strcmp(argp, "--chroot") == 0) { if (argind >= argc) { return printUsage(mpr); } changeRoot = mprGetAbsPath(mpr, argv[++argind]); #endif } else if (strcmp(argp, "--debug") == 0 || strcmp(argp, "-D") == 0 || strcmp(argp, "-d") == 0 || strcmp(argp, "--debugger") == 0) { mprSetDebugMode(mpr, 1); } else if (strcmp(argp, "--ejs") == 0) { if (argind >= argc) { return printUsage(mpr); } ejsPrefix = mprStrdup(mpr, argv[++argind]); if ((ejsPath = strchr(ejsPrefix, ':')) != 0) { *ejsPath++ = '\0'; } ejsPath = mprGetAbsPath(mpr, ejsPath); } else if (strcmp(argp, "--home") == 0) { if (argind >= argc) { return printUsage(mpr); } homeDir = mprGetAbsPath(mpr, argv[++argind]); if (chdir((char*) homeDir) < 0) { mprPrintfError(mpr, "%s: Can't change directory to %s\n", mprGetAppName(mpr), homeDir); exit(2); } } else if (strcmp(argp, "--log") == 0 || strcmp(argp, "-l") == 0) { if (argind >= argc) { return printUsage(mpr); } logSpec = argv[++argind]; maStartLogging(mpr, logSpec); } else if (strcmp(argp, "--name") == 0 || strcmp(argp, "-n") == 0) { if (argind >= argc) { return printUsage(mpr); } mprSetAppName(mpr, argv[++argind], 0, 0); } else if (strcmp(argp, "--threads") == 0) { if (argind >= argc) { return printUsage(mpr); } workers = atoi(argv[++argind]); } else if (strcmp(argp, "--verbose") == 0 || strcmp(argp, "-v") == 0) { maStartLogging(mpr, "stdout:2"); } else if (strcmp(argp, "--version") == 0 || strcmp(argp, "-V") == 0) { outputVersion++; } else { mprPrintfError(mpr, "Unknown switch \"%s\"\n", argp); printUsage(mpr); exit(2); } } if (argc > argind) { if (argc > (argind + 2)) { return printUsage(mpr); } ipAddrPort = argv[argind++]; if (argc > argind) { documentRoot = argv[argind++]; } else { documentRoot = "."; } } if (outputVersion) { mprPrintf(mpr, "%s %s-%s\n", mprGetAppTitle(mpr), BLD_VERSION, BLD_NUMBER); exit(0); } if (ipAddrPort) { mprParseIp(mpr, ipAddrPort, &ipAddr, &port, MA_SERVER_DEFAULT_PORT_NUM); } else { #if BLD_FEATURE_CONFIG_PARSE if (configFile == 0) { configFile = mprStrcat(mpr, -1, mprGetAppName(mpr), ".conf", NULL); } if (!mprPathExists(mpr, configFile, R_OK)) { mprPrintfError(mpr, "Can't open config file %s\n", configFile); exit(2); } #else return printUsage(mpr); #endif #if !BLD_FEATURE_ROMFS if (homeDir == 0) { homeDir = mprGetPathParent(mpr, configFile); if (chdir((char*) homeDir) < 0) { mprPrintfError(mpr, "%s: Can't change directory to %s\n", mprGetAppName(mpr), homeDir); exit(2); } } #endif } homeDir = mprGetCurrentPath(mpr); if (checkEnvironment(mpr, argv[0], homeDir) < 0) { exit(3); } #if BLD_UNIX_LIKE if (changeRoot) { homeDir = mprGetAbsPath(mpr, changeRoot); if (chdir(homeDir) < 0) { mprError(mpr, "%s: Can't change directory to %s", homeDir); exit(4); } if (chroot(homeDir) < 0) { if (errno == EPERM) { mprError(mpr, "%s: Must be super user to use the --chroot option", mprGetAppName(mpr)); } else { mprError(mpr, "%s: Can't change change root directory to %s, errno %d", mprGetAppName(mpr), homeDir, errno); } exit(5); } } #endif /* * Create the top level HTTP service and default HTTP server. Set the initial server root to "." */ http = maCreateHttp(mpr); if (http == 0) { mprUserError(mpr, "Can't create HTTP service for %s", mprGetAppName(mpr)); return MPR_ERR_CANT_INITIALIZE; } server = maCreateServer(http, "default", ".", 0, -1); if (server == 0) { mprUserError(mpr, "Can't create HTTP server for %s", mprGetAppName(mpr)); return MPR_ERR_CANT_INITIALIZE; } if (maConfigureServer(mpr, http, server, configFile, ipAddr, port, documentRoot) < 0) { /* mprUserError(mpr, "Can't configure the server, exiting."); */ exit(6); } if (mpr->ipAddr) { mprLog(mpr, 2, "Server IP address %s", mpr->ipAddr); } timeText = mprFormatLocalTime(mpr, mprGetTime(mpr)); mprLog(mpr, 1, "Started at %s", timeText); mprFree(timeText); #if BLD_FEATURE_EJS if (ejsPrefix) { createEjsAlias(mpr, http, server, ejsPrefix, ejsPath); } #endif #if BLD_FEATURE_MULTITHREAD if (workers >= 0) { mprSetMaxWorkers(http, workers); } #endif #if BLD_WIN_LIKE if (!ejsPrefix) { writePort(server->defaultHost); } #endif if (maStartHttp(http) < 0) { mprUserError(mpr, "Can't start HTTP service, exiting."); exit(7); } #if BLD_FEATURE_MULTITHREAD mprLog(mpr, 1, "HTTP services are ready with max %d worker threads", mprGetMaxWorkers(mpr)); #else mprLog(mpr, 1, "HTTP services are ready (single-threaded)"); #endif /* * Service I/O events until instructed to exit */ while (!mprIsExiting(mpr)) { mprServiceEvents(mpr->dispatcher, -1, MPR_SERVICE_EVENTS | MPR_SERVICE_IO); } /* * Signal a graceful shutdown */ mprLog(http, 1, "Exiting ..."); maStopHttp(http); mprLog(http, 1, "Exit complete"); #if VXWORKS if (mprStop(mpr)) { mprFree(mpr); } #endif return 0; }
int APIENTRY WinMain(HINSTANCE inst, HINSTANCE junk, char *args, int junk2) { char **argv, *argp; int argc, err, nextArg; mpr = mprCreate(0, NULL, MPR_USER_EVENTS_THREAD); app = mprAllocObj(App, manageApp); mprAddRoot(app); mprAddTerminator(terminating); err = 0; app->appInst = inst; app->heartBeatPeriod = HEART_BEAT_PERIOD; setAppDefaults(); mprSetAppName(BLD_PRODUCT "Manager", BLD_NAME "Manager", BLD_VERSION); app->appName = mprGetAppName(); app->appTitle = mprGetAppTitle(mpr); mprSetLogHandler(logHandler); mprSetWinMsgCallback((MprMsgCallback) msgProc); if ((argc = mprMakeArgv(args, &argv, MPR_ARGV_ARGS_ONLY)) < 0) { return FALSE; } for (nextArg = 1; nextArg < argc; nextArg++) { argp = argv[nextArg]; if (*argp != '-' || strcmp(argp, "--") == 0) { break; } if (strcmp(argp, "--args") == 0) { /* Args to pass to service when it starts */ if (nextArg >= argc) { err++; } else { app->serviceArgs = argv[++nextArg]; } } else if (strcmp(argp, "--console") == 0) { /* Allow the service to interact with the console */ app->createConsole++; } else if (strcmp(argp, "--daemon") == 0) { /* Ignored on windows */ } else if (strcmp(argp, "--heartBeat") == 0) { /* Set the heart beat period */ if (nextArg >= argc) { err++; } else { app->heartBeatPeriod = atoi(argv[++nextArg]) * 1000; } } else if (strcmp(argp, "--home") == 0) { /* Change to this directory before starting the service */ if (nextArg >= argc) { err++; } else { app->serviceHome = sclone(argv[++nextArg]); } } else if (strcmp(argp, "--log") == 0) { /* Pass the log directive through to the service */ if (nextArg >= argc) { err++; } else { app->logSpec = sclone(argv[++nextArg]); mprStartLogging(app->logSpec, 0); mprSetCmdlineLogging(1); } } else if (strcmp(argp, "--name") == 0) { if (nextArg >= argc) { err++; } else { app->serviceName = sclone(argv[++nextArg]); } } else if (strcmp(argp, "--program") == 0) { if (nextArg >= argc) { err++; } else { app->serviceProgram = sclone(argv[++nextArg]); } } else if (strcmp(argp, "--verbose") == 0 || strcmp(argp, "-v") == 0) { mprSetLogLevel(1); } else { err++; } if (err) { mprUserError("Bad command line: %s\n" " Usage: %s [options] [program args]\n" " Switches:\n" " --args # Args to pass to service\n" " --console # Display the service console\n" " --heartBeat interval # Heart beat interval period (secs)\n" " --home path # Home directory for service\n" " --log logFile:level # Log directive for service\n" " --name name # Name of the service to manage\n" " --program path # Service program to start\n" " --verbose # Show command feedback\n" " Commands:\n" " disable # Disable the service\n" " enable # Enable the service\n" " start # Start the service\n" " stop # Start the service\n" " run # Run and watch over the service\n", args, app->appName); return -1; } } if (mprStart() < 0) { mprUserError("Can't start MPR for %s", mprGetAppName()); } else { mprStartEventsThread(); if (nextArg >= argc) { return process("run"); } else for (; nextArg < argc; nextArg++) { if (!process(argv[nextArg])) { return FALSE; } } } return TRUE; }
int main(int argc, char *argv[]) { char *argp, *value; int err, nextArg, status; err = 0; mprCreate(argc, argv, MPR_USER_EVENTS_THREAD); app = mprAllocObj(App, manageApp); mprAddRoot(app); mprAddTerminator(terminating); mprAddStandardSignals(); setAppDefaults(); for (nextArg = 1; nextArg < argc && !err; nextArg++) { argp = argv[nextArg]; if (*argp != '-') { break; } if (strcmp(argp, "--args") == 0) { /* Args to pass to service */ if (nextArg >= argc) { err++; } else { app->serviceArgs = argv[++nextArg]; } } else if (strcmp(argp, "--console") == 0) { /* Does nothing. Here for compatibility with windows watcher */ } else if (strcmp(argp, "--daemon") == 0) { app->runAsDaemon++; #if FUTURE } else if (strcmp(argp, "--heartBeat") == 0) { /* Set the frequency to check on the program. */ if (nextArg >= argc) { err++; } else { app->heartBeatPeriod = atoi(argv[++nextArg]); } #endif } else if (strcmp(argp, "--home") == 0) { /* Change to this directory before starting the service */ if (nextArg >= argc) { err++; } else { app->serviceHome = sclone(argv[++nextArg]); } } else if (strcmp(argp, "--log") == 0) { /* Pass the log directive through to the service */ if (nextArg >= argc) { err++; } else { app->logSpec = sclone(argv[++nextArg]); mprStartLogging(app->logSpec, 0); mprSetCmdlineLogging(1); } } else if (strcmp(argp, "--name") == 0) { if (nextArg >= argc) { err++; } else { app->serviceName = sclone(argv[++nextArg]); } } else if (strcmp(argp, "--pidfile") == 0) { if (nextArg >= argc) { err++; } else { app->pidPath = sclone(argv[++nextArg]); } } else if (strcmp(argp, "--program") == 0) { if (nextArg >= argc) { err++; } else { app->serviceProgram = sclone(argv[++nextArg]); } } else if (strcmp(argp, "--retries") == 0) { if (nextArg >= argc) { err++; } else { app->retries = atoi(argv[++nextArg]); } } else if (strcmp(argp, "--signal") == 0) { if (nextArg >= argc) { err++; } else { value = argv[++nextArg]; if (smatch(value, "SIGABRT")) { app->signal = SIGABRT; } else if (smatch(value, "SIGINT")) { app->signal = SIGINT; } else if (smatch(value, "SIGHUP")) { app->signal = SIGHUP; } else if (smatch(value, "SIGQUIT")) { app->signal = SIGQUIT; } else if (smatch(value, "SIGTERM")) { app->signal = SIGTERM; } else if (smatch(value, "SIGUSR1")) { app->signal = SIGUSR1; } else if (smatch(value, "SIGUSR2")) { app->signal = SIGUSR2; } else { app->signal = atoi(argv[++nextArg]); } } } else if (strcmp(argp, "--verbose") == 0 || strcmp(argp, "-v") == 0) { mprSetLogLevel(1); } else { err++; break; } } if (nextArg >= argc) { err++; } if (err) { mprUserError("Bad command line: \n" " Usage: %s [commands]\n" " Switches:\n" " --args # Args to pass to service\n" " --daemon # Run manager as a daemon\n" " --home path # Home directory for service\n" " --log logFile:level # Log directive for service\n" " --retries count # Max count of app restarts\n" " --name name # Name of the service to manage\n" " --pidfile path # Location of the pid file\n" " --program path # Service program to start\n" " --signal signo # Signal number to terminate service\n" " --verbose # Show command feedback\n" #if FUTURE " --heartBeat interval # Heart beat interval period (secs) \n" #endif " Commands:\n" " disable # Disable the service\n" " enable # Enable the service\n" " install # Install the service\n" " run # Run and watch over the service\n" " start # Start the service\n" " stop # Start the service\n" " uninstall # Uninstall the service\n" , app->appName); return -1; } if (!app->pidPath) { app->pidPath = sjoin(app->pidDir, "/", app->serviceName, ".pid", NULL); } if (app->runAsDaemon) { makeDaemon(); } status = 0; if (getuid() != 0) { mprUserError("Must run with administrator privilege. Use sudo."); status = 1; } else if (mprStart() < 0) { mprUserError("Can't start MPR for %s", mprGetAppName()); status = 2; } else { mprStartEventsThread(); for (; nextArg < argc; nextArg++) { if (!process(argv[nextArg], 0)) { status = 3; break; } } } mprDestroy(MPR_EXIT_DEFAULT); return status; }