The HTTP status code can be retrieved from result object
[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
35 #include "giognutls.h"
36 #include "gresolv.h"
37 #include "gweb.h"
38
39 #define DEFAULT_BUFFER_SIZE  2048
40
41 #define SESSION_FLAG_USE_TLS    (1 << 0)
42
43 struct _GWebResult {
44         guint16 status;
45         const guint8 *buffer;
46         gsize length;
47 };
48
49 struct web_session {
50         GWeb *web;
51
52         char *address;
53         char *host;
54         uint16_t port;
55         unsigned long flags;
56
57         GIOChannel *transport_channel;
58         guint transport_watch;
59
60         guint resolv_action;
61         char *request;
62
63         guint8 *receive_buffer;
64         gsize receive_space;
65         GString *current_header;
66         gboolean header_done;
67
68         GWebResult result;
69
70         GWebResultFunc result_func;
71         gpointer result_data;
72 };
73
74 struct _GWeb {
75         gint ref_count;
76
77         guint next_query_id;
78
79         int index;
80         GList *session_list;
81
82         GResolv *resolv;
83         char *accept_option;
84         char *user_agent;
85         gboolean close_connection;
86
87         GWebDebugFunc debug_func;
88         gpointer debug_data;
89 };
90
91 static inline void debug(GWeb *web, const char *format, ...)
92 {
93         char str[256];
94         va_list ap;
95
96         if (web->debug_func == NULL)
97                 return;
98
99         va_start(ap, format);
100
101         if (vsnprintf(str, sizeof(str), format, ap) > 0)
102                 web->debug_func(str, web->debug_data);
103
104         va_end(ap);
105 }
106
107 static void free_session(struct web_session *session)
108 {
109         GWeb *web = session->web;
110
111         if (session == NULL)
112                 return;
113
114         g_free(session->request);
115
116         if (session->resolv_action > 0)
117                 g_resolv_cancel_lookup(web->resolv, session->resolv_action);
118
119         if (session->transport_watch > 0)
120                 g_source_remove(session->transport_watch);
121
122         if (session->transport_channel != NULL)
123                 g_io_channel_unref(session->transport_channel);
124
125         g_string_free(session->current_header, TRUE);
126         g_free(session->receive_buffer);
127
128         g_free(session->host);
129         g_free(session->address);
130         g_free(session);
131 }
132
133 static void flush_sessions(GWeb *web)
134 {
135         GList *list;
136
137         for (list = g_list_first(web->session_list);
138                                         list; list = g_list_next(list))
139                 free_session(list->data);
140
141         g_list_free(web->session_list);
142         web->session_list = NULL;
143 }
144
145 GWeb *g_web_new(int index)
146 {
147         GWeb *web;
148
149         if (index < 0)
150                 return NULL;
151
152         web = g_try_new0(GWeb, 1);
153         if (web == NULL)
154                 return NULL;
155
156         web->ref_count = 1;
157
158         web->next_query_id = 1;
159
160         web->index = index;
161         web->session_list = NULL;
162
163         web->resolv = g_resolv_new(index);
164         if (web->resolv == NULL) {
165                 g_free(web);
166                 return NULL;
167         }
168
169         web->accept_option = g_strdup("*/*");
170         web->user_agent = g_strdup_printf("GWeb/%s", VERSION);
171         web->close_connection = FALSE;
172
173         return web;
174 }
175
176 GWeb *g_web_ref(GWeb *web)
177 {
178         if (web == NULL)
179                 return NULL;
180
181         g_atomic_int_inc(&web->ref_count);
182
183         return web;
184 }
185
186 void g_web_unref(GWeb *web)
187 {
188         if (web == NULL)
189                 return;
190
191         if (g_atomic_int_dec_and_test(&web->ref_count) == FALSE)
192                 return;
193
194         flush_sessions(web);
195
196         g_resolv_unref(web->resolv);
197
198         g_free(web->accept_option);
199         g_free(web->user_agent);
200         g_free(web);
201 }
202
203 void g_web_set_debug(GWeb *web, GWebDebugFunc func, gpointer user_data)
204 {
205         if (web == NULL)
206                 return;
207
208         web->debug_func = func;
209         web->debug_data = user_data;
210
211         g_resolv_set_debug(web->resolv, func, user_data);
212 }
213
214 gboolean g_web_add_nameserver(GWeb *web, const char *address)
215 {
216         if (web == NULL)
217                 return FALSE;
218
219         g_resolv_add_nameserver(web->resolv, address, 53, 0);
220
221         return TRUE;
222 }
223
224 static gboolean set_accept_option(GWeb *web, const char *format, va_list args)
225 {
226         g_free(web->accept_option);
227
228         if (format == NULL) {
229                 web->accept_option = NULL;
230                 debug(web, "clearing accept option");
231         } else {
232                 web->accept_option = g_strdup_vprintf(format, args);
233                 debug(web, "setting accept %s", web->accept_option);
234         }
235
236         return TRUE;
237 }
238
239 gboolean g_web_set_accept(GWeb *web, const char *format, ...)
240 {
241         va_list args;
242         gboolean result;
243
244         if (web == NULL)
245                 return FALSE;
246
247         va_start(args, format);
248         result = set_accept_option(web, format, args);
249         va_end(args);
250
251         return result;
252 }
253
254 static gboolean set_user_agent(GWeb *web, const char *format, va_list args)
255 {
256         g_free(web->user_agent);
257
258         if (format == NULL) {
259                 web->user_agent = NULL;
260                 debug(web, "clearing user agent");
261         } else {
262                 web->user_agent = g_strdup_vprintf(format, args);
263                 debug(web, "setting user agent %s", web->user_agent);
264         }
265
266         return TRUE;
267 }
268
269 gboolean g_web_set_user_agent(GWeb *web, const char *format, ...)
270 {
271         va_list args;
272         gboolean result;
273
274         if (web == NULL)
275                 return FALSE;
276
277         va_start(args, format);
278         result = set_user_agent(web, format, args);
279         va_end(args);
280
281         return result;
282 }
283
284 void g_web_set_close_connection(GWeb *web, gboolean enabled)
285 {
286         if (web == NULL)
287                 return;
288
289         web->close_connection = enabled;
290 }
291
292 gboolean g_web_get_close_connection(GWeb *web)
293 {
294         if (web == NULL)
295                 return FALSE;
296
297         return web->close_connection;
298 }
299
300 static inline void call_result_func(struct web_session *session, guint16 status)
301 {
302         if (session->result_func == NULL)
303                 return;
304
305         if (status != 0)
306                 session->result.status = status;
307
308         session->result_func(&session->result, session->result_data);
309 }
310
311 static gboolean received_data(GIOChannel *channel, GIOCondition cond,
312                                                         gpointer user_data)
313 {
314         struct web_session *session = user_data;
315         guint8 *ptr = session->receive_buffer;
316         gsize bytes_read;
317         GIOStatus status;
318
319         if (cond & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
320                 session->transport_watch = 0;
321                 session->result.buffer = NULL;
322                 session->result.length = 0;
323                 call_result_func(session, 400);
324                 return FALSE;
325         }
326
327         status = g_io_channel_read_chars(channel,
328                                 (gchar *) session->receive_buffer,
329                                 session->receive_space - 1, &bytes_read, NULL);
330
331         debug(session->web, "bytes read %zu", bytes_read);
332
333         if (status != G_IO_STATUS_NORMAL) {
334                 session->transport_watch = 0;
335                 session->result.buffer = NULL;
336                 session->result.length = 0;
337                 call_result_func(session, 0);
338                 return FALSE;
339         }
340
341         session->receive_buffer[bytes_read] = '\0';
342
343         if (session->header_done == TRUE) {
344                 session->result.buffer = session->receive_buffer;
345                 session->result.length = bytes_read;
346                 call_result_func(session, 0);
347                 return TRUE;
348         }
349
350         while (bytes_read > 0) {
351                 guint8 *pos;
352                 gsize count;
353                 char *str;
354
355                 pos = memchr(ptr, '\n', bytes_read);
356                 if (pos == NULL) {
357                         g_string_append_len(session->current_header,
358                                                 (gchar *) ptr, bytes_read);
359                         return TRUE;
360                 }
361
362                 *pos = '\0';
363                 count = strlen((char *) ptr);
364                 if (count > 0 && ptr[count - 1] == '\r') {
365                         ptr[--count] = '\0';
366                         bytes_read--;
367                 }
368
369                 g_string_append_len(session->current_header,
370                                                 (gchar *) ptr, count);
371
372                 bytes_read -= count + 1;
373                 ptr = pos + 1;
374
375                 if (session->current_header->len == 0) {
376                         session->header_done = TRUE;
377                         session->result.buffer = pos + 1;
378                         session->result.length = bytes_read;
379                         call_result_func(session, 0);
380                         break;
381                 }
382
383                 str = session->current_header->str;
384
385                 if (session->result.status == 0) {
386                         unsigned int code;
387
388                         if (sscanf(str, "HTTP/%*s %u %*s", &code) == 1)
389                                 session->result.status = code;
390                 }
391
392                 debug(session->web, "[header] %s", str);
393
394                 g_string_truncate(session->current_header, 0);
395         }
396
397         return TRUE;
398 }
399
400 static int connect_session_transport(struct web_session *session)
401 {
402         struct sockaddr_in sin;
403         int sk;
404
405         sk = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
406         if (sk < 0)
407                 return -EIO;
408
409         memset(&sin, 0, sizeof(sin));
410         sin.sin_family = AF_INET;
411         sin.sin_port = htons(session->port);
412         sin.sin_addr.s_addr = inet_addr(session->address);
413
414         if (connect(sk, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
415                 close(sk);
416                 return -EIO;
417         }
418
419         if (session->flags & SESSION_FLAG_USE_TLS)
420                 session->transport_channel = g_io_channel_gnutls_new(sk);
421         else
422                 session->transport_channel = g_io_channel_unix_new(sk);
423
424         if (session->transport_channel == NULL) {
425                 close(sk);
426                 return -ENOMEM;
427         }
428
429         g_io_channel_set_encoding(session->transport_channel, NULL, NULL);
430         g_io_channel_set_buffered(session->transport_channel, FALSE);
431
432         g_io_channel_set_close_on_unref(session->transport_channel, TRUE);
433
434         session->transport_watch = g_io_add_watch(session->transport_channel,
435                                 G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
436                                                 received_data, session);
437
438         return 0;
439 }
440
441 static int create_transport(struct web_session *session)
442 {
443         int err;
444
445         err = connect_session_transport(session);
446         if (err < 0)
447                 return err;
448
449         debug(session->web, "creating session %s:%u",
450                                         session->address, session->port);
451
452         return 0;
453 }
454
455 static void start_request(struct web_session *session)
456 {
457         GString *buf;
458         gchar *str;
459         gsize count, bytes_written;
460         GIOStatus status;
461
462         debug(session->web, "request %s from %s",
463                                         session->request, session->host);
464
465         buf = g_string_new(NULL);
466         g_string_append_printf(buf, "GET %s HTTP/1.1\r\n", session->request);
467         g_string_append_printf(buf, "Host: %s\r\n", session->host);
468         if (session->web->user_agent != NULL)
469                 g_string_append_printf(buf, "User-Agent: %s\r\n",
470                                                 session->web->user_agent);
471         if (session->web->accept_option != NULL)
472                 g_string_append_printf(buf, "Accept: %s\r\n",
473                                                 session->web->accept_option);
474         if (session->web->close_connection == TRUE)
475                 g_string_append(buf, "Connection: close\r\n");
476         g_string_append(buf, "\r\n");
477         str = g_string_free(buf, FALSE);
478
479         count = strlen(str);
480
481         debug(session->web, "bytes to write %zu", count);
482
483         status = g_io_channel_write_chars(session->transport_channel,
484                                         str, count, &bytes_written, NULL);
485
486         debug(session->web, "status %u bytes written %zu",
487                                                 status, bytes_written);
488
489         //printf("%s", str);
490
491         g_free(str);
492 }
493
494 static int parse_url(struct web_session *session, const char *url)
495 {
496         char *scheme, *host, *port, *path;
497
498         scheme = g_strdup(url);
499         if (scheme == NULL)
500                 return -EINVAL;
501
502         host = strstr(scheme, "://");
503         if (host != NULL) {
504                 *host = '\0';
505                 host += 3;
506
507                 if (strcasecmp(scheme, "https") == 0) {
508                         session->port = 443;
509                         session->flags |= SESSION_FLAG_USE_TLS;
510                 } else if (strcasecmp(scheme, "http") == 0) {
511                         session->port = 80;
512                 } else {
513                         g_free(scheme);
514                         return -EINVAL;
515                 }
516         } else {
517                 host = scheme;
518                 session->port = 80;
519         }
520
521         path = strchr(host, '/');
522         if (path != NULL)
523                 *(path++) = '\0';
524
525         session->request = g_strdup_printf("/%s", path ? path : "");
526
527         port = strrchr(host, ':');
528         if (port != NULL) {
529                 char *end;
530                 int tmp = strtol(port + 1, &end, 10);
531
532                 if (*end == '\0') {
533                         *port = '\0';
534                         session->port = tmp;
535                 }
536         }
537
538         session->host = g_strdup(host);
539
540         g_free(scheme);
541
542         return 0;
543 }
544
545 static void resolv_result(GResolvResultStatus status,
546                                         char **results, gpointer user_data)
547 {
548         struct web_session *session = user_data;
549
550         if (results == NULL || results[0] == NULL) {
551                 call_result_func(session, 404);
552                 return;
553         }
554
555         debug(session->web, "address %s", results[0]);
556
557         if (inet_aton(results[0], NULL) == 0) {
558                 call_result_func(session, 400);
559                 return;
560         }
561
562         session->address = g_strdup(results[0]);
563
564         if (create_transport(session) < 0) {
565                 call_result_func(session, 409);
566                 return;
567         }
568
569         start_request(session);
570 }
571
572 guint g_web_request(GWeb *web, GWebMethod method, const char *url,
573                                 GWebResultFunc func, gpointer user_data)
574 {
575         struct web_session *session;
576
577         if (web == NULL || url == NULL)
578                 return 0;
579
580         debug(web, "request %s", url);
581
582         session = g_try_new0(struct web_session, 1);
583         if (session == NULL)
584                 return 0;
585
586         if (parse_url(session, url) < 0) {
587                 free_session(session);
588                 return 0;
589         }
590
591         debug(web, "host %s:%u", session->host, session->port);
592         debug(web, "flags %lu", session->flags);
593
594         session->web = web;
595
596         session->result_func = func;
597         session->result_data = user_data;
598
599         session->receive_buffer = g_try_malloc(DEFAULT_BUFFER_SIZE);
600         if (session->receive_buffer == NULL) {
601                 free_session(session);
602                 return 0;
603         }
604
605         session->receive_space = DEFAULT_BUFFER_SIZE;
606         session->current_header = g_string_sized_new(0);
607         session->header_done = FALSE;
608
609         if (inet_aton(session->host, NULL) == 0) {
610                 session->resolv_action = g_resolv_lookup_hostname(web->resolv,
611                                         session->host, resolv_result, session);
612                 if (session->resolv_action == 0) {
613                         free_session(session);
614                         return 0;
615                 }
616         } else {
617                 session->address = g_strdup(session->host);
618
619                 if (create_transport(session) < 0) {
620                         free_session(session);
621                         return 0;
622                 }
623
624                 start_request(session);
625         }
626
627         web->session_list = g_list_append(web->session_list, session);
628
629         return web->next_query_id++;
630 }
631
632 guint16 g_web_result_get_status(GWebResult *result)
633 {
634         if (result == NULL)
635                 return 0;
636
637         return result->status;
638 }
639
640 gboolean g_web_result_get_chunk(GWebResult *result,
641                                 const guint8 **chunk, gsize *length)
642 {
643         if (result == NULL)
644                 return FALSE;
645
646         if (chunk == NULL)
647                 return FALSE;
648
649         *chunk = result->buffer;
650
651         if (length != NULL)
652                 *length = result->length;
653
654         return TRUE;
655 }
656
657 struct _GWebParser {
658         gint ref_count;
659         char *begin_token;
660         char *end_token;
661         const char *token_str;
662         size_t token_len;
663         size_t token_pos;
664         gboolean intoken;
665         GString *content;
666         GWebParserFunc func;
667         gpointer user_data;
668 };
669
670 GWebParser *g_web_parser_new(const char *begin, const char *end,
671                                 GWebParserFunc func, gpointer user_data)
672 {
673         GWebParser *parser;
674
675         parser = g_try_new0(GWebParser, 1);
676         if (parser == NULL)
677                 return NULL;
678
679         parser->ref_count = 1;
680
681         parser->begin_token = g_strdup(begin);
682         parser->end_token = g_strdup(end);
683
684         if (parser->begin_token == NULL) {
685                 g_free(parser);
686                 return NULL;
687         }
688
689         parser->func = func;
690         parser->user_data = user_data;
691
692         parser->token_str = parser->begin_token;
693         parser->token_len = strlen(parser->token_str);
694         parser->token_pos = 0;
695
696         parser->intoken = FALSE;
697         parser->content = g_string_sized_new(0);
698
699         return parser;
700 }
701
702 GWebParser *g_web_parser_ref(GWebParser *parser)
703 {
704         if (parser == NULL)
705                 return NULL;
706
707         g_atomic_int_inc(&parser->ref_count);
708
709         return parser;
710 }
711
712 void g_web_parser_unref(GWebParser *parser)
713 {
714         if (parser == NULL)
715                 return;
716
717         if (g_atomic_int_dec_and_test(&parser->ref_count) == FALSE)
718                 return;
719
720         g_string_free(parser->content, TRUE);
721
722         g_free(parser->begin_token);
723         g_free(parser->end_token);
724         g_free(parser);
725 }
726
727 void g_web_parser_feed_data(GWebParser *parser,
728                                 const guint8 *data, gsize length)
729 {
730         const guint8 *ptr = data;
731
732         if (parser == NULL)
733                 return;
734
735         while (length > 0) {
736                 guint8 chr = parser->token_str[parser->token_pos];
737
738                 if (parser->token_pos == 0) {
739                         guint8 *pos;
740
741                         pos = memchr(ptr, chr, length);
742                         if (pos == NULL) {
743                                 if (parser->intoken == TRUE)
744                                         g_string_append_len(parser->content,
745                                                         (gchar *) ptr, length);
746                                 break;
747                         }
748
749                         if (parser->intoken == TRUE)
750                                 g_string_append_len(parser->content,
751                                                 (gchar *) ptr, (pos - ptr) + 1);
752
753                         length -= (pos - ptr) + 1;
754                         ptr = pos + 1;
755
756                         parser->token_pos++;
757                         continue;
758                 }
759
760                 if (parser->intoken == TRUE)
761                         g_string_append_c(parser->content, ptr[0]);
762
763                 if (ptr[0] != chr) {
764                         length--;
765                         ptr++;
766
767                         parser->token_pos = 0;
768                         continue;
769                 }
770
771                 length--;
772                 ptr++;
773
774                 parser->token_pos++;
775
776                 if (parser->token_pos == parser->token_len) {
777                         if (parser->intoken == FALSE) {
778                                 g_string_append(parser->content,
779                                                         parser->token_str);
780
781                                 parser->intoken = TRUE;
782                                 parser->token_str = parser->end_token;
783                                 parser->token_len = strlen(parser->end_token);
784                                 parser->token_pos = 0;
785                         } else {
786                                 char *str;
787                                 str = g_string_free(parser->content, FALSE);
788                                 parser->content = g_string_sized_new(0);
789                                 if (parser->func)
790                                         parser->func(str, parser->user_data);
791                                 g_free(str);
792
793                                 parser->intoken = FALSE;
794                                 parser->token_str = parser->begin_token;
795                                 parser->token_len = strlen(parser->begin_token);
796                                 parser->token_pos = 0;
797                         }
798                 }
799         }
800 }
801
802 void g_web_parser_end_data(GWebParser *parser)
803 {
804         if (parser == NULL)
805                 return;
806 }