gweb: added the capability to restrict the requests to a specific address family.
[platform/upstream/connman.git] / gweb / gweb.c
1 /*
2  *
3  *  Web service library with GLib integration
4  *
5  *  Copyright (C) 2009-2010  Intel Corporation. All rights reserved.
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License version 2 as
9  *  published by the Free Software Foundation.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <stdio.h>
27 #include <errno.h>
28 #include <unistd.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <string.h>
32 #include <sys/socket.h>
33 #include <arpa/inet.h>
34 #include <netdb.h>
35
36 #include "giognutls.h"
37 #include "gresolv.h"
38 #include "gweb.h"
39
40 #define DEFAULT_BUFFER_SIZE  2048
41
42 #define SESSION_FLAG_USE_TLS    (1 << 0)
43
44 enum chunk_state {
45         CHUNK_SIZE,
46         CHUNK_R_BODY,
47         CHUNK_N_BODY,
48         CHUNK_DATA,
49 };
50
51 struct _GWebResult {
52         guint16 status;
53         const guint8 *buffer;
54         gsize length;
55         gboolean use_chunk;
56         gchar *last_key;
57         GHashTable *headers;
58 };
59
60 struct web_session {
61         GWeb *web;
62
63         char *address;
64         char *host;
65         uint16_t port;
66         unsigned long flags;
67         struct addrinfo *addr;
68
69         char *content_type;
70
71         GIOChannel *transport_channel;
72         guint transport_watch;
73         guint send_watch;
74
75         guint resolv_action;
76         char *request;
77
78         guint8 *receive_buffer;
79         gsize receive_space;
80         GString *send_buffer;
81         GString *current_header;
82         gboolean header_done;
83         gboolean body_done;
84         gboolean more_data;
85         gboolean request_started;
86
87         enum chunk_state chunck_state;
88         gsize chunk_size;
89         gsize chunk_left;
90         gsize total_len;
91
92         GWebResult result;
93
94         GWebResultFunc result_func;
95         GWebInputFunc input_func;
96         gpointer user_data;
97 };
98
99 struct _GWeb {
100         gint ref_count;
101
102         guint next_query_id;
103
104         int family;
105
106         int index;
107         GList *session_list;
108
109         GResolv *resolv;
110         char *proxy;
111         char *accept_option;
112         char *user_agent;
113         char *user_agent_profile;
114         char *http_version;
115         gboolean close_connection;
116
117         GWebDebugFunc debug_func;
118         gpointer debug_data;
119 };
120
121 static inline void debug(GWeb *web, const char *format, ...)
122 {
123         char str[256];
124         va_list ap;
125
126         if (web->debug_func == NULL)
127                 return;
128
129         va_start(ap, format);
130
131         if (vsnprintf(str, sizeof(str), format, ap) > 0)
132                 web->debug_func(str, web->debug_data);
133
134         va_end(ap);
135 }
136
137 static void free_session(struct web_session *session)
138 {
139         GWeb *web = session->web;
140
141         if (session == NULL)
142                 return;
143
144         g_free(session->request);
145
146         if (session->resolv_action > 0)
147                 g_resolv_cancel_lookup(web->resolv, session->resolv_action);
148
149         if (session->transport_watch > 0)
150                 g_source_remove(session->transport_watch);
151
152         if (session->send_watch > 0)
153                 g_source_remove(session->send_watch);
154
155         if (session->transport_channel != NULL)
156                 g_io_channel_unref(session->transport_channel);
157
158         g_free(session->result.last_key);
159
160         if (session->result.headers != NULL)
161                 g_hash_table_destroy(session->result.headers);
162
163         if (session->send_buffer != NULL)
164                 g_string_free(session->send_buffer, TRUE);
165
166         if (session->current_header != NULL)
167                 g_string_free(session->current_header, TRUE);
168
169         g_free(session->receive_buffer);
170
171         g_free(session->content_type);
172
173         g_free(session->host);
174         g_free(session->address);
175         if (session->addr != NULL)
176                 freeaddrinfo(session->addr);
177
178         g_free(session);
179 }
180
181 static void flush_sessions(GWeb *web)
182 {
183         GList *list;
184
185         for (list = g_list_first(web->session_list);
186                                         list; list = g_list_next(list))
187                 free_session(list->data);
188
189         g_list_free(web->session_list);
190         web->session_list = NULL;
191 }
192
193 GWeb *g_web_new(int index)
194 {
195         GWeb *web;
196
197         if (index < 0)
198                 return NULL;
199
200         web = g_try_new0(GWeb, 1);
201         if (web == NULL)
202                 return NULL;
203
204         web->ref_count = 1;
205
206         web->next_query_id = 1;
207
208         web->family = AF_UNSPEC;
209
210         web->index = index;
211         web->session_list = NULL;
212
213         web->resolv = g_resolv_new(index);
214         if (web->resolv == NULL) {
215                 g_free(web);
216                 return NULL;
217         }
218
219         web->accept_option = g_strdup("*/*");
220         web->user_agent = g_strdup_printf("GWeb/%s", VERSION);
221         web->close_connection = FALSE;
222
223         return web;
224 }
225
226 GWeb *g_web_ref(GWeb *web)
227 {
228         if (web == NULL)
229                 return NULL;
230
231         g_atomic_int_inc(&web->ref_count);
232
233         return web;
234 }
235
236 void g_web_unref(GWeb *web)
237 {
238         if (web == NULL)
239                 return;
240
241         if (g_atomic_int_dec_and_test(&web->ref_count) == FALSE)
242                 return;
243
244         flush_sessions(web);
245
246         g_resolv_unref(web->resolv);
247
248         g_free(web->proxy);
249
250         g_free(web->accept_option);
251         g_free(web->user_agent);
252         g_free(web->user_agent_profile);
253         g_free(web->http_version);
254
255         g_free(web);
256 }
257
258 void g_web_set_debug(GWeb *web, GWebDebugFunc func, gpointer user_data)
259 {
260         if (web == NULL)
261                 return;
262
263         web->debug_func = func;
264         web->debug_data = user_data;
265
266         g_resolv_set_debug(web->resolv, func, user_data);
267 }
268
269 gboolean g_web_set_proxy(GWeb *web, const char *proxy)
270 {
271         if (web == NULL)
272                 return FALSE;
273
274         g_free(web->proxy);
275
276         if (proxy == NULL) {
277                 web->proxy = NULL;
278                 debug(web, "clearing proxy");
279         } else {
280                 web->proxy = g_strdup(proxy);
281                 debug(web, "setting proxy %s", web->proxy);
282         }
283
284         return TRUE;
285 }
286
287 gboolean g_web_set_address_family(GWeb *web, int family)
288 {
289         if (web == NULL)
290                 return FALSE;
291
292         if (family != AF_UNSPEC && family != AF_INET && family != AF_INET6)
293                 return FALSE;
294
295         web->family = family;
296
297         return TRUE;
298 }
299
300 gboolean g_web_add_nameserver(GWeb *web, const char *address)
301 {
302         if (web == NULL)
303                 return FALSE;
304
305         g_resolv_add_nameserver(web->resolv, address, 53, 0);
306
307         return TRUE;
308 }
309
310 static gboolean set_accept_option(GWeb *web, const char *format, va_list args)
311 {
312         g_free(web->accept_option);
313
314         if (format == NULL) {
315                 web->accept_option = NULL;
316                 debug(web, "clearing accept option");
317         } else {
318                 web->accept_option = g_strdup_vprintf(format, args);
319                 debug(web, "setting accept %s", web->accept_option);
320         }
321
322         return TRUE;
323 }
324
325 gboolean g_web_set_accept(GWeb *web, const char *format, ...)
326 {
327         va_list args;
328         gboolean result;
329
330         if (web == NULL)
331                 return FALSE;
332
333         va_start(args, format);
334         result = set_accept_option(web, format, args);
335         va_end(args);
336
337         return result;
338 }
339
340 static gboolean set_user_agent(GWeb *web, const char *format, va_list args)
341 {
342         g_free(web->user_agent);
343
344         if (format == NULL) {
345                 web->user_agent = NULL;
346                 debug(web, "clearing user agent");
347         } else {
348                 web->user_agent = g_strdup_vprintf(format, args);
349                 debug(web, "setting user agent %s", web->user_agent);
350         }
351
352         return TRUE;
353 }
354
355 gboolean g_web_set_user_agent(GWeb *web, const char *format, ...)
356 {
357         va_list args;
358         gboolean result;
359
360         if (web == NULL)
361                 return FALSE;
362
363         va_start(args, format);
364         result = set_user_agent(web, format, args);
365         va_end(args);
366
367         return result;
368 }
369
370 gboolean g_web_set_ua_profile(GWeb *web, const char *profile)
371 {
372         if (web == NULL)
373                 return FALSE;
374
375         g_free(web->user_agent_profile);
376
377         web->user_agent_profile = g_strdup(profile);
378         debug(web, "setting user agent profile %s", web->user_agent);
379
380         return TRUE;
381 }
382
383 gboolean g_web_set_http_version(GWeb *web, const char *version)
384 {
385         if (web == NULL)
386                 return FALSE;
387
388         g_free(web->http_version);
389
390         if (version == NULL) {
391                 web->http_version = NULL;
392                 debug(web, "clearing HTTP version");
393         } else {
394                 web->http_version = g_strdup(version);
395                 debug(web, "setting HTTP version %s", web->http_version);
396         }
397
398         return TRUE;
399 }
400
401 void g_web_set_close_connection(GWeb *web, gboolean enabled)
402 {
403         if (web == NULL)
404                 return;
405
406         web->close_connection = enabled;
407 }
408
409 gboolean g_web_get_close_connection(GWeb *web)
410 {
411         if (web == NULL)
412                 return FALSE;
413
414         return web->close_connection;
415 }
416
417 static inline void call_result_func(struct web_session *session, guint16 status)
418 {
419         gboolean result;
420
421         if (session->result_func == NULL)
422                 return;
423
424         if (status != 0)
425                 session->result.status = status;
426
427         result = session->result_func(&session->result, session->user_data);
428
429         debug(session->web, "[result function] %s",
430                                         result == TRUE ? "continue" : "stop");
431 }
432
433 static gboolean process_send_buffer(struct web_session *session)
434 {
435         GString *buf = session->send_buffer;
436         gsize count, bytes_written;
437         GIOStatus status;
438
439         count = buf->len;
440
441         if (count == 0) {
442                 if (session->request_started == TRUE &&
443                                         session->more_data == FALSE)
444                         session->body_done = TRUE;
445
446                 return FALSE;
447         }
448
449         status = g_io_channel_write_chars(session->transport_channel,
450                                         buf->str, count, &bytes_written, NULL);
451
452         debug(session->web, "status %u bytes to write %zu bytes written %zu",
453                                         status, count, bytes_written);
454
455         if (status != G_IO_STATUS_NORMAL && status != G_IO_STATUS_AGAIN)
456                 return FALSE;
457
458         g_string_erase(buf, 0, bytes_written);
459
460         return TRUE;
461 }
462
463 static void process_next_chunk(struct web_session *session)
464 {
465         GString *buf = session->send_buffer;
466         const guint8 *body;
467         gsize length;
468
469         if (session->input_func == NULL) {
470                 session->more_data = FALSE;
471                 return;
472         }
473
474         session->more_data = session->input_func(&body, &length,
475                                                 session->user_data);
476
477         if (length > 0) {
478                 g_string_append_printf(buf, "%zx\r\n", length);
479                 g_string_append_len(buf, (char *) body, length);
480                 g_string_append(buf, "\r\n");
481         }
482
483         if (session->more_data == FALSE)
484                 g_string_append(buf, "0\r\n\r\n");
485 }
486
487 static void start_request(struct web_session *session)
488 {
489         GString *buf = session->send_buffer;
490         const char *version;
491         const guint8 *body;
492         gsize length;
493
494         debug(session->web, "request %s from %s",
495                                         session->request, session->host);
496
497         g_string_truncate(buf, 0);
498
499         if (session->web->http_version == NULL)
500                 version = "1.1";
501         else
502                 version = session->web->http_version;
503
504         if (session->content_type == NULL)
505                 g_string_append_printf(buf, "GET %s HTTP/%s\r\n",
506                                                 session->request, version);
507         else
508                 g_string_append_printf(buf, "POST %s HTTP/%s\r\n",
509                                                 session->request, version);
510
511         g_string_append_printf(buf, "Host: %s\r\n", session->host);
512
513         if (session->web->user_agent != NULL)
514                 g_string_append_printf(buf, "User-Agent: %s\r\n",
515                                                 session->web->user_agent);
516
517         if (session->web->user_agent_profile != NULL) {
518                 g_string_append_printf(buf, "x-wap-profile: %s\r\n",
519                                        session->web->user_agent_profile);
520         }
521
522         if (session->web->accept_option != NULL)
523                 g_string_append_printf(buf, "Accept: %s\r\n",
524                                                 session->web->accept_option);
525
526         if (session->content_type != NULL) {
527                 g_string_append_printf(buf, "Content-Type: %s\r\n",
528                                                         session->content_type);
529                 if (session->input_func == NULL) {
530                         session->more_data = FALSE;
531                         length = 0;
532                 } else
533                         session->more_data = session->input_func(&body, &length,
534                                                         session->user_data);
535                 if (session->more_data == FALSE)
536                         g_string_append_printf(buf, "Content-Length: %zu\r\n",
537                                                                         length);
538                 else
539                         g_string_append(buf, "Transfer-Encoding: chunked\r\n");
540         }
541
542         if (session->web->close_connection == TRUE)
543                 g_string_append(buf, "Connection: close\r\n");
544
545         g_string_append(buf, "\r\n");
546
547         if (session->content_type != NULL && length > 0) {
548                 if (session->more_data == TRUE) {
549                         g_string_append_printf(buf, "%zx\r\n", length);
550                         g_string_append_len(buf, (char *) body, length);
551                         g_string_append(buf, "\r\n");
552                 } else
553                         g_string_append_len(buf, (char *) body, length);
554         }
555 }
556
557 static gboolean send_data(GIOChannel *channel, GIOCondition cond,
558                                                 gpointer user_data)
559 {
560         struct web_session *session = user_data;
561
562         if (cond & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
563                 session->send_watch = 0;
564                 return FALSE;
565         }
566
567         if (process_send_buffer(session) == TRUE)
568                 return TRUE;
569
570         if (session->request_started == FALSE) {
571                 session->request_started = TRUE;
572                 start_request(session);
573         } else if (session->more_data == TRUE)
574                 process_next_chunk(session);
575
576         process_send_buffer(session);
577
578         if (session->body_done == TRUE) {
579                 session->send_watch = 0;
580                 return FALSE;
581         }
582
583         return TRUE;
584 }
585
586 static int decode_chunked(struct web_session *session,
587                                         const guint8 *buf, gsize len)
588 {
589         const guint8 *ptr = buf;
590         gsize counter;
591
592         while (len > 0) {
593                 guint8 *pos;
594                 gsize count;
595                 char *str;
596
597                 switch (session->chunck_state) {
598                 case CHUNK_SIZE:
599                         pos = memchr(ptr, '\n', len);
600                         if (pos == NULL) {
601                                 g_string_append_len(session->current_header,
602                                                 (gchar *) ptr, len);
603                                 return 0;
604                         }
605
606                         count = pos - ptr;
607                         if (count < 1 || ptr[count - 1] != '\r')
608                                 return -EILSEQ;
609
610                         g_string_append_len(session->current_header,
611                                                 (gchar *) ptr, count);
612
613                         len -= count + 1;
614                         ptr = pos + 1;
615
616                         str = session->current_header->str;
617
618                         counter = strtoul(str, NULL, 16);
619                         if ((counter == 0 && errno == EINVAL) ||
620                                                 counter == ULONG_MAX)
621                                 return -EILSEQ;
622
623                         session->chunk_size = counter;
624                         session->chunk_left = counter;
625
626                         session->chunck_state = CHUNK_DATA;
627                         break;
628                 case CHUNK_R_BODY:
629                         if (*ptr != '\r')
630                                 return -EILSEQ;
631                         ptr++;
632                         len--;
633                         session->chunck_state = CHUNK_N_BODY;
634                         break;
635                 case CHUNK_N_BODY:
636                         if (*ptr != '\n')
637                                 return -EILSEQ;
638                         ptr++;
639                         len--;
640                         session->chunck_state = CHUNK_SIZE;
641                         break;
642                 case CHUNK_DATA:
643                         if (session->chunk_size == 0) {
644                                 debug(session->web, "Download Done in chunk");
645                                 g_string_truncate(session->current_header, 0);
646                                 return 0;
647                         }
648
649                         if (session->chunk_left <= len) {
650                                 session->result.buffer = ptr;
651                                 session->result.length = session->chunk_left;
652                                 call_result_func(session, 0);
653
654                                 len -= session->chunk_left;
655                                 ptr += session->chunk_left;
656
657                                 session->total_len += session->chunk_left;
658                                 session->chunk_left = 0;
659
660                                 g_string_truncate(session->current_header, 0);
661                                 session->chunck_state = CHUNK_R_BODY;
662                                 break;
663                         }
664                         /* more data */
665                         session->result.buffer = ptr;
666                         session->result.length = len;
667                         call_result_func(session, 0);
668
669                         session->chunk_left -= len;
670                         session->total_len += len;
671
672                         len -= len;
673                         ptr += len;
674                         break;
675                 }
676         }
677
678         return 0;
679 }
680
681 static int handle_body(struct web_session *session,
682                                 const guint8 *buf, gsize len)
683 {
684         int err;
685
686         debug(session->web, "[body] length %zu", len);
687
688         if (session->result.use_chunk == FALSE) {
689                 if (len > 0) {
690                         session->result.buffer = buf;
691                         session->result.length = len;
692                         call_result_func(session, 0);
693                 }
694                 return 0;
695         }
696
697         err = decode_chunked(session, buf, len);
698         if (err < 0) {
699                 debug(session->web, "Error in chunk decode %d", err);
700
701                 session->result.buffer = NULL;
702                 session->result.length = 0;
703                 call_result_func(session, 400);
704         }
705
706         return err;
707 }
708
709 static void handle_multi_line(struct web_session *session)
710 {
711         gsize count;
712         char *str;
713         gchar *value;
714
715         str = session->current_header->str;
716
717         if (str[0] != ' ' && str[0] != '\t')
718                 return;
719
720         while (str[0] == ' ' || str[0] == '\t')
721                 str++;
722
723         count = str - session->current_header->str;
724         if (count > 0) {
725                 g_string_erase(session->current_header, 0, count);
726                 g_string_insert_c(session->current_header, 0, ' ');
727         }
728
729         value = g_hash_table_lookup(session->result.headers,
730                                         session->result.last_key);
731         if (value != NULL) {
732                 g_string_insert(session->current_header, 0, value);
733
734                 str = session->current_header->str;
735
736                 g_hash_table_replace(session->result.headers,
737                                         g_strdup(session->result.last_key),
738                                         g_strdup(str));
739         }
740 }
741
742 static void add_header_field(struct web_session *session)
743 {
744         gsize count;
745         guint8 *pos;
746         char *str;
747         gchar *value;
748         gchar *key;
749
750         str = session->current_header->str;
751
752         pos = memchr(str, ':', session->current_header->len);
753         if (pos != NULL) {
754                 *pos = '\0';
755                 pos++;
756
757                 key = g_strdup(str);
758
759                 /* remove preceding white spaces */
760                 while (*pos == ' ')
761                         pos++;
762
763                 count = (char *) pos - str;
764
765                 g_string_erase(session->current_header, 0, count);
766
767                 value = g_hash_table_lookup(session->result.headers, key);
768                 if (value != NULL) {
769                         g_string_insert_c(session->current_header, 0, ' ');
770                         g_string_insert_c(session->current_header, 0, ';');
771
772                         g_string_insert(session->current_header, 0, value);
773                 }
774
775                 str = session->current_header->str;
776                 g_hash_table_replace(session->result.headers, key,
777                                                         g_strdup(str));
778
779                 g_free(session->result.last_key);
780                 session->result.last_key = g_strdup(key);
781         }
782 }
783
784 static gboolean received_data(GIOChannel *channel, GIOCondition cond,
785                                                         gpointer user_data)
786 {
787         struct web_session *session = user_data;
788         guint8 *ptr = session->receive_buffer;
789         gsize bytes_read;
790         GIOStatus status;
791
792         if (cond & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
793                 session->transport_watch = 0;
794                 session->result.buffer = NULL;
795                 session->result.length = 0;
796                 call_result_func(session, 400);
797                 return FALSE;
798         }
799
800         status = g_io_channel_read_chars(channel,
801                                 (gchar *) session->receive_buffer,
802                                 session->receive_space - 1, &bytes_read, NULL);
803
804         debug(session->web, "bytes read %zu", bytes_read);
805
806         if (status != G_IO_STATUS_NORMAL && status != G_IO_STATUS_AGAIN) {
807                 session->transport_watch = 0;
808                 session->result.buffer = NULL;
809                 session->result.length = 0;
810                 call_result_func(session, 0);
811                 return FALSE;
812         }
813
814         session->receive_buffer[bytes_read] = '\0';
815
816         if (session->header_done == TRUE) {
817                 if (handle_body(session, session->receive_buffer,
818                                                         bytes_read) < 0) {
819                         session->transport_watch = 0;
820                         return FALSE;
821                 }
822                 return TRUE;
823         }
824
825         while (bytes_read > 0) {
826                 guint8 *pos;
827                 gsize count;
828                 char *str;
829
830                 pos = memchr(ptr, '\n', bytes_read);
831                 if (pos == NULL) {
832                         g_string_append_len(session->current_header,
833                                                 (gchar *) ptr, bytes_read);
834                         return TRUE;
835                 }
836
837                 *pos = '\0';
838                 count = strlen((char *) ptr);
839                 if (count > 0 && ptr[count - 1] == '\r') {
840                         ptr[--count] = '\0';
841                         bytes_read--;
842                 }
843
844                 g_string_append_len(session->current_header,
845                                                 (gchar *) ptr, count);
846
847                 bytes_read -= count + 1;
848                 if (bytes_read > 0)
849                         ptr = pos + 1;
850                 else
851                         ptr = NULL;
852
853                 if (session->current_header->len == 0) {
854                         char *val;
855
856                         session->header_done = TRUE;
857
858                         val = g_hash_table_lookup(session->result.headers,
859                                                         "Transfer-Encoding");
860                         if (val != NULL) {
861                                 val = g_strrstr(val, "chunked");
862                                 if (val != NULL) {
863                                         session->result.use_chunk = TRUE;
864
865                                         session->chunck_state = CHUNK_SIZE;
866                                         session->chunk_left = 0;
867                                         session->total_len = 0;
868                                 }
869                         }
870
871                         if (handle_body(session, ptr, bytes_read) < 0) {
872                                 session->transport_watch = 0;
873                                 return FALSE;
874                         }
875                         break;
876                 }
877
878                 str = session->current_header->str;
879
880                 if (session->result.status == 0) {
881                         unsigned int code;
882
883                         if (sscanf(str, "HTTP/%*s %u %*s", &code) == 1)
884                                 session->result.status = code;
885                 }
886
887                 debug(session->web, "[header] %s", str);
888
889                 /* handle multi-line header */
890                 if (str[0] == ' ' || str[0] == '\t')
891                         handle_multi_line(session);
892                 else
893                         add_header_field(session);
894
895                 g_string_truncate(session->current_header, 0);
896         }
897
898         return TRUE;
899 }
900
901 static int connect_session_transport(struct web_session *session)
902 {
903         GIOFlags flags;
904         int sk;
905
906         sk = socket(session->addr->ai_family, SOCK_STREAM, IPPROTO_TCP);
907         if (sk < 0)
908                 return -EIO;
909
910         if (session->flags & SESSION_FLAG_USE_TLS) {
911                 debug(session->web, "using TLS encryption");
912                 session->transport_channel = g_io_channel_gnutls_new(sk);
913         } else {
914                 debug(session->web, "no encryption");
915                 session->transport_channel = g_io_channel_unix_new(sk);
916         }
917
918         if (session->transport_channel == NULL) {
919                 close(sk);
920                 return -ENOMEM;
921         }
922
923         flags = g_io_channel_get_flags(session->transport_channel);
924         g_io_channel_set_flags(session->transport_channel,
925                                         flags | G_IO_FLAG_NONBLOCK, NULL);
926
927         g_io_channel_set_encoding(session->transport_channel, NULL, NULL);
928         g_io_channel_set_buffered(session->transport_channel, FALSE);
929
930         g_io_channel_set_close_on_unref(session->transport_channel, TRUE);
931
932         if (connect(sk, session->addr->ai_addr,
933                         session->addr->ai_addrlen) < 0) {
934                 if (errno != EINPROGRESS) {
935                         close(sk);
936                         return -EIO;
937                 }
938         }
939
940         session->transport_watch = g_io_add_watch(session->transport_channel,
941                                 G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
942                                                 received_data, session);
943
944         session->send_watch = g_io_add_watch(session->transport_channel,
945                                 G_IO_OUT | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
946                                                 send_data, session);
947
948         return 0;
949 }
950
951 static int create_transport(struct web_session *session)
952 {
953         int err;
954
955         err = connect_session_transport(session);
956         if (err < 0)
957                 return err;
958
959         debug(session->web, "creating session %s:%u",
960                                         session->address, session->port);
961
962         return 0;
963 }
964
965 static int parse_url(struct web_session *session,
966                                 const char *url, const char *proxy)
967 {
968         char *scheme, *host, *port, *path;
969
970         scheme = g_strdup(url);
971         if (scheme == NULL)
972                 return -EINVAL;
973
974         host = strstr(scheme, "://");
975         if (host != NULL) {
976                 *host = '\0';
977                 host += 3;
978
979                 if (strcasecmp(scheme, "https") == 0) {
980                         session->port = 443;
981                         session->flags |= SESSION_FLAG_USE_TLS;
982                 } else if (strcasecmp(scheme, "http") == 0) {
983                         session->port = 80;
984                 } else {
985                         g_free(scheme);
986                         return -EINVAL;
987                 }
988         } else {
989                 host = scheme;
990                 session->port = 80;
991         }
992
993         path = strchr(host, '/');
994         if (path != NULL)
995                 *(path++) = '\0';
996
997         if (proxy == NULL)
998                 session->request = g_strdup_printf("/%s", path ? path : "");
999         else
1000                 session->request = g_strdup(url);
1001
1002         port = strrchr(host, ':');
1003         if (port != NULL) {
1004                 char *end;
1005                 int tmp = strtol(port + 1, &end, 10);
1006
1007                 if (*end == '\0') {
1008                         *port = '\0';
1009                         session->port = tmp;
1010                 }
1011
1012                 if (proxy == NULL)
1013                         session->host = g_strdup(host);
1014                 else
1015                         session->host = g_strdup_printf("%s:%u", host, tmp);
1016         } else
1017                 session->host = g_strdup(host);
1018
1019         g_free(scheme);
1020
1021         if (proxy == NULL)
1022                 return 0;
1023
1024         scheme = g_strdup(proxy);
1025         if (scheme == NULL)
1026                 return -EINVAL;
1027
1028         host = strstr(proxy, "://");
1029         if (host != NULL) {
1030                 *host = '\0';
1031                 host += 3;
1032
1033                 if (strcasecmp(scheme, "http") != 0) {
1034                         g_free(scheme);
1035                         return -EINVAL;
1036                 }
1037         } else
1038                 host = scheme;
1039
1040         path = strchr(host, '/');
1041         if (path != NULL)
1042                 *(path++) = '\0';
1043
1044         port = strrchr(host, ':');
1045         if (port != NULL) {
1046                 char *end;
1047                 int tmp = strtol(port + 1, &end, 10);
1048
1049                 if (*end == '\0') {
1050                         *port = '\0';
1051                         session->port = tmp;
1052                 }
1053         }
1054
1055         session->address = g_strdup(host);
1056
1057         g_free(scheme);
1058
1059         return 0;
1060 }
1061
1062 static void resolv_result(GResolvResultStatus status,
1063                                         char **results, gpointer user_data)
1064 {
1065         struct web_session *session = user_data;
1066         struct addrinfo hints;
1067         char *port;
1068         int ret;
1069
1070         if (results == NULL || results[0] == NULL) {
1071                 call_result_func(session, 404);
1072                 return;
1073         }
1074
1075         debug(session->web, "address %s", results[0]);
1076
1077         memset(&hints, 0, sizeof(struct addrinfo));
1078         hints.ai_flags = AI_NUMERICHOST;
1079         hints.ai_family = session->web->family;
1080
1081         if (session->addr != NULL) {
1082                 freeaddrinfo(session->addr);
1083                 session->addr = NULL;
1084         }
1085
1086         port = g_strdup_printf("%u", session->port);
1087         ret = getaddrinfo(results[0], port, &hints, &session->addr);
1088         g_free(port);
1089         if (ret != 0 || session->addr == NULL) {
1090                 call_result_func(session, 400);
1091                 return;
1092         }
1093
1094         session->address = g_strdup(results[0]);
1095
1096         if (create_transport(session) < 0) {
1097                 call_result_func(session, 409);
1098                 return;
1099         }
1100 }
1101
1102 static guint do_request(GWeb *web, const char *url,
1103                                 const char *type, GWebInputFunc input,
1104                                 GWebResultFunc func, gpointer user_data)
1105 {
1106         struct web_session *session;
1107
1108         if (web == NULL || url == NULL)
1109                 return 0;
1110
1111         debug(web, "request %s", url);
1112
1113         session = g_try_new0(struct web_session, 1);
1114         if (session == NULL)
1115                 return 0;
1116
1117         if (parse_url(session, url, web->proxy) < 0) {
1118                 free_session(session);
1119                 return 0;
1120         }
1121
1122         debug(web, "address %s", session->address);
1123         debug(web, "port %u", session->port);
1124         debug(web, "host %s", session->host);
1125         debug(web, "flags %lu", session->flags);
1126         debug(web, "request %s", session->request);
1127
1128         if (type != NULL) {
1129                 session->content_type = g_strdup(type);
1130
1131                 debug(web, "content-type %s", session->content_type);
1132         }
1133
1134         session->web = web;
1135
1136         session->result_func = func;
1137         session->input_func = input;
1138         session->user_data = user_data;
1139
1140         session->receive_buffer = g_try_malloc(DEFAULT_BUFFER_SIZE);
1141         if (session->receive_buffer == NULL) {
1142                 free_session(session);
1143                 return 0;
1144         }
1145
1146         session->result.headers = g_hash_table_new_full(g_str_hash, g_str_equal,
1147                                                         g_free, g_free);
1148         if (session->result.headers == NULL) {
1149                 free_session(session);
1150                 return 0;
1151         }
1152
1153         session->receive_space = DEFAULT_BUFFER_SIZE;
1154         session->send_buffer = g_string_sized_new(0);
1155         session->current_header = g_string_sized_new(0);
1156         session->header_done = FALSE;
1157         session->body_done = FALSE;
1158
1159         if (session->address == NULL && inet_aton(session->host, NULL) == 0) {
1160                 session->resolv_action = g_resolv_lookup_hostname(web->resolv,
1161                                         session->host, resolv_result, session);
1162                 if (session->resolv_action == 0) {
1163                         free_session(session);
1164                         return 0;
1165                 }
1166         } else {
1167                 struct addrinfo hints;
1168                 char *port;
1169                 int ret;
1170
1171                 if (session->address == NULL)
1172                         session->address = g_strdup(session->host);
1173
1174                 memset(&hints, 0, sizeof(struct addrinfo));
1175                 hints.ai_flags = AI_NUMERICHOST;
1176                 hints.ai_family = session->web->family;
1177
1178                 if (session->addr != NULL) {
1179                         freeaddrinfo(session->addr);
1180                         session->addr = NULL;
1181                 }
1182
1183                 port = g_strdup_printf("%u", session->port);
1184                 ret = getaddrinfo(session->address, port, &hints,
1185                                                         &session->addr);
1186                 g_free(port);
1187                 if (ret != 0 || session->addr == NULL) {
1188                         free_session(session);
1189                         return 0;
1190                 }
1191
1192                 if (create_transport(session) < 0) {
1193                         free_session(session);
1194                         return 0;
1195                 }
1196         }
1197
1198         web->session_list = g_list_append(web->session_list, session);
1199
1200         return web->next_query_id++;
1201 }
1202
1203 guint g_web_request_get(GWeb *web, const char *url,
1204                                 GWebResultFunc func, gpointer user_data)
1205 {
1206         return do_request(web, url, NULL, NULL, func, user_data);
1207 }
1208
1209 guint g_web_request_post(GWeb *web, const char *url,
1210                                 const char *type, GWebInputFunc input,
1211                                 GWebResultFunc func, gpointer user_data)
1212 {
1213         return do_request(web, url, type, input, func, user_data);
1214 }
1215
1216 gboolean g_web_cancel_request(GWeb *web, guint id)
1217 {
1218         if (web == NULL)
1219                 return FALSE;
1220
1221         return TRUE;
1222 }
1223
1224 guint16 g_web_result_get_status(GWebResult *result)
1225 {
1226         if (result == NULL)
1227                 return 0;
1228
1229         return result->status;
1230 }
1231
1232 gboolean g_web_result_get_chunk(GWebResult *result,
1233                                 const guint8 **chunk, gsize *length)
1234 {
1235         if (result == NULL)
1236                 return FALSE;
1237
1238         if (chunk == NULL)
1239                 return FALSE;
1240
1241         *chunk = result->buffer;
1242
1243         if (length != NULL)
1244                 *length = result->length;
1245
1246         return TRUE;
1247 }
1248
1249 gboolean g_web_result_get_header(GWebResult *result,
1250                                 const char *header, const char **value)
1251 {
1252         if (result == NULL)
1253                 return FALSE;
1254
1255         if (value == NULL)
1256                 return FALSE;
1257
1258         *value = g_hash_table_lookup(result->headers, header);
1259
1260         if (*value == NULL)
1261                 return FALSE;
1262
1263         return TRUE;
1264 }
1265
1266 struct _GWebParser {
1267         gint ref_count;
1268         char *begin_token;
1269         char *end_token;
1270         const char *token_str;
1271         size_t token_len;
1272         size_t token_pos;
1273         gboolean intoken;
1274         GString *content;
1275         GWebParserFunc func;
1276         gpointer user_data;
1277 };
1278
1279 GWebParser *g_web_parser_new(const char *begin, const char *end,
1280                                 GWebParserFunc func, gpointer user_data)
1281 {
1282         GWebParser *parser;
1283
1284         parser = g_try_new0(GWebParser, 1);
1285         if (parser == NULL)
1286                 return NULL;
1287
1288         parser->ref_count = 1;
1289
1290         parser->begin_token = g_strdup(begin);
1291         parser->end_token = g_strdup(end);
1292
1293         if (parser->begin_token == NULL) {
1294                 g_free(parser);
1295                 return NULL;
1296         }
1297
1298         parser->func = func;
1299         parser->user_data = user_data;
1300
1301         parser->token_str = parser->begin_token;
1302         parser->token_len = strlen(parser->token_str);
1303         parser->token_pos = 0;
1304
1305         parser->intoken = FALSE;
1306         parser->content = g_string_sized_new(0);
1307
1308         return parser;
1309 }
1310
1311 GWebParser *g_web_parser_ref(GWebParser *parser)
1312 {
1313         if (parser == NULL)
1314                 return NULL;
1315
1316         g_atomic_int_inc(&parser->ref_count);
1317
1318         return parser;
1319 }
1320
1321 void g_web_parser_unref(GWebParser *parser)
1322 {
1323         if (parser == NULL)
1324                 return;
1325
1326         if (g_atomic_int_dec_and_test(&parser->ref_count) == FALSE)
1327                 return;
1328
1329         g_string_free(parser->content, TRUE);
1330
1331         g_free(parser->begin_token);
1332         g_free(parser->end_token);
1333         g_free(parser);
1334 }
1335
1336 void g_web_parser_feed_data(GWebParser *parser,
1337                                 const guint8 *data, gsize length)
1338 {
1339         const guint8 *ptr = data;
1340
1341         if (parser == NULL)
1342                 return;
1343
1344         while (length > 0) {
1345                 guint8 chr = parser->token_str[parser->token_pos];
1346
1347                 if (parser->token_pos == 0) {
1348                         guint8 *pos;
1349
1350                         pos = memchr(ptr, chr, length);
1351                         if (pos == NULL) {
1352                                 if (parser->intoken == TRUE)
1353                                         g_string_append_len(parser->content,
1354                                                         (gchar *) ptr, length);
1355                                 break;
1356                         }
1357
1358                         if (parser->intoken == TRUE)
1359                                 g_string_append_len(parser->content,
1360                                                 (gchar *) ptr, (pos - ptr) + 1);
1361
1362                         length -= (pos - ptr) + 1;
1363                         ptr = pos + 1;
1364
1365                         parser->token_pos++;
1366                         continue;
1367                 }
1368
1369                 if (parser->intoken == TRUE)
1370                         g_string_append_c(parser->content, ptr[0]);
1371
1372                 if (ptr[0] != chr) {
1373                         length--;
1374                         ptr++;
1375
1376                         parser->token_pos = 0;
1377                         continue;
1378                 }
1379
1380                 length--;
1381                 ptr++;
1382
1383                 parser->token_pos++;
1384
1385                 if (parser->token_pos == parser->token_len) {
1386                         if (parser->intoken == FALSE) {
1387                                 g_string_append(parser->content,
1388                                                         parser->token_str);
1389
1390                                 parser->intoken = TRUE;
1391                                 parser->token_str = parser->end_token;
1392                                 parser->token_len = strlen(parser->end_token);
1393                                 parser->token_pos = 0;
1394                         } else {
1395                                 char *str;
1396                                 str = g_string_free(parser->content, FALSE);
1397                                 parser->content = g_string_sized_new(0);
1398                                 if (parser->func)
1399                                         parser->func(str, parser->user_data);
1400                                 g_free(str);
1401
1402                                 parser->intoken = FALSE;
1403                                 parser->token_str = parser->begin_token;
1404                                 parser->token_len = strlen(parser->begin_token);
1405                                 parser->token_pos = 0;
1406                         }
1407                 }
1408         }
1409 }
1410
1411 void g_web_parser_end_data(GWebParser *parser)
1412 {
1413         if (parser == NULL)
1414                 return;
1415 }