Add support for HTTP header parsing and body content
[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 LINE_CHUNK_SIZE  2048
40
41 #define SESSION_FLAG_USE_TLS    (1 << 0)
42
43 struct _GWebResult {
44         const guint8 *buffer;
45         gsize length;
46 };
47
48 struct web_session {
49         GWeb *web;
50
51         char *address;
52         char *host;
53         uint16_t port;
54         unsigned long flags;
55
56         GIOChannel *transport_channel;
57         guint transport_watch;
58
59         guint resolv_action;
60         char *request;
61
62         char *line_buffer;
63         char *line_offset;
64         unsigned int line_space;
65         char *current_line;
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_free(session->line_buffer);
126
127         g_free(session->host);
128         g_free(session->address);
129         g_free(session);
130 }
131
132 static void flush_sessions(GWeb *web)
133 {
134         GList *list;
135
136         for (list = g_list_first(web->session_list);
137                                         list; list = g_list_next(list))
138                 free_session(list->data);
139
140         g_list_free(web->session_list);
141         web->session_list = NULL;
142 }
143
144 GWeb *g_web_new(int index)
145 {
146         GWeb *web;
147
148         if (index < 0)
149                 return NULL;
150
151         web = g_try_new0(GWeb, 1);
152         if (web == NULL)
153                 return NULL;
154
155         web->ref_count = 1;
156
157         web->next_query_id = 1;
158
159         web->index = index;
160         web->session_list = NULL;
161
162         web->resolv = g_resolv_new(index);
163         if (web->resolv == NULL) {
164                 g_free(web);
165                 return NULL;
166         }
167
168         web->accept_option = g_strdup("*/*");
169         web->user_agent = g_strdup_printf("GWeb/%s", VERSION);
170         web->close_connection = FALSE;
171
172         return web;
173 }
174
175 GWeb *g_web_ref(GWeb *web)
176 {
177         if (web == NULL)
178                 return NULL;
179
180         g_atomic_int_inc(&web->ref_count);
181
182         return web;
183 }
184
185 void g_web_unref(GWeb *web)
186 {
187         if (web == NULL)
188                 return;
189
190         if (g_atomic_int_dec_and_test(&web->ref_count) == FALSE)
191                 return;
192
193         flush_sessions(web);
194
195         g_resolv_unref(web->resolv);
196
197         g_free(web->accept_option);
198         g_free(web->user_agent);
199         g_free(web);
200 }
201
202 void g_web_set_debug(GWeb *web, GWebDebugFunc func, gpointer user_data)
203 {
204         if (web == NULL)
205                 return;
206
207         web->debug_func = func;
208         web->debug_data = user_data;
209
210         g_resolv_set_debug(web->resolv, func, user_data);
211 }
212
213 gboolean g_web_add_nameserver(GWeb *web, const char *address)
214 {
215         if (web == NULL)
216                 return FALSE;
217
218         g_resolv_add_nameserver(web->resolv, address, 53, 0);
219
220         return TRUE;
221 }
222
223 static gboolean set_accept_option(GWeb *web, const char *format, va_list args)
224 {
225         g_free(web->accept_option);
226
227         if (format == NULL) {
228                 web->accept_option = NULL;
229                 debug(web, "clearing accept option");
230         } else {
231                 web->accept_option = g_strdup_vprintf(format, args);
232                 debug(web, "setting accept %s", web->accept_option);
233         }
234
235         return TRUE;
236 }
237
238 gboolean g_web_set_accept(GWeb *web, const char *format, ...)
239 {
240         va_list args;
241         gboolean result;
242
243         if (web == NULL)
244                 return FALSE;
245
246         va_start(args, format);
247         result = set_accept_option(web, format, args);
248         va_end(args);
249
250         return result;
251 }
252
253 static gboolean set_user_agent(GWeb *web, const char *format, va_list args)
254 {
255         g_free(web->user_agent);
256
257         if (format == NULL) {
258                 web->user_agent = NULL;
259                 debug(web, "clearing user agent");
260         } else {
261                 web->user_agent = g_strdup_vprintf(format, args);
262                 debug(web, "setting user agent %s", web->user_agent);
263         }
264
265         return TRUE;
266 }
267
268 gboolean g_web_set_user_agent(GWeb *web, const char *format, ...)
269 {
270         va_list args;
271         gboolean result;
272
273         if (web == NULL)
274                 return FALSE;
275
276         va_start(args, format);
277         result = set_user_agent(web, format, args);
278         va_end(args);
279
280         return result;
281 }
282
283 void g_web_set_close_connection(GWeb *web, gboolean enabled)
284 {
285         if (web == NULL)
286                 return;
287
288         web->close_connection = enabled;
289 }
290
291 gboolean g_web_get_close_connection(GWeb *web)
292 {
293         if (web == NULL)
294                 return FALSE;
295
296         return web->close_connection;
297 }
298
299 static inline void call_result_func(struct web_session *session, guint status)
300 {
301         if (session->result_func == NULL)
302                 return;
303
304         session->result_func(status, &session->result, session->result_data);
305 }
306
307 static gboolean received_data(GIOChannel *channel, GIOCondition cond,
308                                                         gpointer user_data)
309 {
310         struct web_session *session = user_data;
311         gsize bytes_read, consumed = 0;
312         GIOStatus status;
313         size_t count;
314         char *str;
315
316         if (cond & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
317                 session->transport_watch = 0;
318                 call_result_func(session, 400);
319                 return FALSE;
320         }
321
322         status = g_io_channel_read_chars(channel, session->line_offset,
323                                 session->line_space, &bytes_read, NULL);
324
325         debug(session->web, "status %u bytes read %zu", status, bytes_read);
326
327         if (status != G_IO_STATUS_NORMAL) {
328                 session->transport_watch = 0;
329                 call_result_func(session, 200);
330                 return FALSE;
331         }
332
333         if (session->header_done == TRUE) {
334                 session->result.length = bytes_read;
335                 call_result_func(session, 100);
336                 return TRUE;
337         }
338
339         str = memchr(session->line_offset, '\n', bytes_read);
340
341         while (str != NULL) {
342                 char *start = session->current_line;
343
344                 *str = '\0';
345                 count = strlen(start);
346                 if (count > 0 && start[count - 1] == '\r') {
347                         start[--count] = '\0';
348                         consumed++;
349                 }
350
351                 session->current_line = str + 1;
352                 consumed += count + 1;
353
354                 if (count == 0) {
355                         const void *ptr = session->current_line;
356                         session->header_done = TRUE;
357                         session->result.buffer = ptr;
358                         session->result.length = bytes_read - consumed;
359                         call_result_func(session, 100);
360                         break;
361                 }
362
363                 //printf("[ %s ]\n", start);
364
365                 str = memchr(session->current_line, '\n',
366                                         bytes_read - consumed);
367         }
368
369         if (session->header_done == TRUE) {
370                 gsize size = session->line_offset - session->line_buffer;
371
372                 session->line_offset = session->line_buffer;
373                 session->line_space += size;
374
375                 session->result.buffer = (const guint8 *) session->line_offset;
376                 return TRUE;
377         }
378
379         session->line_offset += bytes_read;
380         session->line_space -= bytes_read;
381
382         if (session->line_space < 32) {
383                 gsize size = session->line_offset - session->line_buffer;
384                 gsize pos = session->current_line - session->line_buffer;
385                 char *buf;
386
387                 printf("realloc, space %u size %zu\n",
388                                         session->line_space, size);
389
390                 buf = g_try_realloc(session->line_buffer,
391                                                 size + LINE_CHUNK_SIZE);
392                 if (buf != NULL) {
393                         session->line_buffer = buf;
394                         session->line_offset = buf + size;
395                         session->line_space = LINE_CHUNK_SIZE;
396                         session->current_line = buf + pos;
397                 }
398         }
399
400         return TRUE;
401 }
402
403 static int connect_session_transport(struct web_session *session)
404 {
405         struct sockaddr_in sin;
406         int sk;
407
408         sk = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
409         if (sk < 0)
410                 return -EIO;
411
412         memset(&sin, 0, sizeof(sin));
413         sin.sin_family = AF_INET;
414         sin.sin_port = htons(session->port);
415         sin.sin_addr.s_addr = inet_addr(session->address);
416
417         if (connect(sk, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
418                 close(sk);
419                 return -EIO;
420         }
421
422         if (session->flags & SESSION_FLAG_USE_TLS)
423                 session->transport_channel = g_io_channel_gnutls_new(sk);
424         else
425                 session->transport_channel = g_io_channel_unix_new(sk);
426
427         if (session->transport_channel == NULL) {
428                 close(sk);
429                 return -ENOMEM;
430         }
431
432         g_io_channel_set_encoding(session->transport_channel, NULL, NULL);
433         g_io_channel_set_buffered(session->transport_channel, FALSE);
434
435         g_io_channel_set_close_on_unref(session->transport_channel, TRUE);
436
437         session->transport_watch = g_io_add_watch(session->transport_channel,
438                                 G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
439                                                 received_data, session);
440
441         return 0;
442 }
443
444 static int create_transport(struct web_session *session)
445 {
446         int err;
447
448         err = connect_session_transport(session);
449         if (err < 0)
450                 return err;
451
452         debug(session->web, "creating session %s:%u",
453                                         session->address, session->port);
454
455         return 0;
456 }
457
458 static void start_request(struct web_session *session)
459 {
460         GString *buf;
461         gchar *str;
462         gsize count, bytes_written;
463         GIOStatus status;
464
465         debug(session->web, "request %s from %s",
466                                         session->request, session->host);
467
468         buf = g_string_new(NULL);
469         g_string_append_printf(buf, "GET %s HTTP/1.1\r\n", session->request);
470         g_string_append_printf(buf, "Host: %s\r\n", session->host);
471         if (session->web->user_agent != NULL)
472                 g_string_append_printf(buf, "User-Agent: %s\r\n",
473                                                 session->web->user_agent);
474         if (session->web->accept_option != NULL)
475                 g_string_append_printf(buf, "Accept: %s\r\n",
476                                                 session->web->accept_option);
477         if (session->web->close_connection == TRUE)
478                 g_string_append(buf, "Connection: close\r\n");
479         g_string_append(buf, "\r\n");
480         str = g_string_free(buf, FALSE);
481
482         count = strlen(str);
483
484         debug(session->web, "bytes to write %zu", count);
485
486         status = g_io_channel_write_chars(session->transport_channel,
487                                         str, count, &bytes_written, NULL);
488
489         debug(session->web, "status %u bytes written %zu",
490                                                 status, bytes_written);
491
492         //printf("%s", str);
493
494         g_free(str);
495 }
496
497 static int parse_url(struct web_session *session, const char *url)
498 {
499         char *scheme, *host, *port, *path;
500
501         scheme = g_strdup(url);
502         if (scheme == NULL)
503                 return -EINVAL;
504
505         host = strstr(scheme, "://");
506         if (host != NULL) {
507                 *host = '\0';
508                 host += 3;
509
510                 if (strcasecmp(scheme, "https") == 0) {
511                         session->port = 443;
512                         session->flags |= SESSION_FLAG_USE_TLS;
513                 } else if (strcasecmp(scheme, "http") == 0) {
514                         session->port = 80;
515                 } else {
516                         g_free(scheme);
517                         return -EINVAL;
518                 }
519         } else {
520                 host = scheme;
521                 session->port = 80;
522         }
523
524         path = strchr(host, '/');
525         if (path != NULL)
526                 *(path++) = '\0';
527
528         session->request = g_strdup_printf("/%s", path ? path : "");
529
530         port = strrchr(host, ':');
531         if (port != NULL) {
532                 char *end;
533                 int tmp = strtol(port + 1, &end, 10);
534
535                 if (*end == '\0') {
536                         *port = '\0';
537                         session->port = tmp;
538                 }
539         }
540
541         session->host = g_strdup(host);
542
543         g_free(scheme);
544
545         return 0;
546 }
547
548 static void resolv_result(GResolvResultStatus status,
549                                         char **results, gpointer user_data)
550 {
551         struct web_session *session = user_data;
552
553         if (results == NULL || results[0] == NULL) {
554                 call_result_func(session, 404);
555                 return;
556         }
557
558         debug(session->web, "address %s", results[0]);
559
560         if (inet_aton(results[0], NULL) == 0) {
561                 call_result_func(session, 400);
562                 return;
563         }
564
565         session->address = g_strdup(results[0]);
566
567         if (create_transport(session) < 0) {
568                 call_result_func(session, 409);
569                 return;
570         }
571
572         start_request(session);
573 }
574
575 guint g_web_request(GWeb *web, GWebMethod method, const char *url,
576                                 GWebResultFunc func, gpointer user_data)
577 {
578         struct web_session *session;
579
580         if (web == NULL || url == NULL)
581                 return 0;
582
583         debug(web, "request %s", url);
584
585         session = g_try_new0(struct web_session, 1);
586         if (session == NULL)
587                 return 0;
588
589         if (parse_url(session, url) < 0) {
590                 free_session(session);
591                 return 0;
592         }
593
594         debug(web, "host %s:%u", session->host, session->port);
595         debug(web, "flags %lu", session->flags);
596
597         session->web = web;
598
599         session->result_func = func;
600         session->result_data = user_data;
601
602         session->line_buffer = g_try_malloc(LINE_CHUNK_SIZE);
603         session->line_offset = session->line_buffer;
604         session->line_space = LINE_CHUNK_SIZE;
605         session->current_line = session->line_buffer;
606         session->header_done = FALSE;
607
608         if (inet_aton(session->host, NULL) == 0) {
609                 session->resolv_action = g_resolv_lookup_hostname(web->resolv,
610                                         session->host, resolv_result, session);
611                 if (session->resolv_action == 0) {
612                         free_session(session);
613                         return 0;
614                 }
615         } else {
616                 session->address = g_strdup(session->host);
617
618                 if (create_transport(session) < 0) {
619                         free_session(session);
620                         return 0;
621                 }
622
623                 start_request(session);
624         }
625
626         web->session_list = g_list_append(web->session_list, session);
627
628         return web->next_query_id++;
629 }
630
631 gboolean g_web_result_get_chunk(GWebResult *result,
632                                 const guint8 **chunk, gsize *length)
633 {
634         if (result == NULL)
635                 return FALSE;
636
637         if (chunk == NULL)
638                 return FALSE;
639
640         *chunk = result->buffer;
641
642         if (length != NULL)
643                 *length = result->length;
644
645         return TRUE;
646 }