Пример #1
0
static bool enableService(int enable)
{
    SC_HANDLE   svc, mgr;
    int         flag;

    mgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (! mgr) {
        mprUserError("Can't open service manager");
        return 0;
    }
    svc = OpenService(mgr, app->serviceName, SERVICE_ALL_ACCESS);
    if (svc == NULL) {
        if (enable) {
            mprUserError("Can't access service");
        }
        CloseServiceHandle(mgr);
        return 0;
    }
    flag = (enable) ? SERVICE_AUTO_START : SERVICE_DISABLED;
    if (!ChangeServiceConfig(svc, SERVICE_NO_CHANGE, flag, SERVICE_NO_CHANGE, NULL, NULL, NULL, NULL, NULL, NULL, NULL)) {
        mprUserError("Can't change service: 0x%x == %d", GetLastError(), GetLastError());
        CloseServiceHandle(svc);
        CloseServiceHandle(mgr);
        return 0;
    }
    CloseServiceHandle(svc);
    CloseServiceHandle(mgr);
    return 1;
}
Пример #2
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;
}
Пример #3
0
/*
 *  Start the Mpr and all services
 */
int mprStart(Mpr *mpr, int startEventsThread)
{
    int     rc;

    rc = mprStartOsService(mpr->osService);
    rc += mprStartModuleService(mpr->moduleService);
#if BLD_FEATURE_MULTITHREAD
    rc += mprStartWorkerService(mpr->workerService);
#endif
    rc += mprStartSocketService(mpr->socketService);
#if BLD_FEATURE_HTTP
    rc += mprStartHttpService(mpr->httpService);
#endif

    if (rc != 0) {
        mprUserError(mpr, "Can't start MPR services");
        return MPR_ERR_CANT_INITIALIZE;
    }
    mpr->flags |= MPR_STARTED;
    mprLog(mpr, MPR_INFO, "MPR services are ready");
#if BLD_FEATURE_MULTITHREAD
    if (startEventsThread) {
        mprStartEventsThread(mpr);
    }
#endif
    return 0;
}
Пример #4
0
/*
 *  Security checks. Make sure we are staring with a safe environment
 */
static int unixSecurityChecks(Mpr *mpr, cchar *program, cchar *home)
{
    struct stat     sbuf;

    if (((stat(home, &sbuf)) != 0) || !(S_ISDIR(sbuf.st_mode))) {
        mprUserError(mpr, "Can't access directory: %s", home);
        return MPR_ERR_BAD_STATE;
    }
    if ((sbuf.st_mode & S_IWOTH) || (sbuf.st_mode & S_IWGRP)) {
        mprUserError(mpr, "Security risk, directory %s is writeable by others", home);
    }

    /*
     *  Should always convert the program name into a fully qualified path. Otherwise this fails.
     */
    if (*program == '/') {
        if ((stat(program, &sbuf)) != 0) {
            mprUserError(mpr, "Can't access program: %s", program);
            return MPR_ERR_BAD_STATE;
        }
        if ((sbuf.st_mode & S_IWOTH) || (sbuf.st_mode & S_IWGRP)) {
            mprUserError(mpr, "Security risk, Program %s is writeable by others", program);
        }
        if (sbuf.st_mode & S_ISUID) {
            mprUserError(mpr, "Security risk, %s is setuid", program);
        }
        if (sbuf.st_mode & S_ISGID) {
            mprUserError(mpr, "Security risk, %s is setgid", program);
        }
    }
    return 0;
}
Пример #5
0
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;
}
Пример #6
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;
}
Пример #7
0
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;                                                                    
}
Пример #8
0
static bool installService()
{
    SC_HANDLE   svc, mgr;
    char        cmd[MPR_MAX_FNAME], key[MPR_MAX_FNAME];
    int         serviceType;

    mgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (! mgr) {
        mprUserError("Can't open service manager");
        return 0;
    }
    /*
        Install this app as a service
     */
    svc = OpenService(mgr, app->serviceName, SERVICE_ALL_ACCESS);
    if (svc == NULL) {
        serviceType = SERVICE_WIN32_OWN_PROCESS;
        if (app->createConsole) {
            serviceType |= SERVICE_INTERACTIVE_PROCESS;
        }
        GetModuleFileName(0, cmd, sizeof(cmd));
        svc = CreateService(mgr, app->serviceName, app->serviceTitle, SERVICE_ALL_ACCESS, serviceType, SERVICE_DISABLED, 
            SERVICE_ERROR_NORMAL, cmd, NULL, NULL, "", NULL, NULL);
        if (! svc) {
            mprUserError("Can't create service: 0x%x == %d", GetLastError(), GetLastError());
            CloseServiceHandle(mgr);
            return 0;
        }
    }
    CloseServiceHandle(svc);
    CloseServiceHandle(mgr);

    /*
        Write a service description
     */
    mprSprintf(key, sizeof(key), "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\" "Services\\%s", app->serviceName);

    if (mprWriteRegistry(key, "Description", SERVICE_DESCRIPTION) < 0) {
        return 0;
    }

    /*
        Write the home directory
     */
    if (app->serviceHome == 0) {
        app->serviceHome = mprGetPathParent(mprGetAppDir());
    }
    if (mprWriteRegistry(key, "HomeDir", app->serviceHome) < 0) {
        return 0;
    }

    /*
        Write the service args
     */
    if (app->serviceArgs && *app->serviceArgs) {
        if (mprWriteRegistry(key, "Args", app->serviceArgs) < 0) {
            return 0;
        }
    }
    return 1;
}
Пример #9
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;
}
Пример #10
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;
}
Пример #11
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;
}
Пример #12
0
int APIENTRY WinMain(HINSTANCE inst, HINSTANCE junk, char *command, int junk2) {
    char    **argv;
    cchar   *documents, *home, *logs, *port, *ssl, *argp, *path, *contents, *revised;
    cchar   *user, *group, *cache, *modules, *bak;
    int     argc, err, nextArg;
    static void logHandler(int flags, int level, cchar *msg);

    if (mprCreate(0, NULL, MPR_USER_EVENTS_THREAD) == NULL) {
        exit(1);
    }
    if ((argc = mprMakeArgv(command, &argv, MPR_ARGV_ARGS_ONLY)) < 0) {
        return FALSE;
    }
    mprSetLogHandler(logHandler);
#else
int main(int argc, char **argv) {
    cchar   *documents, *home, *logs, *port, *ssl, *argp, *path, *contents, *revised;
    cchar   *user, *group, *cache, *modules, *bak;
    int     err, nextArg;
    if (mprCreate(argc, argv, MPR_USER_EVENTS_THREAD) == NULL) {
        exit(1);
    }
#endif
    documents = home = port = ssl = logs = user = group = cache = modules = 0;
    for (err = 0, nextArg = 1; nextArg < argc; nextArg++) {
        argp = argv[nextArg];
        if (*argp != '-') {
            break;
        }
        if (smatch(argp, "--documents") && nextArg < argc) {
            documents = argv[++nextArg];
        } else if (smatch(argp, "--home") && nextArg < argc) {
            home = argv[++nextArg];
        } else if (smatch(argp, "--logs") && nextArg < argc) {
            logs = argv[++nextArg];
        } else if (smatch(argp, "--port") && nextArg < argc) {
            port = argv[++nextArg];
        } else if (smatch(argp, "--ssl") && nextArg < argc) {
            ssl = argv[++nextArg];
        } else if (smatch(argp, "--user") && nextArg < argc) {
            user = argv[++nextArg];
        } else if (smatch(argp, "--group") && nextArg < argc) {
            group = argv[++nextArg];
        } else if (smatch(argp, "--cache") && nextArg < argc) {
            cache = argv[++nextArg];
        } else if (smatch(argp, "--modules") && nextArg < argc) {
            modules = argv[++nextArg];
        } else {
            err++;
        }
    }
    if (nextArg != (argc - 1)) {
        err++;
    }
    if (err) {
#if BIT_WIN_LIKE
        mprUserError("Bad command line:");
#else
        mprUserError("Bad command line:\n"
            "  Usage: pathConfig [options]\n"
            "  Switches:\n"
            "    --cache dir          # Cache dir"
            "    --documents dir      # Static documents directory"
            "    --group groupname    # Group name"
            "    --home dir           # Server home directory"
            "    --logs dir           # Log directory"
            "    --modules dir        # moduels dir"
            "    --port number        # HTTP port number"
            "    --user username      # User name");
#endif
        return 1;
    }
    path = argv[nextArg++];

    if ((contents = mprReadPathContents(path, NULL)) == 0) {
        mprUserError("Cannot read %s", path);
        return 1;
    }
	if (port) {
	    contents = replace(contents, "Listen 80", "Listen %s", port);
	}
	if (ssl) {
	    contents = replace(contents, "443", ssl);
	}
    if (documents) {
        contents = replace(contents, "DocumentRoot", "DocumentRoot \"%s\"", documents);
    }
    if (home) {
        contents = replace(contents, "ServerRoot", "ServerRoot \"%s\"", home);
    }
    if (logs) {
        contents = replace(contents, "ErrorLog", "ErrorLog \"%s\"", mprJoinPath(logs, "error.log"));
        contents = replace(contents, "AccessLog", "AccessLog \"%s\"", mprJoinPath(logs, "access.log"));
    }
    if (user) {
        contents = replace(contents, "UserAccount", "UserAccount %s", user);
    }
    if (group) {
        contents = replace(contents, "GroupAccount", "GroupAccount %s", group);
    }
    if (cache) {
        contents = replace(contents, "EspDir cache", "EspDir cache \"%s\"", cache);
    }
    if (modules) {
        contents = replace(contents, "LoadModulePath", "LoadModulePath \"%s\"", modules);
    }
    revised = mprGetTempPath(mprGetPathDir(path));
    if (mprWritePathContents(revised, contents, -1, 0644) < 0) {
        mprUserError("Cannot write %s", revised);
    }
	bak = sfmt("%s.bak", path);
	mprDeletePath(bak);
	if (rename(path, bak) < 0) {
        mprUserError("Cannot save %s to %s: 0x%x", path, bak, mprGetError());
	}
	mprDeletePath(path);
    if (rename(revised, path) < 0) {
        mprUserError("Cannot rename %s to %s: 0x%x", revised, path, mprGetError());
		rename(bak, path);
    }
    return 0;
}
Пример #13
0
int APIENTRY WinMain(HINSTANCE inst, HINSTANCE junk, char *args, int junk2)
{
    char    **argv, *argp, *serviceArgs, *homeDir;
    int     argc, err, nextArg, installFlag;

    mpr = mprCreate(0, NULL, NULL);

    appInst = inst;
    serviceArgs = 0;
    err = 0;
    exiting = 0;
    installFlag = 0;
    homeDir = 0;
    heartBeatPeriod = HEART_BEAT_PERIOD;

    initService();

    mprSetAppName(mpr, BLD_PRODUCT "Angel", BLD_NAME "Angel", BLD_VERSION);
    appName = mprGetAppName(mpr);
    appTitle = mprGetAppTitle(mpr);

    mprSetLogHandler(mpr, logHandler, NULL);

    /*
     *  Create the window 
     */
    if (initWindow() < 0) {
        mprError(mpr, "Can't initialize application Window");
        return FALSE;
    }

    /*
     *  Parse command line arguments
     */
    if (mprMakeArgv(mpr, "", args, &argc, &argv) < 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 {
                serviceArgs = argv[++nextArg];
            }

        } else if (strcmp(argp, "--console") == 0) {
            /*
             *  Allow the service to interact with the console
             */
            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 {
                heartBeatPeriod = atoi(argv[++nextArg]) * 1000;
            }

        } else if (strcmp(argp, "--home") == 0) {
            /*
             *  Change to this directory before starting the service
             */
            if (nextArg >= argc) {
                err++;
            } else {
                homeDir = argv[++nextArg];
            }

        } else if (strcmp(argp, "--program") == 0) {
            if (nextArg >= argc) {
                err++;
            } else {
                serviceProgram = argv[++nextArg];
            }

        } else if (strcmp(argp, "--install") == 0) {
            installFlag++;

        } else if (strcmp(argp, "--start") == 0) {
            /*
             *  Start the angel
             */
            if (startService() < 0) {
                return FALSE;
            }
            mprSleep(mpr, 2000);    /* Time for service to really start */

        } else if (strcmp(argp, "--stop") == 0) {
            /*
             *  Stop the  angel
             */
            if (removeService(0) < 0) {
                return FALSE;
            }

        } else if (strcmp(argp, "--uninstall") == 0) {
            /*
             *  Remove the  angel
             */
            if (removeService(1) < 0) {
                return FALSE;
            }

        } else if (strcmp(argp, "--verbose") == 0 || strcmp(argp, "-v") == 0) {
            verbose++;

        } else {
            err++;
        }

        if (err) {
            mprUserError(mpr, 
                "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"
                "    --install            # Install the service\n"
                "    --program            # Service program to start\n"
                "    --start              # Start the service\n"
                "    --stop               # Stop the service\n"
                "    --uninstall          # Uninstall the service",
                args, appName);
            return -1;
        }
    }

    if (installFlag) {
        /*
         *  Install the angel
         */
        if (installService(homeDir, serviceArgs) < 0) {
            return FALSE;
        }
    }

    if (argc <= 1) {
        /*
         *  This will block if we are a service and are being started by the
         *  service control manager. While blocked, the svcMain will be called
         *  which becomes the effective main program. 
         */
        startDispatcher(serviceMain);
    }
    return 0;
}