3 * Web service library with GLib integration
5 * Copyright (C) 2009-2010 Intel Corporation. All rights reserved.
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.
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.
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
32 #include <sys/socket.h>
33 #include <arpa/inet.h>
35 #include "giognutls.h"
39 #define DEFAULT_BUFFER_SIZE 2048
41 #define SESSION_FLAG_USE_TLS (1 << 0)
67 GIOChannel *transport_channel;
68 guint transport_watch;
74 guint8 *receive_buffer;
76 GString *current_header;
79 gboolean request_started;
81 enum chunk_state chunck_state;
88 GWebResultFunc result_func;
89 GWebInputFunc input_func;
104 gboolean close_connection;
106 GWebDebugFunc debug_func;
110 static inline void debug(GWeb *web, const char *format, ...)
115 if (web->debug_func == NULL)
118 va_start(ap, format);
120 if (vsnprintf(str, sizeof(str), format, ap) > 0)
121 web->debug_func(str, web->debug_data);
126 static void free_session(struct web_session *session)
128 GWeb *web = session->web;
133 g_free(session->request);
135 if (session->resolv_action > 0)
136 g_resolv_cancel_lookup(web->resolv, session->resolv_action);
138 if (session->transport_watch > 0)
139 g_source_remove(session->transport_watch);
141 if (session->send_watch > 0)
142 g_source_remove(session->send_watch);
144 if (session->transport_channel != NULL)
145 g_io_channel_unref(session->transport_channel);
147 g_string_free(session->current_header, TRUE);
148 g_free(session->receive_buffer);
150 g_free(session->content_type);
152 g_free(session->host);
153 g_free(session->address);
157 static void flush_sessions(GWeb *web)
161 for (list = g_list_first(web->session_list);
162 list; list = g_list_next(list))
163 free_session(list->data);
165 g_list_free(web->session_list);
166 web->session_list = NULL;
169 GWeb *g_web_new(int index)
176 web = g_try_new0(GWeb, 1);
182 web->next_query_id = 1;
185 web->session_list = NULL;
187 web->resolv = g_resolv_new(index);
188 if (web->resolv == NULL) {
193 web->accept_option = g_strdup("*/*");
194 web->user_agent = g_strdup_printf("GWeb/%s", VERSION);
195 web->close_connection = FALSE;
200 GWeb *g_web_ref(GWeb *web)
205 g_atomic_int_inc(&web->ref_count);
210 void g_web_unref(GWeb *web)
215 if (g_atomic_int_dec_and_test(&web->ref_count) == FALSE)
220 g_resolv_unref(web->resolv);
222 g_free(web->accept_option);
223 g_free(web->user_agent);
227 void g_web_set_debug(GWeb *web, GWebDebugFunc func, gpointer user_data)
232 web->debug_func = func;
233 web->debug_data = user_data;
235 g_resolv_set_debug(web->resolv, func, user_data);
238 gboolean g_web_add_nameserver(GWeb *web, const char *address)
243 g_resolv_add_nameserver(web->resolv, address, 53, 0);
248 static gboolean set_accept_option(GWeb *web, const char *format, va_list args)
250 g_free(web->accept_option);
252 if (format == NULL) {
253 web->accept_option = NULL;
254 debug(web, "clearing accept option");
256 web->accept_option = g_strdup_vprintf(format, args);
257 debug(web, "setting accept %s", web->accept_option);
263 gboolean g_web_set_accept(GWeb *web, const char *format, ...)
271 va_start(args, format);
272 result = set_accept_option(web, format, args);
278 static gboolean set_user_agent(GWeb *web, const char *format, va_list args)
280 g_free(web->user_agent);
282 if (format == NULL) {
283 web->user_agent = NULL;
284 debug(web, "clearing user agent");
286 web->user_agent = g_strdup_vprintf(format, args);
287 debug(web, "setting user agent %s", web->user_agent);
293 gboolean g_web_set_user_agent(GWeb *web, const char *format, ...)
301 va_start(args, format);
302 result = set_user_agent(web, format, args);
308 void g_web_set_close_connection(GWeb *web, gboolean enabled)
313 web->close_connection = enabled;
316 gboolean g_web_get_close_connection(GWeb *web)
321 return web->close_connection;
324 static inline void call_result_func(struct web_session *session, guint16 status)
326 if (session->result_func == NULL)
330 session->result.status = status;
332 session->result_func(&session->result, session->user_data);
335 static void process_next_chunk(struct web_session *session)
341 gsize count, bytes_written;
344 if (session->input_func == NULL) {
345 session->more_data = FALSE;
349 session->more_data = session->input_func(&body, &length,
352 buf = g_string_new(NULL);
355 g_string_append_printf(buf, "%zx\r\n", length);
356 g_string_append_len(buf, (char *) body, length);
357 g_string_append(buf, "\r\n");
360 if (session->more_data == FALSE)
361 g_string_append(buf, "0\r\n\r\n");
364 str = g_string_free(buf, FALSE);
367 status = g_io_channel_write_chars(session->transport_channel,
368 str, count, &bytes_written, NULL);
370 debug(session->web, "status %u bytes written %zu",
371 status, bytes_written);
377 static void start_request(struct web_session *session)
383 gsize count, bytes_written;
386 debug(session->web, "request %s from %s",
387 session->request, session->host);
389 buf = g_string_new(NULL);
391 if (session->content_type == NULL)
392 g_string_append_printf(buf, "GET %s HTTP/1.1\r\n",
395 g_string_append_printf(buf, "POST %s HTTP/1.1\r\n",
397 g_string_append_printf(buf, "Host: %s\r\n", session->host);
398 if (session->web->user_agent != NULL)
399 g_string_append_printf(buf, "User-Agent: %s\r\n",
400 session->web->user_agent);
401 if (session->web->accept_option != NULL)
402 g_string_append_printf(buf, "Accept: %s\r\n",
403 session->web->accept_option);
404 if (session->content_type != NULL) {
405 g_string_append_printf(buf, "Content-Type: %s\r\n",
406 session->content_type);
407 if (session->input_func == NULL) {
408 session->more_data = FALSE;
411 session->more_data = session->input_func(&body, &length,
413 if (session->more_data == FALSE)
414 g_string_append_printf(buf, "Content-Length: %zu\r\n",
417 g_string_append(buf, "Transfer-Encoding: chunked\r\n");
419 if (session->web->close_connection == TRUE)
420 g_string_append(buf, "Connection: close\r\n");
421 g_string_append(buf, "\r\n");
423 if (session->content_type != NULL && length > 0) {
424 if (session->more_data == TRUE) {
425 g_string_append_printf(buf, "%zx\r\n", length);
426 g_string_append_len(buf, (char *) body, length);
427 g_string_append(buf, "\r\n");
429 g_string_append_len(buf, (char *) body, length);
433 str = g_string_free(buf, FALSE);
435 debug(session->web, "bytes to write %zu", count);
437 status = g_io_channel_write_chars(session->transport_channel,
438 str, count, &bytes_written, NULL);
440 debug(session->web, "status %u bytes written %zu",
441 status, bytes_written);
448 static gboolean send_data(GIOChannel *channel, GIOCondition cond,
451 struct web_session *session = user_data;
453 if (cond & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
454 session->send_watch = 0;
458 if (session->request_started == FALSE) {
459 session->request_started = TRUE;
460 start_request(session);
461 } else if (session->more_data == TRUE)
462 process_next_chunk(session);
464 if (session->more_data == TRUE)
467 session->send_watch = 0;
472 static int decode_chunked(struct web_session *session,
473 const guint8 *buf, gsize len)
475 const guint8 *ptr = buf;
483 switch (session->chunck_state) {
485 pos = memchr(ptr, '\n', len);
487 g_string_append_len(session->current_header,
493 if (count < 1 || ptr[count - 1] != '\r')
496 g_string_append_len(session->current_header,
497 (gchar *) ptr, count);
502 str = session->current_header->str;
504 counter = strtoul(str, NULL, 16);
505 if ((counter == 0 && errno == EINVAL) ||
506 counter == ULONG_MAX)
509 session->chunk_size = counter;
510 session->chunk_left = counter;
512 session->chunck_state = CHUNK_DATA;
519 session->chunck_state = CHUNK_N_BODY;
526 session->chunck_state = CHUNK_SIZE;
529 if (session->chunk_size == 0) {
530 debug(session->web, "Download Done in chunk");
531 g_string_truncate(session->current_header, 0);
535 if (session->chunk_left <= len) {
536 session->result.buffer = ptr;
537 session->result.length = session->chunk_left;
538 call_result_func(session, 0);
540 len -= session->chunk_left;
541 ptr += session->chunk_left;
543 session->total_len += session->chunk_left;
544 session->chunk_left = 0;
546 g_string_truncate(session->current_header, 0);
547 session->chunck_state = CHUNK_R_BODY;
551 session->result.buffer = ptr;
552 session->result.length = len;
553 call_result_func(session, 0);
555 session->chunk_left -= len;
556 session->total_len += len;
567 static int handle_body(struct web_session *session,
568 const guint8 *buf, gsize len)
572 if (session->result.use_chunk == FALSE) {
573 session->result.buffer = buf;
574 session->result.length = len;
575 call_result_func(session, 0);
579 err = decode_chunked(session, buf, len);
581 debug(session->web, "Error in chunk decode %d", err);
583 session->result.buffer = NULL;
584 session->result.length = 0;
585 call_result_func(session, 400);
591 static gboolean received_data(GIOChannel *channel, GIOCondition cond,
594 struct web_session *session = user_data;
595 guint8 *ptr = session->receive_buffer;
599 if (cond & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
600 session->transport_watch = 0;
601 session->result.buffer = NULL;
602 session->result.length = 0;
603 call_result_func(session, 400);
607 status = g_io_channel_read_chars(channel,
608 (gchar *) session->receive_buffer,
609 session->receive_space - 1, &bytes_read, NULL);
611 debug(session->web, "bytes read %zu", bytes_read);
613 if (status != G_IO_STATUS_NORMAL) {
614 session->transport_watch = 0;
615 session->result.buffer = NULL;
616 session->result.length = 0;
617 call_result_func(session, 0);
621 session->receive_buffer[bytes_read] = '\0';
623 if (session->header_done == TRUE) {
624 if (handle_body(session,
625 session->receive_buffer, bytes_read) < 0) {
626 session->transport_watch = 0;
632 while (bytes_read > 0) {
637 pos = memchr(ptr, '\n', bytes_read);
639 g_string_append_len(session->current_header,
640 (gchar *) ptr, bytes_read);
645 count = strlen((char *) ptr);
646 if (count > 0 && ptr[count - 1] == '\r') {
651 g_string_append_len(session->current_header,
652 (gchar *) ptr, count);
654 bytes_read -= count + 1;
660 if (session->current_header->len == 0) {
661 session->header_done = TRUE;
662 if (handle_body(session, ptr, bytes_read) < 0) {
663 session->transport_watch = 0;
669 str = session->current_header->str;
671 if (session->result.status == 0) {
674 if (sscanf(str, "HTTP/%*s %u %*s", &code) == 1)
675 session->result.status = code;
676 } else if (session->result.use_chunk == FALSE &&
677 g_ascii_strncasecmp("Transfer-Encoding:",
681 val = g_strrstr(str + 18, "chunked");
683 session->result.use_chunk = TRUE;
685 session->chunck_state = CHUNK_SIZE;
686 session->chunk_left = 0;
687 session->chunk_left = 0;
688 session->total_len = 0;
692 debug(session->web, "[header] %s", str);
694 g_string_truncate(session->current_header, 0);
700 static int connect_session_transport(struct web_session *session)
702 struct sockaddr_in sin;
705 sk = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
709 memset(&sin, 0, sizeof(sin));
710 sin.sin_family = AF_INET;
711 sin.sin_port = htons(session->port);
712 sin.sin_addr.s_addr = inet_addr(session->address);
714 if (session->flags & SESSION_FLAG_USE_TLS)
715 session->transport_channel = g_io_channel_gnutls_new(sk);
717 session->transport_channel = g_io_channel_unix_new(sk);
719 if (session->transport_channel == NULL) {
724 g_io_channel_set_flags(session->transport_channel,
725 G_IO_FLAG_NONBLOCK, NULL);
726 g_io_channel_set_encoding(session->transport_channel, NULL, NULL);
727 g_io_channel_set_buffered(session->transport_channel, FALSE);
729 g_io_channel_set_close_on_unref(session->transport_channel, TRUE);
731 if (connect(sk, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
732 if (errno != EINPROGRESS) {
738 session->transport_watch = g_io_add_watch(session->transport_channel,
739 G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
740 received_data, session);
742 session->send_watch = g_io_add_watch(session->transport_channel,
743 G_IO_OUT | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
749 static int create_transport(struct web_session *session)
753 err = connect_session_transport(session);
757 debug(session->web, "creating session %s:%u",
758 session->address, session->port);
763 static int parse_url(struct web_session *session, const char *url)
765 char *scheme, *host, *port, *path;
767 scheme = g_strdup(url);
771 host = strstr(scheme, "://");
776 if (strcasecmp(scheme, "https") == 0) {
778 session->flags |= SESSION_FLAG_USE_TLS;
779 } else if (strcasecmp(scheme, "http") == 0) {
790 path = strchr(host, '/');
794 session->request = g_strdup_printf("/%s", path ? path : "");
796 port = strrchr(host, ':');
799 int tmp = strtol(port + 1, &end, 10);
807 session->host = g_strdup(host);
814 static void resolv_result(GResolvResultStatus status,
815 char **results, gpointer user_data)
817 struct web_session *session = user_data;
819 if (results == NULL || results[0] == NULL) {
820 call_result_func(session, 404);
824 debug(session->web, "address %s", results[0]);
826 if (inet_aton(results[0], NULL) == 0) {
827 call_result_func(session, 400);
831 session->address = g_strdup(results[0]);
833 if (create_transport(session) < 0) {
834 call_result_func(session, 409);
839 static guint do_request(GWeb *web, const char *url,
840 const char *type, GWebInputFunc input,
841 GWebResultFunc func, gpointer user_data)
843 struct web_session *session;
845 if (web == NULL || url == NULL)
848 debug(web, "request %s", url);
850 session = g_try_new0(struct web_session, 1);
854 if (parse_url(session, url) < 0) {
855 free_session(session);
859 debug(web, "host %s:%u", session->host, session->port);
860 debug(web, "flags %lu", session->flags);
863 session->content_type = g_strdup(type);
865 debug(web, "content-type %s", session->content_type);
870 session->result_func = func;
871 session->input_func = input;
872 session->user_data = user_data;
874 session->receive_buffer = g_try_malloc(DEFAULT_BUFFER_SIZE);
875 if (session->receive_buffer == NULL) {
876 free_session(session);
880 session->receive_space = DEFAULT_BUFFER_SIZE;
881 session->current_header = g_string_sized_new(0);
882 session->header_done = FALSE;
884 if (inet_aton(session->host, NULL) == 0) {
885 session->resolv_action = g_resolv_lookup_hostname(web->resolv,
886 session->host, resolv_result, session);
887 if (session->resolv_action == 0) {
888 free_session(session);
892 session->address = g_strdup(session->host);
894 if (create_transport(session) < 0) {
895 free_session(session);
900 web->session_list = g_list_append(web->session_list, session);
902 return web->next_query_id++;
905 guint g_web_request_get(GWeb *web, const char *url,
906 GWebResultFunc func, gpointer user_data)
908 return do_request(web, url, NULL, NULL, func, user_data);
911 guint g_web_request_post(GWeb *web, const char *url,
912 const char *type, GWebInputFunc input,
913 GWebResultFunc func, gpointer user_data)
915 return do_request(web, url, type, input, func, user_data);
918 gboolean g_web_cancel_request(GWeb *web, guint id)
926 guint16 g_web_result_get_status(GWebResult *result)
931 return result->status;
934 gboolean g_web_result_get_chunk(GWebResult *result,
935 const guint8 **chunk, gsize *length)
943 *chunk = result->buffer;
946 *length = result->length;
955 const char *token_str;
964 GWebParser *g_web_parser_new(const char *begin, const char *end,
965 GWebParserFunc func, gpointer user_data)
969 parser = g_try_new0(GWebParser, 1);
973 parser->ref_count = 1;
975 parser->begin_token = g_strdup(begin);
976 parser->end_token = g_strdup(end);
978 if (parser->begin_token == NULL) {
984 parser->user_data = user_data;
986 parser->token_str = parser->begin_token;
987 parser->token_len = strlen(parser->token_str);
988 parser->token_pos = 0;
990 parser->intoken = FALSE;
991 parser->content = g_string_sized_new(0);
996 GWebParser *g_web_parser_ref(GWebParser *parser)
1001 g_atomic_int_inc(&parser->ref_count);
1006 void g_web_parser_unref(GWebParser *parser)
1011 if (g_atomic_int_dec_and_test(&parser->ref_count) == FALSE)
1014 g_string_free(parser->content, TRUE);
1016 g_free(parser->begin_token);
1017 g_free(parser->end_token);
1021 void g_web_parser_feed_data(GWebParser *parser,
1022 const guint8 *data, gsize length)
1024 const guint8 *ptr = data;
1029 while (length > 0) {
1030 guint8 chr = parser->token_str[parser->token_pos];
1032 if (parser->token_pos == 0) {
1035 pos = memchr(ptr, chr, length);
1037 if (parser->intoken == TRUE)
1038 g_string_append_len(parser->content,
1039 (gchar *) ptr, length);
1043 if (parser->intoken == TRUE)
1044 g_string_append_len(parser->content,
1045 (gchar *) ptr, (pos - ptr) + 1);
1047 length -= (pos - ptr) + 1;
1050 parser->token_pos++;
1054 if (parser->intoken == TRUE)
1055 g_string_append_c(parser->content, ptr[0]);
1057 if (ptr[0] != chr) {
1061 parser->token_pos = 0;
1068 parser->token_pos++;
1070 if (parser->token_pos == parser->token_len) {
1071 if (parser->intoken == FALSE) {
1072 g_string_append(parser->content,
1075 parser->intoken = TRUE;
1076 parser->token_str = parser->end_token;
1077 parser->token_len = strlen(parser->end_token);
1078 parser->token_pos = 0;
1081 str = g_string_free(parser->content, FALSE);
1082 parser->content = g_string_sized_new(0);
1084 parser->func(str, parser->user_data);
1087 parser->intoken = FALSE;
1088 parser->token_str = parser->begin_token;
1089 parser->token_len = strlen(parser->begin_token);
1090 parser->token_pos = 0;
1096 void g_web_parser_end_data(GWebParser *parser)