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>
36 #include "giognutls.h"
40 #define DEFAULT_BUFFER_SIZE 2048
42 #define SESSION_FLAG_USE_TLS (1 << 0)
67 struct addrinfo *addr;
71 GIOChannel *transport_channel;
72 guint transport_watch;
78 guint8 *receive_buffer;
81 GString *current_header;
85 gboolean request_started;
87 enum chunk_state chunck_state;
94 GWebResultFunc result_func;
95 GWebInputFunc input_func;
111 char *user_agent_profile;
113 gboolean close_connection;
115 GWebDebugFunc debug_func;
119 static inline void debug(GWeb *web, const char *format, ...)
124 if (web->debug_func == NULL)
127 va_start(ap, format);
129 if (vsnprintf(str, sizeof(str), format, ap) > 0)
130 web->debug_func(str, web->debug_data);
135 static void free_session(struct web_session *session)
137 GWeb *web = session->web;
142 g_free(session->request);
144 if (session->resolv_action > 0)
145 g_resolv_cancel_lookup(web->resolv, session->resolv_action);
147 if (session->transport_watch > 0)
148 g_source_remove(session->transport_watch);
150 if (session->send_watch > 0)
151 g_source_remove(session->send_watch);
153 if (session->transport_channel != NULL)
154 g_io_channel_unref(session->transport_channel);
156 g_free(session->result.last_key);
158 if (session->result.headers != NULL)
159 g_hash_table_destroy(session->result.headers);
161 if (session->send_buffer != NULL)
162 g_string_free(session->send_buffer, TRUE);
164 if (session->current_header != NULL)
165 g_string_free(session->current_header, TRUE);
167 g_free(session->receive_buffer);
169 g_free(session->content_type);
171 g_free(session->host);
172 g_free(session->address);
173 if (session->addr != NULL)
174 freeaddrinfo(session->addr);
179 static void flush_sessions(GWeb *web)
183 for (list = g_list_first(web->session_list);
184 list; list = g_list_next(list))
185 free_session(list->data);
187 g_list_free(web->session_list);
188 web->session_list = NULL;
191 GWeb *g_web_new(int index)
198 web = g_try_new0(GWeb, 1);
204 web->next_query_id = 1;
207 web->session_list = NULL;
209 web->resolv = g_resolv_new(index);
210 if (web->resolv == NULL) {
215 web->accept_option = g_strdup("*/*");
216 web->user_agent = g_strdup_printf("GWeb/%s", VERSION);
217 web->close_connection = FALSE;
222 GWeb *g_web_ref(GWeb *web)
227 g_atomic_int_inc(&web->ref_count);
232 void g_web_unref(GWeb *web)
237 if (g_atomic_int_dec_and_test(&web->ref_count) == FALSE)
242 g_resolv_unref(web->resolv);
246 g_free(web->accept_option);
247 g_free(web->user_agent);
248 g_free(web->user_agent_profile);
249 g_free(web->http_version);
254 void g_web_set_debug(GWeb *web, GWebDebugFunc func, gpointer user_data)
259 web->debug_func = func;
260 web->debug_data = user_data;
262 g_resolv_set_debug(web->resolv, func, user_data);
265 gboolean g_web_set_proxy(GWeb *web, const char *proxy)
274 debug(web, "clearing proxy");
276 web->proxy = g_strdup(proxy);
277 debug(web, "setting proxy %s", web->proxy);
283 gboolean g_web_add_nameserver(GWeb *web, const char *address)
288 g_resolv_add_nameserver(web->resolv, address, 53, 0);
293 static gboolean set_accept_option(GWeb *web, const char *format, va_list args)
295 g_free(web->accept_option);
297 if (format == NULL) {
298 web->accept_option = NULL;
299 debug(web, "clearing accept option");
301 web->accept_option = g_strdup_vprintf(format, args);
302 debug(web, "setting accept %s", web->accept_option);
308 gboolean g_web_set_accept(GWeb *web, const char *format, ...)
316 va_start(args, format);
317 result = set_accept_option(web, format, args);
323 static gboolean set_user_agent(GWeb *web, const char *format, va_list args)
325 g_free(web->user_agent);
327 if (format == NULL) {
328 web->user_agent = NULL;
329 debug(web, "clearing user agent");
331 web->user_agent = g_strdup_vprintf(format, args);
332 debug(web, "setting user agent %s", web->user_agent);
338 gboolean g_web_set_user_agent(GWeb *web, const char *format, ...)
346 va_start(args, format);
347 result = set_user_agent(web, format, args);
353 gboolean g_web_set_ua_profile(GWeb *web, const char *profile)
358 g_free(web->user_agent_profile);
360 web->user_agent_profile = g_strdup(profile);
361 debug(web, "setting user agent profile %s", web->user_agent);
366 gboolean g_web_set_http_version(GWeb *web, const char *version)
371 g_free(web->http_version);
373 if (version == NULL) {
374 web->http_version = NULL;
375 debug(web, "clearing HTTP version");
377 web->http_version = g_strdup(version);
378 debug(web, "setting HTTP version %s", web->http_version);
384 void g_web_set_close_connection(GWeb *web, gboolean enabled)
389 web->close_connection = enabled;
392 gboolean g_web_get_close_connection(GWeb *web)
397 return web->close_connection;
400 static inline void call_result_func(struct web_session *session, guint16 status)
404 if (session->result_func == NULL)
408 session->result.status = status;
410 result = session->result_func(&session->result, session->user_data);
412 debug(session->web, "[result function] %s",
413 result == TRUE ? "continue" : "stop");
416 static gboolean process_send_buffer(struct web_session *session)
418 GString *buf = session->send_buffer;
419 gsize count, bytes_written;
425 if (session->request_started == TRUE &&
426 session->more_data == FALSE)
427 session->body_done = TRUE;
432 debug(session->web, "bytes to write %zu", count);
434 status = g_io_channel_write_chars(session->transport_channel,
435 buf->str, count, &bytes_written, NULL);
437 debug(session->web, "status %u bytes written %zu",
438 status, bytes_written);
440 if (status != G_IO_STATUS_NORMAL && status != G_IO_STATUS_AGAIN)
443 g_string_erase(buf, 0, bytes_written);
448 static void process_next_chunk(struct web_session *session)
450 GString *buf = session->send_buffer;
454 if (session->input_func == NULL) {
455 session->more_data = FALSE;
459 session->more_data = session->input_func(&body, &length,
463 g_string_append_printf(buf, "%zx\r\n", length);
464 g_string_append_len(buf, (char *) body, length);
465 g_string_append(buf, "\r\n");
468 if (session->more_data == FALSE)
469 g_string_append(buf, "0\r\n\r\n");
472 static void start_request(struct web_session *session)
474 GString *buf = session->send_buffer;
479 debug(session->web, "request %s from %s",
480 session->request, session->host);
482 g_string_truncate(buf, 0);
484 if (session->web->http_version == NULL)
487 version = session->web->http_version;
489 if (session->content_type == NULL)
490 g_string_append_printf(buf, "GET %s HTTP/%s\r\n",
491 session->request, version);
493 g_string_append_printf(buf, "POST %s HTTP/%s\r\n",
494 session->request, version);
496 g_string_append_printf(buf, "Host: %s\r\n", session->host);
498 if (session->web->user_agent != NULL)
499 g_string_append_printf(buf, "User-Agent: %s\r\n",
500 session->web->user_agent);
502 if (session->web->user_agent_profile != NULL) {
503 g_string_append_printf(buf, "x-wap-profile: %s\r\n",
504 session->web->user_agent_profile);
507 if (session->web->accept_option != NULL)
508 g_string_append_printf(buf, "Accept: %s\r\n",
509 session->web->accept_option);
511 if (session->content_type != NULL) {
512 g_string_append_printf(buf, "Content-Type: %s\r\n",
513 session->content_type);
514 if (session->input_func == NULL) {
515 session->more_data = FALSE;
518 session->more_data = session->input_func(&body, &length,
520 if (session->more_data == FALSE)
521 g_string_append_printf(buf, "Content-Length: %zu\r\n",
524 g_string_append(buf, "Transfer-Encoding: chunked\r\n");
527 if (session->web->close_connection == TRUE)
528 g_string_append(buf, "Connection: close\r\n");
530 g_string_append(buf, "\r\n");
532 if (session->content_type != NULL && length > 0) {
533 if (session->more_data == TRUE) {
534 g_string_append_printf(buf, "%zx\r\n", length);
535 g_string_append_len(buf, (char *) body, length);
536 g_string_append(buf, "\r\n");
538 g_string_append_len(buf, (char *) body, length);
542 static gboolean send_data(GIOChannel *channel, GIOCondition cond,
545 struct web_session *session = user_data;
547 if (cond & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
548 session->send_watch = 0;
552 if (process_send_buffer(session) == TRUE)
555 if (session->request_started == FALSE) {
556 session->request_started = TRUE;
557 start_request(session);
558 } else if (session->more_data == TRUE)
559 process_next_chunk(session);
561 process_send_buffer(session);
563 if (session->body_done == TRUE) {
564 session->send_watch = 0;
571 static int decode_chunked(struct web_session *session,
572 const guint8 *buf, gsize len)
574 const guint8 *ptr = buf;
582 switch (session->chunck_state) {
584 pos = memchr(ptr, '\n', len);
586 g_string_append_len(session->current_header,
592 if (count < 1 || ptr[count - 1] != '\r')
595 g_string_append_len(session->current_header,
596 (gchar *) ptr, count);
601 str = session->current_header->str;
603 counter = strtoul(str, NULL, 16);
604 if ((counter == 0 && errno == EINVAL) ||
605 counter == ULONG_MAX)
608 session->chunk_size = counter;
609 session->chunk_left = counter;
611 session->chunck_state = CHUNK_DATA;
618 session->chunck_state = CHUNK_N_BODY;
625 session->chunck_state = CHUNK_SIZE;
628 if (session->chunk_size == 0) {
629 debug(session->web, "Download Done in chunk");
630 g_string_truncate(session->current_header, 0);
634 if (session->chunk_left <= len) {
635 session->result.buffer = ptr;
636 session->result.length = session->chunk_left;
637 call_result_func(session, 0);
639 len -= session->chunk_left;
640 ptr += session->chunk_left;
642 session->total_len += session->chunk_left;
643 session->chunk_left = 0;
645 g_string_truncate(session->current_header, 0);
646 session->chunck_state = CHUNK_R_BODY;
650 session->result.buffer = ptr;
651 session->result.length = len;
652 call_result_func(session, 0);
654 session->chunk_left -= len;
655 session->total_len += len;
666 static int handle_body(struct web_session *session,
667 const guint8 *buf, gsize len)
671 debug(session->web, "[body] length %zu", len);
673 if (session->result.use_chunk == FALSE) {
675 session->result.buffer = buf;
676 session->result.length = len;
677 call_result_func(session, 0);
682 err = decode_chunked(session, buf, len);
684 debug(session->web, "Error in chunk decode %d", err);
686 session->result.buffer = NULL;
687 session->result.length = 0;
688 call_result_func(session, 400);
694 static void handle_multi_line(struct web_session *session)
700 str = session->current_header->str;
702 if (str[0] != ' ' && str[0] != '\t')
705 while (str[0] == ' ' || str[0] == '\t')
708 count = str - session->current_header->str;
710 g_string_erase(session->current_header, 0, count);
711 g_string_insert_c(session->current_header, 0, ' ');
714 value = g_hash_table_lookup(session->result.headers,
715 session->result.last_key);
717 g_string_insert(session->current_header, 0, value);
719 str = session->current_header->str;
721 g_hash_table_replace(session->result.headers,
722 g_strdup(session->result.last_key),
727 static void add_header_field(struct web_session *session)
735 str = session->current_header->str;
737 pos = memchr(str, ':', session->current_header->len);
744 /* remove preceding white spaces */
748 count = (char *) pos - str;
750 g_string_erase(session->current_header, 0, count);
752 value = g_hash_table_lookup(session->result.headers, key);
754 g_string_insert_c(session->current_header, 0, ' ');
755 g_string_insert_c(session->current_header, 0, ';');
757 g_string_insert(session->current_header, 0, value);
760 str = session->current_header->str;
761 g_hash_table_replace(session->result.headers, key,
764 g_free(session->result.last_key);
765 session->result.last_key = g_strdup(key);
769 static gboolean received_data(GIOChannel *channel, GIOCondition cond,
772 struct web_session *session = user_data;
773 guint8 *ptr = session->receive_buffer;
777 if (cond & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
778 session->transport_watch = 0;
779 session->result.buffer = NULL;
780 session->result.length = 0;
781 call_result_func(session, 400);
785 status = g_io_channel_read_chars(channel,
786 (gchar *) session->receive_buffer,
787 session->receive_space - 1, &bytes_read, NULL);
789 debug(session->web, "bytes read %zu", bytes_read);
791 if (status != G_IO_STATUS_NORMAL && status != G_IO_STATUS_AGAIN) {
792 session->transport_watch = 0;
793 session->result.buffer = NULL;
794 session->result.length = 0;
795 call_result_func(session, 0);
799 session->receive_buffer[bytes_read] = '\0';
801 if (session->header_done == TRUE) {
802 if (handle_body(session, session->receive_buffer,
804 session->transport_watch = 0;
810 while (bytes_read > 0) {
815 pos = memchr(ptr, '\n', bytes_read);
817 g_string_append_len(session->current_header,
818 (gchar *) ptr, bytes_read);
823 count = strlen((char *) ptr);
824 if (count > 0 && ptr[count - 1] == '\r') {
829 g_string_append_len(session->current_header,
830 (gchar *) ptr, count);
832 bytes_read -= count + 1;
838 if (session->current_header->len == 0) {
841 session->header_done = TRUE;
843 val = g_hash_table_lookup(session->result.headers,
844 "Transfer-Encoding");
846 val = g_strrstr(val, "chunked");
848 session->result.use_chunk = TRUE;
850 session->chunck_state = CHUNK_SIZE;
851 session->chunk_left = 0;
852 session->total_len = 0;
856 if (handle_body(session, ptr, bytes_read) < 0) {
857 session->transport_watch = 0;
863 str = session->current_header->str;
865 if (session->result.status == 0) {
868 if (sscanf(str, "HTTP/%*s %u %*s", &code) == 1)
869 session->result.status = code;
872 debug(session->web, "[header] %s", str);
874 /* handle multi-line header */
875 if (str[0] == ' ' || str[0] == '\t')
876 handle_multi_line(session);
878 add_header_field(session);
880 g_string_truncate(session->current_header, 0);
886 static int connect_session_transport(struct web_session *session)
891 sk = socket(session->addr->ai_family, SOCK_STREAM, IPPROTO_TCP);
895 if (session->flags & SESSION_FLAG_USE_TLS) {
896 debug(session->web, "using TLS encryption");
897 session->transport_channel = g_io_channel_gnutls_new(sk);
899 debug(session->web, "no encryption");
900 session->transport_channel = g_io_channel_unix_new(sk);
903 if (session->transport_channel == NULL) {
908 flags = g_io_channel_get_flags(session->transport_channel);
909 g_io_channel_set_flags(session->transport_channel,
910 flags | G_IO_FLAG_NONBLOCK, NULL);
912 g_io_channel_set_encoding(session->transport_channel, NULL, NULL);
913 g_io_channel_set_buffered(session->transport_channel, FALSE);
915 g_io_channel_set_close_on_unref(session->transport_channel, TRUE);
917 if (connect(sk, session->addr->ai_addr,
918 session->addr->ai_addrlen) < 0) {
919 if (errno != EINPROGRESS) {
925 session->transport_watch = g_io_add_watch(session->transport_channel,
926 G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
927 received_data, session);
929 session->send_watch = g_io_add_watch(session->transport_channel,
930 G_IO_OUT | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
936 static int create_transport(struct web_session *session)
940 err = connect_session_transport(session);
944 debug(session->web, "creating session %s:%u",
945 session->address, session->port);
950 static int parse_url(struct web_session *session,
951 const char *url, const char *proxy)
953 char *scheme, *host, *port, *path;
955 scheme = g_strdup(url);
959 host = strstr(scheme, "://");
964 if (strcasecmp(scheme, "https") == 0) {
966 session->flags |= SESSION_FLAG_USE_TLS;
967 } else if (strcasecmp(scheme, "http") == 0) {
978 path = strchr(host, '/');
983 session->request = g_strdup_printf("/%s", path ? path : "");
985 session->request = g_strdup(url);
987 port = strrchr(host, ':');
990 int tmp = strtol(port + 1, &end, 10);
998 session->host = g_strdup(host);
1000 session->host = g_strdup_printf("%s:%u", host, tmp);
1002 session->host = g_strdup(host);
1009 scheme = g_strdup(proxy);
1013 host = strstr(proxy, "://");
1018 if (strcasecmp(scheme, "http") != 0) {
1025 path = strchr(host, '/');
1029 port = strrchr(host, ':');
1032 int tmp = strtol(port + 1, &end, 10);
1036 session->port = tmp;
1040 session->address = g_strdup(host);
1047 static void resolv_result(GResolvResultStatus status,
1048 char **results, gpointer user_data)
1050 struct web_session *session = user_data;
1051 struct addrinfo hints;
1055 if (results == NULL || results[0] == NULL) {
1056 call_result_func(session, 404);
1060 debug(session->web, "address %s", results[0]);
1062 memset(&hints, 0, sizeof(struct addrinfo));
1063 hints.ai_flags = AI_NUMERICHOST;
1065 if (session->addr != NULL) {
1066 freeaddrinfo(session->addr);
1067 session->addr = NULL;
1070 port = g_strdup_printf("%u", session->port);
1071 ret = getaddrinfo(results[0], port, &hints, &session->addr);
1073 if (ret != 0 || session->addr == NULL) {
1074 call_result_func(session, 400);
1078 session->address = g_strdup(results[0]);
1080 if (create_transport(session) < 0) {
1081 call_result_func(session, 409);
1086 static guint do_request(GWeb *web, const char *url,
1087 const char *type, GWebInputFunc input,
1088 GWebResultFunc func, gpointer user_data)
1090 struct web_session *session;
1092 if (web == NULL || url == NULL)
1095 debug(web, "request %s", url);
1097 session = g_try_new0(struct web_session, 1);
1098 if (session == NULL)
1101 if (parse_url(session, url, web->proxy) < 0) {
1102 free_session(session);
1106 debug(web, "address %s", session->address);
1107 debug(web, "port %u", session->port);
1108 debug(web, "host %s", session->host);
1109 debug(web, "flags %lu", session->flags);
1110 debug(web, "request %s", session->request);
1113 session->content_type = g_strdup(type);
1115 debug(web, "content-type %s", session->content_type);
1120 session->result_func = func;
1121 session->input_func = input;
1122 session->user_data = user_data;
1124 session->receive_buffer = g_try_malloc(DEFAULT_BUFFER_SIZE);
1125 if (session->receive_buffer == NULL) {
1126 free_session(session);
1130 session->result.headers = g_hash_table_new_full(g_str_hash, g_str_equal,
1132 if (session->result.headers == NULL) {
1133 free_session(session);
1137 session->receive_space = DEFAULT_BUFFER_SIZE;
1138 session->send_buffer = g_string_sized_new(0);
1139 session->current_header = g_string_sized_new(0);
1140 session->header_done = FALSE;
1141 session->body_done = FALSE;
1143 if (session->address == NULL && inet_aton(session->host, NULL) == 0) {
1144 session->resolv_action = g_resolv_lookup_hostname(web->resolv,
1145 session->host, resolv_result, session);
1146 if (session->resolv_action == 0) {
1147 free_session(session);
1151 if (session->address == NULL)
1152 session->address = g_strdup(session->host);
1154 if (create_transport(session) < 0) {
1155 free_session(session);
1160 web->session_list = g_list_append(web->session_list, session);
1162 return web->next_query_id++;
1165 guint g_web_request_get(GWeb *web, const char *url,
1166 GWebResultFunc func, gpointer user_data)
1168 return do_request(web, url, NULL, NULL, func, user_data);
1171 guint g_web_request_post(GWeb *web, const char *url,
1172 const char *type, GWebInputFunc input,
1173 GWebResultFunc func, gpointer user_data)
1175 return do_request(web, url, type, input, func, user_data);
1178 gboolean g_web_cancel_request(GWeb *web, guint id)
1186 guint16 g_web_result_get_status(GWebResult *result)
1191 return result->status;
1194 gboolean g_web_result_get_chunk(GWebResult *result,
1195 const guint8 **chunk, gsize *length)
1203 *chunk = result->buffer;
1206 *length = result->length;
1211 gboolean g_web_result_get_header(GWebResult *result,
1212 const char *header, const char **value)
1220 *value = g_hash_table_lookup(result->headers, header);
1228 struct _GWebParser {
1232 const char *token_str;
1237 GWebParserFunc func;
1241 GWebParser *g_web_parser_new(const char *begin, const char *end,
1242 GWebParserFunc func, gpointer user_data)
1246 parser = g_try_new0(GWebParser, 1);
1250 parser->ref_count = 1;
1252 parser->begin_token = g_strdup(begin);
1253 parser->end_token = g_strdup(end);
1255 if (parser->begin_token == NULL) {
1260 parser->func = func;
1261 parser->user_data = user_data;
1263 parser->token_str = parser->begin_token;
1264 parser->token_len = strlen(parser->token_str);
1265 parser->token_pos = 0;
1267 parser->intoken = FALSE;
1268 parser->content = g_string_sized_new(0);
1273 GWebParser *g_web_parser_ref(GWebParser *parser)
1278 g_atomic_int_inc(&parser->ref_count);
1283 void g_web_parser_unref(GWebParser *parser)
1288 if (g_atomic_int_dec_and_test(&parser->ref_count) == FALSE)
1291 g_string_free(parser->content, TRUE);
1293 g_free(parser->begin_token);
1294 g_free(parser->end_token);
1298 void g_web_parser_feed_data(GWebParser *parser,
1299 const guint8 *data, gsize length)
1301 const guint8 *ptr = data;
1306 while (length > 0) {
1307 guint8 chr = parser->token_str[parser->token_pos];
1309 if (parser->token_pos == 0) {
1312 pos = memchr(ptr, chr, length);
1314 if (parser->intoken == TRUE)
1315 g_string_append_len(parser->content,
1316 (gchar *) ptr, length);
1320 if (parser->intoken == TRUE)
1321 g_string_append_len(parser->content,
1322 (gchar *) ptr, (pos - ptr) + 1);
1324 length -= (pos - ptr) + 1;
1327 parser->token_pos++;
1331 if (parser->intoken == TRUE)
1332 g_string_append_c(parser->content, ptr[0]);
1334 if (ptr[0] != chr) {
1338 parser->token_pos = 0;
1345 parser->token_pos++;
1347 if (parser->token_pos == parser->token_len) {
1348 if (parser->intoken == FALSE) {
1349 g_string_append(parser->content,
1352 parser->intoken = TRUE;
1353 parser->token_str = parser->end_token;
1354 parser->token_len = strlen(parser->end_token);
1355 parser->token_pos = 0;
1358 str = g_string_free(parser->content, FALSE);
1359 parser->content = g_string_sized_new(0);
1361 parser->func(str, parser->user_data);
1364 parser->intoken = FALSE;
1365 parser->token_str = parser->begin_token;
1366 parser->token_len = strlen(parser->begin_token);
1367 parser->token_pos = 0;
1373 void g_web_parser_end_data(GWebParser *parser)