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;
77 GString *current_header;
81 gboolean request_started;
83 enum chunk_state chunck_state;
90 GWebResultFunc result_func;
91 GWebInputFunc input_func;
108 gboolean close_connection;
110 GWebDebugFunc debug_func;
114 static inline void debug(GWeb *web, const char *format, ...)
119 if (web->debug_func == NULL)
122 va_start(ap, format);
124 if (vsnprintf(str, sizeof(str), format, ap) > 0)
125 web->debug_func(str, web->debug_data);
130 static void free_session(struct web_session *session)
132 GWeb *web = session->web;
137 g_free(session->request);
139 if (session->resolv_action > 0)
140 g_resolv_cancel_lookup(web->resolv, session->resolv_action);
142 if (session->transport_watch > 0)
143 g_source_remove(session->transport_watch);
145 if (session->send_watch > 0)
146 g_source_remove(session->send_watch);
148 if (session->transport_channel != NULL)
149 g_io_channel_unref(session->transport_channel);
151 g_string_free(session->send_buffer, TRUE);
152 g_string_free(session->current_header, TRUE);
153 g_free(session->receive_buffer);
155 g_free(session->content_type);
157 g_free(session->host);
158 g_free(session->address);
162 static void flush_sessions(GWeb *web)
166 for (list = g_list_first(web->session_list);
167 list; list = g_list_next(list))
168 free_session(list->data);
170 g_list_free(web->session_list);
171 web->session_list = NULL;
174 GWeb *g_web_new(int index)
181 web = g_try_new0(GWeb, 1);
187 web->next_query_id = 1;
190 web->session_list = NULL;
192 web->resolv = g_resolv_new(index);
193 if (web->resolv == NULL) {
198 web->accept_option = g_strdup("*/*");
199 web->user_agent = g_strdup_printf("GWeb/%s", VERSION);
200 web->close_connection = FALSE;
205 GWeb *g_web_ref(GWeb *web)
210 g_atomic_int_inc(&web->ref_count);
215 void g_web_unref(GWeb *web)
220 if (g_atomic_int_dec_and_test(&web->ref_count) == FALSE)
225 g_resolv_unref(web->resolv);
229 g_free(web->accept_option);
230 g_free(web->user_agent);
231 g_free(web->http_version);
236 void g_web_set_debug(GWeb *web, GWebDebugFunc func, gpointer user_data)
241 web->debug_func = func;
242 web->debug_data = user_data;
244 g_resolv_set_debug(web->resolv, func, user_data);
247 gboolean g_web_set_proxy(GWeb *web, const char *proxy)
253 web->proxy = g_strdup(proxy);
258 gboolean g_web_add_nameserver(GWeb *web, const char *address)
263 g_resolv_add_nameserver(web->resolv, address, 53, 0);
268 static gboolean set_accept_option(GWeb *web, const char *format, va_list args)
270 g_free(web->accept_option);
272 if (format == NULL) {
273 web->accept_option = NULL;
274 debug(web, "clearing accept option");
276 web->accept_option = g_strdup_vprintf(format, args);
277 debug(web, "setting accept %s", web->accept_option);
283 gboolean g_web_set_accept(GWeb *web, const char *format, ...)
291 va_start(args, format);
292 result = set_accept_option(web, format, args);
298 static gboolean set_user_agent(GWeb *web, const char *format, va_list args)
300 g_free(web->user_agent);
302 if (format == NULL) {
303 web->user_agent = NULL;
304 debug(web, "clearing user agent");
306 web->user_agent = g_strdup_vprintf(format, args);
307 debug(web, "setting user agent %s", web->user_agent);
313 gboolean g_web_set_user_agent(GWeb *web, const char *format, ...)
321 va_start(args, format);
322 result = set_user_agent(web, format, args);
328 gboolean g_web_set_http_version(GWeb *web, const char *version)
333 g_free(web->http_version);
335 if (version == NULL) {
336 web->http_version = NULL;
337 debug(web, "clearing HTTP version");
339 web->http_version = g_strdup(version);
340 debug(web, "setting HTTP version %s", web->http_version);
346 void g_web_set_close_connection(GWeb *web, gboolean enabled)
351 web->close_connection = enabled;
354 gboolean g_web_get_close_connection(GWeb *web)
359 return web->close_connection;
362 static inline void call_result_func(struct web_session *session, guint16 status)
366 if (session->result_func == NULL)
370 session->result.status = status;
372 result = session->result_func(&session->result, session->user_data);
374 debug(session->web, "[result function] %s",
375 result == TRUE ? "continue" : "stop");
378 static gboolean process_send_buffer(struct web_session *session)
380 GString *buf = session->send_buffer;
381 gsize count, bytes_written;
387 if (session->request_started == TRUE &&
388 session->more_data == FALSE)
389 session->body_done = TRUE;
394 debug(session->web, "bytes to write %zu", count);
396 status = g_io_channel_write_chars(session->transport_channel,
397 buf->str, count, &bytes_written, NULL);
399 debug(session->web, "status %u bytes written %zu",
400 status, bytes_written);
402 if (status != G_IO_STATUS_NORMAL && status != G_IO_STATUS_AGAIN)
405 g_string_erase(buf, 0, bytes_written);
410 static void process_next_chunk(struct web_session *session)
412 GString *buf = session->send_buffer;
416 if (session->input_func == NULL) {
417 session->more_data = FALSE;
421 session->more_data = session->input_func(&body, &length,
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");
430 if (session->more_data == FALSE)
431 g_string_append(buf, "0\r\n\r\n");
434 static void start_request(struct web_session *session)
436 GString *buf = session->send_buffer;
441 debug(session->web, "request %s from %s",
442 session->request, session->host);
444 g_string_truncate(buf, 0);
446 if (session->web->http_version == NULL)
449 version = session->web->http_version;
451 if (session->content_type == NULL)
452 g_string_append_printf(buf, "GET %s HTTP/%s\r\n",
453 session->request, version);
455 g_string_append_printf(buf, "POST %s HTTP/%s\r\n",
456 session->request, version);
458 g_string_append_printf(buf, "Host: %s\r\n", session->host);
460 if (session->web->user_agent != NULL)
461 g_string_append_printf(buf, "User-Agent: %s\r\n",
462 session->web->user_agent);
464 if (session->web->accept_option != NULL)
465 g_string_append_printf(buf, "Accept: %s\r\n",
466 session->web->accept_option);
468 if (session->content_type != NULL) {
469 g_string_append_printf(buf, "Content-Type: %s\r\n",
470 session->content_type);
471 if (session->input_func == NULL) {
472 session->more_data = FALSE;
475 session->more_data = session->input_func(&body, &length,
477 if (session->more_data == FALSE)
478 g_string_append_printf(buf, "Content-Length: %zu\r\n",
481 g_string_append(buf, "Transfer-Encoding: chunked\r\n");
484 if (session->web->close_connection == TRUE)
485 g_string_append(buf, "Connection: close\r\n");
487 g_string_append(buf, "\r\n");
489 if (session->content_type != NULL && length > 0) {
490 if (session->more_data == TRUE) {
491 g_string_append_printf(buf, "%zx\r\n", length);
492 g_string_append_len(buf, (char *) body, length);
493 g_string_append(buf, "\r\n");
495 g_string_append_len(buf, (char *) body, length);
499 static gboolean send_data(GIOChannel *channel, GIOCondition cond,
502 struct web_session *session = user_data;
504 if (cond & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
505 session->send_watch = 0;
509 if (process_send_buffer(session) == TRUE)
512 if (session->request_started == FALSE) {
513 session->request_started = TRUE;
514 start_request(session);
515 } else if (session->more_data == TRUE)
516 process_next_chunk(session);
518 process_send_buffer(session);
520 if (session->body_done == TRUE) {
521 session->send_watch = 0;
528 static int decode_chunked(struct web_session *session,
529 const guint8 *buf, gsize len)
531 const guint8 *ptr = buf;
539 switch (session->chunck_state) {
541 pos = memchr(ptr, '\n', len);
543 g_string_append_len(session->current_header,
549 if (count < 1 || ptr[count - 1] != '\r')
552 g_string_append_len(session->current_header,
553 (gchar *) ptr, count);
558 str = session->current_header->str;
560 counter = strtoul(str, NULL, 16);
561 if ((counter == 0 && errno == EINVAL) ||
562 counter == ULONG_MAX)
565 session->chunk_size = counter;
566 session->chunk_left = counter;
568 session->chunck_state = CHUNK_DATA;
575 session->chunck_state = CHUNK_N_BODY;
582 session->chunck_state = CHUNK_SIZE;
585 if (session->chunk_size == 0) {
586 debug(session->web, "Download Done in chunk");
587 g_string_truncate(session->current_header, 0);
591 if (session->chunk_left <= len) {
592 session->result.buffer = ptr;
593 session->result.length = session->chunk_left;
594 call_result_func(session, 0);
596 len -= session->chunk_left;
597 ptr += session->chunk_left;
599 session->total_len += session->chunk_left;
600 session->chunk_left = 0;
602 g_string_truncate(session->current_header, 0);
603 session->chunck_state = CHUNK_R_BODY;
607 session->result.buffer = ptr;
608 session->result.length = len;
609 call_result_func(session, 0);
611 session->chunk_left -= len;
612 session->total_len += len;
623 static int handle_body(struct web_session *session,
624 const guint8 *buf, gsize len)
628 debug(session->web, "[body] length %zu", len);
630 if (session->result.use_chunk == FALSE) {
632 session->result.buffer = buf;
633 session->result.length = len;
634 call_result_func(session, 0);
639 err = decode_chunked(session, buf, len);
641 debug(session->web, "Error in chunk decode %d", err);
643 session->result.buffer = NULL;
644 session->result.length = 0;
645 call_result_func(session, 400);
651 static gboolean received_data(GIOChannel *channel, GIOCondition cond,
654 struct web_session *session = user_data;
655 guint8 *ptr = session->receive_buffer;
659 if (cond & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
660 session->transport_watch = 0;
661 session->result.buffer = NULL;
662 session->result.length = 0;
663 call_result_func(session, 400);
667 status = g_io_channel_read_chars(channel,
668 (gchar *) session->receive_buffer,
669 session->receive_space - 1, &bytes_read, NULL);
671 debug(session->web, "bytes read %zu", bytes_read);
673 if (status != G_IO_STATUS_NORMAL && status != G_IO_STATUS_AGAIN) {
674 session->transport_watch = 0;
675 session->result.buffer = NULL;
676 session->result.length = 0;
677 call_result_func(session, 0);
681 session->receive_buffer[bytes_read] = '\0';
683 if (session->header_done == TRUE) {
684 if (handle_body(session, session->receive_buffer,
686 session->transport_watch = 0;
692 while (bytes_read > 0) {
697 pos = memchr(ptr, '\n', bytes_read);
699 g_string_append_len(session->current_header,
700 (gchar *) ptr, bytes_read);
705 count = strlen((char *) ptr);
706 if (count > 0 && ptr[count - 1] == '\r') {
711 g_string_append_len(session->current_header,
712 (gchar *) ptr, count);
714 bytes_read -= count + 1;
720 if (session->current_header->len == 0) {
721 session->header_done = TRUE;
722 if (handle_body(session, ptr, bytes_read) < 0) {
723 session->transport_watch = 0;
729 str = session->current_header->str;
731 if (session->result.status == 0) {
734 if (sscanf(str, "HTTP/%*s %u %*s", &code) == 1)
735 session->result.status = code;
736 } else if (session->result.use_chunk == FALSE &&
737 g_ascii_strncasecmp("Transfer-Encoding:",
741 val = g_strrstr(str + 18, "chunked");
743 session->result.use_chunk = TRUE;
745 session->chunck_state = CHUNK_SIZE;
746 session->chunk_left = 0;
747 session->chunk_left = 0;
748 session->total_len = 0;
752 debug(session->web, "[header] %s", str);
754 g_string_truncate(session->current_header, 0);
760 static int connect_session_transport(struct web_session *session)
763 struct sockaddr_in sin;
766 sk = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
770 if (session->flags & SESSION_FLAG_USE_TLS) {
771 debug(session->web, "using TLS encryption");
772 session->transport_channel = g_io_channel_gnutls_new(sk);
774 debug(session->web, "no encryption");
775 session->transport_channel = g_io_channel_unix_new(sk);
778 if (session->transport_channel == NULL) {
783 flags = g_io_channel_get_flags(session->transport_channel);
784 g_io_channel_set_flags(session->transport_channel,
785 flags | G_IO_FLAG_NONBLOCK, NULL);
787 g_io_channel_set_encoding(session->transport_channel, NULL, NULL);
788 g_io_channel_set_buffered(session->transport_channel, FALSE);
790 g_io_channel_set_close_on_unref(session->transport_channel, TRUE);
792 memset(&sin, 0, sizeof(sin));
793 sin.sin_family = AF_INET;
794 sin.sin_port = htons(session->port);
795 sin.sin_addr.s_addr = inet_addr(session->address);
797 if (connect(sk, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
798 if (errno != EINPROGRESS) {
804 session->transport_watch = g_io_add_watch(session->transport_channel,
805 G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
806 received_data, session);
808 session->send_watch = g_io_add_watch(session->transport_channel,
809 G_IO_OUT | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
815 static int create_transport(struct web_session *session)
819 err = connect_session_transport(session);
823 debug(session->web, "creating session %s:%u",
824 session->address, session->port);
829 static int parse_url(struct web_session *session, const char *url)
831 char *scheme, *host, *port, *path;
833 scheme = g_strdup(url);
837 host = strstr(scheme, "://");
842 if (strcasecmp(scheme, "https") == 0) {
844 session->flags |= SESSION_FLAG_USE_TLS;
845 } else if (strcasecmp(scheme, "http") == 0) {
856 path = strchr(host, '/');
860 session->request = g_strdup_printf("/%s", path ? path : "");
862 port = strrchr(host, ':');
865 int tmp = strtol(port + 1, &end, 10);
873 session->host = g_strdup(host);
880 static void resolv_result(GResolvResultStatus status,
881 char **results, gpointer user_data)
883 struct web_session *session = user_data;
885 if (results == NULL || results[0] == NULL) {
886 call_result_func(session, 404);
890 debug(session->web, "address %s", results[0]);
892 if (inet_aton(results[0], NULL) == 0) {
893 call_result_func(session, 400);
897 session->address = g_strdup(results[0]);
899 if (create_transport(session) < 0) {
900 call_result_func(session, 409);
905 static guint do_request(GWeb *web, const char *url,
906 const char *type, GWebInputFunc input,
907 GWebResultFunc func, gpointer user_data)
909 struct web_session *session;
911 if (web == NULL || url == NULL)
914 debug(web, "request %s", url);
916 session = g_try_new0(struct web_session, 1);
920 if (parse_url(session, url) < 0) {
921 free_session(session);
925 debug(web, "host %s:%u", session->host, session->port);
926 debug(web, "flags %lu", session->flags);
929 session->content_type = g_strdup(type);
931 debug(web, "content-type %s", session->content_type);
936 session->result_func = func;
937 session->input_func = input;
938 session->user_data = user_data;
940 session->receive_buffer = g_try_malloc(DEFAULT_BUFFER_SIZE);
941 if (session->receive_buffer == NULL) {
942 free_session(session);
946 session->receive_space = DEFAULT_BUFFER_SIZE;
947 session->send_buffer = g_string_sized_new(0);
948 session->current_header = g_string_sized_new(0);
949 session->header_done = FALSE;
950 session->body_done = FALSE;
952 if (inet_aton(session->host, NULL) == 0) {
953 session->resolv_action = g_resolv_lookup_hostname(web->resolv,
954 session->host, resolv_result, session);
955 if (session->resolv_action == 0) {
956 free_session(session);
960 session->address = g_strdup(session->host);
962 if (create_transport(session) < 0) {
963 free_session(session);
968 web->session_list = g_list_append(web->session_list, session);
970 return web->next_query_id++;
973 guint g_web_request_get(GWeb *web, const char *url,
974 GWebResultFunc func, gpointer user_data)
976 return do_request(web, url, NULL, NULL, func, user_data);
979 guint g_web_request_post(GWeb *web, const char *url,
980 const char *type, GWebInputFunc input,
981 GWebResultFunc func, gpointer user_data)
983 return do_request(web, url, type, input, func, user_data);
986 gboolean g_web_cancel_request(GWeb *web, guint id)
994 guint16 g_web_result_get_status(GWebResult *result)
999 return result->status;
1002 gboolean g_web_result_get_chunk(GWebResult *result,
1003 const guint8 **chunk, gsize *length)
1011 *chunk = result->buffer;
1014 *length = result->length;
1019 struct _GWebParser {
1023 const char *token_str;
1028 GWebParserFunc func;
1032 GWebParser *g_web_parser_new(const char *begin, const char *end,
1033 GWebParserFunc func, gpointer user_data)
1037 parser = g_try_new0(GWebParser, 1);
1041 parser->ref_count = 1;
1043 parser->begin_token = g_strdup(begin);
1044 parser->end_token = g_strdup(end);
1046 if (parser->begin_token == NULL) {
1051 parser->func = func;
1052 parser->user_data = user_data;
1054 parser->token_str = parser->begin_token;
1055 parser->token_len = strlen(parser->token_str);
1056 parser->token_pos = 0;
1058 parser->intoken = FALSE;
1059 parser->content = g_string_sized_new(0);
1064 GWebParser *g_web_parser_ref(GWebParser *parser)
1069 g_atomic_int_inc(&parser->ref_count);
1074 void g_web_parser_unref(GWebParser *parser)
1079 if (g_atomic_int_dec_and_test(&parser->ref_count) == FALSE)
1082 g_string_free(parser->content, TRUE);
1084 g_free(parser->begin_token);
1085 g_free(parser->end_token);
1089 void g_web_parser_feed_data(GWebParser *parser,
1090 const guint8 *data, gsize length)
1092 const guint8 *ptr = data;
1097 while (length > 0) {
1098 guint8 chr = parser->token_str[parser->token_pos];
1100 if (parser->token_pos == 0) {
1103 pos = memchr(ptr, chr, length);
1105 if (parser->intoken == TRUE)
1106 g_string_append_len(parser->content,
1107 (gchar *) ptr, length);
1111 if (parser->intoken == TRUE)
1112 g_string_append_len(parser->content,
1113 (gchar *) ptr, (pos - ptr) + 1);
1115 length -= (pos - ptr) + 1;
1118 parser->token_pos++;
1122 if (parser->intoken == TRUE)
1123 g_string_append_c(parser->content, ptr[0]);
1125 if (ptr[0] != chr) {
1129 parser->token_pos = 0;
1136 parser->token_pos++;
1138 if (parser->token_pos == parser->token_len) {
1139 if (parser->intoken == FALSE) {
1140 g_string_append(parser->content,
1143 parser->intoken = TRUE;
1144 parser->token_str = parser->end_token;
1145 parser->token_len = strlen(parser->end_token);
1146 parser->token_pos = 0;
1149 str = g_string_free(parser->content, FALSE);
1150 parser->content = g_string_sized_new(0);
1152 parser->func(str, parser->user_data);
1155 parser->intoken = FALSE;
1156 parser->token_str = parser->begin_token;
1157 parser->token_len = strlen(parser->begin_token);
1158 parser->token_pos = 0;
1164 void g_web_parser_end_data(GWebParser *parser)