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