Dillo v3.2.0-151-g90488cbf
Loading...
Searching...
No Matches
cookies.c
Go to the documentation of this file.
1/*
2 * File: cookies.c
3 * Cookies server.
4 *
5 * Copyright 2001 Lars Clausen <lrclause@cs.uiuc.edu>
6 * Jörgen Viksell <jorgen.viksell@telia.com>
7 * Copyright 2002-2007 Jorge Arellano Cid <jcid@dillo.org>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 */
15
16/* The current standard for cookies is RFC 6265.
17 *
18 * Info from 2009 on cookies in the wild:
19 * http://www.ietf.org/mail-archive/web/http-state/current/msg00078.html
20 * And dates specifically:
21 * http://www.ietf.org/mail-archive/web/http-state/current/msg00128.html
22 */
23
24#ifdef DISABLE_COOKIES
25
26int main(void)
27{
28 return 0; /* never called */
29}
30
31#else
32
33
34#include <sys/types.h>
35#include <sys/socket.h>
36#include <sys/stat.h>
37#include <sys/un.h>
38#include <netinet/in.h>
39#include <fcntl.h>
40#include <unistd.h>
41#include <errno.h>
42#include <stddef.h>
43#include <string.h>
44#include <stdlib.h>
45#include <stdio.h>
46#include <time.h> /* for time() and time_t */
47#include <limits.h>
48#include <netdb.h>
49#include <signal.h>
50#include "dpiutil.h"
51#include "../dpip/dpip.h"
52
53
54/*
55 * Debugging macros
56 */
57#define _MSG(...)
58#define MSG(...) printf("[cookies dpi]: " __VA_ARGS__)
59
60/*
61 * a_List_add()
62 *
63 * Make sure there's space for 'num_items' items within the list
64 * (First, allocate an 'alloc_step' sized chunk, after that, double the
65 * list size --to make it faster)
66 */
67#define a_List_add(list,num_items,alloc_step) \
68 if (!list) { \
69 list = dMalloc(alloc_step * sizeof((*list))); \
70 } \
71 if (num_items >= alloc_step){ \
72 while ( num_items >= alloc_step ) \
73 alloc_step <<= 1; \
74 list = dRealloc(list, alloc_step * sizeof((*list))); \
75 }
76
77/* The maximum length of a line in the cookie file */
78#define LINE_MAXLEN 4096
79
80#define MAX_DOMAIN_COOKIES 20
81#define MAX_TOTAL_COOKIES 1200
82
88
89typedef struct {
90 char *domain;
92} CookieControl;
93
94typedef struct {
95 char *domain;
96 Dlist *cookies;
97} DomainNode;
98
99typedef struct {
100 char *name;
101 char *value;
102 char *domain;
103 char *path;
104 time_t expires_at;
105 bool_t host_only;
106 bool_t secure;
107 bool_t session_only;
108 long last_used;
109} CookieData_t;
110
111typedef struct {
112 Dsh *sh;
113 int status;
114} ClientInfo;
115
116/*
117 * Local data
118 */
119
121
122/* List of DomainNode. Each node holds a domain and its list of cookies */
124
125/* Variables for access control */
126static CookieControl *ccontrol = NULL;
127static int num_ccontrol = 0;
128static int num_ccontrol_max = 1;
130
131static long cookies_use_counter = 0;
133static FILE *file_stream;
134static const char *const cookies_txt_header_str =
135"# HTTP Cookie File\n"
136"# This is a generated file! Do not edit.\n"
137"# [domain subdomains path secure expiry_time name value]\n\n";
138
139/* The epoch is Jan 1, 1970. When there is difficulty in representing future
140 * dates, use the (by far) most likely last representable time in Jan 19, 2038.
141 */
142static struct tm cookies_epoch_tm = {0, 0, 0, 1, 0, 70, 0, 0, 0, 0, 0};
144
145/*
146 * Forward declarations
147 */
148
149static CookieControlAction Cookies_control_check_domain(const char *domain);
150static int Cookie_control_init(void);
151static void Cookies_add_cookie(CookieData_t *cookie);
152static int Cookies_cmp(const void *a, const void *b);
153
154/*
155 * Compare function for searching a domain node
156 */
157static int Domain_node_cmp(const void *v1, const void *v2)
158{
159 const DomainNode *n1 = v1, *n2 = v2;
160
161 return dStrAsciiCasecmp(n1->domain, n2->domain);
162}
163
164/*
165 * Compare function for searching a domain node by domain
166 */
167static int Domain_node_by_domain_cmp(const void *v1, const void *v2)
168{
169 const DomainNode *node = v1;
170 const char *domain = v2;
171
172 return dStrAsciiCasecmp(node->domain, domain);
173}
174
175/*
176 * Delete node. This will not free any cookies that might be in node->cookies.
177 */
178static void Cookies_delete_node(DomainNode *node)
179{
180 dList_remove(domains, node);
181 dFree(node->domain);
182 dList_free(node->cookies);
183 dFree(node);
184}
185
186/*
187 * Return a file pointer. If the file doesn't exist, try to create it,
188 * with the optional 'init_str' as its content.
189 */
190static FILE *Cookies_fopen(const char *filename, const char *mode,
191 const char *init_str)
192{
193 FILE *F_in;
194 int fd, rc;
195
196 if ((F_in = fopen(filename, mode)) == NULL) {
197 /* Create the file */
198 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
199 if (fd != -1) {
200 if (init_str) {
201 rc = write(fd, init_str, strlen(init_str));
202 if (rc == -1) {
203 MSG("Cookies: Could not write initial string to file %s: %s\n",
204 filename, dStrerror(errno));
205 }
206 }
207 close(fd);
208
209 MSG("Created file: %s\n", filename);
210 F_in = fopen(filename, mode);
211 } else {
212 MSG("Could not create file: %s!\n", filename);
213 }
214 }
215
216 if (F_in) {
217 /* set close on exec */
218 fcntl(fileno(F_in), F_SETFD, FD_CLOEXEC | fcntl(fileno(F_in), F_GETFD));
219 }
220
221 return F_in;
222}
223
224static void Cookies_free_cookie(CookieData_t *cookie)
225{
226 dFree(cookie->name);
227 dFree(cookie->value);
228 dFree(cookie->domain);
229 dFree(cookie->path);
230 dFree(cookie);
231}
232
233static void Cookies_tm_init(struct tm *tm)
234{
235 tm->tm_sec = cookies_epoch_tm.tm_sec;
236 tm->tm_min = cookies_epoch_tm.tm_min;
237 tm->tm_hour = cookies_epoch_tm.tm_hour;
238 tm->tm_mday = cookies_epoch_tm.tm_mday;
239 tm->tm_mon = cookies_epoch_tm.tm_mon;
240 tm->tm_year = cookies_epoch_tm.tm_year;
241 tm->tm_isdst = cookies_epoch_tm.tm_isdst;
242}
243
244/*
245 * Read in cookies from 'stream' (cookies.txt)
246 */
247static void Cookies_load_cookies(FILE *stream)
248{
249 char line[LINE_MAXLEN];
250
252 domains = dList_new(32);
253
254 /* Get all lines in the file */
255 while (!feof(stream)) {
256 line[0] = '\0';
257 if ((fgets(line, LINE_MAXLEN, stream) == NULL) && ferror(stream)) {
258 MSG("Error while reading from cookies.txt: %s\n", dStrerror(errno));
259 break; /* bail out */
260 }
261
262 /* Remove leading and trailing whitespaces */
263 dStrstrip(line);
264
265 if ((line[0] != '\0') && (line[0] != '#')) {
266 /*
267 * Split the row into pieces using a tab as the delimiter.
268 * pieces[0] The domain name
269 * pieces[1] TRUE/FALSE: is the domain a suffix, or a full domain?
270 * pieces[2] The path
271 * pieces[3] TRUE/FALSE: is the cookie for secure use only?
272 * pieces[4] Timestamp of expire date
273 * pieces[5] Name of the cookie
274 * pieces[6] Value of the cookie
275 */
276 CookieControlAction action;
277 char *piece;
278 char *line_marker = line;
279 CookieData_t *cookie = dNew0(CookieData_t, 1);
280
281 cookie->session_only = FALSE;
282 cookie->domain = dStrdup(dStrsep(&line_marker, "\t"));
283 piece = dStrsep(&line_marker, "\t");
284 if (piece != NULL && piece[0] == 'F')
285 cookie->host_only = TRUE;
286 cookie->path = dStrdup(dStrsep(&line_marker, "\t"));
287 piece = dStrsep(&line_marker, "\t");
288 if (piece != NULL && piece[0] == 'T')
289 cookie->secure = TRUE;
290 piece = dStrsep(&line_marker, "\t");
291 if (piece != NULL) {
292 /* There is some problem with simply putting the maximum value
293 * into tm.tm_sec (although a value close to it works).
294 */
295 long seconds = strtol(piece, NULL, 10);
296 struct tm tm;
297 Cookies_tm_init(&tm);
298 tm.tm_min += seconds / 60;
299 tm.tm_sec += seconds % 60;
300 cookie->expires_at = mktime(&tm);
301 } else {
302 cookie->expires_at = (time_t) -1;
303 }
304 cookie->name = dStrdup(dStrsep(&line_marker, "\t"));
305 cookie->value = dStrdup(line_marker ? line_marker : "");
306
307 if (!cookie->domain || cookie->domain[0] == '\0' ||
308 !cookie->path || cookie->path[0] != '/' ||
309 !cookie->name || !cookie->value) {
310 MSG("Malformed line in cookies.txt file!\n");
311 Cookies_free_cookie(cookie);
312 continue;
313 }
314
315 action = Cookies_control_check_domain(cookie->domain);
316 if (action == COOKIE_DENY) {
317 Cookies_free_cookie(cookie);
318 continue;
319 } else if (action == COOKIE_ACCEPT_SESSION) {
320 cookie->session_only = TRUE;
321 }
322
323 /* Save cookie in memory */
324 Cookies_add_cookie(cookie);
325 }
326 }
327 MSG("Cookies loaded: %d.\n", dList_length(all_cookies));
328}
329
330/*
331 * Initialize the cookies module
332 * (The 'disabled' variable is writeable only within Cookies_init)
333 */
334static void Cookies_init(void)
335{
336 char *filename;
337#ifndef HAVE_LOCKF
338 struct flock lck;
339#endif
340 struct tm future_tm = {7, 14, 3, 19, 0, 138, 0, 0, 0, 0, 0};
341
342 /* Default setting */
343 disabled = TRUE;
344
346 cookies_future_time = mktime(&future_tm);
347
348 /* Read and parse the cookie control file (cookiesrc) */
349 if (Cookie_control_init() != 0) {
350 MSG("Disabling cookies.\n");
351 return;
352 }
353
354 /* Get a stream for the cookies file */
355 filename = dStrconcat(dGethomedir(), "/.dillo/cookies.txt", NULL);
357
358 dFree(filename);
359
360 if (!file_stream) {
361 MSG("ERROR: Can't open ~/.dillo/cookies.txt; disabling cookies\n");
362 return;
363 }
364
365 /* Try to get a lock from the file descriptor */
366#ifdef HAVE_LOCKF
367 disabled = (lockf(fileno(file_stream), F_TLOCK, 0) == -1);
368#else /* POSIX lock */
369 lck.l_start = 0; /* start at beginning of file */
370 lck.l_len = 0; /* lock entire file */
371 lck.l_type = F_WRLCK;
372 lck.l_whence = SEEK_SET; /* absolute offset */
373
374 disabled = (fcntl(fileno(file_stream), F_SETLK, &lck) == -1);
375#endif
376 if (disabled) {
377 MSG("The cookies file has a file lock; disabling cookies!\n");
378 fclose(file_stream);
379 return;
380 }
381 MSG("Enabling cookies as per cookiesrc...\n");
382
384}
385
386/*
387 * Flush cookies to disk and free all the memory allocated.
388 */
389static void Cookies_save_and_free(void)
390{
391 int i, fd, saved = 0;
392 DomainNode *node;
393 CookieData_t *cookie;
394 time_t now;
395
396#ifndef HAVE_LOCKF
397 struct flock lck;
398#endif
399
400 if (disabled)
401 return;
402
403 now = time(NULL);
404
405 rewind(file_stream);
406 fd = fileno(file_stream);
407 if (ftruncate(fd, 0) == -1)
408 MSG("Cookies: Truncate file stream failed: %s\n", dStrerror(errno));
409 fprintf(file_stream, "%s", cookies_txt_header_str);
410
411 /* Iterate cookies per domain, saving and freeing */
412 while ((node = dList_nth_data(domains, 0))) {
413 for (i = 0; (cookie = dList_nth_data(node->cookies, i)); ++i) {
414 if (!cookie->session_only && difftime(cookie->expires_at, now) > 0) {
415 int len;
416 char buf[LINE_MAXLEN];
417
418 len = snprintf(buf, LINE_MAXLEN, "%s\t%s\t%s\t%s\t%ld\t%s\t%s\n",
419 cookie->domain,
420 cookie->host_only ? "FALSE" : "TRUE",
421 cookie->path,
422 cookie->secure ? "TRUE" : "FALSE",
423 (long) difftime(cookie->expires_at,
425 cookie->name,
426 cookie->value);
427 if (len < LINE_MAXLEN) {
428 fprintf(file_stream, "%s", buf);
429 saved++;
430 } else {
431 MSG("Not saving overly long cookie for %s.\n", cookie->domain);
432 }
433 }
434 Cookies_free_cookie(cookie);
435 }
437 }
440
441#ifdef HAVE_LOCKF
442 lockf(fd, F_ULOCK, 0);
443#else /* POSIX file lock */
444 lck.l_start = 0; /* start at beginning of file */
445 lck.l_len = 0; /* lock entire file */
446 lck.l_type = F_UNLCK;
447 lck.l_whence = SEEK_SET; /* absolute offset */
448
449 fcntl(fileno(file_stream), F_SETLKW, &lck);
450#endif
451 fclose(file_stream);
452
453 MSG("Cookies saved: %d.\n", saved);
454}
455
456/*
457 * Month parsing
458 */
459static bool_t Cookies_get_month(struct tm *tm, const char **str)
460{
461 static const char *const months[] =
462 { "Jan", "Feb", "Mar",
463 "Apr", "May", "Jun",
464 "Jul", "Aug", "Sep",
465 "Oct", "Nov", "Dec"
466 };
467 int i;
468
469 for (i = 0; i < 12; i++) {
470 if (!dStrnAsciiCasecmp(months[i], *str, 3)) {
471 _MSG("Found month: %s\n", months[i]);
472 tm->tm_mon = i;
473 *str += 3;
474 return TRUE;
475 }
476 }
477 return FALSE;
478}
479
480/*
481 * As seen in the production below, it's just one digit or two.
482 * Return the value, or -1 if no proper value found.
483 */
484static int Cookies_get_timefield(const char **str)
485{
486 int n;
487 const char *s = *str;
488
489 if (!dIsdigit(*s))
490 return -1;
491
492 n = *(s++) - '0';
493 if (dIsdigit(*s)) {
494 n *= 10;
495 n += *(s++) - '0';
496 if (dIsdigit(*s))
497 return -1;
498 }
499 *str = s;
500 return n;
501}
502
503/*
504 * Time parsing: 'time-field ":" time-field ":" time-field'
505 * 'time-field = 1*2DIGIT'
506 */
507static bool_t Cookies_get_time(struct tm *tm, const char **str)
508{
509 const char *s = *str;
510
511 if ((tm->tm_hour = Cookies_get_timefield(&s)) == -1)
512 return FALSE;
513
514 if (*(s++) != ':')
515 return FALSE;
516
517 if ((tm->tm_min = Cookies_get_timefield(&s)) == -1)
518 return FALSE;
519
520 if (*(s++) != ':')
521 return FALSE;
522
523 if ((tm->tm_sec = Cookies_get_timefield(&s)) == -1)
524 return FALSE;
525
526 *str = s;
527 return TRUE;
528}
529
530/*
531 * Day parsing: "day-of-month = 1*2DIGIT"
532 */
533static bool_t Cookies_get_day(struct tm *tm, const char **str)
534{
535 const char *s = *str;
536
537 if ((tm->tm_mday = Cookies_get_timefield(&s)) == -1)
538 return FALSE;
539
540 *str = s;
541 return TRUE;
542}
543
544/*
545 * Date parsing: "year = 2*4DIGIT"
546 */
547static bool_t Cookies_get_year(struct tm *tm, const char **str)
548{
549 int n;
550 const char *s = *str;
551
552 if (dIsdigit(*s))
553 n = *(s++) - '0';
554 else
555 return FALSE;
556 if (dIsdigit(*s)) {
557 n *= 10;
558 n += *(s++) - '0';
559 } else
560 return FALSE;
561 if (dIsdigit(*s)) {
562 n *= 10;
563 n += *(s++) - '0';
564 }
565 if (dIsdigit(*s)) {
566 n *= 10;
567 n += *(s++) - '0';
568 }
569 if (dIsdigit(*s)) {
570 /* Sorry, users of prehistoric software in the year 10000! */
571 return FALSE;
572 }
573 if (n >= 70 && n <= 99)
574 n += 1900;
575 else if (n <= 69)
576 n += 2000;
577
578 tm->tm_year = n - 1900;
579
580 *str = s;
581 return TRUE;
582}
583
584/*
585 * As given in RFC 6265.
586 */
588{
589 return (c == '\x09' ||
590 (c >= '\x20' && c <= '\x2F') ||
591 (c >= '\x3B' && c <= '\x40') ||
592 (c >= '\x5B' && c <= '\x60') ||
593 (c >= '\x7B' && c <= '\x7E'));
594}
595
596/*
597 * Parse date string.
598 *
599 * A true nightmare of date formats appear in cookies, so one basically
600 * has to paw through the soup and look for anything that looks sufficiently
601 * like any of the date fields.
602 *
603 * Return a pointer to a struct tm, or NULL on error.
604 */
605static struct tm *Cookies_parse_date(const char *date)
606{
607 bool_t found_time = FALSE, found_day = FALSE, found_month = FALSE,
608 found_year = FALSE, matched;
609 struct tm *tm = dNew0(struct tm, 1);
610 const char *s = date;
611
612 while (*s) {
613 matched = FALSE;
614
615 if (!found_time)
616 matched = found_time = Cookies_get_time(tm, &s);
617 if (!matched && !found_day)
618 matched = found_day = Cookies_get_day(tm, &s);
619 if (!matched && !found_month)
620 matched = found_month = Cookies_get_month(tm, &s);
621 if (!matched && !found_year)
622 matched = found_year = Cookies_get_year(tm, &s);
623 while (*s && !Cookies_date_delim(*s))
624 s++;
625 while (*s && Cookies_date_delim(*s))
626 s++;
627 }
628 if (!found_time || !found_day || !found_month || !found_year) {
629 dFree(tm);
630 tm = NULL;
631 MSG("In date \"%s\", format not understood.\n", date);
632 }
633
634 /* Error checks. This may be overkill.
635 *
636 * RFC 6265: "Note that leap seconds cannot be represented in this
637 * syntax." I'm not sure whether that's good, but that's what it says.
638 */
639 if (tm &&
640 !(tm->tm_mday > 0 && tm->tm_mday < 32 && tm->tm_mon >= 0 &&
641 tm->tm_mon < 12 && tm->tm_year >= 0 && tm->tm_hour >= 0 &&
642 tm->tm_hour < 24 && tm->tm_min >= 0 && tm->tm_min < 60 &&
643 tm->tm_sec >= 0 && tm->tm_sec < 60)) {
644 MSG("Date \"%s\" values not in range.\n", date);
645 dFree(tm);
646 tm = NULL;
647 }
648
649 return tm;
650}
651
652/*
653 * Find the least recently used cookie among those in the provided list.
654 */
655static CookieData_t *Cookies_get_LRU(Dlist *cookies)
656{
657 int i, n = dList_length(cookies);
658 CookieData_t *lru = dList_nth_data(cookies, 0);
659
660 for (i = 1; i < n; i++) {
661 CookieData_t *curr = dList_nth_data(cookies, i);
662
663 if (curr->last_used < lru->last_used)
664 lru = curr;
665 }
666 return lru;
667}
668
669/*
670 * Delete expired cookies.
671 * If node is given, only check those cookies.
672 * Note that nodes can disappear if all of their cookies were expired.
673 *
674 * Return the number of cookies that were expired.
675 */
676static int Cookies_rm_expired_cookies(DomainNode *node)
677{
678 Dlist *cookies = node ? node->cookies : all_cookies;
679 int removed = 0;
680 int i = 0, n = dList_length(cookies);
681 time_t now = time(NULL);
682
683 while (i < n) {
684 CookieData_t *c = dList_nth_data(cookies, i);
685
686 if (difftime(c->expires_at, now) < 0) {
687 DomainNode *currnode = node ? node :
689 dList_remove(currnode->cookies, c);
690 if (dList_length(currnode->cookies) == 0)
691 Cookies_delete_node(currnode);
694 n--;
695 removed++;
696 } else {
697 i++;
698 }
699 }
700 return removed;
701}
702
703/*
704 * There are too many cookies. Choose one to remove and delete.
705 * If node is given, select from among its cookies only.
706 */
707static void Cookies_too_many(DomainNode *node)
708{
709 CookieData_t *lru = Cookies_get_LRU(node ? node->cookies : all_cookies);
710
711 MSG("Too many cookies! "
712 "Removing LRU cookie for \'%s\': \'%s=%s\'\n", lru->domain,
713 lru->name, lru->value);
714 if (!node)
716
717 dList_remove(node->cookies, lru);
720 if (dList_length(node->cookies) == 0)
722}
723
724static void Cookies_add_cookie(CookieData_t *cookie)
725{
726 Dlist *domain_cookies;
727 CookieData_t *c;
728 DomainNode *node;
729
731 domain_cookies = (node) ? node->cookies : NULL;
732
733 if (domain_cookies) {
734 /* Remove any cookies with the same name, path, and host-only values. */
735 while ((c = dList_find_custom(domain_cookies, cookie, Cookies_cmp))) {
736 dList_remove(domain_cookies, c);
739 }
740 }
741
742 if ((cookie->expires_at == (time_t) -1) ||
743 (difftime(cookie->expires_at, time(NULL)) <= 0)) {
744 /*
745 * Don't add an expired cookie. Whether expiring now == expired, exactly,
746 * is arguable, but we definitely do not want to add a Max-Age=0 cookie.
747 */
748 _MSG("Goodbye, cookie %s=%s d:%s p:%s\n", cookie->name,
749 cookie->value, cookie->domain, cookie->path);
750 Cookies_free_cookie(cookie);
751 } else {
752 if (domain_cookies && dList_length(domain_cookies) >=MAX_DOMAIN_COOKIES){
753 int removed = Cookies_rm_expired_cookies(node);
754
755 if (removed == 0) {
756 Cookies_too_many(node);
757 } else if (removed >= MAX_DOMAIN_COOKIES) {
758 /* So many were removed that the node might have been deleted. */
759 node = dList_find_sorted(domains, cookie->domain,
761 domain_cookies = (node) ? node->cookies : NULL;
762 }
763 }
765 if (Cookies_rm_expired_cookies(NULL) == 0) {
766 Cookies_too_many(NULL);
767 } else if (domain_cookies) {
768 /* Our own node might have just been deleted. */
769 node = dList_find_sorted(domains, cookie->domain,
771 domain_cookies = (node) ? node->cookies : NULL;
772 }
773 }
774
775 cookie->last_used = cookies_use_counter++;
776
777 /* Actually add the cookie! */
778 dList_append(all_cookies, cookie);
779
780 if (!domain_cookies) {
781 domain_cookies = dList_new(5);
782 dList_append(domain_cookies, cookie);
783 node = dNew(DomainNode, 1);
784 node->domain = dStrdup(cookie->domain);
785 node->cookies = domain_cookies;
787 } else {
788 dList_append(domain_cookies, cookie);
789 }
790 }
791 if (domain_cookies && (dList_length(domain_cookies) == 0))
793}
794
795/*
796 * Return the attribute that is present at *cookie_str.
797 */
798static char *Cookies_parse_attr(char **cookie_str)
799{
800 char *str;
801 uint_t len;
802
803 while (dIsspace(**cookie_str))
804 (*cookie_str)++;
805
806 str = *cookie_str;
807 /* find '=' at end of attr, ';' after attr/val pair, '\0' end of string */
808 len = strcspn(str, "=;");
809 *cookie_str += len;
810
811 while (len && (str[len - 1] == ' ' || str[len - 1] == '\t'))
812 len--;
813 return dStrndup(str, len);
814}
815
816/*
817 * Get the value in *cookie_str.
818 */
819static char *Cookies_parse_value(char **cookie_str)
820{
821 uint_t len;
822 char *str;
823
824 if (**cookie_str == '=') {
825 (*cookie_str)++;
826 while (dIsspace(**cookie_str))
827 (*cookie_str)++;
828
829 str = *cookie_str;
830 /* finds ';' after attr/val pair or '\0' at end of string */
831 len = strcspn(str, ";");
832 *cookie_str += len;
833
834 while (len && (str[len - 1] == ' ' || str[len - 1] == '\t'))
835 len--;
836 } else {
837 str = *cookie_str;
838 len = 0;
839 }
840 return dStrndup(str, len);
841}
842
843/*
844 * Advance past any value
845 */
846static void Cookies_eat_value(char **cookie_str)
847{
848 if (**cookie_str == '=')
849 *cookie_str += strcspn(*cookie_str, ";");
850}
851
852/*
853 * Return the number of seconds by which our clock is ahead of the server's
854 * clock.
855 */
856static double Cookies_server_timediff(const char *server_date)
857{
858 double ret = 0;
859
860 if (server_date) {
861 struct tm *server_tm = Cookies_parse_date(server_date);
862
863 if (server_tm) {
864 time_t server_time = mktime(server_tm);
865
866 if (server_time != (time_t) -1)
867 ret = difftime(time(NULL), server_time);
868 dFree(server_tm);
869 }
870 }
871 return ret;
872}
873
874static void Cookies_unquote_string(char *str)
875{
876 if (str && str[0] == '\"') {
877 uint_t len = strlen(str);
878
879 if (len > 1 && str[len - 1] == '\"') {
880 str[len - 1] = '\0';
881 while ((*str = str[1]))
882 str++;
883 }
884 }
885}
886
887/*
888 * Parse cookie. A cookie might look something like:
889 * "Name=Val; Domain=example.com; Max-Age=3600; HttpOnly"
890 */
891static CookieData_t *Cookies_parse(char *cookie_str, const char *server_date)
892{
893 CookieData_t *cookie = NULL;
894 char *str = cookie_str;
895 bool_t first_attr = TRUE;
896 bool_t max_age = FALSE;
897 bool_t expires = FALSE;
898
899 /* Iterate until there is nothing left of the string */
900 while (*str) {
901 char *attr;
902 char *value;
903
904 /* Get attribute */
905 attr = Cookies_parse_attr(&str);
906
907 /* Get the value for the attribute and store it */
908 if (first_attr) {
909 time_t now;
910 struct tm *tm;
911
912 if (*str != '=' || *attr == '\0') {
913 /* disregard nameless cookie */
914 dFree(attr);
915 return NULL;
916 }
917 cookie = dNew0(CookieData_t, 1);
918 cookie->name = attr;
919 cookie->value = Cookies_parse_value(&str);
920
921 /* let's arbitrarily initialise with a year for now */
922 now = time(NULL);
923 tm = gmtime(&now);
924 ++tm->tm_year;
925 cookie->expires_at = mktime(tm);
926 if (cookie->expires_at == (time_t) -1)
927 cookie->expires_at = cookies_future_time;
928 } else if (dStrAsciiCasecmp(attr, "Path") == 0) {
929 value = Cookies_parse_value(&str);
930 dFree(cookie->path);
931 cookie->path = value;
932 } else if (dStrAsciiCasecmp(attr, "Domain") == 0) {
933 value = Cookies_parse_value(&str);
934 dFree(cookie->domain);
935 cookie->domain = value;
936 } else if (dStrAsciiCasecmp(attr, "Max-Age") == 0) {
937 value = Cookies_parse_value(&str);
938 if (dIsdigit(*value) || *value == '-') {
939 long age;
940 time_t now = time(NULL);
941 struct tm *tm = gmtime(&now);
942
943 errno = 0;
944 age = (*value == '-') ? 0 : strtol(value, NULL, 10);
945
946 if (errno == ERANGE ||
947 (age > 0 && (age > INT_MAX - tm->tm_sec))) {
948 /* let's not overflow */
949 tm->tm_sec = INT_MAX;
950 } else {
951 tm->tm_sec += age;
952 }
953 cookie->expires_at = mktime(tm);
954 if (age > 0 && cookie->expires_at == (time_t) -1) {
955 cookie->expires_at = cookies_future_time;
956 }
957 _MSG("Cookie to expire at %s", ctime(&cookie->expires_at));
958 expires = max_age = TRUE;
959 }
960 dFree(value);
961 } else if (dStrAsciiCasecmp(attr, "Expires") == 0) {
962 if (!max_age) {
963 struct tm *tm;
964
965 value = Cookies_parse_value(&str);
967 _MSG("Expires attribute gives %s\n", value);
968 tm = Cookies_parse_date(value);
969 if (tm) {
970 tm->tm_sec += Cookies_server_timediff(server_date);
971 cookie->expires_at = mktime(tm);
972 if (cookie->expires_at == (time_t) -1 && tm->tm_year >= 138) {
973 /* Just checking tm_year does not ensure that the problem was
974 * inability to represent a distant date...
975 */
976 cookie->expires_at = cookies_future_time;
977 }
978 _MSG("Cookie to expire at %s", ctime(&cookie->expires_at));
979 dFree(tm);
980 } else {
981 cookie->expires_at = (time_t) -1;
982 }
983 expires = TRUE;
984 dFree(value);
985 } else {
986 Cookies_eat_value(&str);
987 }
988 } else if (dStrAsciiCasecmp(attr, "Secure") == 0) {
989 cookie->secure = TRUE;
990 Cookies_eat_value(&str);
991 } else if (dStrAsciiCasecmp(attr, "HttpOnly") == 0) {
992 Cookies_eat_value(&str);
993 } else {
994 MSG("Cookie contains unknown attribute: '%s'\n", attr);
995 Cookies_eat_value(&str);
996 }
997
998 if (first_attr)
999 first_attr = FALSE;
1000 else
1001 dFree(attr);
1002
1003 if (*str == ';')
1004 str++;
1005 }
1006 cookie->session_only = expires == FALSE;
1007 return cookie;
1008}
1009
1010/*
1011 * Compare cookies by host_only, name, and path. Return 0 if equal.
1012 */
1013static int Cookies_cmp(const void *a, const void *b)
1014{
1015 const CookieData_t *ca = a, *cb = b;
1016
1017 return (ca->host_only != cb->host_only) ||
1018 (strcmp(ca->name, cb->name) != 0) ||
1019 (strcmp(ca->path, cb->path) != 0);
1020}
1021
1022/*
1023 * Is the domain an IP address?
1024 */
1025static bool_t Cookies_domain_is_ip(const char *domain)
1026{
1027 uint_t len;
1028
1029 if (!domain)
1030 return FALSE;
1031
1032 len = strlen(domain);
1033
1034 if (len == strspn(domain, "0123456789.")) {
1035 _MSG("an IPv4 address\n");
1036 return TRUE;
1037 }
1038 if (strchr(domain, ':') &&
1039 (len == strspn(domain, "0123456789abcdefABCDEF:."))) {
1040 /* The precise format is shown in section 3.2.2 of rfc 3986 */
1041 MSG("an IPv6 address\n");
1042 return TRUE;
1043 }
1044 return FALSE;
1045}
1046
1047/*
1048 * Check whether url_path path-matches cookie_path
1049 *
1050 * Note different user agents apparently vary in path-matching behaviour,
1051 * but this is the recommended method at the moment.
1052 */
1053static bool_t Cookies_path_matches(const char *url_path,
1054 const char *cookie_path)
1055{
1056 bool_t ret = TRUE;
1057
1058 if (!url_path || !cookie_path) {
1059 ret = FALSE;
1060 } else {
1061 uint_t c_len = strlen(cookie_path);
1062 uint_t u_len = strlen(url_path);
1063
1064 ret = (!strncmp(cookie_path, url_path, c_len) &&
1065 ((c_len == u_len) ||
1066 (c_len > 0 && cookie_path[c_len - 1] == '/') ||
1067 (url_path[c_len] == '/')));
1068 }
1069 return ret;
1070}
1071
1072/*
1073 * If cookie path is not properly set, remedy that.
1074 */
1075static void Cookies_validate_path(CookieData_t *cookie, const char *url_path)
1076{
1077 if (!cookie->path || cookie->path[0] != '/') {
1078 dFree(cookie->path);
1079
1080 if (url_path) {
1081 uint_t len = strlen(url_path);
1082
1083 while (len && url_path[len] != '/')
1084 len--;
1085 cookie->path = dStrndup(url_path, len ? len : 1);
1086 } else {
1087 cookie->path = dStrdup("/");
1088 }
1089 }
1090}
1091
1092/*
1093 * Check whether host name A domain-matches host name B.
1094 */
1095static bool_t Cookies_domain_matches(char *A, char *B)
1096{
1097 int diff;
1098
1099 if (!A || !*A || !B || !*B)
1100 return FALSE;
1101
1102 if (*B == '.')
1103 B++;
1104
1105 /* Should we concern ourselves with trailing dots in matching (here or
1106 * elsewhere)? The HTTP State people have found that most user agents
1107 * don't, so: No.
1108 */
1109
1110 if (!dStrAsciiCasecmp(A, B))
1111 return TRUE;
1112
1113 if (Cookies_domain_is_ip(B))
1114 return FALSE;
1115
1116 diff = strlen(A) - strlen(B);
1117
1118 if (diff > 0) {
1119 /* B is the tail of A, and the match is preceded by a '.' */
1120 return (dStrAsciiCasecmp(A + diff, B) == 0 && A[diff - 1] == '.');
1121 } else {
1122 return FALSE;
1123 }
1124}
1125
1126/*
1127 * Based on the host, how many internal dots do we need in a cookie domain
1128 * to make it valid? e.g., "org" is not on the list, so dillo.org is a safe
1129 * cookie domain, but "uk" is on the list, so ac.uk is not safe.
1130 *
1131 * This is imperfect, but it's something. Specifically, checking for these
1132 * TLDs is the solution that Konqueror used once upon a time, according to
1133 * reports.
1134 */
1136{
1137 uint_t ret = 1;
1138
1139 if (host) {
1140 int start, after, tld_len;
1141
1142 /* We may be able to trust the format of the host string more than
1143 * I am here. Trailing dots and no dots are real possibilities, though.
1144 */
1145 after = strlen(host);
1146 if (after > 0 && host[after - 1] == '.')
1147 after--;
1148 start = after;
1149 while (start > 0 && host[start - 1] != '.')
1150 start--;
1151 tld_len = after - start;
1152
1153 if (tld_len > 0) {
1154 /* These TLDs were chosen by examining the current publicsuffix list
1155 * in October 2014 and picking out those where it was simplest for
1156 * them to describe the situation by beginning with a "*.[tld]" rule
1157 * or every rule was "[something].[tld]".
1158 */
1159 const char *const tlds[] = {"bd","bn","ck","cy","er","fj","fk",
1160 "gu","il","jm","ke","kh","kw","mm","mz",
1161 "ni","np","pg","ye","za","zm","zw"};
1162 uint_t i, tld_num = sizeof(tlds) / sizeof(tlds[0]);
1163
1164 for (i = 0; i < tld_num; i++) {
1165 if (strlen(tlds[i]) == (uint_t) tld_len &&
1166 !dStrnAsciiCasecmp(tlds[i], host + start, tld_len)) {
1167 _MSG("TLD code matched %s\n", tlds[i]);
1168 ret++;
1169 break;
1170 }
1171 }
1172 }
1173 }
1174 return ret;
1175}
1176
1177/*
1178 * Validate cookies domain against some security checks.
1179 */
1180static bool_t Cookies_validate_domain(CookieData_t *cookie, char *host)
1181{
1182 uint_t i, internal_dots;
1183
1184 if (!cookie->domain) {
1185 cookie->domain = dStrdup(host);
1186 cookie->host_only = TRUE;
1187 return TRUE;
1188 }
1189
1190 if (!Cookies_domain_matches(host, cookie->domain))
1191 return FALSE;
1192
1193 internal_dots = 0;
1194 for (i = 1; i < strlen(cookie->domain) - 1; i++) {
1195 if (cookie->domain[i] == '.')
1196 internal_dots++;
1197 }
1198
1199 /* All of this dots business is a weak hack.
1200 * TODO: accept the publicsuffix.org list as an optional external file.
1201 */
1202 if (internal_dots < Cookies_internal_dots_required(host)) {
1203 MSG("not enough dots in %s\n", cookie->domain);
1204 return FALSE;
1205 }
1206
1207 _MSG("host %s and domain %s is all right\n", host, cookie->domain);
1208 return TRUE;
1209}
1210
1211/*
1212 * Set the value corresponding to the cookie string
1213 * Return value: 0 set OK, -1 disabled, -2 denied, -3 rejected.
1214 */
1215static int Cookies_set(char *cookie_string, char *url_host,
1216 char *url_path, char *server_date)
1217{
1218 CookieControlAction action;
1219 CookieData_t *cookie;
1220 int ret = -1;
1221
1222 if (disabled)
1223 return ret;
1224
1225 action = Cookies_control_check_domain(url_host);
1226 if (action == COOKIE_DENY) {
1227 MSG("denied SET for %s\n", url_host);
1228 ret = -2;
1229
1230 } else {
1231 MSG("%s SETTING: %s\n", url_host, cookie_string);
1232 ret = -3;
1233 if ((cookie = Cookies_parse(cookie_string, server_date))) {
1234 if (Cookies_validate_domain(cookie, url_host)) {
1235 Cookies_validate_path(cookie, url_path);
1236 if (action == COOKIE_ACCEPT_SESSION)
1237 cookie->session_only = TRUE;
1238 Cookies_add_cookie(cookie);
1239 ret = 0;
1240 } else {
1241 MSG("Rejecting cookie for domain %s from host %s path %s\n",
1242 cookie->domain, url_host, url_path);
1243 Cookies_free_cookie(cookie);
1244 }
1245 }
1246 }
1247
1248 return ret;
1249}
1250
1251/*
1252 * Compare the cookie with the supplied data to see whether it matches
1253 */
1254static bool_t Cookies_match(CookieData_t *cookie, const char *url_path,
1255 bool_t host_only_val, bool_t is_tls)
1256{
1257 if (cookie->host_only != host_only_val)
1258 return FALSE;
1259
1260 /* Insecure cookies match both secure and insecure urls, secure
1261 cookies match only secure urls */
1262 if (cookie->secure && !is_tls)
1263 return FALSE;
1264
1265 if (!Cookies_path_matches(url_path, cookie->path))
1266 return FALSE;
1267
1268 /* It's a match */
1269 return TRUE;
1270}
1271
1272static void Cookies_add_matching_cookies(const char *domain,
1273 const char *url_path,
1274 bool_t host_only_val,
1275 Dlist *matching_cookies,
1276 bool_t is_tls)
1277{
1278 DomainNode *node = dList_find_sorted(domains, domain,
1280 if (node) {
1281 int i;
1282 CookieData_t *cookie;
1283 Dlist *domain_cookies = node->cookies;
1284
1285 for (i = 0; (cookie = dList_nth_data(domain_cookies, i)); ++i) {
1286 /* Remove expired cookie. */
1287 if (difftime(cookie->expires_at, time(NULL)) < 0) {
1288 _MSG("Goodbye, expired cookie %s=%s d:%s p:%s\n", cookie->name,
1289 cookie->value, cookie->domain, cookie->path);
1290 dList_remove(domain_cookies, cookie);
1292 Cookies_free_cookie(cookie);
1293 --i; continue;
1294 }
1295 /* Check if the cookie matches the requesting URL */
1296 if (Cookies_match(cookie, url_path, host_only_val, is_tls)) {
1297 int j;
1298 CookieData_t *curr;
1299 uint_t path_length = strlen(cookie->path);
1300
1301 cookie->last_used = cookies_use_counter;
1302
1303 /* Longest cookies go first */
1304 for (j = 0;
1305 (curr = dList_nth_data(matching_cookies, j)) &&
1306 strlen(curr->path) >= path_length;
1307 j++) ;
1308 dList_insert_pos(matching_cookies, cookie, j);
1309 }
1310 }
1311
1312 if (dList_length(domain_cookies) == 0)
1313 Cookies_delete_node(node);
1314 }
1315}
1316
1317/*
1318 * Return a string that contains all relevant cookies as headers.
1319 */
1320static char *Cookies_get(char *url_host, char *url_path,
1321 char *url_scheme)
1322{
1323 char *domain_str, *str;
1324 CookieData_t *cookie;
1325 Dlist *matching_cookies;
1326 bool_t is_tls, is_ip_addr, host_only_val;
1327
1328 Dstr *cookie_dstring;
1329 int i;
1330
1331 if (disabled)
1332 return dStrdup("");
1333
1334 matching_cookies = dList_new(8);
1335
1336 /* Check if the protocol is secure or not */
1337 is_tls = (!dStrAsciiCasecmp(url_scheme, "https"));
1338
1339 is_ip_addr = Cookies_domain_is_ip(url_host);
1340
1341 /* If a cookie is set that lacks a Domain attribute, its domain is set to
1342 * the server's host and the host_only flag is set for that cookie. Such a
1343 * cookie can only be sent back to that host. Cookies with Domain attrs do
1344 * not have the host_only flag set, and may be sent to subdomains. Domain
1345 * attrs can have leading dots, which should be ignored for matching
1346 * purposes.
1347 */
1348 host_only_val = FALSE;
1349 if (!is_ip_addr) {
1350 /* e.g., sub.example.com set a cookie with domain ".sub.example.com". */
1351 domain_str = dStrconcat(".", url_host, NULL);
1352 Cookies_add_matching_cookies(domain_str, url_path, host_only_val,
1353 matching_cookies, is_tls);
1354 dFree(domain_str);
1355 }
1356 host_only_val = TRUE;
1357 /* e.g., sub.example.com set a cookie with no domain attribute. */
1358 Cookies_add_matching_cookies(url_host, url_path, host_only_val,
1359 matching_cookies, is_tls);
1360 host_only_val = FALSE;
1361 /* e.g., sub.example.com set a cookie with domain "sub.example.com". */
1362 Cookies_add_matching_cookies(url_host, url_path, host_only_val,
1363 matching_cookies, is_tls);
1364
1365 if (!is_ip_addr) {
1366 for (domain_str = strchr(url_host+1, '.');
1367 domain_str != NULL && *domain_str;
1368 domain_str = strchr(domain_str+1, '.')) {
1369 /* e.g., sub.example.com set a cookie with domain ".example.com". */
1370 Cookies_add_matching_cookies(domain_str, url_path, host_only_val,
1371 matching_cookies, is_tls);
1372 if (domain_str[1]) {
1373 domain_str++;
1374 /* e.g., sub.example.com set a cookie with domain "example.com".*/
1375 Cookies_add_matching_cookies(domain_str, url_path, host_only_val,
1376 matching_cookies, is_tls);
1377 }
1378 }
1379 }
1380
1381 /* Found the cookies, now make the string */
1382 cookie_dstring = dStr_new("");
1383 if (dList_length(matching_cookies) > 0) {
1384
1385 dStr_sprintfa(cookie_dstring, "Cookie: ");
1386
1387 for (i = 0; (cookie = dList_nth_data(matching_cookies, i)); ++i) {
1388 dStr_sprintfa(cookie_dstring, "%s=%s", cookie->name, cookie->value);
1389 dStr_append(cookie_dstring,
1390 dList_length(matching_cookies) > i + 1 ? "; " : "\r\n");
1391 }
1392 }
1393
1394 dList_free(matching_cookies);
1395 str = cookie_dstring->str;
1396 dStr_free(cookie_dstring, FALSE);
1397
1398 if (*str) {
1399 MSG("%s GETTING: %s", url_host, str);
1401 }
1402 return str;
1403}
1404
1405/* -------------------------------------------------------------
1406 * Access control routines
1407 * ------------------------------------------------------------- */
1408
1409
1410/*
1411 * Get the cookie control rules (from cookiesrc).
1412 * Return value:
1413 * 0 = Parsed OK, with cookies enabled
1414 * 1 = Parsed OK, with cookies disabled
1415 * 2 = Can't open the control file
1416 */
1417static int Cookie_control_init(void)
1418{
1419 CookieControl cc;
1420 FILE *stream;
1421 char *filename, *rc;
1422 char line[LINE_MAXLEN];
1423 char domain[LINE_MAXLEN];
1424 char rule[LINE_MAXLEN];
1425 bool_t enabled = FALSE;
1426
1427 /* Get a file pointer */
1428 filename = dStrconcat(dGethomedir(), "/.dillo/cookiesrc", NULL);
1429 stream = Cookies_fopen(filename, "r", "DEFAULT DENY\n");
1430 dFree(filename);
1431
1432 if (!stream)
1433 return 2;
1434
1435 /* Get all lines in the file */
1436 while (!feof(stream)) {
1437 line[0] = '\0';
1438 rc = fgets(line, LINE_MAXLEN, stream);
1439 if (!rc && ferror(stream)) {
1440 MSG("Error while reading rule from cookiesrc: %s\n",
1441 dStrerror(errno));
1442 break; /* bail out */
1443 }
1444
1445 /* Remove leading and trailing whitespaces */
1446 dStrstrip(line);
1447
1448 if (line[0] != '\0' && line[0] != '#') {
1449 int i = 0, j = 0;
1450
1451 /* Get the domain */
1452 while (line[i] != '\0' && !dIsspace(line[i]))
1453 domain[j++] = line[i++];
1454 domain[j] = '\0';
1455
1456 /* Skip past whitespaces */
1457 while (dIsspace(line[i]))
1458 i++;
1459
1460 /* Get the rule */
1461 j = 0;
1462 while (line[i] != '\0' && !dIsspace(line[i]))
1463 rule[j++] = line[i++];
1464 rule[j] = '\0';
1465
1466 if (dStrAsciiCasecmp(rule, "ACCEPT") == 0)
1467 cc.action = COOKIE_ACCEPT;
1468 else if (dStrAsciiCasecmp(rule, "ACCEPT_SESSION") == 0)
1469 cc.action = COOKIE_ACCEPT_SESSION;
1470 else if (dStrAsciiCasecmp(rule, "DENY") == 0)
1471 cc.action = COOKIE_DENY;
1472 else {
1473 MSG("Cookies: rule '%s' for domain '%s' is not recognised.\n",
1474 rule, domain);
1475 continue;
1476 }
1477
1478 cc.domain = dStrdup(domain);
1479 if (dStrAsciiCasecmp(cc.domain, "DEFAULT") == 0) {
1480 /* Set the default action */
1481 default_action = cc.action;
1482 dFree(cc.domain);
1483 } else {
1484 int i;
1485 uint_t len = strlen(cc.domain);
1486
1487 /* Insert into list such that longest rules come first. */
1489 for (i = num_ccontrol++;
1490 i > 0 && (len > strlen(ccontrol[i-1].domain));
1491 i--) {
1492 ccontrol[i] = ccontrol[i-1];
1493 }
1494 ccontrol[i] = cc;
1495 }
1496
1497 if (cc.action != COOKIE_DENY)
1498 enabled = TRUE;
1499 }
1500 }
1501
1502 fclose(stream);
1503
1504 return (enabled ? 0 : 1);
1505}
1506
1507/*
1508 * Check the rules for an appropriate action for this domain.
1509 * The rules are ordered by domain length, with longest first, so the
1510 * first match is the most specific.
1511 */
1513{
1514 int i, diff;
1515
1516 for (i = 0; i < num_ccontrol; i++) {
1517 if (ccontrol[i].domain[0] == '.') {
1518 diff = strlen(domain) - strlen(ccontrol[i].domain);
1519 if (diff >= 0) {
1520 if (dStrAsciiCasecmp(domain + diff, ccontrol[i].domain) != 0)
1521 continue;
1522 } else {
1523 continue;
1524 }
1525 } else {
1526 if (dStrAsciiCasecmp(domain, ccontrol[i].domain) != 0)
1527 continue;
1528 }
1529
1530 /* If we got here we have a match */
1531 return( ccontrol[i].action );
1532 }
1533
1534 return default_action;
1535}
1536
1537/* -- Dpi parser ----------------------------------------------------------- */
1538
1539/*
1540 * Parse a data stream (dpi protocol)
1541 * Note: Buf is a zero terminated string
1542 * Return code: { 0:OK, 1:Abort, 2:Close }
1543 */
1544static int srv_parse_tok(Dsh *sh, ClientInfo *client, char *Buf)
1545{
1546 char *cmd, *cookie, *host, *path;
1547 int ret = 1;
1548 size_t BufSize = strlen(Buf);
1549
1550 cmd = a_Dpip_get_attr_l(Buf, BufSize, "cmd");
1551
1552 if (!cmd) {
1553 /* abort */
1554 } else if (client->status == 0) {
1555 /* authenticate */
1556 if (a_Dpip_check_auth(Buf) == 1) {
1557 client->status = 1;
1558 ret = 0;
1559 }
1560 } else if (strcmp(cmd, "DpiBye") == 0) {
1561 dFree(cmd);
1562 MSG("(pid %d): Got DpiBye.\n", (int)getpid());
1563 exit(0);
1564
1565 } else if (strcmp(cmd, "set_cookie") == 0) {
1566 int st;
1567 char *date;
1568
1569 cookie = a_Dpip_get_attr_l(Buf, BufSize, "cookie");
1570 host = a_Dpip_get_attr_l(Buf, BufSize, "host");
1571 path = a_Dpip_get_attr_l(Buf, BufSize, "path");
1572 date = a_Dpip_get_attr_l(Buf, BufSize, "date");
1573
1574 st = Cookies_set(cookie, host, path, date);
1575
1576 dFree(cmd);
1577 cmd = a_Dpip_build_cmd("cmd=%s msg=%s", "set_cookie_answer",
1578 st == 0 ? "ok" : "not set");
1579 a_Dpip_dsh_write_str(sh, 1, cmd);
1580
1581 dFree(date);
1582 dFree(path);
1583 dFree(host);
1584 dFree(cookie);
1585 ret = 2;
1586
1587 } else if (strcmp(cmd, "get_cookie") == 0) {
1588 char *scheme = a_Dpip_get_attr_l(Buf, BufSize, "scheme");
1589
1590 host = a_Dpip_get_attr_l(Buf, BufSize, "host");
1591 path = a_Dpip_get_attr_l(Buf, BufSize, "path");
1592
1593 cookie = Cookies_get(host, path, scheme);
1594 dFree(scheme);
1595 dFree(path);
1596 dFree(host);
1597
1598 dFree(cmd);
1599 cmd = a_Dpip_build_cmd("cmd=%s cookie=%s", "get_cookie_answer", cookie);
1600
1601 if (a_Dpip_dsh_write_str(sh, 1, cmd)) {
1602 ret = 1;
1603 } else {
1604 _MSG("a_Dpip_dsh_write_str: SUCCESS cmd={%s}\n", cmd);
1605 ret = 2;
1606 }
1607 dFree(cookie);
1608 }
1609 dFree(cmd);
1610
1611 return ret;
1612}
1613
1614/* -- Termination handlers ----------------------------------------------- */
1615/*
1616 * (was to delete the local namespace socket),
1617 * but this is handled by 'dpid' now.
1618 */
1619static void cleanup(void)
1620{
1622 MSG("cleanup\n");
1623 /* no more cleanup required */
1624}
1625
1626/*
1627 * Perform any necessary cleanups upon abnormal termination
1628 */
1629static void termination_handler(int signum)
1630{
1631 exit(signum);
1632}
1633
1634
1635/*
1636 * -- MAIN -------------------------------------------------------------------
1637 */
1638int main(void) {
1639 struct sockaddr_in sin;
1640 socklen_t address_size;
1641 ClientInfo *client;
1642 int sock_fd, code;
1643 char *buf;
1644 Dsh *sh;
1645
1646 /* Arrange the cleanup function for terminations via exit() */
1647 atexit(cleanup);
1648
1649 /* Arrange the cleanup function for abnormal terminations */
1650 if (signal (SIGINT, termination_handler) == SIG_IGN)
1651 signal (SIGINT, SIG_IGN);
1652 if (signal (SIGHUP, termination_handler) == SIG_IGN)
1653 signal (SIGHUP, SIG_IGN);
1654 if (signal (SIGTERM, termination_handler) == SIG_IGN)
1655 signal (SIGTERM, SIG_IGN);
1656
1657 Cookies_init();
1658 MSG("(v.1) accepting connections...\n");
1659
1660 if (disabled)
1661 exit(1);
1662
1663 /* some OSes may need this... */
1664 address_size = sizeof(struct sockaddr_in);
1665
1666 while (1) {
1667 sock_fd = accept(STDIN_FILENO, (struct sockaddr *)&sin, &address_size);
1668 if (sock_fd == -1) {
1669 perror("[accept]");
1670 exit(1);
1671 }
1672
1673 /* create the Dsh structure */
1674 sh = a_Dpip_dsh_new(sock_fd, sock_fd, 8*1024);
1675 client = dNew(ClientInfo,1);
1676 client->sh = sh;
1677 client->status = 0;
1678
1679 while (1) {
1680 code = 1;
1681 if ((buf = a_Dpip_dsh_read_token(sh, 1)) != NULL) {
1682 /* Let's see what we fished... */
1683 _MSG(" buf = {%s}\n", buf);
1684 code = srv_parse_tok(sh, client, buf);
1685 dFree(buf);
1686 }
1687
1688 _MSG(" code = %d %s\n", code, code == 1 ? "EXIT" : "BREAK");
1689 if (code == 1) {
1690 exit(1);
1691 } else if (code == 2) {
1692 break;
1693 }
1694 }
1695
1696 _MSG("Closing Dsh\n");
1699 dFree(client);
1700
1701 }/*while*/
1702
1703 return 0;
1704}
1705
1706#endif /* !DISABLE_COOKIES */
unsigned int uint_t
Definition d_size.h:20
unsigned char bool_t
Definition d_size.h:21
static Dsh * sh
Definition datauri.c:38
char * dStrconcat(const char *s1,...)
Concatenate a NULL-terminated list of strings.
Definition dlib.c:101
void dList_insert_sorted(Dlist *lp, void *data, dCompareFunc func)
Insert an element into a sorted list.
Definition dlib.c:796
char * dStrsep(char **orig, const char *delim)
strsep() implementation
Definition dlib.c:158
void dFree(void *mem)
Definition dlib.c:67
int dStrAsciiCasecmp(const char *s1, const char *s2)
Definition dlib.c:202
void dStr_sprintfa(Dstr *ds, const char *format,...)
Printf-like function that appends.
Definition dlib.c:463
char * dStrstrip(char *s)
Remove leading and trailing whitespace.
Definition dlib.c:121
void dStr_append(Dstr *ds, const char *s)
Append a C string to a Dstr.
Definition dlib.c:315
void dList_insert_pos(Dlist *lp, void *data, int pos0)
Insert an element at a given position [0 based].
Definition dlib.c:603
char * dStrdup(const char *s)
Definition dlib.c:76
Dlist * dList_new(int size)
Create a new empty list.
Definition dlib.c:575
int dStrnAsciiCasecmp(const char *s1, const char *s2, size_t n)
Definition dlib.c:214
int dList_length(Dlist *lp)
For completing the ADT.
Definition dlib.c:640
void * dList_nth_data(Dlist *lp, int n0)
Return the nth data item, NULL when not found or 'n0' is out of range.
Definition dlib.c:689
void dList_remove_fast(Dlist *lp, const void *data)
Remove a data item without preserving order.
Definition dlib.c:650
void dStr_free(Dstr *ds, int all)
Free a dillo string.
Definition dlib.c:336
char * dStrndup(const char *s, size_t sz)
Definition dlib.c:87
Dstr * dStr_new(const char *s)
Create a new string.
Definition dlib.c:324
void dList_append(Dlist *lp, void *data)
Append a data item to the list.
Definition dlib.c:624
void * dList_find_sorted(Dlist *lp, const void *data, dCompareFunc func)
Search a sorted list.
Definition dlib.c:823
void dList_free(Dlist *lp)
Free a list (not its elements)
Definition dlib.c:591
void * dList_find_custom(Dlist *lp, const void *data, dCompareFunc func)
Search a data item using a custom function.
Definition dlib.c:731
void dList_remove(Dlist *lp, const void *data)
Definition dlib.c:668
char * dGethomedir(void)
Return the home directory in a static string (don't free)
Definition dlib.c:933
#define dStrerror
Definition dlib.h:124
static int dIsdigit(unsigned char c)
Definition dlib.h:50
#define dNew0(type, count)
Definition dlib.h:80
static int dIsspace(unsigned char c)
Definition dlib.h:53
#define TRUE
Definition dlib.h:36
#define FALSE
Definition dlib.h:32
#define dNew(type, count)
Definition dlib.h:78
static int Cookies_rm_expired_cookies(DomainNode *node)
Definition cookies.c:676
static bool_t Cookies_get_time(struct tm *tm, const char **str)
Definition cookies.c:507
static int num_ccontrol
Definition cookies.c:127
static void Cookies_add_matching_cookies(const char *domain, const char *url_path, bool_t host_only_val, Dlist *matching_cookies, bool_t is_tls)
Definition cookies.c:1272
#define _MSG(...)
Definition cookies.c:57
static CookieData_t * Cookies_get_LRU(Dlist *cookies)
Definition cookies.c:655
static struct tm cookies_epoch_tm
Definition cookies.c:142
#define MAX_DOMAIN_COOKIES
Definition cookies.c:80
static struct tm * Cookies_parse_date(const char *date)
Definition cookies.c:605
static bool_t Cookies_domain_matches(char *A, char *B)
Definition cookies.c:1095
static int srv_parse_tok(Dsh *sh, ClientInfo *client, char *Buf)
Definition cookies.c:1544
#define MSG(...)
Definition cookies.c:58
static bool_t Cookies_date_delim(char c)
Definition cookies.c:587
static Dlist * all_cookies
Definition cookies.c:120
static void Cookies_too_many(DomainNode *node)
Definition cookies.c:707
static void Cookies_load_cookies(FILE *stream)
Definition cookies.c:247
static int num_ccontrol_max
Definition cookies.c:128
static void Cookies_delete_node(DomainNode *node)
Definition cookies.c:178
static long cookies_use_counter
Definition cookies.c:131
static int Domain_node_cmp(const void *v1, const void *v2)
Definition cookies.c:157
static CookieControl * ccontrol
Definition cookies.c:126
static char * Cookies_parse_attr(char **cookie_str)
Definition cookies.c:798
static int Domain_node_by_domain_cmp(const void *v1, const void *v2)
Definition cookies.c:167
static void cleanup(void)
Definition cookies.c:1619
static bool_t Cookies_get_day(struct tm *tm, const char **str)
Definition cookies.c:533
static int Cookies_get_timefield(const char **str)
Definition cookies.c:484
static bool_t Cookies_get_year(struct tm *tm, const char **str)
Definition cookies.c:547
static void Cookies_init(void)
Definition cookies.c:334
static int Cookie_control_init(void)
Definition cookies.c:1417
static time_t cookies_epoch_time
Definition cookies.c:143
static uint_t Cookies_internal_dots_required(const char *host)
Definition cookies.c:1135
int main(void)
Definition cookies.c:1638
#define MAX_TOTAL_COOKIES
Definition cookies.c:81
#define a_List_add(list, num_items, alloc_step)
Definition cookies.c:67
static CookieControlAction default_action
Definition cookies.c:129
static void termination_handler(int signum)
Definition cookies.c:1629
static bool_t Cookies_get_month(struct tm *tm, const char **str)
Definition cookies.c:459
static bool_t Cookies_match(CookieData_t *cookie, const char *url_path, bool_t host_only_val, bool_t is_tls)
Definition cookies.c:1254
static bool_t Cookies_path_matches(const char *url_path, const char *cookie_path)
Definition cookies.c:1053
static bool_t Cookies_domain_is_ip(const char *domain)
Definition cookies.c:1025
static const char *const cookies_txt_header_str
Definition cookies.c:134
static FILE * file_stream
Definition cookies.c:133
static void Cookies_eat_value(char **cookie_str)
Definition cookies.c:846
static bool_t Cookies_validate_domain(CookieData_t *cookie, char *host)
Definition cookies.c:1180
CookieControlAction
Definition cookies.c:83
@ COOKIE_ACCEPT_SESSION
Definition cookies.c:85
@ COOKIE_ACCEPT
Definition cookies.c:84
@ COOKIE_DENY
Definition cookies.c:86
static CookieControlAction Cookies_control_check_domain(const char *domain)
Definition cookies.c:1512
static void Cookies_add_cookie(CookieData_t *cookie)
Definition cookies.c:724
static CookieData_t * Cookies_parse(char *cookie_str, const char *server_date)
Definition cookies.c:891
static int Cookies_set(char *cookie_string, char *url_host, char *url_path, char *server_date)
Definition cookies.c:1215
static void Cookies_save_and_free(void)
Definition cookies.c:389
static Dlist * domains
Definition cookies.c:123
static void Cookies_tm_init(struct tm *tm)
Definition cookies.c:233
static double Cookies_server_timediff(const char *server_date)
Definition cookies.c:856
static int Cookies_cmp(const void *a, const void *b)
Definition cookies.c:1013
static bool_t disabled
Definition cookies.c:132
static void Cookies_free_cookie(CookieData_t *cookie)
Definition cookies.c:224
static FILE * Cookies_fopen(const char *filename, const char *mode, const char *init_str)
Definition cookies.c:190
static void Cookies_validate_path(CookieData_t *cookie, const char *url_path)
Definition cookies.c:1075
static time_t cookies_future_time
Definition cookies.c:143
static char * Cookies_parse_value(char **cookie_str)
Definition cookies.c:819
static void Cookies_unquote_string(char *str)
Definition cookies.c:874
#define LINE_MAXLEN
Definition cookies.c:78
static char * Cookies_get(char *url_host, char *url_path, char *url_scheme)
Definition cookies.c:1320
void a_Dpip_dsh_free(Dsh *dsh)
Free the SockHandler structure.
Definition dpip.c:525
char * a_Dpip_build_cmd(const char *format,...)
Printf like function for building dpip commands.
Definition dpip.c:83
int a_Dpip_dsh_write_str(Dsh *dsh, int flush, const char *str)
Convenience function.
Definition dpip.c:374
char * a_Dpip_dsh_read_token(Dsh *dsh, int blocking)
Return a newlly allocated string with the next dpip token in the socket.
Definition dpip.c:493
void a_Dpip_dsh_close(Dsh *dsh)
Close this socket for reading and writing.
Definition dpip.c:504
char * a_Dpip_get_attr_l(const char *tag, size_t tagsize, const char *attrname)
Task: given a tag, its size and an attribute name, return the attribute value (stuffing of ' is remov...
Definition dpip.c:134
int a_Dpip_check_auth(const char *auth_tag)
Check whether the given 'auth' string equals what dpid saved.
Definition dpip.c:201
Dsh * a_Dpip_dsh_new(int fd_in, int fd_out, int flush_sz)
Create and initialize a dpip socket handler.
Definition dpip.c:247
Definition dlib.h:161
Dpip socket handler type.
Definition dpip.h:31
int status
status code: DPIP_EAGAIN | DPIP_ERROR | DPIP_EOF
Definition dpip.h:42
Definition dlib.h:131
Dstr_char_t * str
Definition dlib.h:134
static void path()
Definition cookies.c:858