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