Exemplo n.º 1
0
int MprWinService::install(char *displayName, char *cmd)
{
	SC_HANDLE	svc, mgr;

	mgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	if (! mgr) {
		mprError(MPR_L, MPR_LOG, "Can't open service manager");
		return MPR_ERR_CANT_ACCESS;
	}

	//
	//	Install this app as a service
	// 
	svc = OpenService(mgr, svcName, SERVICE_ALL_ACCESS);
	if (svc == NULL) {
		svc = CreateService(mgr, svcName, displayName, SERVICE_ALL_ACCESS,
			SERVICE_INTERACTIVE_PROCESS | SERVICE_WIN32_OWN_PROCESS,
			SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, cmd, NULL, NULL, 
			"", NULL, NULL);
		if (! svc) {
			mprError(MPR_L, MPR_LOG, "Can't create service: 0x%x == %d", 
				GetLastError(), GetLastError());
			CloseServiceHandle(mgr);
			return MPR_ERR_CANT_CREATE;
		}
	}

	CloseServiceHandle(svc);
	CloseServiceHandle(mgr);
	return 0;
}
Exemplo n.º 2
0
int MprWinService::start()
{
	SC_HANDLE	svc, mgr;

	mgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	if (! mgr) {
		mprError(MPR_L, MPR_LOG, "Can't open service manager");
		return MPR_ERR_CANT_ACCESS;
	}

	svc = OpenService(mgr, svcName, SERVICE_ALL_ACCESS);
	if (! svc) {
		mprError(MPR_L, MPR_LOG, "Can't open service");
		CloseServiceHandle(mgr);
		return MPR_ERR_CANT_OPEN;
	}

	if (! StartService(svc, 0, NULL)) {
		mprError(MPR_L, MPR_LOG, "Can't start service: %x", GetLastError());
		return MPR_ERR_CANT_INITIALIZE;
	}

	CloseServiceHandle(svc);
	CloseServiceHandle(mgr);

	return 0;
}
Exemplo n.º 3
0
static int makeChannel(MprCmd *cmd, int index)
{
    MprCmdFile      *file;
    static int      tempSeed = 0;

    file = &cmd->files[index];

    file->name = mprAsprintf(cmd, -1, "/pipe/%s_%d_%d", BLD_PRODUCT, taskIdSelf(), tempSeed++);

    if (pipeDevCreate(file->name, 5, MPR_BUFSIZE) < 0) {
        mprError(cmd, "Can't create pipes to run %s", cmd->program);
        return MPR_ERR_CANT_OPEN;
    }
    
    /*
     *  Open the server end of the pipe. MPR_CMD_STDIN is from the client's perspective.
     */
    if (index == MPR_CMD_STDIN) {
        file->fd = open(file->name, O_WRONLY, 0644);
    } else {
        file->fd = open(file->name, O_RDONLY, 0644);
    }
    if (file->fd < 0) {
        mprError(cmd, "Can't create stdio pipes. Err %d", mprGetOsError());
        return MPR_ERR_CANT_CREATE;
    }
    return 0;
}
Exemplo n.º 4
0
int maSetHttpUser(MaHttp *http, cchar *newUser)
{
#if BLD_UNIX_LIKE
    struct passwd   *pp;

    if (allDigits(newUser)) {
        http->uid = atoi(newUser);
        if ((pp = getpwuid(http->uid)) == 0) {
            mprError(http, "Bad user id: %d", http->uid);
            return MPR_ERR_CANT_ACCESS;
        }
        newUser = pp->pw_name;

    } else {
        if ((pp = getpwnam(newUser)) == 0) {
            mprError(http, "Bad user name: %s", newUser);
            return MPR_ERR_CANT_ACCESS;
        }
        http->uid = pp->pw_uid;
    }
#endif

    mprFree(http->username);
    http->username = mprStrdup(http, newUser);

    return 0;
}
Exemplo n.º 5
0
/*
 *  Create a web server described by a config file. 
 */
MaHttp *maCreateWebServer(cchar *configFile)
{
    Mpr         *mpr;
    MaHttp      *http;
    MaServer    *server;

    /*
     *  Initialize and start the portable runtime services.
     */
    if ((mpr = mprCreate(0, NULL, NULL)) == 0) {
        mprError(mpr, "Can't create the web server runtime");
        return 0;
    }
    if (mprStart(mpr, 0) < 0) {
        mprError(mpr, "Can't start the web server runtime");
        return 0;
    }
    http = maCreateHttp(mpr);
    if ((server = maCreateServer(http, configFile, NULL, NULL, -1)) == 0) {
        mprError(mpr, "Can't create the web server");
        return 0;
    }
    if (maParseConfig(server, configFile) < 0) {
        mprError(mpr, "Can't parse the config file %s", configFile);
        return 0;
    }
    return http;
}
Exemplo n.º 6
0
int maWriteUserFile(MaServer *server, MaAuth *auth, char *path)
{
    MprFile         *file;
    MprHash         *hp;
    MaUser          *up;
    char            buf[MA_MAX_PASS * 2];
    char            *tempFile;

    tempFile = mprGetTempPath(auth, NULL);
    if ((file = mprOpen(auth, tempFile, O_CREAT | O_TRUNC | O_WRONLY | O_TEXT, 0444)) == 0) {
        mprError(server, "Can't open %s", tempFile);
        mprFree(tempFile);
        return MPR_ERR_CANT_OPEN;
    }
    mprFree(tempFile);

    hp = mprGetNextHash(auth->users, 0);
    while (hp) {
        up = (MaUser*) hp->data;
        mprSprintf(buf, sizeof(buf), "%d: %s: %s: %s\n", up->enabled, up->name, up->realm, up->password);
        mprWrite(file, buf, (int) strlen(buf));
        hp = mprGetNextHash(auth->users, hp);
    }

    mprFree(file);

    unlink(path);
    if (rename(tempFile, path) < 0) {
        mprError(server, "Can't create new %s", path);
        return MPR_ERR_CANT_WRITE;
    }
    return 0;
}
Exemplo n.º 7
0
static int updatePassFile(char *passFile)
{
	User	*up;
	char	tempFile[MPR_MAX_FNAME];
	int		fd;

	mprMakeTempFileName(tempFile, sizeof(tempFile), "httpPass", 1);
	fd = open(tempFile, O_CREAT | O_TRUNC | O_WRONLY | O_TEXT, 0664);
	if (fd < 0) {
		mprError(MPR_L, MPR_USER, "Can't open %s\n", tempFile);
		return MPR_ERR_CANT_OPEN;
	}
	up = (User*) users.getFirst();
	while (up) {
		if (mprFprintf(fd, "%d: %s: %s: %s\n", up->getEnabled(), up->getName(), 
				up->getRealm(), up->getPassword()) < 0) {
			mprError(MPR_L, MPR_USER, "Can't write to %s\n", tempFile);
			return MPR_ERR_CANT_WRITE;
		}
		up = (User*) users.getNext(up);
	}
	close(fd);
	unlink(passFile);
	if (rename(tempFile, passFile) < 0) {
		mprError(MPR_L, MPR_USER, "Can't rename %s to %s\n", tempFile, 
			passFile);
		return MPR_ERR_CANT_WRITE;
	}
	return 0;
}
Exemplo n.º 8
0
/*
 *  Secondary entry point when started by the service control manager. Remember 
 *  that the main program thread is blocked in the startDispatcher called from
 *  winMain and will be used on callbacks from WinService.
 */ 
static void WINAPI serviceMain(ulong argc, char **argv)
{
    int     threadId;

    serviceThreadEvent = CreateEvent(0, TRUE, FALSE, 0);
    heartBeatEvent = CreateEvent(0, TRUE, FALSE, 0);

    if (serviceThreadEvent == 0 || heartBeatEvent == 0) {
        mprError(mpr, "Can't create wait events");
        return;
    }

    threadHandle = CreateThread(0, 0, (LPTHREAD_START_ROUTINE) serviceThread, (void*) 0, 0, (ulong*) &threadId);

    if (threadHandle == 0) {
        mprError(mpr, "Can't create service thread");
        return;
    }

    WaitForSingleObject(serviceThreadEvent, INFINITE);
    CloseHandle(serviceThreadEvent);

    /*
     *  We are now exiting, so wakeup the heart beat thread
     */
    exiting = 1;
    SetEvent(heartBeatEvent);
    CloseHandle(heartBeatEvent);
}
Exemplo n.º 9
0
int maSetHttpGroup(MaHttp *http, cchar *newGroup)
{
#if BLD_UNIX_LIKE
    struct group    *gp;

    if (allDigits(newGroup)) {
        http->gid = atoi(newGroup);
        if ((gp = getgrgid(http->gid)) == 0) {
            mprError(http, "Bad group id: %d", http->gid);
            return MPR_ERR_CANT_ACCESS;
        }
        newGroup = gp->gr_name;

    } else {
        if ((gp = getgrnam(newGroup)) == 0) {
            mprError(http, "Bad group name: %s", newGroup);
            return MPR_ERR_CANT_ACCESS;
        }
        http->gid = gp->gr_gid;
    }
#endif

    mprFree(http->groupname);
    http->groupname = mprStrdup(http, newGroup);

    return 0;
}
Exemplo n.º 10
0
/*
    Query the service. Return the service state:
  
        SERVICE_CONTINUE_PENDING
        SERVICE_PAUSE_PENDING
        SERVICE_PAUSED
        SERVICE_RUNNING
        SERVICE_START_PENDING
        SERVICE_STOP_PENDING
        SERVICE_STOPPED
 */ 
static uint queryService()
{
    SC_HANDLE       svc, mgr;
    SERVICE_STATUS  status;
    int             rc;

    mgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (! mgr) {
        mprError("appweb monitor", "Cannot open service manager");
        return MPR_ERR_CANT_ACCESS;
    }
    svc = OpenService(mgr, app->serviceName, SERVICE_ALL_ACCESS);
    if (! svc) {
        /* No warnings on error. Makes Monitor more useful */
        CloseServiceHandle(mgr);
        return MPR_ERR_CANT_OPEN;
    }
    rc = QueryServiceStatus(svc, &status);
    if (rc == 0) {
        mprError("appweb monitor", "Cannot start %s service: %d", app->serviceName, GetLastError());
        return 0;
    }
    CloseServiceHandle(svc);
    CloseServiceHandle(mgr);
    return status.dwCurrentState;
}
Exemplo n.º 11
0
/*
    Stop the service in the current process. 
 */ 
static int stopService()
{
    SC_HANDLE       svc, mgr;
    SERVICE_STATUS  status;
    int             rc;

    mgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (! mgr) {
        mprError("appweb monitor", "Cannot open service manager");
        return MPR_ERR_CANT_ACCESS;
    }
    svc = OpenService(mgr, app->serviceName, SERVICE_ALL_ACCESS);
    if (! svc) {
        mprError("appweb monitor", "Cannot open service");
        CloseServiceHandle(mgr);
        return MPR_ERR_CANT_OPEN;
    }
    rc = ControlService(svc, SERVICE_CONTROL_STOP, &status);
    if (rc == 0) {
        mprError("appweb monitor", "Cannot stop %s service: %d", app->serviceName, GetLastError());
        return MPR_ERR_CANT_INITIALIZE;
    }
    CloseServiceHandle(svc);
    CloseServiceHandle(mgr);
    return 0;
}
Exemplo n.º 12
0
static int startDispatcher(LPSERVICE_MAIN_FUNCTION svcMain)
{
    SC_HANDLE       mgr;
    char            name[80];
    ulong           len;

    if (!(mgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS))) {
        mprError(mpr, "Can't open service manager");
        return MPR_ERR_CANT_OPEN;
    }

    /*
     *  Is the service installed?
     */
    len = sizeof(name);
    if (GetServiceDisplayName(mgr, serviceName, name, &len) == 0) {
        CloseServiceHandle(mgr);
        return MPR_ERR_CANT_READ;
    }

    /*
     *  Register this service with the SCM. This call will block and consume the main thread if the service is 
     *  installed and the app was started by the SCM. If started manually, this routine will return 0.
     */
    svcTable[0].lpServiceProc = svcMain;
    if (StartServiceCtrlDispatcher(svcTable) == 0) {
        mprError(mpr, "Could not start the service control dispatcher");
        return MPR_ERR_CANT_INITIALIZE;
    }
    return 0;
}
Exemplo n.º 13
0
int MaHttp::setGroup(char *newGroup)
{
#if CYGWIN || LINUX || MACOSX || FREEBSD
	struct group	*gp;

    if (allDigits(newGroup)) {
		gid = atoi(newGroup);
		if ((gp = getgrgid(gid)) == 0) {
			mprError(MPR_L, MPR_USER, "Bad group id: %d", gid);
			return MPR_ERR_CANT_ACCESS;
		}
		newGroup = gp->gr_name;

	} else {
		if ((gp = getgrnam(newGroup)) == 0) {
			mprError(MPR_L, MPR_USER, "Bad group name: %s", newGroup);
			return MPR_ERR_CANT_ACCESS;
		}
		gid = gp->gr_gid;
    }
#endif
	if (group) {
		mprFree(group);
	}
	group = mprStrdup(newGroup);
	return 0;
}
Exemplo n.º 14
0
int MaHttp::setUser(char *newUser)
{
#if CYGWIN || LINUX || MACOSX || FREEBSD
	struct passwd	*pp;

    if (allDigits(newUser)) {
		uid = atoi(newUser);
		if ((pp = getpwuid(uid)) == 0) {
			mprError(MPR_L, MPR_USER, "Bad user id: %d", uid);
			return MPR_ERR_CANT_ACCESS;
		}
		newUser = pp->pw_name;

	} else {
		if ((pp = getpwnam(newUser)) == 0) {
			mprError(MPR_L, MPR_USER, "Bad user name: %s", newUser);
			return MPR_ERR_CANT_ACCESS;
		}
		uid = pp->pw_uid;
    }
#endif
	if (user) {
		mprFree(user);
	}
	user = mprStrdup(newUser);
	return 0;
}
Exemplo n.º 15
0
/*
 *  Accept a new client connection. If multithreaded, this will come in on a worker thread dedicated to this connection.
 *  This is called from the listen wait handler.
 */
int maAcceptConn(MprSocket *sock, MaServer *server, cchar *ip, int port)
{
    MaHostAddress   *address;
    MaHost          *host;
    MaConn          *conn;
    MprSocket       *listenSock;
    MprHeap         *arena;
    int             rc;

    mprAssert(server);
    mprAssert(sock);
    mprAssert(ip);
    mprAssert(port > 0);

    rc = 0;
    listenSock = sock->listenSock;

    mprLog(server, 4, "New connection from %s:%d for %s:%d %s",
        ip, port, listenSock->ipAddr, listenSock->port, listenSock->sslSocket ? "(secure)" : "");

    /*
     *  Map the address onto a suitable host to initially serve the request initially until we can parse the Host header.
     */
    address = (MaHostAddress*) maLookupHostAddress(server, listenSock->ipAddr, listenSock->port);

    if (address == 0 || (host = mprGetFirstItem(address->vhosts)) == 0) {
        mprError(server, "No host configured for request %s:%d", listenSock->ipAddr, listenSock->port);
        mprFree(sock);
        return 1;
    }
    arena = mprAllocHeap(host, "conn", 1, 0, NULL);
    if (arena == 0) {
        mprError(server, "Can't create connect arena object. Insufficient memory.");
        mprFree(sock);
        return 1;
    }
    conn = createConn(arena, host, sock, ip, port, address);
    if (conn == 0) {
        mprError(server, "Can't create connect object. Insufficient memory.");
        mprFree(sock);
        mprFree(arena);
        return 1;
    }
    conn->arena = arena;
    if (maAddConn(host, conn) < 0) {
        mprFree(sock);
#if BLD_FEATURE_MULTITHREAD
        mprEnableSocketEvents(listenSock);
#endif
        mprFree(arena);
        return 1;
    }
    mprSetSocketCallback(conn->sock, (MprSocketProc) ioEvent, conn, MPR_READABLE, MPR_NORMAL_PRIORITY);
 
#if BLD_FEATURE_MULTITHREAD
    mprEnableSocketEvents(listenSock);
#endif
    return rc;
}
Exemplo n.º 16
0
MAIN(simpleClient, int argc, char** argv)
{
    Mpr     *mpr;
    App     *app;
    cchar   *content;
    int     code;

    /* 
       Create the Multithreaded Portable Runtime
     */
    mpr = mprCreate(argc, argv, MPR_USER_EVENTS_THREAD);
    if ((app = mprAllocObj(App, manageApp)) == 0) {
        return MPR_ERR_MEMORY;
    }
    mprAddRoot(app);
    mprAddStandardSignals(app);

    /* 
       Start the Multithreaded Portable Runtime
     */
    mprStart();

    /* 
       Create an Http service object
     */
    app->http = httpCreate(mpr);

    /* 
       Get a client http object to work with. We can issue multiple requests with this one object.
     */
    app->conn = httpCreateConn(app->http, NULL, NULL);

    /* 
       Get a URL
     */
    if (httpConnect(app->conn, "GET", "http://www.embedthis.com/index.html") < 0) {
        mprError("Can't get URL");
        exit(2);
    }

    /* 
       Examine the HTTP response HTTP code. 200 is success.
     */
    code = httpGetStatus(app->conn);
    if (code != 200) {
        mprError("Server responded with code %d\n", code);
        exit(1);
    } 

    /* 
       Get the actual response content
     */
    content = httpReadString(app->conn);
    if (content) {
        mprPrintf("Server responded with: %s\n", content);
    }
    mprDestroy(MPR_EXIT_DEFAULT);
    return 0;
}
Exemplo n.º 17
0
static int writeBody(MprHttp *http, MprList *fields, MprList *files)
{
    MprFile     *file;
    char        buf[MPR_HTTP_BUFSIZE], *path, *pair;
    int         bytes, next, count, rc, len;

    rc = 0;

    mprSetSocketBlockingMode(http->sock, 1);
    if (upload) {
        if (mprWriteHttpUploadData(http, files, fields) < 0) {
            mprError(http, "Can't write upload data %s", mprGetHttpError(http));
            mprSetSocketBlockingMode(http->sock, 0);
            return MPR_ERR_CANT_WRITE;
        }
    } else {
        if (fields) {
            count = mprGetListCount(fields);
            for (next = 0; !rc && (pair = mprGetNextItem(fields, &next)) != 0; ) {
                len = (int) strlen(pair);
                if (next < count) {
                    len = (int) strlen(pair);
                    if (mprWriteSocket(http->sock, pair, len) != len || mprWriteSocket(http->sock, "&", 1) != 1) {
                        return MPR_ERR_CANT_WRITE;
                    }
                } else {
                    if (mprWriteSocket(http->sock, pair, len) != len) {
                        return MPR_ERR_CANT_WRITE;
                    }
                }
            }
        }
        if (files) {
            mprAssert(mprGetListCount(files) == 1);
            for (rc = next = 0; !rc && (path = mprGetNextItem(files, &next)) != 0; ) {
                file = mprOpen(http, path, O_RDONLY | O_BINARY, 0);
                if (file == 0) {
                    mprError(http, "Can't open \"%s\"", path);
                    return MPR_ERR_CANT_OPEN;
                }
                if (verbose && upload) {
                    mprPrintf(http, "uploading: %s\n", path);
                }
                while ((bytes = mprRead(file, buf, sizeof(buf))) > 0) {
                    if (mprWriteHttp(http, buf, bytes) != bytes) {
                        mprFree(file);
                        return MPR_ERR_CANT_WRITE;
                    }
                }
                mprFree(file);
            }
        }
        if (mprFinalizeHttpWriting(http) < 0) {
            return MPR_ERR_CANT_WRITE;
        }
    }
    mprSetSocketBlockingMode(http->sock, 0);
    return rc;
}
Exemplo n.º 18
0
static int process(EjsMod *mp, cchar *output, int argc, char **argv)
{
    Ejs         *ejs;
    EjsModule   *module;
    MprFile     *outfile;
    MprList     *depends;
    int         count, i, next, moduleCount;

    ejs = mp->ejs;

    if (output) {
        outfile = mprOpenFile(output, O_CREAT | O_WRONLY | O_TRUNC | O_BINARY, 0664);
    } else {
        outfile = 0;
    }
    ejs->loaderCallback = (mp->listing) ? emListingLoadCallback : 0;
    mp->firstGlobal = ejsGetLength(ejs, ejs->global);

    /*
        For each module on the command line
     */
    for (i = 0; i < argc && !mp->fatalError; i++) {
        moduleCount = mprGetListLength(ejs->modules);
        ejs->loadData = mp;
        if (!mprPathExists(argv[i], R_OK)) {
            mprError("Can't access module %s", argv[i]);
            return EJS_ERR;
        }
        if ((ejsLoadModule(ejs, ejsCreateStringFromAsc(ejs, argv[i]), -1, -1, EJS_LOADER_NO_INIT)) < 0) {
            ejs->loaderCallback = NULL;
            mprError("Can't load module %s\n%s", argv[i], ejsGetErrorMsg(ejs, 0));
            return EJS_ERR;
        }
        if (mp->genSlots) {
            for (next = moduleCount; (module = mprGetNextItem(ejs->modules, &next)) != 0; ) {
                emCreateSlotFiles(mp, module, outfile);
            }
        }
        if (mp->depends) {
            depends = mprCreateList(-1, 0);
            for (next = moduleCount; (module = mprGetNextItem(ejs->modules, &next)) != 0; ) {
                getDepends(ejs, depends, module);
            }
            count = mprGetListLength(depends);
            for (next = 1; (module = mprGetNextItem(depends, &next)) != 0; ) {
                int version = module->version;
                mprPrintf("%@-%d.%d.%d%s", module->name, EJS_MAJOR(version), EJS_MINOR(version), EJS_PATCH(version),
                          (next >= count) ? "" : " ");
            }
            printf("\n");
        }
    }
    if (mp->html || mp->xml) {
        emCreateDoc(mp);
    }
    mprCloseFile(outfile);
    return 0;
}
Exemplo n.º 19
0
static int reportResponse(HttpConn *conn, cchar *url, MprTime elapsed)
{
    HttpRx      *rx;
    MprOff      bytesRead;
    char        *responseHeaders;
    int         status;

    if (mprShouldAbortRequests(conn)) {
        return 0;
    }
    app->status = status = httpGetStatus(conn);
    bytesRead = httpGetContentLength(conn);
    if (bytesRead < 0 && conn->rx) {
        bytesRead = conn->rx->bytesRead;
    }
    mprLog(6, "Response status %d, elapsed %Ld", status, elapsed);
    if (conn->error) {
        app->success = 0;
    }
    if (conn->rx && bytesRead > 0) {
        if (!app->noout) {
            mprPrintf("\n");
        }
        if (app->showHeaders) {
            responseHeaders = httpGetHeaders(conn);
            rx = conn->rx;
            mprPrintf("%s %d %s\n", conn->protocol, status, rx->statusMessage);
            if (responseHeaders) {
                mprPrintf("%s\n", responseHeaders);
            }
        } else if (app->showStatus) {
            mprPrintf("%d\n", status);
        }
    }
    if (status < 0) {
        mprError("Can't process request for \"%s\" %s", url, httpGetError(conn));
        return MPR_ERR_CANT_READ;

    } else if (status == 0 && conn->protocol == 0) {
        /* Ignore */;

    } else if (!(200 <= status && status <= 206) && !(301 <= status && status <= 304)) {
        if (!app->zeroOnErrors) {
            app->success = 0;
        }
        if (!app->showStatus) {
            mprError("Can't process request for \"%s\" (%d) %s", url, status, httpGetError(conn));
            return MPR_ERR_CANT_READ;
        }
    }
    mprLock(app->mutex);
    if (app->verbose && app->noout) {
        trace(conn, url, app->fetchCount, app->method, status, bytesRead);
    }
    mprUnlock(app->mutex);
    return 0;
}
Exemplo n.º 20
0
MAIN(simpleClient, int argc, char **argv, char **envp)
{
    Http        *http;
    HttpConn    *conn;
    cchar       *content;
    int         code;

    /* 
       Create the Multithreaded Portable Runtime and start it.
     */
    mprCreate(argc, argv, 0);
    mprStart();

    /* 
       Get a client http object to work with. We can issue multiple requests with this one object.
       Add the conn as a root object so the GC won't collect it while we are using it.
     */
    http = httpCreate(HTTP_CLIENT_SIDE);
    conn = httpCreateConn(http, NULL, NULL);
    mprAddRoot(conn);

    /* 
        Open a connection to issue the GET. Then finalize the request output - this forces the request out.
     */
    if (httpConnect(conn, "GET", "http://www.embedthis.com/index.html", NULL) < 0) {
        mprError("Can't get URL");
        exit(2);
    }
    httpFinalizeOutput(conn);

    /*
        Wait for a response
     */
    if (httpWait(conn, HTTP_STATE_PARSED, 10000) < 0) {
        mprError("No response");
        exit(2);
    }

    /* 
       Examine the HTTP response HTTP code. 200 is success.
     */
    code = httpGetStatus(conn);
    if (code != 200) {
        mprError("Server responded with code %d\n", code);
        exit(1);
    } 

    /* 
       Get the actual response content
     */
    content = httpReadString(conn);
    if (content) {
        mprPrintf("Server responded with: %s\n", content);
    }
    mprDestroy(MPR_EXIT_DEFAULT);
    return 0;
}
Exemplo n.º 21
0
MAIN(httpMain, int argc, char *argv[])
{
    MprTime     start;
    double      elapsed;

    if (mprCreate(argc, argv, MPR_USER_EVENTS_THREAD) == 0) {
        return MPR_ERR_MEMORY;
    }
    if ((app = mprAllocObj(App, manageApp)) == 0) {
        return MPR_ERR_MEMORY;
    }
    mprAddRoot(app);
    mprAddStandardSignals();

    initSettings();
    if (!parseArgs(argc, argv)) {
        showUsage();
        return MPR_ERR_BAD_ARGS;
    }
    mprSetMaxWorkers(app->workers);

#if BLD_FEATURE_SSL
    if (!mprLoadSsl(1)) {
        mprError("Can't load SSL");
        exit(1);
    }
#endif
    if (mprStart() < 0) {
        mprError("Can't start MPR for %s", mprGetAppTitle());
        exit(2);
    }
    start = mprGetTime();
    app->http = httpCreate();
    httpEaseLimits(app->http->clientLimits);

    processing();
    mprServiceEvents(-1, 0);

    if (app->benchmark) {
        elapsed = (double) (mprGetTime() - start);
        if (app->fetchCount == 0) {
            elapsed = 0;
            app->fetchCount = 1;
        }
        mprPrintf("\nRequest Count:       %13d\n", app->fetchCount);
        mprPrintf("Time elapsed:        %13.4f sec\n", elapsed / 1000.0);
        mprPrintf("Time per request:    %13.4f sec\n", elapsed / 1000.0 / app->fetchCount);
        mprPrintf("Requests per second: %13.4f\n", app->fetchCount * 1.0 / (elapsed / 1000.0));
        mprPrintf("Load threads:        %13d\n", app->loadThreads);
        mprPrintf("Worker threads:      %13d\n", app->workers);
    }
    if (!app->success && app->verbose) {
        mprError("Request failed");
    }
    return (app->success) ? 0 : 255;
}
Exemplo n.º 22
0
PUBLIC int mprLoadNativeModule(MprModule *mp)
{
    MprModuleEntry  fn;
    MprPath         info;
    char            *at;
    void            *handle;

    assert(mp);

    /*
        Search the image incase the module has been statically linked
     */
#ifdef RTLD_DEFAULT
    handle = RTLD_DEFAULT;
#else
#ifdef RTLD_MAIN_ONLY
    handle = RTLD_MAIN_ONLY;
#else
    handle = 0;
#endif
#endif
    if (!mp->entry || !dlsym(handle, mp->entry)) {
        if ((at = mprSearchForModule(mp->path)) == 0) {
            mprError("Cannot find module \"%s\", cwd: \"%s\", search path \"%s\"", mp->path, mprGetCurrentPath(),
                mprGetModuleSearchPath());
            return MPR_ERR_CANT_ACCESS;
        }
        mp->path = at;
        mprGetPathInfo(mp->path, &info);
        mp->modified = info.mtime;
        mprLog(2, "Loading native module %s", mprGetPathBase(mp->path));
        if ((handle = dlopen(mp->path, RTLD_LAZY | RTLD_GLOBAL)) == 0) {
            mprError("Cannot load module %s\nReason: \"%s\"", mp->path, dlerror());
            return MPR_ERR_CANT_OPEN;
        } 
        mp->handle = handle;

    } else if (mp->entry) {
        mprLog(2, "Activating native module %s", mp->name);
    }
    if (mp->entry) {
        if ((fn = (MprModuleEntry) dlsym(handle, mp->entry)) != 0) {
            if ((fn)(mp->moduleData, mp) < 0) {
                mprError("Initialization for module %s failed", mp->name);
                dlclose(handle);
                return MPR_ERR_CANT_INITIALIZE;
            }
        } else {
            mprError("Cannot load module %s\nReason: can't find function \"%s\"", mp->path, mp->entry);
            dlclose(handle);
            return MPR_ERR_CANT_READ;
        }
    }
    return 0;
}
Exemplo n.º 23
0
MAIN(testMain, int argc, char *argv[]) 
{
    Mpr             *mpr;
    MprTestService  *ts;
    MprTestGroup    *gp;
    int             rc;

    mpr = mprCreate(argc, argv, 0);

#if VXWORKS || WINCE
    /*
     *  These platforms pass an arg string in via the argc value. Assumes 32-bit.
     */
    mprMakeArgv(mpr, "testMpr", (char*) argc, &argc, &argv);
#endif

    ts = mprCreateTestService(mpr);
    if (ts == 0) {
        mprError(mpr, "Can't create test service");
        exit(2);
    }
    
    if (mprParseTestArgs(ts, argc, argv) < 0) {
        mprFree(mpr);
        exit(3);
    }
    
    gp = mprAddTestGroup(ts, &master);
    if (gp == 0) {
        exit(4);
    }

#if BLD_FEATURE_SSL && (BLD_FEATURE_MATRIXSSL || BLD_FEATURE_OPENSSL)
    if (!mprLoadSsl(mpr, 0)) {
        exit(5);
    }
#endif

    /*
     *  Need a background event thread as we use the main thread to run the tests.
     */
    if (mprStart(mpr, 0)) {
        mprError(mpr, "Can't start mpr services");
        exit(4);
    }

    /*
     *  Run the tests and return zero if 100% success
     */
    rc = mprRunTests(ts);
    mprReportTestResults(ts);

    return (rc == 0) ? 0 : 6;
}
Exemplo n.º 24
0
static int createEndpoints(int argc, char **argv)
{
    cchar   *endpoint;
    char    *ip;
    int     argind, port, secure;

    ip = 0;
    port = -1;
    endpoint = 0;
    argind = 0;

    if ((app->appweb = maCreateAppweb()) == 0) {
        mprError("Cannot create HTTP service for %s", mprGetAppName());
        return MPR_ERR_CANT_CREATE;
    }
    if ((app->server = maCreateServer(app->appweb, "default")) == 0) {
        mprError("Cannot create HTTP server for %s", mprGetAppName());
        return MPR_ERR_CANT_CREATE;
    }
    loadStaticModules();

    if (argc > argind) {
        app->documents = sclone(argv[argind++]);
        mprLog(2, "Documents %s", app->documents);
    }
    if (argind == argc) {
        if (maParseConfig(app->server, app->configFile, 0) < 0) {
            return MPR_ERR_CANT_CREATE;
        }
    } else {
        while (argind < argc) {
            endpoint = argv[argind++];
            mprParseSocketAddress(endpoint, &ip, &port, &secure, 80);
            if (maConfigureServer(app->server, NULL, app->home, app->documents, ip, port) < 0) {
                return MPR_ERR_CANT_CREATE;
            }
        }
    }
    if (app->workers >= 0) {
        mprSetMaxWorkers(app->workers);
    }
    /*
        Call any ESP initializers from slink.c
     */
    appwebStaticInitialize();
    
#if BIT_WIN_LIKE
    writePort(app->server);
#elif BIT_UNIX_LIKE
    addSignals();
#endif
    return 0;
}
Exemplo n.º 25
0
static int startProcess(MprCmd *cmd)
{
    PROCESS_INFORMATION procInfo;
    STARTUPINFO         startInfo;
    int                 err;

    memset(&startInfo, 0, sizeof(startInfo));
    startInfo.cb = sizeof(startInfo);

    startInfo.dwFlags = STARTF_USESHOWWINDOW;
    if (cmd->flags & MPR_CMD_SHOW) {
        startInfo.wShowWindow = SW_SHOW;
    } else {
        startInfo.wShowWindow = SW_HIDE;
    }
    startInfo.dwFlags |= STARTF_USESTDHANDLES;

    if (cmd->flags & MPR_CMD_IN) {
        if (cmd->files[MPR_CMD_STDIN].clientFd > 0) {
            startInfo.hStdInput = (HANDLE) _get_osfhandle(cmd->files[MPR_CMD_STDIN].clientFd);
        }
    } else {
        startInfo.hStdInput = (HANDLE) _get_osfhandle((int) fileno(stdin));
    }
    if (cmd->flags & MPR_CMD_OUT) {
        if (cmd->files[MPR_CMD_STDOUT].clientFd > 0) {
            startInfo.hStdOutput = (HANDLE)_get_osfhandle(cmd->files[MPR_CMD_STDOUT].clientFd);
        }
    } else {
        startInfo.hStdOutput = (HANDLE)_get_osfhandle((int) fileno(stdout));
    }
    if (cmd->flags & MPR_CMD_ERR) {
        if (cmd->files[MPR_CMD_STDERR].clientFd > 0) {
            startInfo.hStdError = (HANDLE) _get_osfhandle(cmd->files[MPR_CMD_STDERR].clientFd);
        }
    } else {
        startInfo.hStdError = (HANDLE) _get_osfhandle((int) fileno(stderr));
    }

    if (! CreateProcess(0, cmd->command, 0, 0, 1, 0, cmd->env, cmd->dir, &startInfo, &procInfo)) {
        err = mprGetOsError();
        if (err == ERROR_DIRECTORY) {
            mprError(cmd, "Can't create process: %s, directory %s is invalid", cmd->program, cmd->dir);
        } else {
            mprError(cmd, "Can't create process: %s, %d", cmd->program, err);
        }
        return MPR_ERR_CANT_CREATE;
    }
    cmd->thread = procInfo.hThread;
    cmd->process = procInfo.hProcess;
    cmd->pid = procInfo.dwProcessId;
    return 0;
}
Exemplo n.º 26
0
MAIN(httpMain, int argc, char **argv, char **envp)
{
    MprTime     start;
    double      elapsed;

    if (mprCreate(argc, argv, MPR_USER_EVENTS_THREAD) == 0) {
        return MPR_ERR_MEMORY;
    }
    if ((app = mprAllocObj(App, manageApp)) == 0) {
        return MPR_ERR_MEMORY;
    }
    mprAddRoot(app);
    mprAddStandardSignals();

    initSettings();
    if (parseArgs(argc, argv) < 0) {
        return MPR_ERR_BAD_ARGS;
    }
    mprSetMaxWorkers(app->workers);
    if (mprStart() < 0) {
        mprError("Cannot start MPR for %s", mprGetAppTitle());
        exit(2);
    }
    start = mprGetTime();
    app->http = httpCreate(HTTP_CLIENT_SIDE);
    httpEaseLimits(app->http->clientLimits);
#if BIT_STATIC && BIT_PACK_SSL
    extern MprModuleEntry mprSslInit;
    mprNop(mprSslInit);
#endif
    processing();
    mprServiceEvents(-1, 0);

    if (app->benchmark) {
        elapsed = (double) (mprGetTime() - start);
        if (app->fetchCount == 0) {
            elapsed = 0;
            app->fetchCount = 1;
        }
        mprPrintf("\nRequest Count:       %13d\n", app->fetchCount);
        mprPrintf("Time elapsed:        %13.4f sec\n", elapsed / 1000.0);
        mprPrintf("Time per request:    %13.4f sec\n", elapsed / 1000.0 / app->fetchCount);
        mprPrintf("Requests per second: %13.4f\n", app->fetchCount * 1.0 / (elapsed / 1000.0));
        mprPrintf("Load threads:        %13d\n", app->loadThreads);
        mprPrintf("Worker threads:      %13d\n", app->workers);
    }
    if (!app->success && app->verbose) {
        mprError("Request failed");
    }
    mprDestroy(MPR_EXIT_DEFAULT);
    return (app->success) ? 0 : 255;
}
Exemplo n.º 27
0
static int makeChannel(MprCmd *cmd, int index)
{
    SECURITY_ATTRIBUTES clientAtt, serverAtt, *att;
    HANDLE              readHandle, writeHandle;
    MprCmdFile          *file;
    char                *path;
    int                 readFd, writeFd;

    memset(&clientAtt, 0, sizeof(clientAtt));
    clientAtt.nLength = sizeof(SECURITY_ATTRIBUTES);
    clientAtt.bInheritHandle = 1;

    /*
     *  Server fds are not inherited by the child
     */
    memset(&serverAtt, 0, sizeof(serverAtt));
    serverAtt.nLength = sizeof(SECURITY_ATTRIBUTES);
    serverAtt.bInheritHandle = 0;

    file = &cmd->files[index];
    path = mprGetTempPath(cmd, NULL);

    att = (index == MPR_CMD_STDIN) ? &clientAtt : &serverAtt;
    readHandle = CreateFile(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, att, OPEN_ALWAYS, 
        FILE_ATTRIBUTE_NORMAL,0);
    if (readHandle == INVALID_HANDLE_VALUE) {
        mprError(cmd, "Can't create stdio pipes %s. Err %d\n", path, mprGetOsError());
        return MPR_ERR_CANT_CREATE;
    }
    readFd = (int) (int64) _open_osfhandle((int*) readHandle, 0);

    att = (index == MPR_CMD_STDIN) ? &serverAtt: &clientAtt;
    writeHandle = CreateFile(path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, att, OPEN_ALWAYS, 
        FILE_ATTRIBUTE_NORMAL, 0);
    writeFd = (int) _open_osfhandle((int*) writeHandle, 0);

    if (readFd < 0 || writeFd < 0) {
        mprError(cmd, "Can't create stdio pipes %s. Err %d\n", path, mprGetOsError());
        return MPR_ERR_CANT_CREATE;
    }
    if (index == MPR_CMD_STDIN) {
        file->clientFd = readFd;
        file->fd = writeFd;
        file->handle = writeHandle;
    } else {
        file->clientFd = writeFd;
        file->fd = readFd;
        file->handle = readHandle;
    }
    mprFree(path);
    return 0;
}
Exemplo n.º 28
0
/*
 *  Start the user's default browser
 */
static int runBrowser(char *page)
{
    PROCESS_INFORMATION procInfo;
    STARTUPINFO         startInfo;
    char                cmdBuf[MPR_MAX_STRING];
    char                *path;
    char                *pathArg;
    int                 port;

    port = getAppwebPort();
    if (port < 0) {
        mprError(mpr, "Can't get Appweb listening port");
        return -1;
    }

    path = getBrowserPath(MPR_MAX_STRING);
    if (path == 0) {
        mprError(mpr, "Can't get browser startup command");
        return -1;
    }

    pathArg = strstr(path, "\"%1\"");
    if (*page == '/') {
        page++;
    }

    if (pathArg == 0) {
        mprSprintf(cmdBuf, MPR_MAX_STRING, "%s http://localhost:%d/%s", path, port, page);

    } else {
        /*
         *  Patch out the "%1"
         */
        *pathArg = '\0';
        mprSprintf(cmdBuf, MPR_MAX_STRING, "%s \"http://localhost:%d/%s\"", path, port, page);
    }

    mprLog(mpr, 4, "Running %s\n", cmdBuf);

    memset(&startInfo, 0, sizeof(startInfo));
    startInfo.cb = sizeof(startInfo);

    if (! CreateProcess(0, cmdBuf, 0, 0, FALSE, 0, 0, 0, &startInfo, &procInfo)) {
        mprError(mpr, "Can't create process: %s, %d", cmdBuf, mprGetOsError());
        return -1;
    }
    CloseHandle(procInfo.hProcess);

    mprFree(path);
    return 0;
}
Exemplo n.º 29
0
MaHttp *maCreateHttp(MprCtx ctx)
{
    MaHttp      *http;

    http = mprAllocObjWithDestructorZeroed(ctx, MaHttp, httpDestructor);
    if (http == 0) {
        return 0;
    }
    mprGetMpr(ctx)->appwebHttpService = http;
    http->servers = mprCreateList(http);
    http->stages = mprCreateHash(http, 0);

#if BLD_FEATURE_MULTITHREAD
    http->mutex = mprCreateLock(http);
#endif

    initLimits(http);

#if BLD_UNIX_LIKE
{
    struct passwd   *pp;
    struct group    *gp;

    http->uid = getuid();
    if ((pp = getpwuid(http->uid)) == 0) {
        mprError(http, "Can't read user credentials: %d. Check your /etc/passwd file.", http->uid);
    } else {
        http->username = mprStrdup(http, pp->pw_name);
    }

    http->gid = getgid();
    if ((gp = getgrgid(http->gid)) == 0) {
        mprError(http, "Can't read group credentials: %d. Check your /etc/group file", http->gid);
    } else {
        http->groupname = mprStrdup(http, gp->gr_name);
    }
}
#else
    http->uid = http->gid = -1;
#endif

#if BLD_FEATURE_SEND
    maOpenSendConnector(http);
#endif
#if BLD_FEATURE_NET
    maOpenNetConnector(http);
#endif
    maOpenPassHandler(http);
    return http;
}
Exemplo n.º 30
0
/*
 *  Create an ejs application location block and alias
 */
static void createEjsAlias(Mpr *mpr, MaHttp *http, MaServer *server, cchar *ejsPrefix, cchar *ejsPath)
{
    MaAlias     *alias;
    MaHost      *host;
    MaDir       *dir, *parent;
    MaLocation  *location;
    int         flags;

    host = server->defaultHost;
    flags = host->location->flags & (MA_LOC_BROWSER | MA_LOC_AUTO_SESSION);

    alias = maCreateAlias(host, ejsPrefix, ejsPath, 0);
    maInsertAlias(host, alias);
    mprLog(http, 4, "Alias \"%s\" for \"%s\"", ejsPrefix, ejsPath);

    if (maLookupLocation(host, ejsPrefix)) {
        mprError(http, "Location block already exists for \"%s\"", ejsPrefix);
        return;
    }
    location = maCreateLocation(host, host->location);
    maSetLocationAuth(location, host->location->auth);
    maSetLocationPrefix(location, ejsPrefix);
    maAddLocation(host, location);
    maSetLocationFlags(location, MA_LOC_APP | flags);
    maSetHandler(http, host, location, "ejsHandler");

#if BLD_FEATURE_UPLOAD
    /*
        Upload configuration
     */
    location->autoDelete = 1;
    if (maAddFilter(http, location, "chunkFilter", "", MA_FILTER_INCOMING) < 0) {
        mprError(server, "Can't add chunkFilter for ejs");
    }
    if (maAddFilter(http, location, "uploadFilter", "", MA_FILTER_INCOMING) < 0) {
        mprError(server, "Can't add uploadFilter for ejs");
    }
#endif

    /*
     *  Make sure there is a directory for the alias target
     */
    dir = maLookupBestDir(host, ejsPath);
    if (dir == 0) {
        parent = mprGetFirstItem(host->dirs);
        dir = maCreateDir(host, alias->filename, parent);
        maInsertDir(host, dir);
    }
}