Don't pass NULL to soup_message_headers_replace(), call
[platform/upstream/libsoup.git] / libsoup / soup-cookie-jar.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  * soup-cookie-jar.c
4  *
5  * Copyright (C) 2008 Red Hat, Inc.
6  */
7
8 #ifdef HAVE_CONFIG_H
9 #include <config.h>
10 #endif
11
12 #include <stdio.h>
13 #include <string.h>
14
15 #include "soup-cookie.h"
16 #include "soup-cookie-jar.h"
17 #include "soup-date.h"
18 #include "soup-marshal.h"
19 #include "soup-message.h"
20 #include "soup-session-feature.h"
21 #include "soup-uri.h"
22
23 /**
24  * SECTION:soup-cookie-jar
25  * @short_description: Automatic cookie handling for #SoupSession
26  *
27  * A #SoupCookieJar stores #SoupCookie<!-- -->s and arrange for them
28  * to be sent with the appropriate #SoupMessage<!-- -->s.
29  * #SoupCookieJar implements #SoupSessionFeature, so you can add a
30  * cookie jar to a session with soup_session_add_feature() or
31  * soup_session_add_feature_by_type().
32  *
33  * Note that the base #SoupCookieJar class does not support any form
34  * of long-term cookie persistence.
35  **/
36
37 static void soup_cookie_jar_session_feature_init (SoupSessionFeatureInterface *feature_interface, gpointer interface_data);
38 static void request_queued (SoupSessionFeature *feature, SoupSession *session,
39                             SoupMessage *msg);
40 static void request_started (SoupSessionFeature *feature, SoupSession *session,
41                              SoupMessage *msg, SoupSocket *socket);
42 static void request_unqueued (SoupSessionFeature *feature, SoupSession *session,
43                               SoupMessage *msg);
44
45 G_DEFINE_TYPE_WITH_CODE (SoupCookieJar, soup_cookie_jar, G_TYPE_OBJECT,
46                          G_IMPLEMENT_INTERFACE (SOUP_TYPE_SESSION_FEATURE,
47                                                 soup_cookie_jar_session_feature_init))
48
49 enum {
50         CHANGED,
51         LAST_SIGNAL
52 };
53
54 static guint signals[LAST_SIGNAL] = { 0 };
55
56 enum {
57         PROP_0,
58
59         PROP_READ_ONLY,
60
61         LAST_PROP
62 };
63
64 typedef struct {
65         gboolean constructed, read_only;
66         GHashTable *domains;
67 } SoupCookieJarPrivate;
68 #define SOUP_COOKIE_JAR_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), SOUP_TYPE_COOKIE_JAR, SoupCookieJarPrivate))
69
70 static void set_property (GObject *object, guint prop_id,
71                           const GValue *value, GParamSpec *pspec);
72 static void get_property (GObject *object, guint prop_id,
73                           GValue *value, GParamSpec *pspec);
74
75 static void
76 soup_cookie_jar_init (SoupCookieJar *jar)
77 {
78         SoupCookieJarPrivate *priv = SOUP_COOKIE_JAR_GET_PRIVATE (jar);
79
80         priv->domains = g_hash_table_new_full (g_str_hash, g_str_equal,
81                                                g_free, NULL);
82 }
83
84 static void
85 constructed (GObject *object)
86 {
87         SoupCookieJarPrivate *priv = SOUP_COOKIE_JAR_GET_PRIVATE (object);
88
89         priv->constructed = TRUE;
90 }
91
92 static void
93 finalize (GObject *object)
94 {
95         SoupCookieJarPrivate *priv = SOUP_COOKIE_JAR_GET_PRIVATE (object);
96         GHashTableIter iter;
97         gpointer key, value;
98
99         g_hash_table_iter_init (&iter, priv->domains);
100         while (g_hash_table_iter_next (&iter, &key, &value))
101                 soup_cookies_free (value);
102         g_hash_table_destroy (priv->domains);
103
104         G_OBJECT_CLASS (soup_cookie_jar_parent_class)->finalize (object);
105 }
106
107 static void
108 soup_cookie_jar_class_init (SoupCookieJarClass *jar_class)
109 {
110         GObjectClass *object_class = G_OBJECT_CLASS (jar_class);
111
112         g_type_class_add_private (jar_class, sizeof (SoupCookieJarPrivate));
113
114         object_class->constructed = constructed;
115         object_class->finalize = finalize;
116         object_class->set_property = set_property;
117         object_class->get_property = get_property;
118
119         /**
120          * SoupCookieJar::changed
121          * @jar: the #SoupCookieJar
122          * @old_cookie: the old #SoupCookie value
123          * @new_cookie: the new #SoupCookie value
124          *
125          * Emitted when @jar changes. If a cookie has been added,
126          * @new_cookie will contain the newly-added cookie and
127          * @old_cookie will be %NULL. If a cookie has been deleted,
128          * @old_cookie will contain the to-be-deleted cookie and
129          * @new_cookie will be %NULL. If a cookie has been changed,
130          * @old_cookie will contain its old value, and @new_cookie its
131          * new value.
132          **/
133         signals[CHANGED] =
134                 g_signal_new ("changed",
135                               G_OBJECT_CLASS_TYPE (object_class),
136                               G_SIGNAL_RUN_FIRST,
137                               G_STRUCT_OFFSET (SoupCookieJarClass, changed),
138                               NULL, NULL,
139                               soup_marshal_NONE__BOXED_BOXED,
140                               G_TYPE_NONE, 2, 
141                               SOUP_TYPE_COOKIE | G_SIGNAL_TYPE_STATIC_SCOPE,
142                               SOUP_TYPE_COOKIE | G_SIGNAL_TYPE_STATIC_SCOPE);
143
144         g_object_class_install_property (
145                 object_class, PROP_READ_ONLY,
146                 g_param_spec_boolean (SOUP_COOKIE_JAR_READ_ONLY,
147                                       "Read-only",
148                                       "Whether or not the cookie jar is read-only",
149                                       FALSE,
150                                       G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
151 }
152
153 static void
154 soup_cookie_jar_session_feature_init (SoupSessionFeatureInterface *feature_interface,
155                                       gpointer interface_data)
156 {
157         feature_interface->request_queued = request_queued;
158         feature_interface->request_started = request_started;
159         feature_interface->request_unqueued = request_unqueued;
160 }
161
162 static void
163 set_property (GObject *object, guint prop_id,
164               const GValue *value, GParamSpec *pspec)
165 {
166         SoupCookieJarPrivate *priv =
167                 SOUP_COOKIE_JAR_GET_PRIVATE (object);
168
169         switch (prop_id) {
170         case PROP_READ_ONLY:
171                 priv->read_only = g_value_get_boolean (value);
172                 break;
173         default:
174                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
175                 break;
176         }
177 }
178
179 static void
180 get_property (GObject *object, guint prop_id,
181               GValue *value, GParamSpec *pspec)
182 {
183         SoupCookieJarPrivate *priv =
184                 SOUP_COOKIE_JAR_GET_PRIVATE (object);
185
186         switch (prop_id) {
187         case PROP_READ_ONLY:
188                 g_value_set_boolean (value, priv->read_only);
189                 break;
190         default:
191                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
192                 break;
193         }
194 }
195
196 /**
197  * soup_cookie_jar_new:
198  *
199  * Creates a new #SoupCookieJar. The base #SoupCookieJar class does
200  * not support persistent storage of cookies; use a subclass for that.
201  *
202  * Returns: a new #SoupCookieJar
203  **/
204 SoupCookieJar *
205 soup_cookie_jar_new (void) 
206 {
207         return g_object_new (SOUP_TYPE_COOKIE_JAR, NULL);
208 }
209
210 void
211 soup_cookie_jar_save (SoupCookieJar *jar)
212 {
213         /* Does nothing, obsolete */
214 }
215
216 static void
217 soup_cookie_jar_changed (SoupCookieJar *jar,
218                          SoupCookie *old, SoupCookie *new)
219 {
220         SoupCookieJarPrivate *priv = SOUP_COOKIE_JAR_GET_PRIVATE (jar);
221
222         if (priv->read_only || !priv->constructed)
223                 return;
224
225         g_signal_emit (jar, signals[CHANGED], 0, old, new);
226 }
227
228 /**
229  * soup_cookie_jar_get_cookies:
230  * @jar: a #SoupCookieJar
231  * @uri: a #SoupURI
232  * @for_http: whether or not the return value is being passed directly
233  * to an HTTP operation
234  *
235  * Retrieves (in Cookie-header form) the list of cookies that would
236  * be sent with a request to @uri.
237  *
238  * If @for_http is %TRUE, the return value will include cookies marked
239  * "HttpOnly" (that is, cookies that the server wishes to keep hidden
240  * from client-side scripting operations such as the JavaScript
241  * document.cookies property). Since #SoupCookieJar sets the Cookie
242  * header itself when making the actual HTTP request, you should
243  * almost certainly be setting @for_http to %FALSE if you are calling
244  * this.
245  *
246  * Return value: the cookies, in string form, or %NULL if there are no
247  * cookies for @uri.
248  **/
249 char *
250 soup_cookie_jar_get_cookies (SoupCookieJar *jar, SoupURI *uri,
251                              gboolean for_http)
252 {
253         SoupCookieJarPrivate *priv;
254         GSList *cookies, *domain_cookies;
255         char *domain, *cur, *next_domain, *result;
256         GSList *new_head, *cookies_to_remove = NULL, *p;
257
258         g_return_val_if_fail (SOUP_IS_COOKIE_JAR (jar), NULL);
259         priv = SOUP_COOKIE_JAR_GET_PRIVATE (jar);
260
261         /* The logic here is a little weird, but the plan is that if
262          * uri->host is "www.foo.com", we will end up looking up
263          * cookies for ".www.foo.com", "www.foo.com", ".foo.com", and
264          * ".com", in that order. (Logic stolen from Mozilla.)
265          */
266         cookies = NULL;
267         domain = cur = g_strdup_printf (".%s", uri->host);
268         next_domain = domain + 1;
269         do {
270                 new_head = domain_cookies = g_hash_table_lookup (priv->domains, cur);
271                 while (domain_cookies) {
272                         GSList *next = domain_cookies->next;
273                         SoupCookie *cookie = domain_cookies->data;
274
275                         if (cookie->expires && soup_date_is_past (cookie->expires)) {
276                                 cookies_to_remove = g_slist_append (cookies_to_remove,
277                                                                     cookie);
278                                 new_head = g_slist_delete_link (new_head, domain_cookies);
279                                 g_hash_table_insert (priv->domains,
280                                                      g_strdup (cur),
281                                                      new_head);
282                         } else if (soup_cookie_applies_to_uri (cookie, uri) &&
283                                    (for_http || !cookie->http_only))
284                                 cookies = g_slist_append (cookies, cookie);
285
286                         domain_cookies = next;
287                 }
288                 cur = next_domain;
289                 if (cur)
290                         next_domain = strchr (cur + 1, '.');
291         } while (cur);
292         g_free (domain);
293
294         for (p = cookies_to_remove; p; p = p->next) {
295                 SoupCookie *cookie = p->data;
296
297                 soup_cookie_jar_changed (jar, cookie, NULL);
298                 soup_cookie_free (cookie);
299         }
300         g_slist_free (cookies_to_remove);
301
302         if (cookies) {
303                 /* FIXME: sort? */
304                 result = soup_cookies_to_cookie_header (cookies);
305                 g_slist_free (cookies);
306                 return result;
307         } else
308                 return NULL;
309 }
310
311 /**
312  * soup_cookie_jar_add_cookie:
313  * @jar: a #SoupCookieJar
314  * @cookie: a #SoupCookie
315  *
316  * Adds @cookie to @jar, emitting the 'changed' signal if we are modifying
317  * an existing cookie or adding a valid new cookie ('valid' means
318  * that the cookie's expire date is not in the past).
319  *
320  * @cookie will be 'stolen' by the jar, so don't free it afterwards.
321  **/
322 void
323 soup_cookie_jar_add_cookie (SoupCookieJar *jar, SoupCookie *cookie)
324 {
325         SoupCookieJarPrivate *priv;
326         GSList *old_cookies, *oc, *prev = NULL;
327         SoupCookie *old_cookie;
328
329         g_return_if_fail (SOUP_IS_COOKIE_JAR (jar));
330         g_return_if_fail (cookie != NULL);
331
332         priv = SOUP_COOKIE_JAR_GET_PRIVATE (jar);
333         old_cookies = g_hash_table_lookup (priv->domains, cookie->domain);
334         for (oc = old_cookies; oc; oc = oc->next) {
335                 old_cookie = oc->data;
336                 if (!strcmp (cookie->name, old_cookie->name)) {
337                         if (cookie->expires && soup_date_is_past (cookie->expires)) {
338                                 /* The new cookie has an expired date,
339                                  * this is the way the the server has
340                                  * of telling us that we have to
341                                  * remove the cookie.
342                                  */
343                                 old_cookies = g_slist_delete_link (old_cookies, oc);
344                                 g_hash_table_insert (priv->domains,
345                                                      g_strdup (cookie->domain),
346                                                      old_cookies);
347                                 soup_cookie_jar_changed (jar, old_cookie, NULL);
348                                 soup_cookie_free (old_cookie);
349                                 soup_cookie_free (cookie);
350                         } else {
351                                 oc->data = cookie;
352                                 soup_cookie_jar_changed (jar, old_cookie, cookie);
353                                 soup_cookie_free (old_cookie);
354                         }
355
356                         return;
357                 }
358                 prev = oc;
359         }
360
361         /* The new cookie is... a new cookie */
362         if (cookie->expires && soup_date_is_past (cookie->expires)) {
363                 soup_cookie_free (cookie);
364                 return;
365         }
366
367         if (prev)
368                 prev = g_slist_append (prev, cookie);
369         else {
370                 old_cookies = g_slist_append (NULL, cookie);
371                 g_hash_table_insert (priv->domains, g_strdup (cookie->domain),
372                                      old_cookies);
373         }
374
375         soup_cookie_jar_changed (jar, NULL, cookie);
376 }
377
378 /**
379  * soup_cookie_jar_set_cookie:
380  * @jar: a #SoupCookieJar
381  * @uri: the URI setting the cookie
382  * @cookie: the stringified cookie to set
383  *
384  * Adds @cookie to @jar, exactly as though it had appeared in a
385  * Set-Cookie header returned from a request to @uri.
386  **/
387 void
388 soup_cookie_jar_set_cookie (SoupCookieJar *jar, SoupURI *uri,
389                             const char *cookie)
390 {
391         SoupCookie *soup_cookie;
392
393         g_return_if_fail (SOUP_IS_COOKIE_JAR (jar));
394         g_return_if_fail (cookie != NULL);
395
396         soup_cookie = soup_cookie_parse (cookie, uri);
397         if (soup_cookie) {
398                 /* will steal or free soup_cookie */
399                 soup_cookie_jar_add_cookie (jar, soup_cookie);
400         }
401 }
402
403 static void
404 process_set_cookie_header (SoupMessage *msg, gpointer user_data)
405 {
406         SoupCookieJar *jar = user_data;
407         GSList *new_cookies, *nc;
408
409         new_cookies = soup_cookies_from_response (msg);
410         for (nc = new_cookies; nc; nc = nc->next)
411                 soup_cookie_jar_add_cookie (jar, nc->data);
412         g_slist_free (new_cookies);
413 }
414
415 static void
416 request_queued (SoupSessionFeature *feature, SoupSession *session,
417                 SoupMessage *msg)
418 {
419         soup_message_add_header_handler (msg, "got-headers",
420                                          "Set-Cookie",
421                                          G_CALLBACK (process_set_cookie_header),
422                                          feature);
423 }
424
425 static void
426 request_started (SoupSessionFeature *feature, SoupSession *session,
427                  SoupMessage *msg, SoupSocket *socket)
428 {
429         SoupCookieJar *jar = SOUP_COOKIE_JAR (feature);
430         char *cookies;
431
432         cookies = soup_cookie_jar_get_cookies (jar, soup_message_get_uri (msg), TRUE);
433         if (cookies) {
434                 soup_message_headers_replace (msg->request_headers,
435                                               "Cookie", cookies);
436                 g_free (cookies);
437         } else
438                 soup_message_headers_remove (msg->request_headers, "Cookie");
439 }
440
441 static void
442 request_unqueued (SoupSessionFeature *feature, SoupSession *session,
443                   SoupMessage *msg)
444 {
445         g_signal_handlers_disconnect_by_func (msg, process_set_cookie_header, feature);
446 }
447
448 /**
449  * soup_cookie_jar_all_cookies:
450  * @jar: a #SoupCookieJar
451  *
452  * Constructs a #GSList with every cookie inside the @jar.
453  * The cookies in the list are a copy of the original, so
454  * you have to free them when you are done with them.
455  *
456  * Return value: a #GSList with all the cookies in the @jar.
457  **/
458 GSList *
459 soup_cookie_jar_all_cookies (SoupCookieJar *jar)
460 {
461         SoupCookieJarPrivate *priv;
462         GHashTableIter iter;
463         GSList *l = NULL;
464         gpointer key, value;
465
466         g_return_val_if_fail (SOUP_IS_COOKIE_JAR (jar), NULL);
467
468         priv = SOUP_COOKIE_JAR_GET_PRIVATE (jar);
469
470         g_hash_table_iter_init (&iter, priv->domains);
471
472         while (g_hash_table_iter_next (&iter, &key, &value)) {
473                 GSList *p, *cookies = value;
474                 for (p = cookies; p; p = p->next)
475                         l = g_slist_prepend (l, soup_cookie_copy (p->data));
476         }
477
478         return l;
479 }
480
481 /**
482  * soup_cookie_jar_delete_cookie:
483  * @jar: a #SoupCookieJar
484  * @cookie: a #SoupCookie
485  *
486  * Deletes @cookie from @jar, emitting the 'changed' signal.
487  **/
488 void
489 soup_cookie_jar_delete_cookie (SoupCookieJar *jar,
490                                SoupCookie    *cookie)
491 {
492         SoupCookieJarPrivate *priv;
493         GSList *cookies, *p;
494         char *domain;
495
496         g_return_if_fail (SOUP_IS_COOKIE_JAR (jar));
497         g_return_if_fail (cookie != NULL);
498
499         priv = SOUP_COOKIE_JAR_GET_PRIVATE (jar);
500
501         domain = g_strdup (cookie->domain);
502
503         cookies = g_hash_table_lookup (priv->domains, domain);
504         if (cookies == NULL)
505                 return;
506
507         for (p = cookies; p; p = p->next ) {
508                 SoupCookie *c = (SoupCookie*)p->data;
509                 if (soup_cookie_equal (cookie, c)) {
510                         cookies = g_slist_delete_link (cookies, p);
511                         g_hash_table_insert (priv->domains,
512                                              domain,
513                                              cookies);
514                         soup_cookie_jar_changed (jar, c, NULL);
515                         soup_cookie_free (c);
516                         return;
517                 }
518         }
519 }