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