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