gresolv: Make debug func print more useful information
[platform/upstream/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
438         if (session->result_func == NULL)
439                 return;
440
441         if (status != 0)
442                 session->result.status = status;
443
444         session->result_func(&session->result, session->user_data);
445
446 }
447
448 static inline void call_route_func(struct web_session *session)
449 {
450         if (session->route_func != NULL)
451                 session->route_func(session->address, session->addr->ai_family,
452                                 session->web->index, session->user_data);
453 }
454
455 static gboolean process_send_buffer(struct web_session *session)
456 {
457         GString *buf;
458         gsize count, bytes_written;
459         GIOStatus status;
460
461         if (session == NULL)
462                 return FALSE;
463
464         buf = session->send_buffer;
465         count = buf->len;
466
467         if (count == 0) {
468                 if (session->request_started == TRUE &&
469                                         session->more_data == FALSE &&
470                                         session->fd == -1)
471                         session->body_done = TRUE;
472
473                 return FALSE;
474         }
475
476         status = g_io_channel_write_chars(session->transport_channel,
477                                         buf->str, count, &bytes_written, NULL);
478
479         debug(session->web, "status %u bytes to write %zu bytes written %zu",
480                                         status, count, bytes_written);
481
482         if (status != G_IO_STATUS_NORMAL && status != G_IO_STATUS_AGAIN)
483                 return FALSE;
484
485         g_string_erase(buf, 0, bytes_written);
486
487         return TRUE;
488 }
489
490 static gboolean process_send_file(struct web_session *session)
491 {
492         int sk;
493         off_t offset;
494         ssize_t bytes_sent;
495
496         if (session->fd == -1)
497                 return FALSE;
498
499         if (session->request_started == FALSE || session->more_data == TRUE)
500                 return FALSE;
501
502         sk = g_io_channel_unix_get_fd(session->transport_channel);
503         if (sk < 0)
504                 return FALSE;
505
506         offset = session->offset;
507
508         bytes_sent = sendfile(sk, session->fd, &offset, session->length);
509
510         debug(session->web, "errno: %d, bytes to send %zu / bytes sent %zu",
511                         errno, session->length, bytes_sent);
512
513         if (bytes_sent < 0 && errno != EAGAIN)
514                 return FALSE;
515
516         session->offset = offset;
517         session->length -= bytes_sent;
518
519         if (session->length == 0) {
520                 session->body_done = TRUE;
521                 return FALSE;
522         }
523
524         return TRUE;
525 }
526
527 static void process_next_chunk(struct web_session *session)
528 {
529         GString *buf = session->send_buffer;
530         const guint8 *body;
531         gsize length;
532
533         if (session->input_func == NULL) {
534                 session->more_data = FALSE;
535                 return;
536         }
537
538         session->more_data = session->input_func(&body, &length,
539                                                 session->user_data);
540
541         if (length > 0) {
542                 g_string_append_printf(buf, "%zx\r\n", length);
543                 g_string_append_len(buf, (char *) body, length);
544                 g_string_append(buf, "\r\n");
545         }
546
547         if (session->more_data == FALSE)
548                 g_string_append(buf, "0\r\n\r\n");
549 }
550
551 static void start_request(struct web_session *session)
552 {
553         GString *buf = session->send_buffer;
554         const char *version;
555         const guint8 *body;
556         gsize length;
557
558         debug(session->web, "request %s from %s",
559                                         session->request, session->host);
560
561         g_string_truncate(buf, 0);
562
563         if (session->web->http_version == NULL)
564                 version = "1.1";
565         else
566                 version = session->web->http_version;
567
568         if (session->content_type == NULL)
569                 g_string_append_printf(buf, "GET %s HTTP/%s\r\n",
570                                                 session->request, version);
571         else
572                 g_string_append_printf(buf, "POST %s HTTP/%s\r\n",
573                                                 session->request, version);
574
575         g_string_append_printf(buf, "Host: %s\r\n", session->host);
576
577         if (session->web->user_agent != NULL)
578                 g_string_append_printf(buf, "User-Agent: %s\r\n",
579                                                 session->web->user_agent);
580
581         if (session->web->user_agent_profile != NULL) {
582                 g_string_append_printf(buf, "x-wap-profile: %s\r\n",
583                                        session->web->user_agent_profile);
584         }
585
586         if (session->web->accept_option != NULL)
587                 g_string_append_printf(buf, "Accept: %s\r\n",
588                                                 session->web->accept_option);
589
590         if (session->content_type != NULL) {
591                 g_string_append_printf(buf, "Content-Type: %s\r\n",
592                                                         session->content_type);
593                 if (session->input_func == NULL) {
594                         session->more_data = FALSE;
595                         length = session->length;
596                 } else
597                         session->more_data = session->input_func(&body, &length,
598                                                         session->user_data);
599                 if (session->more_data == FALSE)
600                         g_string_append_printf(buf, "Content-Length: %zu\r\n",
601                                                                         length);
602                 else
603                         g_string_append(buf, "Transfer-Encoding: chunked\r\n");
604         }
605
606         if (session->web->close_connection == TRUE)
607                 g_string_append(buf, "Connection: close\r\n");
608
609         g_string_append(buf, "\r\n");
610
611         if (session->content_type != NULL && length > 0) {
612                 if (session->more_data == TRUE) {
613                         g_string_append_printf(buf, "%zx\r\n", length);
614                         g_string_append_len(buf, (char *) body, length);
615                         g_string_append(buf, "\r\n");
616                 } else if (session->fd == -1)
617                         g_string_append_len(buf, (char *) body, length);
618         }
619 }
620
621 static gboolean send_data(GIOChannel *channel, GIOCondition cond,
622                                                 gpointer user_data)
623 {
624         struct web_session *session = user_data;
625
626         if (cond & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
627                 session->send_watch = 0;
628                 return FALSE;
629         }
630
631         if (process_send_buffer(session) == TRUE)
632                 return TRUE;
633
634         if (process_send_file(session) == TRUE)
635                 return TRUE;
636
637         if (session->request_started == FALSE) {
638                 session->request_started = TRUE;
639                 start_request(session);
640         } else if (session->more_data == TRUE)
641                 process_next_chunk(session);
642
643         process_send_buffer(session);
644
645         if (session->body_done == TRUE) {
646                 session->send_watch = 0;
647                 return FALSE;
648         }
649
650         return TRUE;
651 }
652
653 static int decode_chunked(struct web_session *session,
654                                         const guint8 *buf, gsize len)
655 {
656         const guint8 *ptr = buf;
657         gsize counter;
658
659         while (len > 0) {
660                 guint8 *pos;
661                 gsize count;
662                 char *str;
663
664                 switch (session->chunck_state) {
665                 case CHUNK_SIZE:
666                         pos = memchr(ptr, '\n', len);
667                         if (pos == NULL) {
668                                 g_string_append_len(session->current_header,
669                                                 (gchar *) ptr, len);
670                                 return 0;
671                         }
672
673                         count = pos - ptr;
674                         if (count < 1 || ptr[count - 1] != '\r')
675                                 return -EILSEQ;
676
677                         g_string_append_len(session->current_header,
678                                                 (gchar *) ptr, count);
679
680                         len -= count + 1;
681                         ptr = pos + 1;
682
683                         str = session->current_header->str;
684
685                         counter = strtoul(str, NULL, 16);
686                         if ((counter == 0 && errno == EINVAL) ||
687                                                 counter == ULONG_MAX)
688                                 return -EILSEQ;
689
690                         session->chunk_size = counter;
691                         session->chunk_left = counter;
692
693                         session->chunck_state = CHUNK_DATA;
694                         break;
695                 case CHUNK_R_BODY:
696                         if (*ptr != '\r')
697                                 return -EILSEQ;
698                         ptr++;
699                         len--;
700                         session->chunck_state = CHUNK_N_BODY;
701                         break;
702                 case CHUNK_N_BODY:
703                         if (*ptr != '\n')
704                                 return -EILSEQ;
705                         ptr++;
706                         len--;
707                         session->chunck_state = CHUNK_SIZE;
708                         break;
709                 case CHUNK_DATA:
710                         if (session->chunk_size == 0) {
711                                 debug(session->web, "Download Done in chunk");
712                                 g_string_truncate(session->current_header, 0);
713                                 return 0;
714                         }
715
716                         if (session->chunk_left <= len) {
717                                 session->result.buffer = ptr;
718                                 session->result.length = session->chunk_left;
719                                 call_result_func(session, 0);
720
721                                 len -= session->chunk_left;
722                                 ptr += session->chunk_left;
723
724                                 session->total_len += session->chunk_left;
725                                 session->chunk_left = 0;
726
727                                 g_string_truncate(session->current_header, 0);
728                                 session->chunck_state = CHUNK_R_BODY;
729                                 break;
730                         }
731                         /* more data */
732                         session->result.buffer = ptr;
733                         session->result.length = len;
734                         call_result_func(session, 0);
735
736                         session->chunk_left -= len;
737                         session->total_len += len;
738
739                         len -= len;
740                         ptr += len;
741                         break;
742                 }
743         }
744
745         return 0;
746 }
747
748 static int handle_body(struct web_session *session,
749                                 const guint8 *buf, gsize len)
750 {
751         int err;
752
753         debug(session->web, "[body] length %zu", len);
754
755         if (session->result.use_chunk == FALSE) {
756                 if (len > 0) {
757                         session->result.buffer = buf;
758                         session->result.length = len;
759                         call_result_func(session, 0);
760                 }
761                 return 0;
762         }
763
764         err = decode_chunked(session, buf, len);
765         if (err < 0) {
766                 debug(session->web, "Error in chunk decode %d", err);
767
768                 session->result.buffer = NULL;
769                 session->result.length = 0;
770                 call_result_func(session, 400);
771         }
772
773         return err;
774 }
775
776 static void handle_multi_line(struct web_session *session)
777 {
778         gsize count;
779         char *str;
780         gchar *value;
781
782         str = session->current_header->str;
783
784         if (str[0] != ' ' && str[0] != '\t')
785                 return;
786
787         while (str[0] == ' ' || str[0] == '\t')
788                 str++;
789
790         count = str - session->current_header->str;
791         if (count > 0) {
792                 g_string_erase(session->current_header, 0, count);
793                 g_string_insert_c(session->current_header, 0, ' ');
794         }
795
796         value = g_hash_table_lookup(session->result.headers,
797                                         session->result.last_key);
798         if (value != NULL) {
799                 g_string_insert(session->current_header, 0, value);
800
801                 str = session->current_header->str;
802
803                 g_hash_table_replace(session->result.headers,
804                                         g_strdup(session->result.last_key),
805                                         g_strdup(str));
806         }
807 }
808
809 static void add_header_field(struct web_session *session)
810 {
811         gsize count;
812         guint8 *pos;
813         char *str;
814         gchar *value;
815         gchar *key;
816
817         str = session->current_header->str;
818
819         pos = memchr(str, ':', session->current_header->len);
820         if (pos != NULL) {
821                 *pos = '\0';
822                 pos++;
823
824                 key = g_strdup(str);
825
826                 /* remove preceding white spaces */
827                 while (*pos == ' ')
828                         pos++;
829
830                 count = (char *) pos - str;
831
832                 g_string_erase(session->current_header, 0, count);
833
834                 value = g_hash_table_lookup(session->result.headers, key);
835                 if (value != NULL) {
836                         g_string_insert_c(session->current_header, 0, ' ');
837                         g_string_insert_c(session->current_header, 0, ';');
838
839                         g_string_insert(session->current_header, 0, value);
840                 }
841
842                 str = session->current_header->str;
843                 g_hash_table_replace(session->result.headers, key,
844                                                         g_strdup(str));
845
846                 g_free(session->result.last_key);
847                 session->result.last_key = g_strdup(key);
848         }
849 }
850
851 static gboolean received_data(GIOChannel *channel, GIOCondition cond,
852                                                         gpointer user_data)
853 {
854         struct web_session *session = user_data;
855         guint8 *ptr = session->receive_buffer;
856         gsize bytes_read;
857         GIOStatus status;
858
859         if (cond & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
860                 session->transport_watch = 0;
861                 session->result.buffer = NULL;
862                 session->result.length = 0;
863                 call_result_func(session, 400);
864                 return FALSE;
865         }
866
867         status = g_io_channel_read_chars(channel,
868                                 (gchar *) session->receive_buffer,
869                                 session->receive_space - 1, &bytes_read, NULL);
870
871         debug(session->web, "bytes read %zu", bytes_read);
872
873         if (status != G_IO_STATUS_NORMAL && status != G_IO_STATUS_AGAIN) {
874                 session->transport_watch = 0;
875                 session->result.buffer = NULL;
876                 session->result.length = 0;
877                 call_result_func(session, 0);
878                 return FALSE;
879         }
880
881         session->receive_buffer[bytes_read] = '\0';
882
883         if (session->header_done == TRUE) {
884                 if (handle_body(session, session->receive_buffer,
885                                                         bytes_read) < 0) {
886                         session->transport_watch = 0;
887                         return FALSE;
888                 }
889                 return TRUE;
890         }
891
892         while (bytes_read > 0) {
893                 guint8 *pos;
894                 gsize count;
895                 char *str;
896
897                 pos = memchr(ptr, '\n', bytes_read);
898                 if (pos == NULL) {
899                         g_string_append_len(session->current_header,
900                                                 (gchar *) ptr, bytes_read);
901                         return TRUE;
902                 }
903
904                 *pos = '\0';
905                 count = strlen((char *) ptr);
906                 if (count > 0 && ptr[count - 1] == '\r') {
907                         ptr[--count] = '\0';
908                         bytes_read--;
909                 }
910
911                 g_string_append_len(session->current_header,
912                                                 (gchar *) ptr, count);
913
914                 bytes_read -= count + 1;
915                 if (bytes_read > 0)
916                         ptr = pos + 1;
917                 else
918                         ptr = NULL;
919
920                 if (session->current_header->len == 0) {
921                         char *val;
922
923                         session->header_done = TRUE;
924
925                         val = g_hash_table_lookup(session->result.headers,
926                                                         "Transfer-Encoding");
927                         if (val != NULL) {
928                                 val = g_strrstr(val, "chunked");
929                                 if (val != NULL) {
930                                         session->result.use_chunk = TRUE;
931
932                                         session->chunck_state = CHUNK_SIZE;
933                                         session->chunk_left = 0;
934                                         session->total_len = 0;
935                                 }
936                         }
937
938                         if (handle_body(session, ptr, bytes_read) < 0) {
939                                 session->transport_watch = 0;
940                                 return FALSE;
941                         }
942                         break;
943                 }
944
945                 str = session->current_header->str;
946
947                 if (session->result.status == 0) {
948                         unsigned int code;
949
950                         if (sscanf(str, "HTTP/%*s %u %*s", &code) == 1)
951                                 session->result.status = code;
952                 }
953
954                 debug(session->web, "[header] %s", str);
955
956                 /* handle multi-line header */
957                 if (str[0] == ' ' || str[0] == '\t')
958                         handle_multi_line(session);
959                 else
960                         add_header_field(session);
961
962                 g_string_truncate(session->current_header, 0);
963         }
964
965         return TRUE;
966 }
967
968 static int bind_to_address(int sk, const char *interface, int family)
969 {
970         struct ifaddrs *ifaddr_list, *ifaddr;
971         int size, err = -1;
972
973         if (getifaddrs(&ifaddr_list) < 0)
974                 return err;
975
976         for (ifaddr = ifaddr_list; ifaddr != NULL; ifaddr = ifaddr->ifa_next) {
977                 if (g_strcmp0(ifaddr->ifa_name, interface) != 0)
978                         continue;
979
980                 if (ifaddr->ifa_addr == NULL ||
981                                 ifaddr->ifa_addr->sa_family != family)
982                         continue;
983
984                 switch (family) {
985                 case AF_INET:
986                         size = sizeof(struct sockaddr_in);
987                         break;
988                 case AF_INET6:
989                         size = sizeof(struct sockaddr_in6);
990                         break;
991                 default:
992                         continue;
993                 }
994
995                 err = bind(sk, (struct sockaddr *) ifaddr->ifa_addr, size);
996                 break;
997         }
998
999         freeifaddrs(ifaddr_list);
1000         return err;
1001 }
1002
1003 static inline int bind_socket(int sk, int index, int family)
1004 {
1005         char interface[IF_NAMESIZE];
1006         int err;
1007
1008         if (if_indextoname(index, interface) == NULL)
1009                 return -1;
1010
1011         err = setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
1012                                         interface, IF_NAMESIZE);
1013         if (err < 0)
1014                 err = bind_to_address(sk, interface, family);
1015
1016         return err;
1017 }
1018
1019 static int connect_session_transport(struct web_session *session)
1020 {
1021         GIOFlags flags;
1022         int sk;
1023
1024         sk = socket(session->addr->ai_family, SOCK_STREAM | SOCK_CLOEXEC,
1025                         IPPROTO_TCP);
1026         if (sk < 0)
1027                 return -EIO;
1028
1029         if (session->web->index > 0) {
1030                 if (bind_socket(sk, session->web->index,
1031                                         session->addr->ai_family) < 0) {
1032                         debug(session->web, "bind() %s", strerror(errno));
1033                         close(sk);
1034                         return -EIO;
1035                 }
1036         }
1037
1038         if (session->flags & SESSION_FLAG_USE_TLS) {
1039                 debug(session->web, "using TLS encryption");
1040                 session->transport_channel = g_io_channel_gnutls_new(sk);
1041         } else {
1042                 debug(session->web, "no encryption");
1043                 session->transport_channel = g_io_channel_unix_new(sk);
1044         }
1045
1046         if (session->transport_channel == NULL) {
1047                 debug(session->web, "channel missing");
1048                 close(sk);
1049                 return -ENOMEM;
1050         }
1051
1052         flags = g_io_channel_get_flags(session->transport_channel);
1053         g_io_channel_set_flags(session->transport_channel,
1054                                         flags | G_IO_FLAG_NONBLOCK, NULL);
1055
1056         g_io_channel_set_encoding(session->transport_channel, NULL, NULL);
1057         g_io_channel_set_buffered(session->transport_channel, FALSE);
1058
1059         g_io_channel_set_close_on_unref(session->transport_channel, TRUE);
1060
1061         if (connect(sk, session->addr->ai_addr,
1062                         session->addr->ai_addrlen) < 0) {
1063                 if (errno != EINPROGRESS) {
1064                         debug(session->web, "connect() %s", strerror(errno));
1065                         close(sk);
1066                         return -EIO;
1067                 }
1068         }
1069
1070         session->transport_watch = g_io_add_watch(session->transport_channel,
1071                                 G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
1072                                                 received_data, session);
1073
1074         session->send_watch = g_io_add_watch(session->transport_channel,
1075                                 G_IO_OUT | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
1076                                                 send_data, session);
1077
1078         return 0;
1079 }
1080
1081 static int create_transport(struct web_session *session)
1082 {
1083         int err;
1084
1085         err = connect_session_transport(session);
1086         if (err < 0)
1087                 return err;
1088
1089         debug(session->web, "creating session %s:%u",
1090                                         session->address, session->port);
1091
1092         return 0;
1093 }
1094
1095 static int parse_url(struct web_session *session,
1096                                 const char *url, const char *proxy)
1097 {
1098         char *scheme, *host, *port, *path;
1099
1100         scheme = g_strdup(url);
1101         if (scheme == NULL)
1102                 return -EINVAL;
1103
1104         host = strstr(scheme, "://");
1105         if (host != NULL) {
1106                 *host = '\0';
1107                 host += 3;
1108
1109                 if (strcasecmp(scheme, "https") == 0) {
1110                         session->port = 443;
1111                         session->flags |= SESSION_FLAG_USE_TLS;
1112                 } else if (strcasecmp(scheme, "http") == 0) {
1113                         session->port = 80;
1114                 } else {
1115                         g_free(scheme);
1116                         return -EINVAL;
1117                 }
1118         } else {
1119                 host = scheme;
1120                 session->port = 80;
1121         }
1122
1123         path = strchr(host, '/');
1124         if (path != NULL)
1125                 *(path++) = '\0';
1126
1127         if (proxy == NULL)
1128                 session->request = g_strdup_printf("/%s", path ? path : "");
1129         else
1130                 session->request = g_strdup(url);
1131
1132         port = strrchr(host, ':');
1133         if (port != NULL) {
1134                 char *end;
1135                 int tmp = strtol(port + 1, &end, 10);
1136
1137                 if (*end == '\0') {
1138                         *port = '\0';
1139                         session->port = tmp;
1140                 }
1141
1142                 if (proxy == NULL)
1143                         session->host = g_strdup(host);
1144                 else
1145                         session->host = g_strdup_printf("%s:%u", host, tmp);
1146         } else
1147                 session->host = g_strdup(host);
1148
1149         g_free(scheme);
1150
1151         if (proxy == NULL)
1152                 return 0;
1153
1154         scheme = g_strdup(proxy);
1155         if (scheme == NULL)
1156                 return -EINVAL;
1157
1158         host = strstr(proxy, "://");
1159         if (host != NULL) {
1160                 *host = '\0';
1161                 host += 3;
1162
1163                 if (strcasecmp(scheme, "http") != 0) {
1164                         g_free(scheme);
1165                         return -EINVAL;
1166                 }
1167         } else
1168                 host = scheme;
1169
1170         path = strchr(host, '/');
1171         if (path != NULL)
1172                 *(path++) = '\0';
1173
1174         port = strrchr(host, ':');
1175         if (port != NULL) {
1176                 char *end;
1177                 int tmp = strtol(port + 1, &end, 10);
1178
1179                 if (*end == '\0') {
1180                         *port = '\0';
1181                         session->port = tmp;
1182                 }
1183         }
1184
1185         session->address = g_strdup(host);
1186
1187         g_free(scheme);
1188
1189         return 0;
1190 }
1191
1192 static void resolv_result(GResolvResultStatus status,
1193                                         char **results, gpointer user_data)
1194 {
1195         struct web_session *session = user_data;
1196         struct addrinfo hints;
1197         char *port;
1198         int ret;
1199
1200         if (results == NULL || results[0] == NULL) {
1201                 call_result_func(session, 404);
1202                 return;
1203         }
1204
1205         debug(session->web, "address %s", results[0]);
1206
1207         memset(&hints, 0, sizeof(struct addrinfo));
1208         hints.ai_flags = AI_NUMERICHOST;
1209         hints.ai_family = session->web->family;
1210
1211         if (session->addr != NULL) {
1212                 freeaddrinfo(session->addr);
1213                 session->addr = NULL;
1214         }
1215
1216         port = g_strdup_printf("%u", session->port);
1217         ret = getaddrinfo(results[0], port, &hints, &session->addr);
1218         g_free(port);
1219         if (ret != 0 || session->addr == NULL) {
1220                 call_result_func(session, 400);
1221                 return;
1222         }
1223
1224         session->address = g_strdup(results[0]);
1225         call_route_func(session);
1226
1227         if (create_transport(session) < 0) {
1228                 call_result_func(session, 409);
1229                 return;
1230         }
1231 }
1232
1233 static guint do_request(GWeb *web, const char *url,
1234                                 const char *type, GWebInputFunc input,
1235                                 int fd, gsize length, GWebResultFunc func,
1236                                 GWebRouteFunc route, gpointer user_data)
1237 {
1238         struct web_session *session;
1239
1240         if (web == NULL || url == NULL)
1241                 return 0;
1242
1243         debug(web, "request %s", url);
1244
1245         session = g_try_new0(struct web_session, 1);
1246         if (session == NULL)
1247                 return 0;
1248
1249         if (parse_url(session, url, web->proxy) < 0) {
1250                 free_session(session);
1251                 return 0;
1252         }
1253
1254         debug(web, "address %s", session->address);
1255         debug(web, "port %u", session->port);
1256         debug(web, "host %s", session->host);
1257         debug(web, "flags %lu", session->flags);
1258         debug(web, "request %s", session->request);
1259
1260         if (type != NULL) {
1261                 session->content_type = g_strdup(type);
1262
1263                 debug(web, "content-type %s", session->content_type);
1264         }
1265
1266         session->web = web;
1267
1268         session->result_func = func;
1269         session->route_func = route;
1270         session->input_func = input;
1271         session->fd = fd;
1272         session->length = length;
1273         session->offset = 0;
1274         session->user_data = user_data;
1275
1276         session->receive_buffer = g_try_malloc(DEFAULT_BUFFER_SIZE);
1277         if (session->receive_buffer == NULL) {
1278                 free_session(session);
1279                 return 0;
1280         }
1281
1282         session->result.headers = g_hash_table_new_full(g_str_hash, g_str_equal,
1283                                                         g_free, g_free);
1284         if (session->result.headers == NULL) {
1285                 free_session(session);
1286                 return 0;
1287         }
1288
1289         session->receive_space = DEFAULT_BUFFER_SIZE;
1290         session->send_buffer = g_string_sized_new(0);
1291         session->current_header = g_string_sized_new(0);
1292         session->header_done = FALSE;
1293         session->body_done = FALSE;
1294
1295         if (session->address == NULL && inet_aton(session->host, NULL) == 0) {
1296                 session->resolv_action = g_resolv_lookup_hostname(web->resolv,
1297                                         session->host, resolv_result, session);
1298                 if (session->resolv_action == 0) {
1299                         free_session(session);
1300                         return 0;
1301                 }
1302         } else {
1303                 struct addrinfo hints;
1304                 char *port;
1305                 int ret;
1306
1307                 if (session->address == NULL)
1308                         session->address = g_strdup(session->host);
1309
1310                 memset(&hints, 0, sizeof(struct addrinfo));
1311                 hints.ai_flags = AI_NUMERICHOST;
1312                 hints.ai_family = session->web->family;
1313
1314                 if (session->addr != NULL) {
1315                         freeaddrinfo(session->addr);
1316                         session->addr = NULL;
1317                 }
1318
1319                 port = g_strdup_printf("%u", session->port);
1320                 ret = getaddrinfo(session->address, port, &hints,
1321                                                         &session->addr);
1322                 g_free(port);
1323                 if (ret != 0 || session->addr == NULL) {
1324                         free_session(session);
1325                         return 0;
1326                 }
1327
1328                 if (create_transport(session) < 0) {
1329                         free_session(session);
1330                         return 0;
1331                 }
1332         }
1333
1334         web->session_list = g_list_append(web->session_list, session);
1335
1336         return web->next_query_id++;
1337 }
1338
1339 guint g_web_request_get(GWeb *web, const char *url, GWebResultFunc func,
1340                 GWebRouteFunc route, gpointer user_data)
1341 {
1342         return do_request(web, url, NULL, NULL, -1, 0, func, route, user_data);
1343 }
1344
1345 guint g_web_request_post(GWeb *web, const char *url,
1346                                 const char *type, GWebInputFunc input,
1347                                 GWebResultFunc func, gpointer user_data)
1348 {
1349         return do_request(web, url, type, input, -1, 0, func, NULL, user_data);
1350 }
1351
1352 guint g_web_request_post_file(GWeb *web, const char *url,
1353                                 const char *type, const char *file,
1354                                 GWebResultFunc func, gpointer user_data)
1355 {
1356         struct stat st;
1357         int fd;
1358         guint ret;
1359
1360         if (stat(file, &st) < 0)
1361                 return 0;
1362
1363         fd = open(file, O_RDONLY);
1364         if (fd < 0)
1365                 return 0;
1366
1367         ret = do_request(web, url, type, NULL, fd, st.st_size, func, NULL,
1368                         user_data);
1369         if (ret == 0)
1370                 close(fd);
1371
1372         return ret;
1373 }
1374
1375 gboolean g_web_cancel_request(GWeb *web, guint id)
1376 {
1377         if (web == NULL)
1378                 return FALSE;
1379
1380         return TRUE;
1381 }
1382
1383 guint16 g_web_result_get_status(GWebResult *result)
1384 {
1385         if (result == NULL)
1386                 return 0;
1387
1388         return result->status;
1389 }
1390
1391 gboolean g_web_result_get_chunk(GWebResult *result,
1392                                 const guint8 **chunk, gsize *length)
1393 {
1394         if (result == NULL)
1395                 return FALSE;
1396
1397         if (chunk == NULL)
1398                 return FALSE;
1399
1400         *chunk = result->buffer;
1401
1402         if (length != NULL)
1403                 *length = result->length;
1404
1405         return TRUE;
1406 }
1407
1408 gboolean g_web_result_get_header(GWebResult *result,
1409                                 const char *header, const char **value)
1410 {
1411         if (result == NULL)
1412                 return FALSE;
1413
1414         if (value == NULL)
1415                 return FALSE;
1416
1417         *value = g_hash_table_lookup(result->headers, header);
1418
1419         if (*value == NULL)
1420                 return FALSE;
1421
1422         return TRUE;
1423 }
1424
1425 struct _GWebParser {
1426         gint ref_count;
1427         char *begin_token;
1428         char *end_token;
1429         const char *token_str;
1430         size_t token_len;
1431         size_t token_pos;
1432         gboolean intoken;
1433         GString *content;
1434         GWebParserFunc func;
1435         gpointer user_data;
1436 };
1437
1438 GWebParser *g_web_parser_new(const char *begin, const char *end,
1439                                 GWebParserFunc func, gpointer user_data)
1440 {
1441         GWebParser *parser;
1442
1443         parser = g_try_new0(GWebParser, 1);
1444         if (parser == NULL)
1445                 return NULL;
1446
1447         parser->ref_count = 1;
1448
1449         parser->begin_token = g_strdup(begin);
1450         parser->end_token = g_strdup(end);
1451
1452         if (parser->begin_token == NULL) {
1453                 g_free(parser);
1454                 return NULL;
1455         }
1456
1457         parser->func = func;
1458         parser->user_data = user_data;
1459
1460         parser->token_str = parser->begin_token;
1461         parser->token_len = strlen(parser->token_str);
1462         parser->token_pos = 0;
1463
1464         parser->intoken = FALSE;
1465         parser->content = g_string_sized_new(0);
1466
1467         return parser;
1468 }
1469
1470 GWebParser *g_web_parser_ref(GWebParser *parser)
1471 {
1472         if (parser == NULL)
1473                 return NULL;
1474
1475         __sync_fetch_and_add(&parser->ref_count, 1);
1476
1477         return parser;
1478 }
1479
1480 void g_web_parser_unref(GWebParser *parser)
1481 {
1482         if (parser == NULL)
1483                 return;
1484
1485         if (__sync_fetch_and_sub(&parser->ref_count, 1) != 1)
1486                 return;
1487
1488         g_string_free(parser->content, TRUE);
1489
1490         g_free(parser->begin_token);
1491         g_free(parser->end_token);
1492         g_free(parser);
1493 }
1494
1495 void g_web_parser_feed_data(GWebParser *parser,
1496                                 const guint8 *data, gsize length)
1497 {
1498         const guint8 *ptr = data;
1499
1500         if (parser == NULL)
1501                 return;
1502
1503         while (length > 0) {
1504                 guint8 chr = parser->token_str[parser->token_pos];
1505
1506                 if (parser->token_pos == 0) {
1507                         guint8 *pos;
1508
1509                         pos = memchr(ptr, chr, length);
1510                         if (pos == NULL) {
1511                                 if (parser->intoken == TRUE)
1512                                         g_string_append_len(parser->content,
1513                                                         (gchar *) ptr, length);
1514                                 break;
1515                         }
1516
1517                         if (parser->intoken == TRUE)
1518                                 g_string_append_len(parser->content,
1519                                                 (gchar *) ptr, (pos - ptr) + 1);
1520
1521                         length -= (pos - ptr) + 1;
1522                         ptr = pos + 1;
1523
1524                         parser->token_pos++;
1525                         continue;
1526                 }
1527
1528                 if (parser->intoken == TRUE)
1529                         g_string_append_c(parser->content, ptr[0]);
1530
1531                 if (ptr[0] != chr) {
1532                         length--;
1533                         ptr++;
1534
1535                         parser->token_pos = 0;
1536                         continue;
1537                 }
1538
1539                 length--;
1540                 ptr++;
1541
1542                 parser->token_pos++;
1543
1544                 if (parser->token_pos == parser->token_len) {
1545                         if (parser->intoken == FALSE) {
1546                                 g_string_append(parser->content,
1547                                                         parser->token_str);
1548
1549                                 parser->intoken = TRUE;
1550                                 parser->token_str = parser->end_token;
1551                                 parser->token_len = strlen(parser->end_token);
1552                                 parser->token_pos = 0;
1553                         } else {
1554                                 char *str;
1555                                 str = g_string_free(parser->content, FALSE);
1556                                 parser->content = g_string_sized_new(0);
1557                                 if (parser->func)
1558                                         parser->func(str, parser->user_data);
1559                                 g_free(str);
1560
1561                                 parser->intoken = FALSE;
1562                                 parser->token_str = parser->begin_token;
1563                                 parser->token_len = strlen(parser->begin_token);
1564                                 parser->token_pos = 0;
1565                         }
1566                 }
1567         }
1568 }
1569
1570 void g_web_parser_end_data(GWebParser *parser)
1571 {
1572         if (parser == NULL)
1573                 return;
1574 }