Add support for parsing HTTP status code response
[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         guint 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         char *line_buffer;
64         char *line_offset;
65         unsigned int line_space;
66         char *current_line;
67         gboolean header_done;
68
69         GWebResult result;
70
71         GWebResultFunc result_func;
72         gpointer result_data;
73 };
74
75 struct _GWeb {
76         gint ref_count;
77
78         guint next_query_id;
79
80         int index;
81         GList *session_list;
82
83         GResolv *resolv;
84         char *accept_option;
85         char *user_agent;
86         gboolean close_connection;
87
88         GWebDebugFunc debug_func;
89         gpointer debug_data;
90 };
91
92 static inline void debug(GWeb *web, const char *format, ...)
93 {
94         char str[256];
95         va_list ap;
96
97         if (web->debug_func == NULL)
98                 return;
99
100         va_start(ap, format);
101
102         if (vsnprintf(str, sizeof(str), format, ap) > 0)
103                 web->debug_func(str, web->debug_data);
104
105         va_end(ap);
106 }
107
108 static void free_session(struct web_session *session)
109 {
110         GWeb *web = session->web;
111
112         if (session == NULL)
113                 return;
114
115         g_free(session->request);
116
117         if (session->resolv_action > 0)
118                 g_resolv_cancel_lookup(web->resolv, session->resolv_action);
119
120         if (session->transport_watch > 0)
121                 g_source_remove(session->transport_watch);
122
123         if (session->transport_channel != NULL)
124                 g_io_channel_unref(session->transport_channel);
125
126         g_free(session->line_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, guint status)
301 {
302         if (session->result_func == NULL)
303                 return;
304
305         session->result_func(status, &session->result, session->result_data);
306 }
307
308 static gboolean received_data(GIOChannel *channel, GIOCondition cond,
309                                                         gpointer user_data)
310 {
311         struct web_session *session = user_data;
312         gsize bytes_read, consumed = 0;
313         GIOStatus status;
314         size_t count;
315         char *str;
316
317         if (cond & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
318                 session->transport_watch = 0;
319                 call_result_func(session, 400);
320                 return FALSE;
321         }
322
323         status = g_io_channel_read_chars(channel, session->line_offset,
324                                 session->line_space, &bytes_read, NULL);
325
326         debug(session->web, "status %u bytes read %zu", status, bytes_read);
327
328         if (status != G_IO_STATUS_NORMAL) {
329                 session->transport_watch = 0;
330                 call_result_func(session, 200);
331                 return FALSE;
332         }
333
334         if (session->header_done == TRUE) {
335                 session->result.length = bytes_read;
336                 call_result_func(session, 100);
337                 return TRUE;
338         }
339
340         str = memchr(session->line_offset, '\n', bytes_read);
341
342         while (str != NULL) {
343                 char *start = session->current_line;
344                 unsigned int code;
345
346                 *str = '\0';
347                 count = strlen(start);
348                 if (count > 0 && start[count - 1] == '\r') {
349                         start[--count] = '\0';
350                         consumed++;
351                 }
352
353                 session->current_line = str + 1;
354                 consumed += count + 1;
355
356                 if (count == 0) {
357                         const void *ptr = session->current_line;
358                         session->header_done = TRUE;
359                         session->result.buffer = ptr;
360                         session->result.length = bytes_read - consumed;
361                         call_result_func(session, 100);
362                         break;
363                 }
364
365                 //printf("[ %s ]\n", start);
366
367                 if (session->result.status == 0) {
368                         if (sscanf(start, "HTTP/%*s %u %*s", &code) == 1)
369                                 session->result.status = code;
370                 }
371
372                 str = memchr(session->current_line, '\n',
373                                         bytes_read - consumed);
374         }
375
376         if (session->header_done == TRUE) {
377                 gsize size = session->line_offset - session->line_buffer;
378
379                 session->line_offset = session->line_buffer;
380                 session->line_space += size;
381
382                 session->result.buffer = (const guint8 *) session->line_offset;
383                 return TRUE;
384         }
385
386         session->line_offset += bytes_read;
387         session->line_space -= bytes_read;
388
389         if (session->line_space < 32) {
390                 gsize size = session->line_offset - session->line_buffer;
391                 gsize pos = session->current_line - session->line_buffer;
392                 char *buf;
393
394                 printf("realloc, space %u size %zu\n",
395                                         session->line_space, size);
396
397                 buf = g_try_realloc(session->line_buffer,
398                                                 size + LINE_CHUNK_SIZE);
399                 if (buf != NULL) {
400                         session->line_buffer = buf;
401                         session->line_offset = buf + size;
402                         session->line_space = LINE_CHUNK_SIZE;
403                         session->current_line = buf + pos;
404                 }
405         }
406
407         return TRUE;
408 }
409
410 static int connect_session_transport(struct web_session *session)
411 {
412         struct sockaddr_in sin;
413         int sk;
414
415         sk = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
416         if (sk < 0)
417                 return -EIO;
418
419         memset(&sin, 0, sizeof(sin));
420         sin.sin_family = AF_INET;
421         sin.sin_port = htons(session->port);
422         sin.sin_addr.s_addr = inet_addr(session->address);
423
424         if (connect(sk, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
425                 close(sk);
426                 return -EIO;
427         }
428
429         if (session->flags & SESSION_FLAG_USE_TLS)
430                 session->transport_channel = g_io_channel_gnutls_new(sk);
431         else
432                 session->transport_channel = g_io_channel_unix_new(sk);
433
434         if (session->transport_channel == NULL) {
435                 close(sk);
436                 return -ENOMEM;
437         }
438
439         g_io_channel_set_encoding(session->transport_channel, NULL, NULL);
440         g_io_channel_set_buffered(session->transport_channel, FALSE);
441
442         g_io_channel_set_close_on_unref(session->transport_channel, TRUE);
443
444         session->transport_watch = g_io_add_watch(session->transport_channel,
445                                 G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
446                                                 received_data, session);
447
448         return 0;
449 }
450
451 static int create_transport(struct web_session *session)
452 {
453         int err;
454
455         err = connect_session_transport(session);
456         if (err < 0)
457                 return err;
458
459         debug(session->web, "creating session %s:%u",
460                                         session->address, session->port);
461
462         return 0;
463 }
464
465 static void start_request(struct web_session *session)
466 {
467         GString *buf;
468         gchar *str;
469         gsize count, bytes_written;
470         GIOStatus status;
471
472         debug(session->web, "request %s from %s",
473                                         session->request, session->host);
474
475         buf = g_string_new(NULL);
476         g_string_append_printf(buf, "GET %s HTTP/1.1\r\n", session->request);
477         g_string_append_printf(buf, "Host: %s\r\n", session->host);
478         if (session->web->user_agent != NULL)
479                 g_string_append_printf(buf, "User-Agent: %s\r\n",
480                                                 session->web->user_agent);
481         if (session->web->accept_option != NULL)
482                 g_string_append_printf(buf, "Accept: %s\r\n",
483                                                 session->web->accept_option);
484         if (session->web->close_connection == TRUE)
485                 g_string_append(buf, "Connection: close\r\n");
486         g_string_append(buf, "\r\n");
487         str = g_string_free(buf, FALSE);
488
489         count = strlen(str);
490
491         debug(session->web, "bytes to write %zu", count);
492
493         status = g_io_channel_write_chars(session->transport_channel,
494                                         str, count, &bytes_written, NULL);
495
496         debug(session->web, "status %u bytes written %zu",
497                                                 status, bytes_written);
498
499         //printf("%s", str);
500
501         g_free(str);
502 }
503
504 static int parse_url(struct web_session *session, const char *url)
505 {
506         char *scheme, *host, *port, *path;
507
508         scheme = g_strdup(url);
509         if (scheme == NULL)
510                 return -EINVAL;
511
512         host = strstr(scheme, "://");
513         if (host != NULL) {
514                 *host = '\0';
515                 host += 3;
516
517                 if (strcasecmp(scheme, "https") == 0) {
518                         session->port = 443;
519                         session->flags |= SESSION_FLAG_USE_TLS;
520                 } else if (strcasecmp(scheme, "http") == 0) {
521                         session->port = 80;
522                 } else {
523                         g_free(scheme);
524                         return -EINVAL;
525                 }
526         } else {
527                 host = scheme;
528                 session->port = 80;
529         }
530
531         path = strchr(host, '/');
532         if (path != NULL)
533                 *(path++) = '\0';
534
535         session->request = g_strdup_printf("/%s", path ? path : "");
536
537         port = strrchr(host, ':');
538         if (port != NULL) {
539                 char *end;
540                 int tmp = strtol(port + 1, &end, 10);
541
542                 if (*end == '\0') {
543                         *port = '\0';
544                         session->port = tmp;
545                 }
546         }
547
548         session->host = g_strdup(host);
549
550         g_free(scheme);
551
552         return 0;
553 }
554
555 static void resolv_result(GResolvResultStatus status,
556                                         char **results, gpointer user_data)
557 {
558         struct web_session *session = user_data;
559
560         if (results == NULL || results[0] == NULL) {
561                 call_result_func(session, 404);
562                 return;
563         }
564
565         debug(session->web, "address %s", results[0]);
566
567         if (inet_aton(results[0], NULL) == 0) {
568                 call_result_func(session, 400);
569                 return;
570         }
571
572         session->address = g_strdup(results[0]);
573
574         if (create_transport(session) < 0) {
575                 call_result_func(session, 409);
576                 return;
577         }
578
579         start_request(session);
580 }
581
582 guint g_web_request(GWeb *web, GWebMethod method, const char *url,
583                                 GWebResultFunc func, gpointer user_data)
584 {
585         struct web_session *session;
586
587         if (web == NULL || url == NULL)
588                 return 0;
589
590         debug(web, "request %s", url);
591
592         session = g_try_new0(struct web_session, 1);
593         if (session == NULL)
594                 return 0;
595
596         if (parse_url(session, url) < 0) {
597                 free_session(session);
598                 return 0;
599         }
600
601         debug(web, "host %s:%u", session->host, session->port);
602         debug(web, "flags %lu", session->flags);
603
604         session->web = web;
605
606         session->result_func = func;
607         session->result_data = user_data;
608
609         session->line_buffer = g_try_malloc(LINE_CHUNK_SIZE);
610         session->line_offset = session->line_buffer;
611         session->line_space = LINE_CHUNK_SIZE;
612         session->current_line = session->line_buffer;
613         session->header_done = FALSE;
614
615         if (inet_aton(session->host, NULL) == 0) {
616                 session->resolv_action = g_resolv_lookup_hostname(web->resolv,
617                                         session->host, resolv_result, session);
618                 if (session->resolv_action == 0) {
619                         free_session(session);
620                         return 0;
621                 }
622         } else {
623                 session->address = g_strdup(session->host);
624
625                 if (create_transport(session) < 0) {
626                         free_session(session);
627                         return 0;
628                 }
629
630                 start_request(session);
631         }
632
633         web->session_list = g_list_append(web->session_list, session);
634
635         return web->next_query_id++;
636 }
637
638 guint16 g_web_result_get_status(GWebResult *result)
639 {
640         if (result == NULL)
641                 return 0;
642
643         return result->status;
644 }
645
646 gboolean g_web_result_get_chunk(GWebResult *result,
647                                 const guint8 **chunk, gsize *length)
648 {
649         if (result == NULL)
650                 return FALSE;
651
652         if (chunk == NULL)
653                 return FALSE;
654
655         *chunk = result->buffer;
656
657         if (length != NULL)
658                 *length = result->length;
659
660         return TRUE;
661 }