/* $Cambridge: hermes/src/prayer/cmd/cmd_check_cookie.c,v 1.2 2008/05/19 15:55:54 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 config *config = session->config;
    struct request *request = session->request;
    char *s = assoc_lookup(request->hdrs, "cookie");
    char *t;
    char *u;
    BOOL have_cookie = NIL;
    char *key;

    if (config->http_cookie_use_port)
        key = pool_printf(request->pool, "%s:%lu",
                          session->username, session->session_port);
    else
        key = session->username;

    /* 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");
}
