void MaSslConfig::setCipherSuite(char *ciphers) { mprFree(this->ciphers); this->ciphers = mprStrdup(ciphers); }
static int configureViaApi() { MaHostAddress *address; MaHost *host; MprList *listens; MaListen *lp; MprHashTable *hostAddresses; MaDir *dir; MaAlias *ap; MaLocation *loc; char *cp, *docRootPath; char addrBuf[MPR_MAX_IP_ADDR_PORT], pathBuf[MPR_MAX_FNAME]; int port; mprLog(MPR_CONFIG, "Configuration via Command Line\n"); #if BLD_FEATURE_ROMFS mprLog(MPR_CONFIG, "Server Root \"%s\" in ROM\n", serverRoot); docRootPath = mprStrdup(docRoot); #else // // Set the document root. Is relative to the server root unless an absolute path is used. // #if WIN if (*docRoot != '/' && docRoot[1] != ':' && docRoot[2] != '/') #elif WINCE if (*docRoot != '\\' && docRoot != '/') #else if (*docRoot != '/') #endif { if (*docRoot) { mprAllocSprintf(&docRootPath, MPR_MAX_FNAME, "%s/%s", serverRoot, docRoot); } else { docRootPath = mprStrdup(serverRoot); } } else { docRootPath = mprStrdup(docRoot); } #endif // BLD_FEATURE_ROMFS mprLog(MPR_CONFIG, "Document Root \"%s\"\n", docRootPath); // // Setup the listening addresses. If only a port is specified, listen on // all interfaces. If only the IP address is specified without a port, // then default to port 80. IF autoScan is on, scan for a free port // starting from the base address. // listens = server->getListens(); port = MA_SERVER_DEFAULT_PORT_NUM; if ((cp = strchr(ipAddr, ':')) != 0) { *cp++ = '\0'; port = atoi(cp); if (port <= 0 || port > 65535) { mprError(MPR_L, MPR_USER, "Bad listen port number %d", port); return MPR_ERR_BAD_SYNTAX; } if (autoScan) { port = findFreePort(ipAddr, port); } listens->insert(new MaListen(ipAddr, port, 0)); } else { if (isdigit((uchar) *ipAddr) && strchr(ipAddr, '.') == 0) { port = atoi(ipAddr); if (port <= 0 || port > 65535) { mprError(MPR_L, MPR_USER, "Bad listen port number %d", port); return MPR_ERR_BAD_SYNTAX; } if (autoScan) { port = findFreePort("", port); } listens->insert(new MaListen("", port)); } else { if (autoScan) { port = findFreePort(ipAddr, MA_SERVER_DEFAULT_PORT_NUM); } listens->insert(new MaListen(ipAddr, port)); } } mprFree(ipAddr); ipAddr = 0; host = server->newHost(docRootPath); if (host == 0) { return MPR_ERR_CANT_OPEN; } // // Add the default server listening addresses to the HostAddress hash. // FUTURE -- this should be moved into newHost // hostAddresses = server->getHostAddresses(); lp = (MaListen*) listens->getFirst(); while (lp) { mprSprintf(addrBuf, sizeof(addrBuf), "%s:%d", lp->getIpAddr(), lp->getPort()); address = (MaHostAddress*) hostAddresses->lookup(addrBuf); if (address == 0) { address = new MaHostAddress(addrBuf); hostAddresses->insert(address); } mprLog(MPR_CONFIG, "Listening for HTTP on %s\n", addrBuf); address->insertVhost(new MaVhost(host)); lp = (MaListen*) listens->getNext(lp); mprFree(ipAddr); ipAddr = mprStrdup(addrBuf); } // // Setup a module search path that works for production and developement. // #if BLD_FEATURE_DLL char searchPath[MPR_MAX_FNAME]; mprSprintf(searchPath, sizeof(searchPath), "./lib ../lib ../lib/modules ../../lib ../../lib/modules %s/lib", BLD_PREFIX); host->setModuleDirs(searchPath); #endif // // Load all possible modules // #if BLD_FEATURE_AUTH_MODULE // // Handler must be added first to authorize all requests. // if (server->loadModule("auth") == 0) { host->addHandler("authHandler", ""); } #endif #if BLD_FEATURE_UPLOAD_MODULE // // Must be after auth and before ESP, EGI. // if (server->loadModule("upload") == 0) { host->addHandler("uploadHandler", ""); } #endif #if BLD_FEATURE_CGI_MODULE if (server->loadModule("cgi") == 0) { host->addHandler("cgiHandler", ".cgi .cgi-nph .bat .cmd .pl .py"); } #endif #if BLD_FEATURE_EGI_MODULE if (server->loadModule("egi") == 0) { host->addHandler("egiHandler", ".egi"); } #endif #if BLD_FEATURE_ESP_MODULE if (server->loadModule("esp") == 0) { host->addHandler("espHandler", ".esp .asp"); } #endif #if BLD_FEATURE_C_API_MODULE server->loadModule("capi"); #endif #if BLD_FEATURE_GACOMPAT_MODULE server->loadModule("compat"); #endif #if BLD_FEATURE_SSL_MODULE server->loadModule("ssl"); #endif // // Only load one of matrixSsl / openssl // #if BLD_FEATURE_OPENSSL_MODULE server->loadModule("openSsl"); #elif BLD_FEATURE_MATRIXSSL_MODULE server->loadModule("matrixSsl"); #endif #if BLD_FEATURE_PHP5_MODULE if (server->loadModule("php5") == 0) { host->addHandler("php5Handler", ".php"); } #endif #if BLD_FEATURE_COPY_MODULE // // Handler must be added last to be the catch all // if (server->loadModule("copy") == 0) { host->addHandler("copyHandler", ""); } #endif // // Create the top level directory // dir = new MaDir(host); dir->setPath(docRootPath); host->insertDir(dir); // // Add cgi-bin // mprSprintf(pathBuf, sizeof(pathBuf), "%s/cgi-bin", serverRoot); ap = new MaAlias("/cgi-bin/", pathBuf); mprLog(4, "ScriptAlias \"/cgi-bin/\":\n\t\t\t\"%s\"\n", pathBuf); host->insertAlias(ap); loc = new MaLocation(dir->getAuth()); loc->setPrefix("/cgi-bin/"); loc->setHandler("cgiHandler"); host->insertLocation(loc); mprFree(docRootPath); return 0; }
/* * Create the host addresses for a host. Called for hosts or for NameVirtualHost directives (host == 0). */ int maCreateHostAddresses(MaServer *server, MaHost *host, cchar *configValue) { MaListen *listen; MaHostAddress *address; char *ipAddrPort, *ipAddr, *value, *tok; char addrBuf[MPR_MAX_IP_ADDR_PORT]; int next, port; address = 0; value = mprStrdup(server, configValue); ipAddrPort = mprStrTok(value, " \t", &tok); while (ipAddrPort) { if (mprStrcmpAnyCase(ipAddrPort, "_default_") == 0) { mprAssert(0); ipAddrPort = "*:*"; } if (mprParseIp(server, ipAddrPort, &ipAddr, &port, -1) < 0) { mprError(server, "Can't parse ipAddr %s", ipAddrPort); continue; } mprAssert(ipAddr && *ipAddr); if (ipAddr[0] == '*') { ipAddr = mprStrdup(server, ""); } /* * For each listening endpiont, */ for (next = 0; (listen = mprGetNextItem(server->listens, &next)) != 0; ) { if (port > 0 && port != listen->port) { continue; } if (listen->ipAddr[0] != '\0' && ipAddr[0] != '\0' && strcmp(ipAddr, listen->ipAddr) != 0) { continue; } /* * Find the matching host address or create a new one */ if ((address = maLookupHostAddress(server, listen->ipAddr, listen->port)) == 0) { address = maCreateHostAddress(server, listen->ipAddr, listen->port); mprAddItem(server->hostAddresses, address); } /* * If a host is specified */ if (host == 0) { maSetNamedVirtualHostAddress(address); } else { maInsertVirtualHost(address, host); if (listen->ipAddr[0] != '\0') { mprSprintf(addrBuf, sizeof(addrBuf), "%s:%d", listen->ipAddr, listen->port); } else { mprSprintf(addrBuf, sizeof(addrBuf), "%s:%d", ipAddr, listen->port); } maSetHostName(host, addrBuf); } } mprFree(ipAddr); ipAddrPort = mprStrTok(0, " \t", &tok); } if (host) { if (address == 0) { mprError(server, "No valid IP address for host %s", host->name); mprFree(value); return MPR_ERR_CANT_INITIALIZE; } if (maIsNamedVirtualHostAddress(address)) { maSetNamedVirtualHost(host); } } mprFree(value); return 0; }
MprLogModule::~MprLogModule() { mprGetMpr()->logService->removeModule(this); mprFree(name); }
static int realMain(MprCmdLine *cmdLine) { MaHttp *http; char portNumBuf[MPR_MAX_IP_PORT]; char *argp, *logSpec; int c, errflg, kill, poolThreads, outputVersion; mprSetMemHandler(memoryFailure); mprCreateMemHeap(0, 16 * 1024, MAXINT); program = mprGetBaseName(cmdLine->getArgv()[0]); poolThreads = -1; kill = errflg = 0; logSpec = 0; outputVersion = 0; autoScan = 1; background = 0; serverRoot = 0; docRoot = "web"; #if !WIN && !WINCE && !VXWORKS if (getuid()) { ipAddr = mprStrdup("4000"); } else { mprSprintf(portNumBuf, sizeof(portNumBuf), "%d", MA_SERVER_DEFAULT_PORT_NUM); ipAddr = mprStrdup(portNumBuf); } #else mprSprintf(portNumBuf, sizeof(portNumBuf), "%d", MA_SERVER_DEFAULT_PORT_NUM); ipAddr = mprStrdup(portNumBuf); #endif while ((c = cmdLine->next(&argp)) != EOF) { switch(c) { case 'A': autoScan = 0; break; case 'a': mprFree(ipAddr); ipAddr = mprStrdup(argp); break; case 'b': background++; break; case 'c': /* Ignored */ break; case 'D': mprSetDebugMode(1); break; case 'd': docRoot = argp; break; case 'f': #if BLD_FEATURE_CONFIG_PARSE configFile = argp; autoScan = 0; #else errflg++; #endif break; case 'k': kill++; logSpec = 0; break; case 'l': logSpec = (*argp) ? argp : 0; break; case 'm': mprRequestMemStats(1); break; case 'r': serverRoot = argp; break; case 't': poolThreads = atoi(argp); break; // // FUTURE -- just for test. Will be removed // case 'w': writeFile = argp; break; case 'v': outputVersion++; break; #if WIN && BLD_FEATURE_RUN_AS_SERVICE case 'i': serviceOp = MPR_INSTALL_SERVICE; if (strcmp(argp, "none") == 0) { serviceCmdLine = ""; } else if (strcmp(argp, "default") == 0) { serviceCmdLine = "-b -c -f " BLD_PRODUCT ".conf"; } else { serviceCmdLine = argp; } break; case 'g': serviceOp = MPR_GO_SERVICE; break; case 's': serviceOp = MPR_STOP_SERVICE; break; case 'u': serviceOp = MPR_UNINSTALL_SERVICE; break; #endif default: errflg++; break; } } if (errflg) { printUsage(program); return MPR_ERR_BAD_SYNTAX; } mp = new Mpr(program); mp->setAppName(BLD_PRODUCT); mp->setAppTitle(BLD_NAME); mp->setHeadless(isService || background); #if BLD_HOST_UNIX || VXWORKS initSignals(); #endif if (kill) { mp->killMpr(); delete mp; exit(0); } if (outputVersion) { printVersion(); delete mp; exit(0); } // // Create the top level HTTP service and default HTTP server // http = new MaHttp(); server = new MaServer(http, "default"); setupFileSystem(); setLogging(logSpec); // // Confirm the location of the server root // if (locateServerRoot(serverRoot) < 0) { mprError(MPR_L, MPR_USER, "Can't start server, exiting."); exit(2); } if (securityChecks(cmdLine->getArgv()[0]) < 0) { exit(3); } #if WIN #if BLD_FEATURE_RUN_AS_SERVICE if (serviceOp) { windowsServiceOps(); delete mp; return 0; } #endif if (windowsInit() < 0) { delete mp; return MPR_ERR_CANT_INITIALIZE; } #endif // // Start the MPR. This starts Timer, Socket and Pool services // if (mp->start(MPR_KILLABLE) < 0) { mprError(MPR_L, MPR_USER, "Can't start MPR for %s", mp->getAppTitle()); delete mp; return MPR_ERR_CANT_INITIALIZE; } // // Load the statically linked modules // maLoadStaticModules(); if (setupServer(http, poolThreads) < 0) { mprError(MPR_L, MPR_USER, "Can't configure the server, exiting."); exit(6); } #if BLD_FEATURE_CONFIG_SAVE if (writeFile) { server->saveConfig(writeFile); mprLog(0, "Configuration saved to %s\nExiting ...\n", writeFile); exit(0); } #endif if (http->start() < 0) { mprError(MPR_L, MPR_USER, "Can't start server, exiting."); exit(7); } else { #if LINUX && BLD_FEATURE_RUN_AS_SERVICE if (background && mp->makeDaemon(1) < 0) { mprError(MPR_L, MPR_USER, "Could not run in the background"); } else #endif { #if BLD_FEATURE_MULTITHREAD mprLog(MPR_CONFIG, "HTTP services are ready with %d pool threads\n", http->getLimits()->maxThreads); #else mprLog(MPR_CONFIG, "HTTP services are ready (single-threaded).\n"); #endif } mp->setHeadless(1); eventLoop(); mprLog(MPR_WARN, "Stopping HTTP services.\n"); http->stop(); } #if WIN if (trayIcon > 0) { closeTrayIcon(); } if (trayTimer) { trayTimer->stop(MPR_TIMEOUT_STOP); trayTimer->dispose(); trayTimer = 0; } #endif mprLog(MPR_WARN, "Stopping MPR services.\n"); mp->stop(0); maUnloadStaticModules(); delete server; delete http; delete mp; mprFree(ipAddr); #if BLD_FEATURE_ROMFS delete romFileSystem; #endif #if BLD_FEATURE_LOG mprLog(MPR_WARN, "Closing log.\n"); if (logger) { delete logger; } #if WIN if (dialog) { delete dialog; } #endif #endif return 0; }
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; }
MprLogToFile::~MprLogToFile() { mprFree(logFileName); stop(); }
void MaRomFileSystem::setRoot(char *path) { mprFree(root); root = mprStrdup(path); rootLen = strlen(root); }
MaRomFileSystem::~MaRomFileSystem() { mprFree(root); delete fileIndex; }
/* * Format the stack backtrace */ char *ejsFormatStack(Ejs *ejs, EjsError *error) { EjsType *type; EjsFrame *fp; cchar *typeName, *functionName, *line, *typeSep, *codeSep; char *backtrace, *traceLine; int level, len, oldFlags; mprAssert(ejs); backtrace = 0; len = 0; level = 0; /* * Pretend to be the compiler so we can access function frame names */ oldFlags = ejs->flags; ejs->flags |= EJS_FLAG_COMPILER; for (fp = ejs->state->fp; fp; fp = fp->caller) { typeName = ""; functionName = "global"; if (fp->currentLine == 0) { line = ""; } else { for (line = fp->currentLine; *line && isspace((int) *line); line++) { ; } } if (fp) { if (fp->function.owner && fp->function.slotNum >= 0) { functionName = ejsGetPropertyName(ejs, fp->function.owner, fp->function.slotNum).name; } if (ejsIsType(fp->function.owner)) { type = (EjsType*) fp->function.owner; if (type) { typeName = type->qname.name; } } } typeSep = (*typeName) ? "." : ""; codeSep = (*line) ? "->" : ""; if (error && backtrace == 0) { error->filename = mprStrdup(error, fp->filename); error->lineNumber = fp->lineNumber; } if ((traceLine = mprAsprintf(ejs, MPR_MAX_STRING, " [%02d] %s, %s%s%s, line %d %s %s\n", level++, fp->filename ? fp->filename : "script", typeName, typeSep, functionName, fp->lineNumber, codeSep, line)) == NULL) { break; } backtrace = (char*) mprRealloc(ejs, backtrace, len + (int) strlen(traceLine) + 1); if (backtrace == 0) { return 0; } memcpy(&backtrace[len], traceLine, strlen(traceLine) + 1); len += (int) strlen(traceLine); mprFree(traceLine); } ejs->flags = oldFlags; if (error) { error->stack = backtrace; } return backtrace; }
MAIN(ejscMain, int argc, char **argv) #endif { Mpr *mpr; Ejs *ejs; EcCompiler *cp; EjsService *vmService; MprList *useModules; char *argp, *searchPath, *outputFile, *certFile, *name, *tok, *modules, *spec; int nextArg, err, ejsFlags, ecFlags, bind, debug, doc, empty, merge; int warnLevel, noout, parseOnly, tabWidth, optimizeLevel, compilerMode, lang; /* * Create the Embedthis Portable Runtime (MPR) and setup a memory failure handler */ mpr = mprCreate(argc, argv, ejsMemoryFailure); mprSetAppName(mpr, argv[0], 0, 0); if (mprStart(mpr, 0) < 0) { mprError(mpr, "Can't start mpr services"); return EJS_ERR; } err = 0; searchPath = 0; compilerMode = PRAGMA_MODE_STANDARD; certFile = 0; ecFlags = 0; bind = 0; debug = 0; doc = 0; empty = 0; merge = 0; noout = 0; parseOnly = 0; tabWidth = 4; warnLevel = 1; outputFile = 0; optimizeLevel = 9; lang = BLD_FEATURE_EJS_LANG; useModules = mprCreateList(mpr); for (nextArg = 1; nextArg < argc; nextArg++) { argp = argv[nextArg]; if (*argp != '-') { break; } if (strcmp(argp, "--bind") == 0) { bind = 1; } else if (strcmp(argp, "--debug") == 0) { debug = 1; } else if (strcmp(argp, "--doc") == 0) { doc = 1; } else if (strcmp(argp, "--lang") == 0) { if (nextArg >= argc) { err++; } else { spec = argv[++nextArg]; if (mprStrcmpAnyCase(spec, "ecma") == 0) { lang = EJS_SPEC_ECMA; } else if (mprStrcmpAnyCase(spec, "plus") == 0) { lang = EJS_SPEC_PLUS; } else if (mprStrcmpAnyCase(spec, "fixed") == 0) { lang = EJS_SPEC_FIXED; } } } else if (strcmp(argp, "--empty") == 0) { empty = 1; } else if (strcmp(argp, "--log") == 0) { /* * Undocumented logging switch */ if (nextArg >= argc) { err++; } else { ejsStartLogging(mpr, argv[++nextArg]); } } else if (strcmp(argp, "--merge") == 0) { merge = 1; } else if (strcmp(argp, "--nobind") == 0) { bind = 0; } else if (strcmp(argp, "--noout") == 0) { noout = 1; } else if (strcmp(argp, "--standard") == 0) { compilerMode = PRAGMA_MODE_STANDARD; } else if (strcmp(argp, "--strict") == 0) { compilerMode = PRAGMA_MODE_STRICT; } else if (strcmp(argp, "--optimize") == 0) { if (nextArg >= argc) { err++; } else { optimizeLevel = atoi(argv[++nextArg]); } } else if (strcmp(argp, "--out") == 0) { /* * Create a single output module file containing all modules */ if (nextArg >= argc) { err++; } else { outputFile = argv[++nextArg]; } } else if (strcmp(argp, "--parse") == 0) { parseOnly = 1; } else if (strcmp(argp, "--search") == 0 || strcmp(argp, "--searchpath") == 0) { if (nextArg >= argc) { err++; } else { searchPath = argv[++nextArg]; } } else if (strcmp(argp, "--sign") == 0) { if (nextArg >= argc) { err++; } else { certFile = argv[++nextArg]; } } else if (strcmp(argp, "--tabWidth") == 0) { if (nextArg >= argc) { err++; } else { tabWidth = atoi(argv[++nextArg]); } } else if (strcmp(argp, "--use") == 0) { if (nextArg >= argc) { err++; } else { modules = mprStrdup(mpr, argv[++nextArg]); name = mprStrTok(modules, " \t", &tok); while (name != NULL) { mprAddItem(useModules, name); name = mprStrTok(NULL, " \t", &tok); } } } else if (strcmp(argp, "--version") == 0 || strcmp(argp, "-V") == 0) { mprPrintfError(mpr, "%s %s-%s\n", BLD_NAME, BLD_VERSION, BLD_VERSION); return 0; } else if (strcmp(argp, "--warn") == 0) { if (nextArg >= argc) { err++; } else { warnLevel = atoi(argv[++nextArg]); } #if BLD_FEATURE_EJS_WEB } else if (strcmp(argp, "--web") == 0) { #if BLD_FEATURE_EJS_DB mprAddItem(useModules, "ejs.db"); #endif mprAddItem(useModules, "ejs.web"); #endif } else { err++; break; } } if (noout || merge) { bind = 1; } if (outputFile && noout) { mprPrintfError(mpr, "Can't use --out and --noout\n"); err++; } if (argc == nextArg) { err++; } if (err) { /* * Usage Examples: * ejsc Person.es User.es Customer.es * ejsc --out group.mod Person.es User.es Customer.es * ejsc --out group.mod Person.es User.es Customer.es */ mprPrintfError(mpr, "Usage: %s [options] files...\n" " Ejscript compiler options:\n" " --bind # Bind global properties to slots. Requires --out.\n" " --debug # Include symbolic debugging information in output\n" " --doc # Include documentation strings in output\n" " --lang # Language compliance (ecma|plus|fixed)\n" " --empty # Create empty interpreter\n" " --merge # Merge dependent input modules into the output\n" " --noout # Do not generate any output\n" " --optimize level # Set optimization level (0-9)\n" " --out filename # Name a single output module (default: \"default.mod\")\n" " --parse # Just parse source. No output\n" " --search ejsPath # Module search path\n" " --standard # Default compilation mode to standard (default)\n" " --strict # Default compilation mode to strict\n" #if FUTURE " --sign certFile # Sign the module file (not implemented) \n" " --tabwidth # Tab width for '^' error reporting\n" #endif " --use 'module, ...' # List of modules to pre-load\n" " --version # Emit the compiler version information\n" " --warn level # Set the warning message level (0-9)\n\n", mpr->name); return -1; } /* * Need an interpreter when compiling */ vmService = ejsCreateService(mpr); if (vmService == 0) { return MPR_ERR_NO_MEMORY; } ejsFlags = EJS_FLAG_NO_EXE; if (empty) { ejsFlags |= EJS_FLAG_EMPTY; } if (doc) { ejsFlags |= EJS_FLAG_DOC; } ejs = ejsCreate(vmService, NULL, searchPath, ejsFlags); if (ejs == 0) { return MPR_ERR_NO_MEMORY; } ecFlags = 0; ecFlags |= (debug) ? EC_FLAGS_DEBUG: 0; ecFlags |= (empty) ? EC_FLAGS_EMPTY: 0; ecFlags |= (merge) ? EC_FLAGS_MERGE: 0; ecFlags |= (bind) ? EC_FLAGS_BIND: 0; ecFlags |= (noout) ? EC_FLAGS_NO_OUT: 0; ecFlags |= (parseOnly) ? EC_FLAGS_PARSE_ONLY: 0; cp = ecCreateCompiler(ejs, ecFlags, lang); if (cp == 0) { return MPR_ERR_NO_MEMORY; } ecSetOptimizeLevel(cp, optimizeLevel); ecSetWarnLevel(cp, warnLevel); ecSetDefaultMode(cp, compilerMode); ecSetTabWidth(cp, tabWidth); ecSetOutputFile(cp, outputFile); ecSetCertFile(cp, certFile); if (preloadModules(cp, useModules) < 0) { return EJS_ERR; } if (nextArg < argc) { /* * Compile the source files supplied on the command line. This will compile in-memory and * optionally also save to module files. */ if (ecCompile(cp, argc - nextArg, &argv[nextArg], 0) < 0) { err++; } } if (cp->errorCount > 0) { err++; } #if VXWORKS mprFree(cp); mprFree(ejs); if (mprStop(mpr)) { mprFree(mpr); } #endif return err; }
MaDir::~MaDir() { mprFree(indexName); mprFree(path); }
void MaDir::setIndex(char *name) { mprFree(indexName); indexName = mprStrdup(name); inherited = false; }
MAIN(runProgramMain, int argc, char* argv[]) { Mpr *mpr; MprFile *out; char buf[256], *ep; int i, len, exitCode, sofar; mpr = mprCreate(argc, argv, NULL); #if TRACE_PROGRESS MprFile *f = mprOpen(mpr, "/tmp/r.log", O_CREAT|O_TRUNC|O_WRONLY, 0664); mprWriteFormat(f, "runProgram: argc %d\n", argc); for (i = 0; i < argc; i++) { mprWriteFormat(f, "runProgram: arg[%d] = %s\n", i, argv[i]); } mprFree(f); #endif if (argc < 2) { mprPrintfError(mpr, "Usage: runProgram exitCode args...\n"); exit(3); } exitCode = atoi(argv[1]); out = mprGetStdout(mpr); if (exitCode != 99) { /* * Echo the args */ for (i = 2; i < argc; ) { mprPuts(out, argv[i]); if (++i != argc) { mprPutc(out, ' '); } } mprPutc(out, '\n'); /* * Echo the CMD_ENV environment variable value */ ep = getenv("CMD_ENV"); if (ep) { mprPuts(out, "CMD_ENV="); mprPuts(out, ep); } else { mprPuts(out, "Can't find CMD_ENV"); } mprPutc(out, '\n'); mprFlush(out); } /* * Read the input */ sofar = 0; while ((len = (int) read(0, buf, sizeof(buf))) > 0) { sofar += (int) write(1, buf, len); } if (exitCode != 99) { mprPuts(out, "END"); mprPutc(out, '\n'); } mprFlush(out); return exitCode; }
MAIN(ejsMain, int argc, char **argv) #endif { Mpr *mpr; EcCompiler *cp; EjsService *vmService; Ejs *ejs; MprList *useModules, *files; cchar *cmd, *className, *methodName; char *argp, *searchPath, *modules, *name, *tok, *extraFiles, *spec; int nextArg, err, ecFlags, run, merge, bind, noout, debug, optimizeLevel, warnLevel; int compilerMode, lang; /* * Create the Embedthis Portable Runtime (MPR) and setup a memory failure handler */ mpr = mprCreate(argc, argv, ejsMemoryFailure); mprSetAppName(mpr, argv[0], 0, 0); setupSignals(); if (mprStart(mpr, MPR_START_EVENTS_THREAD) < 0) { mprError(mpr, "Can't start mpr services"); return EJS_ERR; } err = 0; className = 0; cmd = 0; methodName = 0; searchPath = 0; run = 1; merge = 0; bind = 1; noout = 1; debug = 1; warnLevel = 1; optimizeLevel = 9; compilerMode = PRAGMA_MODE_STANDARD; lang = BLD_FEATURE_EJS_LANG; useModules = mprCreateList(mpr); files = mprCreateList(mpr); for (nextArg = 1; nextArg < argc; nextArg++) { argp = argv[nextArg]; if (*argp != '-') { break; } if (strcmp(argp, "--bind") == 0) { bind = 1; } else if (strcmp(argp, "--class") == 0) { if (nextArg >= argc) { err++; } else { className = argv[++nextArg]; } } else if (strcmp(argp, "--cmd") == 0 || strcmp(argp, "-c") == 0) { if (nextArg >= argc) { err++; } else { cmd = argv[++nextArg]; } } else if (strcmp(argp, "--debug") == 0) { debug = 1; } else if (strcmp(argp, "--lang") == 0) { if (nextArg >= argc) { err++; } else { spec = argv[++nextArg]; if (mprStrcmpAnyCase(spec, "ecma") == 0) { lang = EJS_SPEC_ECMA; } else if (mprStrcmpAnyCase(spec, "plus") == 0) { lang = EJS_SPEC_PLUS; } else if (mprStrcmpAnyCase(spec, "fixed") == 0) { lang = EJS_SPEC_FIXED; } } } else if (strcmp(argp, "--files") == 0 || strcmp(argp, "-f") == 0) { /* Compatibility with mozilla shell */ if (nextArg >= argc) { err++; } else { extraFiles = mprStrdup(mpr, argv[++nextArg]); name = mprStrTok(extraFiles, " \t", &tok); while (name != NULL) { mprAddItem(files, name); name = mprStrTok(NULL, " \t", &tok); } } } else if (strcmp(argp, "--log") == 0) { if (nextArg >= argc) { err++; } else { ejsStartLogging(mpr, argv[++nextArg]); } } else if (strcmp(argp, "--method") == 0) { if (nextArg >= argc) { err++; } else { methodName = argv[++nextArg]; } } else if (strcmp(argp, "--nobind") == 0) { bind = 0; } else if (strcmp(argp, "--nodebug") == 0) { debug = 0; } else if (strcmp(argp, "--optimize") == 0) { if (nextArg >= argc) { err++; } else { optimizeLevel = atoi(argv[++nextArg]); } } else if (strcmp(argp, "-s") == 0) { /* Compatibility with mozilla shell. Just ignore */ } else if (strcmp(argp, "--search") == 0 || strcmp(argp, "--searchpath") == 0) { if (nextArg >= argc) { err++; } else { searchPath = argv[++nextArg]; } } else if (strcmp(argp, "--standard") == 0) { compilerMode = PRAGMA_MODE_STANDARD; } else if (strcmp(argp, "--strict") == 0) { compilerMode = PRAGMA_MODE_STRICT; } else if (strcmp(argp, "--use") == 0) { if (nextArg >= argc) { err++; } else { modules = mprStrdup(mpr, argv[++nextArg]); name = mprStrTok(modules, " \t", &tok); while (name != NULL) { mprAddItem(useModules, name); name = mprStrTok(NULL, " \t", &tok); } } } else if (strcmp(argp, "--version") == 0 || strcmp(argp, "-V") == 0) { mprPrintfError(mpr, "%s %s-%s\n", BLD_NAME, BLD_VERSION, BLD_NUMBER); return 0; } else if (strcmp(argp, "--warn") == 0) { 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(mpr, "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" " --debug # Use symbolic debugging information (default)\n" " --files \"files..\" # Extra source to compile\n" " --lang # Language compliance (ecma|plus|fixed)\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" " --search ejsPath # Module search path\n" " --standard # Default compilation mode to standard (default)\n" " --strict # Default compilation mode to strict\n" " --use 'module, ...' # List of modules to pre-load\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; } vmService = ejsCreateService(mpr); if (vmService == 0) { return MPR_ERR_NO_MEMORY; } ecInitCompiler(vmService); ejs = ejsCreate(vmService, NULL, searchPath, 0); if (ejs == 0) { return MPR_ERR_NO_MEMORY; } ecFlags = 0; ecFlags |= (run) ? EC_FLAGS_RUN: 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 = ecCreateCompiler(ejs, ecFlags, lang); if (cp == 0) { return MPR_ERR_NO_MEMORY; } ecSetOptimizeLevel(cp, optimizeLevel); ecSetWarnLevel(cp, warnLevel); ecSetDefaultMode(cp, compilerMode); if (preloadModules(cp, useModules) < 0) { return EJS_ERR; } if (nextArg < argc) { mprAddItem(files, argv[nextArg]); } if (cmd) { if (interpretCommands(cp, cmd) < 0) { err++; } } else if (mprGetListCount(files) > 0) { if (interpretFiles(cp, files, argc - nextArg, &argv[nextArg], className, methodName, lang) < 0) { err++; } } else { /* * No args - run as an interactive shell */ if (interpretCommands(cp, NULL) < 0) { err++; } } #if VXWORKS mprFree(cp); mprFree(ejs); if (mprStop(mpr)) { mprFree(mpr); } #endif return err; }
static void outputHeader(MaQueue *q, cchar *path, int nameSize) { Dir *dir; char *parent, *parentSuffix; int order, reverseOrder, fancy, isRootDir, sep; dir = q->stage->stageData; fancy = 1; maWrite(q, "<!DOCTYPE HTML PUBLIC \"-/*W3C//DTD HTML 3.2 Final//EN\">\r\n"); maWrite(q, "<html>\r\n <head>\r\n <title>Index of %s</title>\r\n", path); maWrite(q, " </head>\r\n"); maWrite(q, "<body>\r\n"); maWrite(q, "<h1>Index of %s</h1>\r\n", path); if (dir->sortOrder > 0) { order = 'A'; reverseOrder = 'D'; } else { order = 'D'; reverseOrder = 'A'; } if (dir->fancyIndexing == 0) { fancy = '0'; } else if (dir->fancyIndexing == 1) { fancy = '1'; } else if (dir->fancyIndexing == 2) { fancy = '2'; } parent = mprGetPathDir(q, path); sep = mprGetPathSeparator(q, parent); if (parent[strlen(parent) - 1] != sep) { parentSuffix = "/"; } else { parentSuffix = ""; } isRootDir = (strcmp(path, "/") == 0); if (dir->fancyIndexing == 2) { maWrite(q, "<table><tr><th><img src=\"/icons/blank.gif\" alt=\"[ICO]\" /></th>"); maWrite(q, "<th><a href=\"?C=N;O=%c;F=%c\">Name</a></th>", reverseOrder, fancy); maWrite(q, "<th><a href=\"?C=M;O=%c;F=%c\">Last modified</a></th>", reverseOrder, fancy); maWrite(q, "<th><a href=\"?C=S;O=%c;F=%c\">Size</a></th>", reverseOrder, fancy); maWrite(q, "<th><a href=\"?C=D;O=%c;F=%c\">Description</a></th>\r\n", reverseOrder, fancy); maWrite(q, "</tr><tr><th colspan=\"5\"><hr /></th></tr>\r\n"); if (! isRootDir) { maWrite(q, "<tr><td valign=\"top\"><img src=\"/icons/back.gif\""); maWrite(q, "alt=\"[DIR]\" /></td><td><a href=\"%s%s\">", parent, parentSuffix); maWrite(q, "Parent Directory</a></td>"); maWrite(q, "<td align=\"right\"> - </td></tr>\r\n"); } } else if (dir->fancyIndexing == 1) { maWrite(q, "<pre><img src=\"/icons/space.gif\" alt=\"Icon\" /> "); maWrite(q, "<a href=\"?C=N;O=%c;F=%c\">Name</a>%*s", reverseOrder, fancy, nameSize - 3, " "); maWrite(q, "<a href=\"?C=M;O=%c;F=%c\">Last modified</a> ", reverseOrder, fancy); maWrite(q, "<a href=\"?C=S;O=%c;F=%c\">Size</a> ", reverseOrder, fancy); maWrite(q, "<a href=\"?C=D;O=%c;F=%c\">Description</a>\r\n", reverseOrder, fancy); maWrite(q, "<hr />"); if (! isRootDir) { maWrite(q, "<img src=\"/icons/parent.gif\" alt=\"[DIR]\" />"); maWrite(q, " <a href=\"%s%s\">Parent Directory</a>\r\n", parent, parentSuffix); } } else { maWrite(q, "<ul>\n"); if (! isRootDir) { maWrite(q, "<li><a href=\"%s%s\"> Parent Directory</a></li>\r\n", parent, parentSuffix); } } mprFree(parent); }
void maFreePacket(MaQueue *q, MaPacket *packet) { mprFree(packet); }
static void outputLine(MaQueue *q, MprDirEntry *ep, cchar *path, int nameSize) { MprPath info; Dir *dir; MprTime when; MaHost *host; char *newPath, sizeBuf[16], timeBuf[48], *icon; struct tm tm; bool isDir; int len; cchar *ext, *mimeType; char *dirSuffix; char *months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; dir = q->stage->stageData; if (ep->size >= (1024*1024*1024)) { fmtNum(sizeBuf, sizeof(sizeBuf), (int) ep->size, 1024 * 1024 * 1024, "G"); } else if (ep->size >= (1024*1024)) { fmtNum(sizeBuf, sizeof(sizeBuf), (int) ep->size, 1024 * 1024, "M"); } else if (ep->size >= 1024) { fmtNum(sizeBuf, sizeof(sizeBuf), (int) ep->size, 1024, "K"); } else { mprSprintf(sizeBuf, sizeof(sizeBuf), "%6d", (int) ep->size); } newPath = mprJoinPath(q, path, ep->name); if (mprGetPathInfo(q, newPath, &info) < 0) { when = mprGetTime(q); isDir = 0; } else { isDir = info.isDir ? 1 : 0; when = (MprTime) info.mtime * MPR_TICKS_PER_SEC; } mprFree(newPath); if (isDir) { icon = "folder"; dirSuffix = "/"; } else { host = q->conn->host; ext = mprGetPathExtension(q, ep->name); if ((mimeType = maLookupMimeType(host, ext)) != 0) { if (strcmp(ext, "es") == 0 || strcmp(ext, "ejs") == 0 || strcmp(ext, "php") == 0) { icon = "text"; } else if (strstr(mimeType, "text") != 0) { icon = "text"; } else { icon = "compressed"; } } else { icon = "compressed"; } dirSuffix = ""; } mprDecodeLocalTime(q, &tm, when); mprSprintf(timeBuf, sizeof(timeBuf), "%02d-%3s-%4d %02d:%02d", tm.tm_mday, months[tm.tm_mon], tm.tm_year + 1900, tm.tm_hour, tm.tm_min); len = (int) strlen(ep->name) + (int) strlen(dirSuffix); if (dir->fancyIndexing == 2) { maWrite(q, "<tr><td valign=\"top\">"); maWrite(q, "<img src=\"/icons/%s.gif\" alt=\"[ ]\", /></td>", icon); maWrite(q, "<td><a href=\"%s%s\">%s%s</a></td>", ep->name, dirSuffix, ep->name, dirSuffix); maWrite(q, "<td>%s</td><td>%s</td></tr>\r\n", timeBuf, sizeBuf); } else if (dir->fancyIndexing == 1) { maWrite(q, "<img src=\"/icons/%s.gif\" alt=\"[ ]\", /> ", icon); maWrite(q, "<a href=\"%s%s\">%s%s</a>%-*s %17s %4s\r\n", ep->name, dirSuffix, ep->name, dirSuffix, nameSize - len, "", timeBuf, sizeBuf); } else { maWrite(q, "<li><a href=\"%s%s\"> %s%s</a></li>\r\n", ep->name, dirSuffix, ep->name, dirSuffix); } }
MprBuf::~MprBuf() { if (buf && growBy >= 0) { mprFree(buf); } }
static int parseDir(MaHttp *http, cchar *key, char *value, MaConfigState *state) { MaStage *handler; Dir *dir; char *name, *extensions, *option, *nextTok, *junk; handler = maLookupStage(http, "dirHandler"); dir = handler->stageData; mprAssert(dir); if (mprStrcmpAnyCase(key, "AddIcon") == 0) { /* AddIcon file ext ext ext */ /* Not yet supported */ name = mprStrTok(value, " \t", &extensions); parseWords(dir->extList, extensions); return 1; } else if (mprStrcmpAnyCase(key, "DefaultIcon") == 0) { /* DefaultIcon file */ /* Not yet supported */ dir->defaultIcon = mprStrTok(value, " \t", &junk); return 1; } else if (mprStrcmpAnyCase(key, "IndexOrder") == 0) { /* IndexOrder ascending|descending name|date|size */ mprFree(dir->sortField); dir->sortField = 0; option = mprStrTok(value, " \t", &dir->sortField); if (mprStrcmpAnyCase(option, "ascending") == 0) { dir->sortOrder = 1; } else { dir->sortOrder = -1; } if (dir->sortField) { dir->sortField = mprStrdup(dir, dir->sortField); } return 1; } else if (mprStrcmpAnyCase(key, "IndexIgnore") == 0) { /* IndexIgnore pat ... */ /* Not yet supported */ parseWords(dir->ignoreList, value); return 1; } else if (mprStrcmpAnyCase(key, "IndexOptions") == 0) { /* IndexOptions FancyIndexing|FoldersFirst ... (set of options) */ option = mprStrTok(value, " \t", &nextTok); while (option) { if (mprStrcmpAnyCase(option, "FancyIndexing") == 0) { dir->fancyIndexing = 1; } else if (mprStrcmpAnyCase(option, "HTMLTable") == 0) { dir->fancyIndexing = 2; } else if (mprStrcmpAnyCase(option, "FoldersFirst") == 0) { dir->foldersFirst = 1; } option = mprStrTok(nextTok, " \t", &nextTok); } return 1; } else if (mprStrcmpAnyCase(key, "Options") == 0) { /* Options Indexes */ option = mprStrTok(value, " \t", &nextTok); while (option) { if (mprStrcmpAnyCase(option, "Indexes") == 0) { dir->enabled = 1; } option = mprStrTok(nextTok, " \t", &nextTok); } return 1; } return 0; }
int MprLogService::setLogSpec(char *fileSpec) { MprLogModule *mp; MprLogListener *lp; char namBuf[MPR_MAX_FNAME]; char *spec, *cp, *sizeStr; int maxSize; mprAssert(!logging); #if BLD_FEATURE_MULTITHREAD if (mutex == 0) { mutex = new MprMutex(); } #endif lock(); logging = 1; if (fileSpec == NULL || *fileSpec == '\0') { fileSpec = "trace.txt"; } logSpec = mprStrdup(fileSpec); spec = mprStrdup(fileSpec); for (cp = spec; *cp; cp++) { if (*cp == ':' && isdigit(cp[1])) { break; } } maxSize = MPR_MAX_LOG_SIZE; if (*cp) { *cp++ = '\0'; moduleSpecs = strchr(cp, ','); sizeStr = strchr(cp, '.'); if (sizeStr != 0) { *sizeStr++ = '\0'; maxSize = atoi(sizeStr); // Size in MB } // // Set all modules to the default trace level and then examine // the modules spec to override specified modules // defaultLevel = atoi(cp); if (defaultLevel < 0) { defaultLevel = 0; } mp = (MprLogModule*) moduleList.getFirst(); while (mp) { mp->setLevel(defaultLevel); mp = (MprLogModule*) moduleList.getNext(mp); } if (moduleSpecs) { moduleSpecs++; mp = (MprLogModule*) moduleList.getFirst(); while (mp) { mprSprintf(namBuf, sizeof(namBuf), "%s:", mp->getName()); if ((cp = strstr(moduleSpecs, namBuf)) != 0) { if ((cp = strchr(cp, ':')) != 0) { mp->setLevel(atoi(++cp)); } } mp = (MprLogModule*) moduleList.getNext(mp); } } } if (spec != 0 && *spec != '\0') { lp = (MprLogListener*) listeners.getFirst(); while (lp) { if (lp->setLogSpec(spec, maxSize) < 0) { mprFree(spec); unlock(); return MPR_ERR_CANT_OPEN; } lp = (MprLogListener*) listeners.getNext(lp); } } mprFree(spec); unlock(); return 0; }
static void printVars(MaQueue *q) { MaConn *conn; MaResponse *resp; MaRequest *req; char *sw; char *newLocation; int responseStatus; conn = q->conn; resp = conn->response; req = conn->request; newLocation = 0; responseStatus = 0; sw = 0; /* * Parse the switches */ if (req->parsedUri->query) { sw = (char*) strstr(req->parsedUri->query, "SWITCHES="); if (sw) { sw = mprStrdup(resp, sw + 9); mprUrlDecode(sw, (int) strlen(sw) + 1, sw); if (*sw == '-') { if (sw[1] == 'l') { newLocation = sw + 3; } else if (sw[1] == 's') { responseStatus = atoi(sw + 3); } } } } maSetResponseCode(conn, 200); maSetResponseMimeType(conn, "text/html"); maDontCacheResponse(conn); /* * Test writing headers. The Server header overwrote the "Server" header * * maSetHeader(conn, "MyCustomHeader", "true"); * maSetHeader(conn, "Server", "private"); */ if (maGetCookies(conn) == 0) { maSetCookie(conn, "appwebTest", "Testing can be fun", 43200, "/", 0); } if (newLocation) { maRedirect(conn, 302, newLocation); } else if (responseStatus) { maFailRequest(conn, responseStatus, "Custom Status"); } else { maWrite(q, "<HTML><TITLE>egiProgram: EGI Output</TITLE><BODY>\r\n"); printRequestHeaders(q); printQueryData(q); printBodyData(q); maWrite(q, "</BODY></HTML>\r\n"); } if (sw) { mprFree(sw); } }
/* * Determine if this user is specified as being eligible for this realm. We examine the requiredUsers and requiredGroups. */ static bool isUserValid(MaAuth *auth, cchar *realm, cchar *user) { MaGroup *gp; MaUser *up; cchar *tok, *gtok; char ubuf[80], gbuf[80], *key, *requiredUser, *group, *name; int rc, next; if (auth->anyValidUser) { key = mprStrcat(auth, -1, realm, ":", user, NULL); if (auth->users == 0) { return 0; } rc = mprLookupHash(auth->users, key) != 0; mprFree(key); return rc; } if (auth->requiredUsers) { tok = NULL; requiredUser = mprGetWordTok(ubuf, sizeof(ubuf), auth->requiredUsers, " \t", &tok); while (requiredUser) { if (strcmp(user, requiredUser) == 0) { return 1; } requiredUser = mprGetWordTok(ubuf, sizeof(ubuf), 0, " \t", &tok); } } if (auth->requiredGroups) { gtok = NULL; group = mprGetWordTok(gbuf, sizeof(gbuf), auth->requiredGroups, " \t", >ok); /* * For each group, check all the users in the group. */ while (group) { if (auth->groups == 0) { gp = 0; } else { gp = (MaGroup*) mprLookupHash(auth->groups, group); } if (gp == 0) { mprError(auth, "Can't find group %s", group); group = mprGetWordTok(gbuf, sizeof(gbuf), 0, " \t", >ok); continue; } for (next = 0; (name = mprGetNextItem(gp->users, &next)) != 0; ) { if (strcmp(user, name) == 0) { return 1; } } group = mprGetWordTok(gbuf, sizeof(gbuf), 0, " \t", >ok); } } if (auth->requiredAcl != 0) { key = mprStrcat(auth, -1, realm, ":", user, NULL); up = (MaUser*) mprLookupHash(auth->users, key); if (up) { mprLog(auth, 6, "UserRealm \"%s\" has ACL %lx, Required ACL %lx", key, up->acl, auth->requiredAcl); if (up->acl & auth->requiredAcl) { mprFree(key); return 1; } } mprFree(key); } return 0; }
void MprSocket::close(int timeout) { MprSelectService *ss; Mpr *mpr; char buf[1024]; int handlerFlags, timesUp; mpr = mprGetMpr(); mprLog(7, log, "%d: close\n", sock); ss = mpr->selectService; lock(); mprAssert(!(flags & MPR_SOCKET_CLOSED)); if (flags & MPR_SOCKET_CLOSED) { unlock(); return; } flags |= MPR_SOCKET_CLOSED; handlerFlags = (handler) ? handler->getFlags() : 0; if (handler) { handler->dispose(); handler = 0; } if (sock >= 0) { // // Do a graceful shutdown. Read any outstanding read data to prevent // resets. Then do a shutdown to send a FIN and read outstanding // data. All non-blocking. // //TODO - what about WINCE? #if WIN if (ss->getFlags() & MPR_ASYNC_SELECT) { if (handlerFlags & MPR_SELECT_CLIENT_CLOSED) { // // Client initiated close. We have already received an FD_CLOSE // closesocket(sock); sock = -1; } else { if (shutdown(sock, SHUT_WR) == 0) { // // Do a graceful shutdown. Read any outstanding read data to // prevent resets. Then do a shutdown to send a FIN and lastly // read data when the FD_CLOSE is received (see select.cpp). // All done non-blocking. // timesUp = mprGetTime(0) + timeout; do { if (recv(sock, buf, sizeof(buf), 0) <= 0) { break; } } while (mprGetTime(0) < timesUp); } // // Delayed close call must be first so we are ready when the // FD_CLOSE arrives. Other way round and there is a race if // multi-threaded. // ss->delayedClose(sock); // // We need to ensure we receive an FD_CLOSE to complete the // delayed close. Despite disposing the hander above, socket // messages will still be sent from windows and so select can // cleanup the delayed close socket. // WSAAsyncSelect(sock, ss->getHwnd(), ss->getMessage(), FD_CLOSE); } } else { #endif if (shutdown(sock, SHUT_WR) < 0) { ss->delayedClose(sock); } else { setBlockingMode(0); timesUp = mprGetTime(0) + timeout; do { if (recv(sock, buf, sizeof(buf), 0) <= 0) { break; } } while (mprGetTime(0) < timesUp); } // // Use delayed close to prevent anyone else reusing the socket // while select has not fully cleaned it out of its masks. // ss->delayedClose(sock); ss->awaken(0); } #if WIN } #endif // // Re-initialize all socket variables so the Socket can be reused. // acceptCallback = 0; acceptData = 0; selectEvents = 0; currentEvents = 0; error = 0; flags = MPR_SOCKET_CLOSED; ioCallback = 0; ioData = 0; ioData2 = 0; handlerMask = 0; handlerPriority = MPR_NORMAL_PRIORITY; interestEvents = 0; port = -1; sock = -1; if (ipAddr) { mprFree(ipAddr); ipAddr = 0; } unlock(); }
static int locateServerRoot(char *path) { #if BLD_FEATURE_CONFIG_PARSE && !BLD_FEATURE_ROMFS if (serverRoot == 0) { MprFileInfo info; char searchPath[MPR_MAX_FNAME * 8], pathBuf[MPR_MAX_FNAME]; char cwd[MPR_MAX_FNAME]; char *tok, *searchBuf; // // No explicit server root switch was supplied so search for // "mime.types" in the search path: // . // .. // ../productName // ../../productName // For windows, we also do: // modDir (where the exe was loaded from) // modDir/.. // modDir/../productName // modDir/../../productName // For all: // BLD_PREFIX // #if WIN || WINCE char modDir[MPR_MAX_FNAME], modPath[MPR_MAX_FNAME]; char module[MPR_MAX_FNAME]; // // Initially change directory to where the exe lives // GetModuleFileName(0, module, sizeof(module)); mprGetDirName(modDir, sizeof(modDir), module); mprGetFullPathName(modPath, sizeof(modPath), modDir); #if WIN /* NOTE: use tabs not spaces between items */ mprSprintf(searchPath, sizeof(searchPath), ". .. ../%s ../../%s " "%s %s/.. %s/../%s %s/../../%s %s", BLD_PRODUCT, BLD_PRODUCT, modPath, modPath, modPath, BLD_PRODUCT, modPath, BLD_PRODUCT, BLD_PREFIX); #else /* NOTE: use tabs not spaces between items */ mprSprintf(searchPath, sizeof(searchPath), "%s %s ../%s ../../%s " "%s/.. %s/../%s", MPR_STORAGE, modPath, BLD_PRODUCT, BLD_PRODUCT, modPath, modPath, modPath); #endif #else mprSprintf(searchPath, sizeof(searchPath), ". .. ../%s ../../%s %s", BLD_PRODUCT, BLD_PRODUCT, BLD_PREFIX); #endif getcwd(cwd, sizeof(cwd) - 1); mprLog(3, "Root search path %s, cwd %s\n", searchPath, cwd); searchBuf = mprStrdup(searchPath); path = mprStrTok(searchBuf, "\t", &tok); while (path) { mprSprintf(pathBuf, sizeof(pathBuf), "%s/mime.types", path); mprLog(4, "Searching for %s\n", pathBuf); if (fileSystem->stat(pathBuf, &info) == 0) { break; } path = mprStrTok(0, "\t", &tok); } if (path == 0) { mprError(MPR_L, MPR_USER, "Can't find suitable server root directory\n" "Using search path %s, and current directory %s\n" "Ensure you have adequate permissions to access the required " "directories.\n", searchPath, cwd); mprFree(searchBuf); return MPR_ERR_CANT_ACCESS; } server->setServerRoot(path); mprFree(searchBuf); } else { // // Must program the server up for the server root. It will convert this // path to an absolute path which we reassign to our notion of // serverRoot. // server->setServerRoot(path); } serverRoot = server->getServerRoot(); #endif #if !BLD_FEATURE_ROMFS chdir(serverRoot); #endif return 0; }
/* * Add a shell parameter then do the regular init */ Mpr *mprCreateEx(int argc, char **argv, MprAllocNotifier cback, void *shell) { MprFileSystem *fs; Mpr *mpr; char *cp; if (cback == 0) { cback = memoryFailure; } mpr = (Mpr*) mprCreateAllocService(cback, (MprDestructor) mprDestructor); if (mpr == 0) { mprAssert(mpr); return 0; } /* * Wince and Vxworks passes an arg via argc, and the program name in argv. NOTE: this will only work on 32-bit systems. */ #if WINCE mprMakeArgv(mpr, (char*) argv, mprToAsc(mpr, (uni*) argc), &argc, &argv); #elif VXWORKS mprMakeArgv(mpr, NULL, (char*) argc, &argc, &argv); #endif mpr->argc = argc; mpr->argv = argv; mpr->name = mprStrdup(mpr, BLD_PRODUCT); mpr->title = mprStrdup(mpr, BLD_NAME); mpr->version = mprStrdup(mpr, BLD_VERSION); mpr->idleCallback = mprServicesAreIdle; if (mprCreateTimeService(mpr) < 0) { goto error; } if ((mpr->osService = mprCreateOsService(mpr)) < 0) { goto error; } /* * See if any of the preceeding allocations failed and mark all blocks allocated so far as required. * They will then be omitted from leak reports. */ if (mprHasAllocError(mpr)) { goto error; } #if BREW mprSetShell(mpr, shell); #endif #if BLD_FEATURE_MULTITHREAD mpr->multiThread = 1; if ((mpr->threadService = mprCreateThreadService(mpr)) == 0) { goto error; } mpr->mutex = mprCreateLock(mpr); mpr->spin = mprCreateSpinLock(mpr); #endif if ((fs = mprCreateFileSystem(mpr, "/")) == 0) { goto error; } mprAddFileSystem(mpr, fs); if ((mpr->moduleService = mprCreateModuleService(mpr)) == 0) { goto error; } if ((mpr->dispatcher = mprCreateDispatcher(mpr)) == 0) { goto error; } #if BLD_FEATURE_CMD if ((mpr->cmdService = mprCreateCmdService(mpr)) == 0) { goto error; } #endif #if BLD_FEATURE_MULTITHREAD if ((mpr->workerService = mprCreateWorkerService(mpr)) == 0) { goto error; } #endif if ((mpr->waitService = mprCreateWaitService(mpr)) == 0) { goto error; } if ((mpr->socketService = mprCreateSocketService(mpr)) == 0) { goto error; } #if BLD_FEATURE_HTTP if ((mpr->httpService = mprCreateHttpService(mpr)) == 0) { goto error; } #endif if (mpr->argv && mpr->argv[0] && *mpr->argv[0]) { mprFree(mpr->name); mpr->name = mprGetPathBase(mpr, mpr->argv[0]); if ((cp = strchr(mpr->name, '.')) != 0) { *cp = '\0'; } } /* * Now catch all memory allocation errors up to this point. Should be none. */ if (mprHasAllocError(mpr)) { goto error; } return mpr; /* * Error return */ error: mprFree(mpr); return 0; }
/* * Encode the files as C code */ static int binToC(Mpr *mpr, MprList *files, char *romName, char *prefix) { MprFileInfo info; MprFile *file; char buf[512]; char *filename, *cp, *sl, *p; int next, j, i, len; mprPrintf(mpr, "/*\n * %s -- Compiled Files\n */\n", romName); mprPrintf(mpr, "#include \"mpr.h\"\n\n"); mprPrintf(mpr, "#if BLD_FEATURE_ROMFS\n"); /* * Open each input file and compile */ for (next = 0; (filename = mprGetNextItem(files, &next)) != 0; ) { if (mprGetFileInfo(mpr, filename, &info) == 0 && info.isDir) { mprError(mpr, "Skipping directory %s", filename); continue; } if ((file = mprOpen(mpr, filename, O_RDONLY | O_BINARY, 0666)) < 0) { mprError(mpr, "Can't open file %s\n", filename); return -1; } mprPrintf(mpr, "static uchar _file_%d[] = {\n", next); while ((len = mprRead(file, buf, sizeof(buf))) > 0) { p = buf; for (i = 0; i < len; ) { mprPrintf(mpr, " "); for (j = 0; p < &buf[len] && j < 16; j++, p++) { mprPrintf(mpr, "%3d,", (unsigned char) *p); } i += j; mprPrintf(mpr, "\n"); } } mprPrintf(mpr, " 0 };\n\n"); mprFree(file); } /* * Now output the page index */ mprPrintf(mpr, "MprRomInode %s[] = {\n", romName); for (next = 0; (filename = mprGetNextItem(files, &next)) != 0; ) { /* * Replace the prefix with a leading "/" */ if (strncmp(filename, prefix, strlen(prefix)) == 0) { cp = &filename[strlen(prefix)]; } else { cp = filename; } while((sl = strchr(filename, '\\')) != NULL) { *sl = '/'; } if (*cp == '/') { cp++; } if (*cp == '.' && cp[1] == '\0') { cp++; } if (mprGetFileInfo(mpr, filename, &info) == 0 && info.isDir) { mprPrintf(mpr, " { \"%s\", 0, 0, 0 },\n", cp); continue; } mprPrintf(mpr, " { \"%s\", _file_%d, %d, %d },\n", cp, next, (int) info.size, next); } mprPrintf(mpr, " { 0, 0, 0, 0 },\n"); mprPrintf(mpr, "};\n"); mprPrintf(mpr, "#endif /* BLD_FEATURE_ROMFS */\n"); return 0; }
void MprCmd::setCwd(char *dir) { mprFree(cwd); cwd = mprStrdup(dir); }
static void reportFailure(MaConn *conn, int code, cchar *fmt, va_list args) { MaResponse *resp; MaRequest *req; cchar *url, *status; char *emsg, *msg, *filename; mprAssert(fmt); if (conn->requestFailed) { return; } conn->requestFailed = 1; if (fmt == 0) { fmt = ""; } req = conn->request; resp = conn->response; maDontCacheResponse(conn); msg = mprVasprintf(conn, MA_BUFSIZE, fmt, args); if (resp == 0 || req == 0) { mprLog(conn, 2, "\"%s\", code %d: %s.", mprGetHttpCodeString(conn, code), code, msg); } else { resp->code = code; filename = resp->filename ? resp->filename : 0; /* 711 is a custom error used by the test suite. */ if (code != 711) { mprLog(resp, 2, "Error: \"%s\", code %d for URI \"%s\", file \"%s\": %s.", mprGetHttpCodeString(conn, code), code, req->url ? req->url : "", filename ? filename : "", msg); } /* * Use an error document rather than standard error boilerplate. */ if (req->location) { url = maLookupErrorDocument(req->location, code); if (url && *url) { maRedirect(conn, 302, url); mprFree(msg); return; } } /* * If the headers have already been filled, this alternate response body will be ignored. */ if (resp->altBody == 0) { status = mprGetHttpCodeString(conn, code); /* * For security, escape the message */ emsg = mprEscapeHtml(resp, msg); resp->altBody = mprAsprintf(resp, -1, "<!DOCTYPE html>\r\n" "<html><head><title>Document Error: %s</title></head>\r\n" "<body><h2>Access Error: %d -- %s</h2>\r\n<p>%s</p>\r\n</body>\r\n</html>\r\n", status, code, status, emsg); } resp->flags |= MA_RESP_NO_BODY; } mprFree(msg); }
void MaSslConfig::setCaPath(char *path) { mprFree(caPath); caPath = mprStrdup(path); }