/* $Cambridge: hermes/src/prayer/cmd/cmd_check_cookie.c,v 1.5 2010/07/07 15:49:34 dpc22 Exp $ */
/************************************************
 *    Prayer - a Webmail Interface              *
 ************************************************/

/* Copyright (c) University of Cambridge 2000 - 2008 */
/* See the file NOTICE for conditions of use and distribution. */

#include "prayer_session.h"

void cmd_check_cookie(struct session *session)
{
    struct request *request = session->request;
    char *s = assoc_lookup(request->hdrs, "cookie");
    char *t;
    char *u;
    BOOL have_cookie = NIL;
    char *key;
    unsigned long pid = (unsigned long)getpid();

    key = pool_printf(request->pool, "%s:%lu", session->username, pid);
                      

    /* Look for username:port=VALUE in cookie */
    while (s && *s && (t = strchr(s, '='))) {
        *t++ = '\0';
        if ((u = strchr(t, ';')))
            *u++ = '\0';

        if (!strcmp(key, string_trim_whitespace(s))) {
            if (!strcmp(session->sessionid, string_trim_whitespace(t)))
                have_cookie = T;
            break;
        }
        s = u;
    }

    if (have_cookie) {
        /* Force update for session URLs */
        session->use_cookie = T;
        session_update_sequence(session);
    }

    /* Define sane last_cmd: don't want to end up back here! */
    session_record_last_cmd(session, "welcome");

    if (have_cookie)
        session_make_session_redirect(session, request, "welcome");
    else
        session_redirect(session, request, "welcome");
}
