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