Example #1
0
static bool matchRow(MdbCol *col, cchar *existing, int op, cchar *value)
{
    if (value == 0 || *value == '\0') {
        return 0;
    }
    //  MOB - must ensure database NEVER has a null
    switch (op) {
    case OP_EQ:
        if (smatch(existing, value)) {
            return 1;
        }
        break;
    case OP_NEQ:
        if (!smatch(existing, value)) {
            return 1;
        }
        break;
#if MOB && TODO
    case OP_LT:
    case OP_GT:
    case OP_LTE:
    case OP_GTE:
#endif
    default:
        mprAssert(0);
    }
    return 0;
}
Example #2
0
File: uri.c Project: DavidQuan/http
PUBLIC HttpUri *httpCloneUri(HttpUri *base, int flags)
{
    HttpUri     *up;
    char        *path, *cp, *tok;

    if ((up = mprAllocObj(HttpUri, manageUri)) == 0) {
        up->valid = 0;
        return 0;
    }
    if (!base || !base->valid) {
        up->valid = 0;
        return up;
    }
    if (base->scheme) {
        up->scheme = sclone(base->scheme);
    } else if (flags & HTTP_COMPLETE_URI) {
        up->scheme = sclone("http");
    }
    up->secure = (smatch(up->scheme, "https") || smatch(up->scheme, "wss"));
    up->webSockets = (smatch(up->scheme, "ws") || smatch(up->scheme, "wss"));
    if (base->host) {
        up->host = sclone(base->host);
    } else if (flags & HTTP_COMPLETE_URI) {
        up->host = sclone("localhost");
    }
    if (base->port) {
        up->port = base->port;
    } else if (flags & HTTP_COMPLETE_URI) {
        up->port = up->secure ? 443 : 80;
    }
    path = base->path;
    if (path) {
        while (path[0] == '/' && path[1] == '/') {
            path++;
        }
        up->path = sclone(path);
    }
    if (flags & (HTTP_COMPLETE_URI | HTTP_COMPLETE_URI_PATH)) {
        if (up->path == 0 || *up->path == '\0') {
            up->path = sclone("/");
        }
    }
    if (base->reference) {
        up->reference = sclone(base->reference);
    }
    if (base->query) {
        up->query = sclone(base->query);
    }
    if (up->path && (tok = srchr(up->path, '.')) != 0) {
        if ((cp = srchr(up->path, '/')) != 0) {
            if (cp <= tok) {
                up->ext = sclone(&tok[1]);
            }
        } else {
            up->ext = sclone(&tok[1]);
        }
    }
    up->valid = 1;
    return up;
}
Example #3
0
PUBLIC bool websVerifyPassword(Webs *wp)
{
    char      passbuf[BIT_LIMIT_PASSWORD * 3 + 3];
    bool        success;

    assure(wp);
    if (!wp->encoded) {
        fmt(passbuf, sizeof(passbuf), "%s:%s:%s", wp->username, BIT_REALM, wp->password);
        wfree(wp->password);
        wp->password = websMD5(passbuf);
        wp->encoded = 1;
    }
    if (!wp->user && (wp->user = websLookupUser(wp->username)) == 0) {
        trace(5, "verifyUser: Unknown user \"%s\"", wp->username);
        return 0;
    }
    /*
        Verify the password
     */
    if (wp->digest) {
        success = smatch(wp->password, wp->digest);
    } else {
        success = smatch(wp->password, wp->user->password);
    }
    if (success) {
        trace(5, "User \"%s\" authenticated", wp->username);
    } else {
        trace(5, "Password for user \"%s\" failed to authenticate", wp->username);
    }
    return success;
}
Example #4
0
PUBLIC void espScript(HttpConn *conn, cchar *uri, cchar *optionString)
{
    MprHash     *options;
    cchar       *indent, *newline, *path;
    EspScript   *sp;
    EspRoute    *eroute;
    bool        minified;
   
    eroute = conn->rx->route->eroute;
    options = httpGetOptions(optionString);
    if (uri) {
        espRender(conn, "<script src='%s' type='text/javascript'></script>", httpUri(conn, uri));
    } else {
        minified = smatch(httpGetOption(options, "minified", 0), "true");
        indent = "";
        for (sp = defaultScripts; sp->name; sp++) {
            if (sp->option && !smatch(httpGetOption(options, sp->option, "false"), "true")) {
                continue;
            }
            if (sp->flags & SCRIPT_IE) {
                espRender(conn, "%s<!-- [if lt IE 9]>\n", indent);
            }
            path = sjoin("~/", mprGetPathBase(eroute->clientDir), sp->name, minified ? ".min.js" : ".js", NULL);
            uri = httpUri(conn, path);
            newline = sp[1].name ? "\r\n" :  "";
            espRender(conn, "%s<script src='%s' type='text/javascript'></script>%s", indent, uri, newline);
            if (sp->flags & SCRIPT_IE) {
                espRender(conn, "%s<![endif]-->\n", indent);
            }
            indent = "    ";
        }
    }
}
Example #5
0
PUBLIC int websSetRouteAuth(WebsRoute *route, char *auth)
{
    WebsParseAuth parseAuth;
    WebsAskLogin  askLogin;

    assure(route);
    assure(auth && *auth);

    askLogin = 0;
    parseAuth = 0;
    if (smatch(auth, "basic")) {
        askLogin = basicLogin;
        parseAuth = parseBasicDetails;
#if BIT_DIGEST
    } else if (smatch(auth, "digest")) {
        askLogin = digestLogin;
        parseAuth = parseDigestDetails;
#endif
    } else {
        auth = 0;
    }
    route->authType = sclone(auth);
    route->askLogin = askLogin;
    route->parseAuth = parseAuth;
    return 0;
}
Example #6
0
/*
    tabs(makeGrid("[{ name: 'Status', uri: 'pane-1' }, { name: 'Edit', uri: 'pane-2' }]"))

    Options:
        click
        toggle
        remote
 */
PUBLIC void espTabs(HttpConn *conn, EdiGrid *grid, cchar *optionString)
{
    MprHash     *options;
    EdiRec      *rec;
    cchar       *attr, *uri, *name, *klass;
    int         r, toggle;

    options = httpGetOptions(optionString);
    httpInsertOption(options, "class", ESTYLE("tabs"));

    attr = httpGetOption(options, "toggle", EDATA("click"));
    if ((toggle = smatch(attr, "true")) != 0) {
        attr = EDATA("toggle");
    }
    espRender(conn, "<div%s>\r\n    <ul>\r\n", map(conn, options));
    for (r = 0; r < grid->nrecords; r++) {
        rec = grid->records[r];
        name = ediGetFieldValue(rec, "name");
        uri = ediGetFieldValue(rec, "uri");
        uri = toggle ? uri : httpUri(conn, uri);
        if ((r == 0 && toggle) || smatch(uri, conn->rx->pathInfo)) {
            klass = smatch(uri, conn->rx->pathInfo) ? " class='esp-selected'" : "";
        } else {
            klass = "";
        }
        espRender(conn, "          <li %s='%s'%s>%s</li>\r\n", attr, uri, klass, name);
    }
    espRender(conn, "        </ul>\r\n    </div>\r\n");
}
Example #7
0
/*
    Get the username and password credentials. If using an in-protocol auth scheme like basic|digest, the
    rx->authDetails will contain the credentials and the parseAuth callback will be invoked to parse.
    Otherwise, it is expected that "username" and "password" fields are present in the request parameters.

    This is called by authCondition which thereafter calls httpLogin
 */
PUBLIC bool httpGetCredentials(HttpConn *conn, cchar **username, cchar **password)
{
    HttpAuth    *auth;

    assert(username);
    assert(password);
    *username = *password = NULL;

    auth = conn->rx->route->auth;
    if (!auth || !auth->type) {
        return 0;
    }
    if (auth->type) {
        if (conn->authType && !smatch(conn->authType, auth->type->name)) {
            if (!(smatch(auth->type->name, "form") && conn->rx->flags & HTTP_POST)) {
                /* If a posted form authentication, ignore any basic|digest details in request */
                return 0;
            }
        }
        if (auth->type->parseAuth && (auth->type->parseAuth)(conn, username, password) < 0) {
            return 0;
        }
    } else {
        *username = httpGetParam(conn, "username", 0);
        *password = httpGetParam(conn, "password", 0);
    }
    return 1;
}
Example #8
0
PUBLIC bool websVerifyPasswordFromFile(Webs *wp)
{
    char    passbuf[ME_GOAHEAD_LIMIT_PASSWORD * 3 + 3];
    bool    success;

    assert(wp);
    if (!wp->user && (wp->user = websLookupUser(wp->username)) == 0) {
        trace(5, "verifyUser: Unknown user \"%s\"", wp->username);
        return 0;
    }
    /*
        Verify the password. If using Digest auth, we compare the digest of the password.
        Otherwise we encode the plain-text password and compare that
     */
    if (!wp->encoded) {
        fmt(passbuf, sizeof(passbuf), "%s:%s:%s", wp->username, ME_GOAHEAD_REALM, wp->password);
        wfree(wp->password);
        wp->password = websMD5(passbuf);
        wp->encoded = 1;
    }
    if (wp->digest) {
        success = smatch(wp->password, wp->digest);
    } else {
        success = smatch(wp->password, wp->user->password);
    }
    if (success) {
        trace(5, "User \"%s\" authenticated", wp->username);
    } else {
        trace(5, "Password for user \"%s\" failed to authenticate", wp->username);
    }
    return success;
}
Example #9
0
File: uri.c Project: BIDXOM/http-2
static int getPort(HttpUri *uri)
{
    if (uri->port) {
        return uri->port;
    }
    return (uri->scheme && (smatch(uri->scheme, "https") || smatch(uri->scheme, "wss"))) ? 443 : 80;
}
Example #10
0
PUBLIC int websOpenAuth(int minimal)
{
    char    sbuf[64];
    
    assert(minimal == 0 || minimal == 1);

    if ((users = hashCreate(-1)) < 0) {
        return -1;
    }
    if ((roles = hashCreate(-1)) < 0) {
        return -1;
    }
    if (!minimal) {
        fmt(sbuf, sizeof(sbuf), "%x:%x", rand(), OSTimeGet());
        secret = websMD5(sbuf);
#if ME_GOAHEAD_JAVASCRIPT && FUTURE
        websJsDefine("can", jsCan);
#endif
        websDefineAction("login", loginServiceProc);
        websDefineAction("logout", logoutServiceProc);
    }
    if (smatch(ME_GOAHEAD_AUTH_STORE, "file")) {
        verifyPassword = websVerifyPasswordFromFile;
#if ME_COMPILER_HAS_PAM
    } else if (smatch(ME_GOAHEAD_AUTH_STORE, "pam")) {
        verifyPassword = websVerifyPasswordFromPam;
#endif
    }
    return 0;
}
Example #11
0
/*  
    Define headers and create an empty header packet that will be filled later by the pipeline.
 */
static int setClientHeaders(HttpConn *conn)
{
    HttpAuthType    *authType;

    mprAssert(conn);

    if (smatch(conn->protocol, "HTTP/1.0")) {
        conn->http10 = 1;
    }
    if (conn->authType && (authType = httpLookupAuthType(conn->authType)) != 0) {
        (authType->setAuth)(conn);
        conn->setCredentials = 1;
    }
    if (conn->port != 80) {
        httpAddHeader(conn, "Host", "%s:%d", conn->ip, conn->port);
    } else {
        httpAddHeaderString(conn, "Host", conn->ip);
    }
#if UNUSED
    if (conn->http10 && !smatch(conn->tx->method, "GET")) {
        conn->keepAliveCount = 0;
    }
#endif
    if (conn->keepAliveCount > 0) {
        httpSetHeaderString(conn, "Connection", "Keep-Alive");
    } else {
        httpSetHeaderString(conn, "Connection", "close");
    }
    return 0;
}
Example #12
0
static char *getModuleEntry(EspRoute *eroute, cchar *kind, cchar *source, cchar *cacheName)
{
    char    *cp, *entry;

    if (smatch(kind, "view")) {
        entry = sfmt("esp_%s", cacheName);

    } else if (smatch(kind, "app")) {
        if (eroute->combine) {
            entry = sfmt("esp_%s_%s_combine", kind, eroute->appName);
        } else {
            entry = sfmt("esp_%s_%s", kind, eroute->appName);
        }
    } else {
        /* Controller */
        if (eroute->appName) {
            entry = sfmt("esp_%s_%s_%s", kind, eroute->appName, mprTrimPathExt(mprGetPathBase(source)));
        } else {
            entry = sfmt("esp_%s_%s", kind, mprTrimPathExt(mprGetPathBase(source)));
        }
    }
    for (cp = entry; *cp; cp++) {
        if (!isalnum((uchar) *cp) && *cp != '_') {
            *cp = '_';
        }
    }
    return entry;
}
Example #13
0
/*
    Check the certificate peer name validates and matches the desired name
 */
static int checkPeerCertName(MprSocket *sp)
{
    MprSsl      *ssl;
    OpenSocket  *osp;
    X509        *cert;
    X509_NAME   *xSubject;
    char        subject[512], issuer[512], peerName[512], *target, *certName, *tp;

    ssl = sp->ssl;
    osp = (OpenSocket*) sp->sslSocket;

    if ((cert = SSL_get_peer_certificate(osp->handle)) == 0) {
        peerName[0] = '\0';
    } else {
        xSubject = X509_get_subject_name(cert);
        X509_NAME_oneline(xSubject, subject, sizeof(subject) -1);
        X509_NAME_oneline(X509_get_issuer_name(cert), issuer, sizeof(issuer) -1);
        X509_NAME_get_text_by_NID(xSubject, NID_commonName, peerName, sizeof(peerName) - 1);
        sp->peerName = sclone(peerName);
        sp->peerCert = sclone(subject);
        sp->peerCertIssuer = sclone(issuer);
        X509_free(cert);
    }
    if (ssl->verifyPeer && osp->requiredPeerName) {
        target = osp->requiredPeerName;
        certName = peerName;

        if (target == 0 || *target == '\0' || strchr(target, '.') == 0) {
            sp->errorMsg = sfmt("Bad peer name");
            return MPR_ERR_BAD_VALUE;
        }
        if (!smatch(certName, "localhost")) {
            if (strchr(certName, '.') == 0) {
                sp->errorMsg = sfmt("Peer certificate must have a domain: \"%s\"", certName);
                return MPR_ERR_BAD_VALUE;
            }
            if (*certName == '*' && certName[1] == '.') {
                /* Wildcard cert */
                certName = &certName[2];
                if (strchr(certName, '.') == 0) {
                    /* Peer must be of the form *.domain.tld. i.e. *.com is not valid */
                    sp->errorMsg = sfmt("Peer CN is not valid %s", peerName);
                    return MPR_ERR_BAD_VALUE;
                }
                if ((tp = strchr(target, '.')) != 0 && strchr(&tp[1], '.')) {
                    /* Strip host name if target has a host name */
                    target = &tp[1];
                }
            }
        }
        if (!smatch(target, certName)) {
            sp->errorMsg = sfmt("Certificate common name mismatch CN \"%s\" vs required \"%s\"", peerName,
                osp->requiredPeerName);
            return MPR_ERR_BAD_VALUE;
        }
    }
    return 0;
}
Example #14
0
File: uri.c Project: DavidQuan/http
PUBLIC HttpUri *httpResolveUri(HttpConn *conn, HttpUri *base, HttpUri *other)
{
    HttpHost        *host;
    HttpEndpoint    *endpoint;
    HttpUri         *current;

    if (!base || !base->valid) {
        return other;
    }
    if (!other || !other->valid) {
        return base;
    }
    current = httpCloneUri(base, 0);

    /*
        Must not inherit the query or reference
     */
    current->query = 0;
    current->reference = 0;

    if (other->scheme && !smatch(current->scheme, other->scheme)) {
        current->scheme = sclone(other->scheme);
        /*
            If the scheme is changed (test above), then accept an explict port.
            If no port, then must not use the current port as the scheme has changed.
         */
        if (other->port) {
            current->port = other->port;
        } else {
            host = conn ? conn->host : httpGetDefaultHost();
            endpoint = smatch(current->scheme, "https") ? host->secureEndpoint : host->defaultEndpoint;
            if (endpoint) {
                current->port = endpoint->port;
            } else {
                current->port = 0;
            }
        }
    }
    if (other->host) {
        current->host = sclone(other->host);
    }
    if (other->port) {
        current->port = other->port;
    }
    if (other->path) {
        trimPathToDirname(current);
        httpJoinUriPath(current, current, other);
        current->path = httpNormalizeUriPath(current->path);
    }
    if (other->reference) {
        current->reference = sclone(other->reference);
    }
    if (other->query) {
        current->query = sclone(other->query);
    }
    current->ext = mprGetPathExt(current->path);
    return current;
}
Example #15
0
static void logoutServiceProc(Webs *wp)
{
    assure(wp);
    websRemoveSessionVar(wp, WEBS_SESSION_USERNAME);
    if (smatch(wp->authType, "basic") || smatch(wp->authType, "digest")) {
        websError(wp, HTTP_CODE_UNAUTHORIZED, "Logged out.");
        return;
    }
    websRedirectByStatus(wp, HTTP_CODE_OK);
}
Example #16
0
PUBLIC int httpSetGroupAccount(cchar *newGroup)
{
    Http    *http;

    http = HTTP;
    if (smatch(newGroup, "HTTP") || smatch(newGroup, "APPWEB")) {
#if ME_UNIX_LIKE
        /* Only change group if root */
        if (getuid() != 0) {
            return 0;
        }
#endif
#if MACOSX || FREEBSD
        newGroup = "_www";
#elif LINUX || ME_UNIX_LIKE
{
        char    *buf;
        newGroup = "nobody";
        /*
            Debian has nogroup, Fedora has nobody. Ugh!
         */
        if ((buf = mprReadPathContents("/etc/group", NULL)) != 0) {
            if (scontains(buf, "nogroup:")) {
                newGroup = "nogroup";
            }
        }
}
#elif WINDOWS
        newGroup = "Administrator";
#endif
    }
#if ME_UNIX_LIKE
    struct group    *gp;

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

    } else {
        if ((gp = getgrnam(newGroup)) == 0) {
            mprLog("critical http", 0, "Bad group name: %s", newGroup);
            return MPR_ERR_CANT_ACCESS;
        }
        http->gid = gp->gr_gid;
    }
    http->groupChanged = 1;
#endif
    http->group = sclone(newGroup);
    return 0;
}
Example #17
0
PUBLIC bool websLogoutUser(Webs *wp)
{
    assert(wp);
    websRemoveSessionVar(wp, WEBS_SESSION_USERNAME);
    if (smatch(wp->authType, "basic") || smatch(wp->authType, "digest")) {
        websError(wp, HTTP_CODE_UNAUTHORIZED, "Logged out.");
        return 0;
    }
    websRedirectByStatus(wp, HTTP_CODE_OK);
    return 1;
}
Example #18
0
File: user.c Project: leemit/esp
/*
    Common controller run for every action invoked
    This tests if the user is logged in and authenticated.
    Access to certain pages are permitted without authentication so the user can login
 */
static void commonController(HttpConn *conn)
{
    cchar   *uri;

    if (!httpLoggedIn(conn)) {
        uri = getUri();
        if (sstarts(uri, "/public/") || smatch(uri, "/user/login") || smatch(uri, "/user/logout")) {
            return;
        }
        httpError(conn, HTTP_CODE_UNAUTHORIZED, "Access Denied. Login required");
    }
}
Example #19
0
/*
    Map options to an attribute string. Remove all internal control specific options and transparently handle URI link options.
    WARNING: this returns a non-cloned reference and relies on no GC yield until the returned value is used or cloned.
    This is done as an optimization to reduce memeory allocations.
 */
static cchar *map(HttpConn *conn, MprHash *options)
{
    Esp         *esp;
    EspReq      *req;
    MprHash     *params;
    MprKey      *kp;
    MprBuf      *buf;
    cchar       *value;
    char        *pstr;

    if (options == 0 || mprGetHashLength(options) == 0) {
        return MPR->emptyString;
    }
    req = conn->data;
    if (httpGetOption(options, EDATA("refresh"), 0) && !httpGetOption(options, "id", 0)) {
        httpAddOption(options, "id", sfmt("id_%d", req->lastDomID++));
    }
    esp = MPR->espService;
    buf = mprCreateBuf(-1, -1);
    for (kp = 0; (kp = mprGetNextKey(options, kp)) != 0; ) {
        if (kp->type != MPR_JSON_OBJ && kp->type != MPR_JSON_ARRAY && !mprLookupKey(esp->internalOptions, kp->key)) {
            mprPutCharToBuf(buf, ' ');
            value = kp->data;
            /*
                Support link template resolution for these options
             */
            if (smatch(kp->key, EDATA("click")) || smatch(kp->key, EDATA("remote")) || smatch(kp->key, EDATA("refresh"))) {
                value = httpUriEx(conn, value, options);
                if ((params = httpGetOptionHash(options, "params")) != 0) {
                    pstr = (char*) "";
                    for (kp = 0; (kp = mprGetNextKey(params, kp)) != 0; ) {
                        pstr = sjoin(pstr, mprUriEncode(kp->key, MPR_ENCODE_URI_COMPONENT), "=", 
                            mprUriEncode(kp->data, MPR_ENCODE_URI_COMPONENT), "&", NULL);
                    }
                    if (pstr[0]) {
                        /* Trim last "&" */
                        pstr[strlen(pstr) - 1] = '\0';
                    }
                    mprPutToBuf(buf, "%s-params='%s", params);
                }
            }
            mprPutStringToBuf(buf, kp->key);
            mprPutStringToBuf(buf, "='");
            mprPutStringToBuf(buf, value);
            mprPutCharToBuf(buf, '\'');
        }
    }
    mprAddNullToBuf(buf);
    return mprGetBufStart(buf);
}
Example #20
0
static void setDefaultHeaders(HttpConn *conn)
{
    HttpAuthType    *ap;

    assert(conn);

    if (smatch(conn->protocol, "HTTP/1.0")) {
        conn->http10 = 1;
    }
    if (conn->username && conn->authType) {
        if ((ap = httpLookupAuthType(conn->authType)) != 0) {
            if ((ap->setAuth)(conn, conn->username, conn->password)) {
                conn->authRequested = 1;
            }
        }
    }
    if (conn->port != 80 && conn->port != 443) {
        httpAddHeader(conn, "Host", "%s:%d", conn->ip, conn->port);
    } else {
        httpAddHeaderString(conn, "Host", conn->ip);
    }
    httpAddHeaderString(conn, "Accept", "*/*");
    if (conn->keepAliveCount > 0) {
        httpSetHeaderString(conn, "Connection", "Keep-Alive");
    } else {
        httpSetHeaderString(conn, "Connection", "close");
    }
}
Example #21
0
int ediAddValidation(Edi *edi, cchar *name, cchar *tableName, cchar *columnName, cvoid *data)
{
    EdiService          *es;
    EdiValidation       *vp; 
    cchar               *errMsg;
    int                 column;

    es = MPR->ediService;
    if ((vp = mprAllocObj(EdiValidation, manageValidation)) == 0) {
        return MPR_ERR_MEMORY;
    }
    vp->name = sclone(name);
    if ((vp->vfn = mprLookupKey(es->validations, name)) == 0) {
        mprError("Can't find validation '%s'", name);
        return MPR_ERR_CANT_FIND;
    }
    if (smatch(name, "format")) {
        if ((vp->mdata = pcre_compile2(data, 0, 0, &errMsg, &column, NULL)) == 0) {
            mprError("Can't compile validation pattern. Error %s at column %d", errMsg, column); 
            return MPR_ERR_BAD_SYNTAX;
        }
        data = 0;
    }
    vp->data = data;
    return edi->provider->addValidation(edi, tableName, columnName, vp);
}
Example #22
0
PUBLIC bool modeIs(cchar *kind)
{
    HttpRoute   *route;

    route = getStream()->rx->route;
    return smatch(route->mode, kind);
}
Example #23
0
/*
    Parse the cert info and write properties to the buffer. Modifies the info argument.
 */
static void parseCertFields(MprBuf *buf, char *info)
{
    char    c, *cp, *term, *key, *value;

    if (info) {
        key = 0;
        term = cp = info;
        do {
            c = *cp;
            if (c == '/' || c == '\0') {
                *cp = '\0';
                key = ssplit(term, "=", &value);
                if (smatch(key, "emailAddress")) {
                    key = "email";
                }
                mprPutToBuf(buf, "\"%s\":\"%s\",", key, value);
                term = &cp[1];
                *cp = c;
            }
        } while (*cp++ != '\0');
        if (key) {
            mprAdjustBufEnd(buf, -1);
        }
    }
}
Example #24
0
/*
    Authenticate a user using the session stored username. This will set HttpRx.authenticated if authentication succeeds.
    Note: this does not call httpLogin except for auto-login cases where a password is not used.
 */
PUBLIC bool httpAuthenticate(HttpConn *conn)
{
    HttpRx      *rx;
    HttpAuth    *auth;
    cchar       *ip, *username;

    rx = conn->rx;
    auth = rx->route->auth;

    if (!rx->authenticateProbed) {
        rx->authenticateProbed = 1;
        ip = httpGetSessionVar(conn, HTTP_SESSION_IP, 0);
        username = httpGetSessionVar(conn, HTTP_SESSION_USERNAME, 0);
        if (!smatch(ip, conn->ip) || !username) {
            if (auth->username && *auth->username) {
                /* Auto-login */
                httpLogin(conn, auth->username, NULL);
                username = httpGetSessionVar(conn, HTTP_SESSION_USERNAME, 0);
            }
            if (!username) {
                return 0;
            }
        }
        httpTrace(conn, "auth.login.authenticated", "context", 
            "msg: 'Using cached authentication data', username: '******'", username);
        conn->username = username;
        rx->authenticated = 1;
    }
    return rx->authenticated;
}
Example #25
0
/*
    dropdown("priority", makeGrid("[{ id: 0, low: 0}, { id: 1, med: 1}, {id: 2, high: 2}]"), 0)
    dropdown("priority", makeGrid("[{ low: 0}, { med: 1}, {high: 2}]"), 0)
    dropdown("priority", makeGrid("[0, 10, 100]"), 0)

    Options can provide the defaultValue in a "value" property.
 */
PUBLIC void espDropdown(HttpConn *conn, cchar *field, EdiGrid *choices, cchar *optionString) 
{
    EdiRec      *rec;
    MprHash     *options;
    cchar       *id, *currentValue, *selected, *value;
    int         r;

    if (choices == 0) {
        return;
    }
    options = httpGetOptions(optionString);
    currentValue = getValue(conn, field, options);
    if (field == 0) {
        field = httpGetOption(options, "field", "id");
    }
    espRender(conn, "<select name='%s'%s>\r\n", field, map(conn, options));
    for (r = 0; r < choices->nrecords; r++) {
        rec = choices->records[r];
        if (rec->nfields == 1) {
            value = rec->fields[0].value;
        } else {
            value = ediGetFieldValue(rec, field);
        }
        if ((id = ediGetFieldValue(choices->records[r], "id")) == 0) {
            id = value;
        }
        selected = (smatch(value, currentValue)) ? " selected='yes'" : "";
        espRender(conn, "        <option value='%s'%s>%s</option>\r\n", id, selected, value);
    }
    espRender(conn, "    </select>");
}
Example #26
0
static cchar *getValue(HttpConn *conn, cchar *fieldName, MprHash *options)
{
    EdiRec      *record;
    MprKey      *field;
    cchar       *value, *msg;

    record = conn->record;
    value = 0;

    if (record) {
        value = ediGetFieldValue(record, fieldName);
        if (record->errors) {
            for (ITERATE_KEY_DATA(record->errors, field, msg)) {
                if (smatch(field->key, fieldName)) {
                    httpInsertOption(options, "class", ESTYLE("field-error"));
                }
            }
        }
    }
    if (value == 0) {
        value = httpGetOption(options, "value", 0);
    }
    if (httpGetOption(options, "escape", 0)) {
        value = mprEscapeHtml(value);
    }
    return value;
}
Example #27
0
/*
    Map iana names to OpenSSL names so users can provide IANA names as well as OpenSSL cipher names
 */
static char *mapCipherNames(char *ciphers)
{
    WebsBuf     buf;
    CipherMap   *cp;
    char        *cipher, *next, *str;

    if (!ciphers || *ciphers == 0) {
        return 0;
    }
    bufCreate(&buf, 0, 0);
    ciphers = sclone(ciphers);
    for (next = ciphers; (cipher = stok(next, ":, \t", &next)) != 0; ) {
        for (cp = cipherMap; cp->name; cp++) {
            if (smatch(cp->name, cipher)) {
                bufPut(&buf, "%s:", cp->ossName);
                break;
            }
        }
        if (cp->name == 0) {
            bufPut(&buf, "%s:", cipher);
        }
    }
    wfree(ciphers);
    str = sclone(bufStart(&buf));
    bufFree(&buf);
    return str;
}
Example #28
0
int main(int argc, char **argv)
{
	int i;
	reg_func func;

	sm_outfd = stdout;
	parse_args(&argc, &argv);

	/* this gets set back to zero when we parse the first function */
	final_pass = 1;

	data_dir = get_data_dir(argv[0]);

	allocate_hook_memory();
	create_function_hook_hash();
	open_smatch_db();
	for (i = 1; i < ARRAY_SIZE(reg_funcs); i++) {
		func = reg_funcs[i].func;
		/* The script IDs start at 1.
		   0 is used for internal stuff. */
		if (!option_enable || reg_funcs[i].enabled || !strncmp(reg_funcs[i].name, "register_", 9))
			func(i);
	}

	smatch(argc, argv);
	free_string(data_dir);
	return 0;
}
Example #29
0
File: app.c Project: embedthis/esp
/*
    Common base run for every request.
 */
static void commonBase(HttpStream *stream)
{
    cchar   *uri;

    if (!httpIsAuthenticated(stream)) {
        /*
            Access to certain pages are permitted without authentication so the user can login and logout.
         */
        uri = getUri();
        if (sstarts(uri, "/public/") || smatch(uri, "/user/login") || smatch(uri, "/user/logout")) {
            return;
        }
        feedback("error", "Access Denied. Login required.");
        redirect("/public/login.esp");
    }
}
Example #30
0
/*
    Add the client 'Authorization' header for authenticated requests
    Must first get a 401 response to get the authData.
 */
PUBLIC bool httpDigestSetHeaders(HttpConn *conn, cchar *username, cchar *password)
{ 
    Http        *http;
    HttpTx      *tx;
    DigestData  *dp;
    char        *ha1, *ha2, *digest, *cnonce;

    http = conn->http;
    tx = conn->tx;
    if ((dp = conn->authData) == 0) {
        /* Need to await a failing auth response */
        return 0;
    }
    cnonce = sfmt("%s:%s:%x", http->secret, dp->realm, (int) http->now);
    ha1 = mprGetMD5(sfmt("%s:%s:%s", username, dp->realm, password));
    ha2 = mprGetMD5(sfmt("%s:%s", tx->method, tx->parsedUri->path));
    if (smatch(dp->qop, "auth")) {
        digest = mprGetMD5(sfmt("%s:%s:%08x:%s:%s:%s", ha1, dp->nonce, dp->nc, cnonce, dp->qop, ha2));
        httpAddHeader(conn, "Authorization", "Digest username=\"%s\", realm=\"%s\", domain=\"%s\", "
            "algorithm=\"MD5\", qop=\"%s\", cnonce=\"%s\", nc=\"%08x\", nonce=\"%s\", opaque=\"%s\", "
            "stale=\"FALSE\", uri=\"%s\", response=\"%s\"", username, dp->realm, dp->domain, dp->qop, 
            cnonce, dp->nc, dp->nonce, dp->opaque, tx->parsedUri->path, digest);
    } else {
        digest = mprGetMD5(sfmt("%s:%s:%s", ha1, dp->nonce, ha2));
        httpAddHeader(conn, "Authorization", "Digest username=\"%s\", realm=\"%s\", nonce=\"%s\", "
            "uri=\"%s\", response=\"%s\"", username, dp->realm, dp->nonce, tx->parsedUri->path, digest);
    }
    return 1;
}