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