gweb: Add SOCK_CLOEXEC to socket()
[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 | SOCK_CLOEXEC,
909                         IPPROTO_TCP);
910         if (sk < 0)
911                 return -EIO;
912
913         if (session->flags & SESSION_FLAG_USE_TLS) {
914                 debug(session->web, "using TLS encryption");
915                 session->transport_channel = g_io_channel_gnutls_new(sk);
916         } else {
917                 debug(session->web, "no encryption");
918                 session->transport_channel = g_io_channel_unix_new(sk);
919         }
920
921         if (session->transport_channel == NULL) {
922                 close(sk);
923                 return -ENOMEM;
924         }
925
926         flags = g_io_channel_get_flags(session->transport_channel);
927         g_io_channel_set_flags(session->transport_channel,
928                                         flags | G_IO_FLAG_NONBLOCK, NULL);
929
930         g_io_channel_set_encoding(session->transport_channel, NULL, NULL);
931         g_io_channel_set_buffered(session->transport_channel, FALSE);
932
933         g_io_channel_set_close_on_unref(session->transport_channel, TRUE);
934
935         if (connect(sk, session->addr->ai_addr,
936                         session->addr->ai_addrlen) < 0) {
937                 if (errno != EINPROGRESS) {
938                         close(sk);
939                         return -EIO;
940                 }
941         }
942
943         session->transport_watch = g_io_add_watch(session->transport_channel,
944                                 G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
945                                                 received_data, session);
946
947         session->send_watch = g_io_add_watch(session->transport_channel,
948                                 G_IO_OUT | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
949                                                 send_data, session);
950
951         return 0;
952 }
953
954 static int create_transport(struct web_session *session)
955 {
956         int err;
957
958         err = connect_session_transport(session);
959         if (err < 0)
960                 return err;
961
962         debug(session->web, "creating session %s:%u",
963                                         session->address, session->port);
964
965         return 0;
966 }
967
968 static int parse_url(struct web_session *session,
969                                 const char *url, const char *proxy)
970 {
971         char *scheme, *host, *port, *path;
972
973         scheme = g_strdup(url);
974         if (scheme == NULL)
975                 return -EINVAL;
976
977         host = strstr(scheme, "://");
978         if (host != NULL) {
979                 *host = '\0';
980                 host += 3;
981
982                 if (strcasecmp(scheme, "https") == 0) {
983                         session->port = 443;
984                         session->flags |= SESSION_FLAG_USE_TLS;
985                 } else if (strcasecmp(scheme, "http") == 0) {
986                         session->port = 80;
987                 } else {
988                         g_free(scheme);
989                         return -EINVAL;
990                 }
991         } else {
992                 host = scheme;
993                 session->port = 80;
994         }
995
996         path = strchr(host, '/');
997         if (path != NULL)
998                 *(path++) = '\0';
999
1000         if (proxy == NULL)
1001                 session->request = g_strdup_printf("/%s", path ? path : "");
1002         else
1003                 session->request = g_strdup(url);
1004
1005         port = strrchr(host, ':');
1006         if (port != NULL) {
1007                 char *end;
1008                 int tmp = strtol(port + 1, &end, 10);
1009
1010                 if (*end == '\0') {
1011                         *port = '\0';
1012                         session->port = tmp;
1013                 }
1014
1015                 if (proxy == NULL)
1016                         session->host = g_strdup(host);
1017                 else
1018                         session->host = g_strdup_printf("%s:%u", host, tmp);
1019         } else
1020                 session->host = g_strdup(host);
1021
1022         g_free(scheme);
1023
1024         if (proxy == NULL)
1025                 return 0;
1026
1027         scheme = g_strdup(proxy);
1028         if (scheme == NULL)
1029                 return -EINVAL;
1030
1031         host = strstr(proxy, "://");
1032         if (host != NULL) {
1033                 *host = '\0';
1034                 host += 3;
1035
1036                 if (strcasecmp(scheme, "http") != 0) {
1037                         g_free(scheme);
1038                         return -EINVAL;
1039                 }
1040         } else
1041                 host = scheme;
1042
1043         path = strchr(host, '/');
1044         if (path != NULL)
1045                 *(path++) = '\0';
1046
1047         port = strrchr(host, ':');
1048         if (port != NULL) {
1049                 char *end;
1050                 int tmp = strtol(port + 1, &end, 10);
1051
1052                 if (*end == '\0') {
1053                         *port = '\0';
1054                         session->port = tmp;
1055                 }
1056         }
1057
1058         session->address = g_strdup(host);
1059
1060         g_free(scheme);
1061
1062         return 0;
1063 }
1064
1065 static void resolv_result(GResolvResultStatus status,
1066                                         char **results, gpointer user_data)
1067 {
1068         struct web_session *session = user_data;
1069         struct addrinfo hints;
1070         char *port;
1071         int ret;
1072
1073         if (results == NULL || results[0] == NULL) {
1074                 call_result_func(session, 404);
1075                 return;
1076         }
1077
1078         debug(session->web, "address %s", results[0]);
1079
1080         memset(&hints, 0, sizeof(struct addrinfo));
1081         hints.ai_flags = AI_NUMERICHOST;
1082         hints.ai_family = session->web->family;
1083
1084         if (session->addr != NULL) {
1085                 freeaddrinfo(session->addr);
1086                 session->addr = NULL;
1087         }
1088
1089         port = g_strdup_printf("%u", session->port);
1090         ret = getaddrinfo(results[0], port, &hints, &session->addr);
1091         g_free(port);
1092         if (ret != 0 || session->addr == NULL) {
1093                 call_result_func(session, 400);
1094                 return;
1095         }
1096
1097         session->address = g_strdup(results[0]);
1098
1099         if (create_transport(session) < 0) {
1100                 call_result_func(session, 409);
1101                 return;
1102         }
1103 }
1104
1105 static guint do_request(GWeb *web, const char *url,
1106                                 const char *type, GWebInputFunc input,
1107                                 GWebResultFunc func, gpointer user_data)
1108 {
1109         struct web_session *session;
1110
1111         if (web == NULL || url == NULL)
1112                 return 0;
1113
1114         debug(web, "request %s", url);
1115
1116         session = g_try_new0(struct web_session, 1);
1117         if (session == NULL)
1118                 return 0;
1119
1120         if (parse_url(session, url, web->proxy) < 0) {
1121                 free_session(session);
1122                 return 0;
1123         }
1124
1125         debug(web, "address %s", session->address);
1126         debug(web, "port %u", session->port);
1127         debug(web, "host %s", session->host);
1128         debug(web, "flags %lu", session->flags);
1129         debug(web, "request %s", session->request);
1130
1131         if (type != NULL) {
1132                 session->content_type = g_strdup(type);
1133
1134                 debug(web, "content-type %s", session->content_type);
1135         }
1136
1137         session->web = web;
1138
1139         session->result_func = func;
1140         session->input_func = input;
1141         session->user_data = user_data;
1142
1143         session->receive_buffer = g_try_malloc(DEFAULT_BUFFER_SIZE);
1144         if (session->receive_buffer == NULL) {
1145                 free_session(session);
1146                 return 0;
1147         }
1148
1149         session->result.headers = g_hash_table_new_full(g_str_hash, g_str_equal,
1150                                                         g_free, g_free);
1151         if (session->result.headers == NULL) {
1152                 free_session(session);
1153                 return 0;
1154         }
1155
1156         session->receive_space = DEFAULT_BUFFER_SIZE;
1157         session->send_buffer = g_string_sized_new(0);
1158         session->current_header = g_string_sized_new(0);
1159         session->header_done = FALSE;
1160         session->body_done = FALSE;
1161
1162         if (session->address == NULL && inet_aton(session->host, NULL) == 0) {
1163                 session->resolv_action = g_resolv_lookup_hostname(web->resolv,
1164                                         session->host, resolv_result, session);
1165                 if (session->resolv_action == 0) {
1166                         free_session(session);
1167                         return 0;
1168                 }
1169         } else {
1170                 struct addrinfo hints;
1171                 char *port;
1172                 int ret;
1173
1174                 if (session->address == NULL)
1175                         session->address = g_strdup(session->host);
1176
1177                 memset(&hints, 0, sizeof(struct addrinfo));
1178                 hints.ai_flags = AI_NUMERICHOST;
1179                 hints.ai_family = session->web->family;
1180
1181                 if (session->addr != NULL) {
1182                         freeaddrinfo(session->addr);
1183                         session->addr = NULL;
1184                 }
1185
1186                 port = g_strdup_printf("%u", session->port);
1187                 ret = getaddrinfo(session->address, port, &hints,
1188                                                         &session->addr);
1189                 g_free(port);
1190                 if (ret != 0 || session->addr == NULL) {
1191                         free_session(session);
1192                         return 0;
1193                 }
1194
1195                 if (create_transport(session) < 0) {
1196                         free_session(session);
1197                         return 0;
1198                 }
1199         }
1200
1201         web->session_list = g_list_append(web->session_list, session);
1202
1203         return web->next_query_id++;
1204 }
1205
1206 guint g_web_request_get(GWeb *web, const char *url,
1207                                 GWebResultFunc func, gpointer user_data)
1208 {
1209         return do_request(web, url, NULL, NULL, func, user_data);
1210 }
1211
1212 guint g_web_request_post(GWeb *web, const char *url,
1213                                 const char *type, GWebInputFunc input,
1214                                 GWebResultFunc func, gpointer user_data)
1215 {
1216         return do_request(web, url, type, input, func, user_data);
1217 }
1218
1219 gboolean g_web_cancel_request(GWeb *web, guint id)
1220 {
1221         if (web == NULL)
1222                 return FALSE;
1223
1224         return TRUE;
1225 }
1226
1227 guint16 g_web_result_get_status(GWebResult *result)
1228 {
1229         if (result == NULL)
1230                 return 0;
1231
1232         return result->status;
1233 }
1234
1235 gboolean g_web_result_get_chunk(GWebResult *result,
1236                                 const guint8 **chunk, gsize *length)
1237 {
1238         if (result == NULL)
1239                 return FALSE;
1240
1241         if (chunk == NULL)
1242                 return FALSE;
1243
1244         *chunk = result->buffer;
1245
1246         if (length != NULL)
1247                 *length = result->length;
1248
1249         return TRUE;
1250 }
1251
1252 gboolean g_web_result_get_header(GWebResult *result,
1253                                 const char *header, const char **value)
1254 {
1255         if (result == NULL)
1256                 return FALSE;
1257
1258         if (value == NULL)
1259                 return FALSE;
1260
1261         *value = g_hash_table_lookup(result->headers, header);
1262
1263         if (*value == NULL)
1264                 return FALSE;
1265
1266         return TRUE;
1267 }
1268
1269 struct _GWebParser {
1270         gint ref_count;
1271         char *begin_token;
1272         char *end_token;
1273         const char *token_str;
1274         size_t token_len;
1275         size_t token_pos;
1276         gboolean intoken;
1277         GString *content;
1278         GWebParserFunc func;
1279         gpointer user_data;
1280 };
1281
1282 GWebParser *g_web_parser_new(const char *begin, const char *end,
1283                                 GWebParserFunc func, gpointer user_data)
1284 {
1285         GWebParser *parser;
1286
1287         parser = g_try_new0(GWebParser, 1);
1288         if (parser == NULL)
1289                 return NULL;
1290
1291         parser->ref_count = 1;
1292
1293         parser->begin_token = g_strdup(begin);
1294         parser->end_token = g_strdup(end);
1295
1296         if (parser->begin_token == NULL) {
1297                 g_free(parser);
1298                 return NULL;
1299         }
1300
1301         parser->func = func;
1302         parser->user_data = user_data;
1303
1304         parser->token_str = parser->begin_token;
1305         parser->token_len = strlen(parser->token_str);
1306         parser->token_pos = 0;
1307
1308         parser->intoken = FALSE;
1309         parser->content = g_string_sized_new(0);
1310
1311         return parser;
1312 }
1313
1314 GWebParser *g_web_parser_ref(GWebParser *parser)
1315 {
1316         if (parser == NULL)
1317                 return NULL;
1318
1319         g_atomic_int_inc(&parser->ref_count);
1320
1321         return parser;
1322 }
1323
1324 void g_web_parser_unref(GWebParser *parser)
1325 {
1326         if (parser == NULL)
1327                 return;
1328
1329         if (g_atomic_int_dec_and_test(&parser->ref_count) == FALSE)
1330                 return;
1331
1332         g_string_free(parser->content, TRUE);
1333
1334         g_free(parser->begin_token);
1335         g_free(parser->end_token);
1336         g_free(parser);
1337 }
1338
1339 void g_web_parser_feed_data(GWebParser *parser,
1340                                 const guint8 *data, gsize length)
1341 {
1342         const guint8 *ptr = data;
1343
1344         if (parser == NULL)
1345                 return;
1346
1347         while (length > 0) {
1348                 guint8 chr = parser->token_str[parser->token_pos];
1349
1350                 if (parser->token_pos == 0) {
1351                         guint8 *pos;
1352
1353                         pos = memchr(ptr, chr, length);
1354                         if (pos == NULL) {
1355                                 if (parser->intoken == TRUE)
1356                                         g_string_append_len(parser->content,
1357                                                         (gchar *) ptr, length);
1358                                 break;
1359                         }
1360
1361                         if (parser->intoken == TRUE)
1362                                 g_string_append_len(parser->content,
1363                                                 (gchar *) ptr, (pos - ptr) + 1);
1364
1365                         length -= (pos - ptr) + 1;
1366                         ptr = pos + 1;
1367
1368                         parser->token_pos++;
1369                         continue;
1370                 }
1371
1372                 if (parser->intoken == TRUE)
1373                         g_string_append_c(parser->content, ptr[0]);
1374
1375                 if (ptr[0] != chr) {
1376                         length--;
1377                         ptr++;
1378
1379                         parser->token_pos = 0;
1380                         continue;
1381                 }
1382
1383                 length--;
1384                 ptr++;
1385
1386                 parser->token_pos++;
1387
1388                 if (parser->token_pos == parser->token_len) {
1389                         if (parser->intoken == FALSE) {
1390                                 g_string_append(parser->content,
1391                                                         parser->token_str);
1392
1393                                 parser->intoken = TRUE;
1394                                 parser->token_str = parser->end_token;
1395                                 parser->token_len = strlen(parser->end_token);
1396                                 parser->token_pos = 0;
1397                         } else {
1398                                 char *str;
1399                                 str = g_string_free(parser->content, FALSE);
1400                                 parser->content = g_string_sized_new(0);
1401                                 if (parser->func)
1402                                         parser->func(str, parser->user_data);
1403                                 g_free(str);
1404
1405                                 parser->intoken = FALSE;
1406                                 parser->token_str = parser->begin_token;
1407                                 parser->token_len = strlen(parser->begin_token);
1408                                 parser->token_pos = 0;
1409                         }
1410                 }
1411         }
1412 }
1413
1414 void g_web_parser_end_data(GWebParser *parser)
1415 {
1416         if (parser == NULL)
1417                 return;
1418 }