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