bottleneck testcase based on rubbos
[bottlenecks.git] / rubbos / app / httpd-2.0.64 / modules / metadata / mod_usertrack.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /* User Tracking Module (Was mod_cookies.c)
18  *
19  * *** IMPORTANT NOTE: This module is not designed to generate
20  * *** cryptographically secure cookies.  This means you should not
21  * *** use cookies generated by this module for authentication purposes
22  *
23  * This Apache module is designed to track users paths through a site.
24  * It uses the client-side state ("Cookie") protocol developed by Netscape.
25  * It is known to work on most browsers.
26  *
27  * Each time a page is requested we look to see if the browser is sending
28  * us a Cookie: header that we previously generated.
29  *
30  * If we don't find one then the user hasn't been to this site since
31  * starting their browser or their browser doesn't support cookies.  So
32  * we generate a unique Cookie for the transaction and send it back to
33  * the browser (via a "Set-Cookie" header)
34  * Future requests from the same browser should keep the same Cookie line.
35  *
36  * By matching up all the requests with the same cookie you can
37  * work out exactly what path a user took through your site.  To log
38  * the cookie use the " %{Cookie}n " directive in a custom access log;
39  *
40  * Example 1 : If you currently use the standard Log file format (CLF)
41  * and use the command "TransferLog somefilename", add the line
42  *       LogFormat "%h %l %u %t \"%r\" %s %b %{Cookie}n"
43  * to your config file.
44  *
45  * Example 2 : If you used to use the old "CookieLog" directive, you
46  * can emulate it by adding the following command to your config file
47  *       CustomLog filename "%{Cookie}n \"%r\" %t"
48  *
49  * Mark Cox, mjc@apache.org, 6 July 95
50  *
51  * This file replaces mod_cookies.c
52  */
53
54 #include "apr.h"
55 #include "apr_lib.h"
56 #include "apr_strings.h"
57
58 #define APR_WANT_STRFUNC
59 #include "apr_want.h"
60
61 #include "httpd.h"
62 #include "http_config.h"
63 #include "http_core.h"
64 #include "http_request.h"
65
66
67 module AP_MODULE_DECLARE_DATA usertrack_module;
68
69 typedef struct {
70     int always;
71     int expires;
72 } cookie_log_state;
73
74 typedef enum {
75     CT_UNSET,
76     CT_NETSCAPE,
77     CT_COOKIE,
78     CT_COOKIE2
79 } cookie_type_e;
80
81 typedef struct {
82     int enabled;
83     cookie_type_e style;
84     char *cookie_name;
85     char *cookie_domain;
86     char *regexp_string;  /* used to compile regexp; save for debugging */
87     regex_t *regexp;  /* used to find usertrack cookie in cookie header */
88 } cookie_dir_rec;
89
90 /* Make Cookie: Now we have to generate something that is going to be
91  * pretty unique.  We can base it on the pid, time, hostip */
92
93 #define COOKIE_NAME "Apache"
94
95 static void make_cookie(request_rec *r)
96 {
97     cookie_log_state *cls = ap_get_module_config(r->server->module_config,
98                                                  &usertrack_module);
99     /* 1024 == hardcoded constant */
100     char cookiebuf[1024];
101     char *new_cookie;
102     const char *rname = ap_get_remote_host(r->connection, r->per_dir_config,
103                                            REMOTE_NAME, NULL);
104     cookie_dir_rec *dcfg;
105
106     dcfg = ap_get_module_config(r->per_dir_config, &usertrack_module);
107
108     /* XXX: hmm, this should really tie in with mod_unique_id */
109     apr_snprintf(cookiebuf, sizeof(cookiebuf), "%s.%" APR_TIME_T_FMT, rname, 
110                  apr_time_now());
111
112     if (cls->expires) {
113
114         /* Cookie with date; as strftime '%a, %d-%h-%y %H:%M:%S GMT' */
115         new_cookie = apr_psprintf(r->pool, "%s=%s; path=/",
116                                   dcfg->cookie_name, cookiebuf);
117
118         if ((dcfg->style == CT_UNSET) || (dcfg->style == CT_NETSCAPE)) {
119             apr_time_exp_t tms;
120             apr_time_exp_gmt(&tms, r->request_time 
121                                  + apr_time_from_sec(cls->expires));
122             new_cookie = apr_psprintf(r->pool,
123                                        "%s; expires=%s, "
124                                        "%.2d-%s-%.2d %.2d:%.2d:%.2d GMT",
125                                        new_cookie, apr_day_snames[tms.tm_wday],
126                                        tms.tm_mday,
127                                        apr_month_snames[tms.tm_mon],
128                                        tms.tm_year % 100,
129                                        tms.tm_hour, tms.tm_min, tms.tm_sec);
130         }
131         else {
132             new_cookie = apr_psprintf(r->pool, "%s; max-age=%d",
133                                       new_cookie, cls->expires);
134         }
135     }
136     else {
137         new_cookie = apr_psprintf(r->pool, "%s=%s; path=/",
138                                   dcfg->cookie_name, cookiebuf);
139     }
140     if (dcfg->cookie_domain != NULL) {
141         new_cookie = apr_pstrcat(r->pool, new_cookie, "; domain=",
142                                  dcfg->cookie_domain,
143                                  (dcfg->style == CT_COOKIE2
144                                   ? "; version=1"
145                                   : ""),
146                                  NULL);
147     }
148
149     apr_table_addn(r->headers_out,
150                    (dcfg->style == CT_COOKIE2 ? "Set-Cookie2" : "Set-Cookie"),
151                    new_cookie);
152     apr_table_setn(r->notes, "cookie", apr_pstrdup(r->pool, cookiebuf));   /* log first time */
153     return;
154 }
155
156 /* dcfg->regexp is "^cookie_name=([^;]+)|;[ \t]+cookie_name=([^;]+)",
157  * which has three subexpressions, $0..$2 */
158 #define NUM_SUBS 3
159
160 static void set_and_comp_regexp(cookie_dir_rec *dcfg, 
161                                 apr_pool_t *p,
162                                 const char *cookie_name) 
163 {
164     int danger_chars = 0;
165     const char *sp = cookie_name;
166
167     /* The goal is to end up with this regexp, 
168      * ^cookie_name=([^;]+)|;[\t]+cookie_name=([^;]+) 
169      * with cookie_name obviously substituted either
170      * with the real cookie name set by the user in httpd.conf, or with the
171      * default COOKIE_NAME.
172      */
173
174     /* Anyway, we need to escape the cookie_name before pasting it
175      * into the regex
176      */
177     while (*sp) {
178         if (!apr_isalnum(*sp)) {
179             ++danger_chars;
180         }
181         ++sp;
182     }
183
184     if (danger_chars) {
185         char *cp;
186         cp = apr_palloc(p, sp - cookie_name + danger_chars + 1); /* 1 == \0 */
187         sp = cookie_name;
188         cookie_name = cp;
189         while (*sp) {
190             if (!apr_isalnum(*sp)) {
191                 *cp++ = '\\';
192             }
193             *cp++ = *sp++;
194         }
195         *cp = '\0';
196     }
197
198     dcfg->regexp_string = apr_pstrcat(p, "^",
199                                       cookie_name,
200                                       "=([^;]+)|;[ \t]+",
201                                       cookie_name,
202                                       "=([^;]+)", NULL);
203
204     dcfg->regexp = ap_pregcomp(p, dcfg->regexp_string, REG_EXTENDED);
205     ap_assert(dcfg->regexp != NULL);
206 }
207
208 static int spot_cookie(request_rec *r)
209 {
210     cookie_dir_rec *dcfg = ap_get_module_config(r->per_dir_config,
211                                                 &usertrack_module);
212     const char *cookie_header;
213     regmatch_t regm[NUM_SUBS];
214
215     /* Do not run in subrequests */
216     if (!dcfg->enabled || r->main) {
217         return DECLINED;
218     }
219
220     if ((cookie_header = apr_table_get(r->headers_in, "Cookie"))) {
221         if (!ap_regexec(dcfg->regexp, cookie_header, NUM_SUBS, regm, 0)) {
222             char *cookieval = NULL;
223             /* Our regexp,
224              * ^cookie_name=([^;]+)|;[ \t]+cookie_name=([^;]+)
225              * only allows for $1 or $2 to be available. ($0 is always
226              * filled with the entire matched expression, not just
227              * the part in parentheses.) So just check for either one
228              * and assign to cookieval if present. */
229             if (regm[1].rm_so != -1) {
230                 cookieval = ap_pregsub(r->pool, "$1", cookie_header,
231                                        NUM_SUBS, regm);
232             }
233             if (regm[2].rm_so != -1) {
234                 cookieval = ap_pregsub(r->pool, "$2", cookie_header,
235                                        NUM_SUBS, regm);
236             }
237             /* Set the cookie in a note, for logging */
238             apr_table_setn(r->notes, "cookie", cookieval);
239
240             return DECLINED;    /* There's already a cookie, no new one */
241         }
242     }
243     make_cookie(r);
244     return OK;                  /* We set our cookie */
245 }
246
247 static void *make_cookie_log_state(apr_pool_t *p, server_rec *s)
248 {
249     cookie_log_state *cls =
250     (cookie_log_state *) apr_palloc(p, sizeof(cookie_log_state));
251
252     cls->expires = 0;
253
254     return (void *) cls;
255 }
256
257 static void *make_cookie_dir(apr_pool_t *p, char *d)
258 {
259     cookie_dir_rec *dcfg;
260
261     dcfg = (cookie_dir_rec *) apr_pcalloc(p, sizeof(cookie_dir_rec));
262     dcfg->cookie_name = COOKIE_NAME;
263     dcfg->cookie_domain = NULL;
264     dcfg->style = CT_UNSET;
265     dcfg->enabled = 0;
266
267     /* In case the user does not use the CookieName directive,
268      * we need to compile the regexp for the default cookie name. */
269     set_and_comp_regexp(dcfg, p, COOKIE_NAME);
270
271     return dcfg;
272 }
273
274 static const char *set_cookie_enable(cmd_parms *cmd, void *mconfig, int arg)
275 {
276     cookie_dir_rec *dcfg = mconfig;
277
278     dcfg->enabled = arg;
279     return NULL;
280 }
281
282 static const char *set_cookie_exp(cmd_parms *parms, void *dummy,
283                                   const char *arg)
284 {
285     cookie_log_state *cls;
286     time_t factor, modifier = 0;
287     time_t num = 0;
288     char *word;
289
290     cls  = ap_get_module_config(parms->server->module_config,
291                                 &usertrack_module);
292     /* The simple case first - all numbers (we assume) */
293     if (apr_isdigit(arg[0]) && apr_isdigit(arg[strlen(arg) - 1])) {
294         cls->expires = atol(arg);
295         return NULL;
296     }
297
298     /*
299      * The harder case - stolen from mod_expires 
300      *
301      * CookieExpires "[plus] {<num> <type>}*"
302      */
303
304     word = ap_getword_conf(parms->pool, &arg);
305     if (!strncasecmp(word, "plus", 1)) {
306         word = ap_getword_conf(parms->pool, &arg);
307     };
308
309     /* {<num> <type>}* */
310     while (word[0]) {
311         /* <num> */
312         if (apr_isdigit(word[0]))
313             num = atoi(word);
314         else
315             return "bad expires code, numeric value expected.";
316
317         /* <type> */
318         word = ap_getword_conf(parms->pool, &arg);
319         if (!word[0])
320             return "bad expires code, missing <type>";
321
322         factor = 0;
323         if (!strncasecmp(word, "years", 1))
324             factor = 60 * 60 * 24 * 365;
325         else if (!strncasecmp(word, "months", 2))
326             factor = 60 * 60 * 24 * 30;
327         else if (!strncasecmp(word, "weeks", 1))
328             factor = 60 * 60 * 24 * 7;
329         else if (!strncasecmp(word, "days", 1))
330             factor = 60 * 60 * 24;
331         else if (!strncasecmp(word, "hours", 1))
332             factor = 60 * 60;
333         else if (!strncasecmp(word, "minutes", 2))
334             factor = 60;
335         else if (!strncasecmp(word, "seconds", 1))
336             factor = 1;
337         else
338             return "bad expires code, unrecognized type";
339
340         modifier = modifier + factor * num;
341
342         /* next <num> */
343         word = ap_getword_conf(parms->pool, &arg);
344     }
345
346     cls->expires = modifier;
347
348     return NULL;
349 }
350
351 static const char *set_cookie_name(cmd_parms *cmd, void *mconfig,
352                                    const char *name)
353 {
354     cookie_dir_rec *dcfg = (cookie_dir_rec *) mconfig;
355
356     dcfg->cookie_name = apr_pstrdup(cmd->pool, name);
357
358     set_and_comp_regexp(dcfg, cmd->pool, name);
359
360     if (dcfg->regexp == NULL) {
361         return "Regular expression could not be compiled.";
362     }
363     if (dcfg->regexp->re_nsub + 1 != NUM_SUBS) {
364         return apr_pstrcat(cmd->pool, "Invalid cookie name \"",
365                            name, "\"", NULL);
366     }
367
368     return NULL;
369 }
370
371 /*
372  * Set the value for the 'Domain=' attribute.
373  */
374 static const char *set_cookie_domain(cmd_parms *cmd, void *mconfig,
375                                      const char *name)
376 {
377     cookie_dir_rec *dcfg;
378
379     dcfg = (cookie_dir_rec *) mconfig;
380
381     /*
382      * Apply the restrictions on cookie domain attributes.
383      */
384     if (strlen(name) == 0) {
385         return "CookieDomain values may not be null";
386     }
387     if (name[0] != '.') {
388         return "CookieDomain values must begin with a dot";
389     }
390     if (ap_strchr_c(&name[1], '.') == NULL) {
391         return "CookieDomain values must contain at least one embedded dot";
392     }
393
394     dcfg->cookie_domain = apr_pstrdup(cmd->pool, name);
395     return NULL;
396 }
397
398 /*
399  * Make a note of the cookie style we should use.
400  */
401 static const char *set_cookie_style(cmd_parms *cmd, void *mconfig,
402                                     const char *name)
403 {
404     cookie_dir_rec *dcfg;
405
406     dcfg = (cookie_dir_rec *) mconfig;
407
408     if (strcasecmp(name, "Netscape") == 0) {
409         dcfg->style = CT_NETSCAPE;
410     }
411     else if ((strcasecmp(name, "Cookie") == 0)
412              || (strcasecmp(name, "RFC2109") == 0)) {
413         dcfg->style = CT_COOKIE;
414     }
415     else if ((strcasecmp(name, "Cookie2") == 0)
416              || (strcasecmp(name, "RFC2965") == 0)) {
417         dcfg->style = CT_COOKIE2;
418     }
419     else {
420         return apr_psprintf(cmd->pool, "Invalid %s keyword: '%s'",
421                             cmd->cmd->name, name);
422     }
423
424     return NULL;
425 }
426
427 static const command_rec cookie_log_cmds[] = {
428     AP_INIT_TAKE1("CookieExpires", set_cookie_exp, NULL, OR_FILEINFO,
429                   "an expiry date code"),
430     AP_INIT_TAKE1("CookieDomain", set_cookie_domain, NULL, OR_FILEINFO,
431                   "domain to which this cookie applies"),
432     AP_INIT_TAKE1("CookieStyle", set_cookie_style, NULL, OR_FILEINFO,
433                   "'Netscape', 'Cookie' (RFC2109), or 'Cookie2' (RFC2965)"),
434     AP_INIT_FLAG("CookieTracking", set_cookie_enable, NULL, OR_FILEINFO,
435                  "whether or not to enable cookies"),
436     AP_INIT_TAKE1("CookieName", set_cookie_name, NULL, OR_FILEINFO,
437                   "name of the tracking cookie"),
438     {NULL}
439 };
440
441 static void register_hooks(apr_pool_t *p)
442 {
443     ap_hook_fixups(spot_cookie,NULL,NULL,APR_HOOK_MIDDLE);
444 }
445
446 module AP_MODULE_DECLARE_DATA usertrack_module = {
447     STANDARD20_MODULE_STUFF,
448     make_cookie_dir,            /* dir config creater */
449     NULL,                       /* dir merger --- default is to override */
450     make_cookie_log_state,      /* server config */
451     NULL,                       /* merge server configs */
452     cookie_log_cmds,            /* command apr_table_t */
453     register_hooks              /* register hooks */
454 };