1 /* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */
2 /* http-method.c - The HTTP method implementation for the GNOME Virtual File
5 Copyright (C) 1999 Free Software Foundation
6 Copyright (C) 2000-2001 Eazel, Inc
8 The Gnome Library is free software; you can redistribute it and/or
9 modify it under the terms of the GNU Library General Public License as
10 published by the Free Software Foundation; either version 2 of the
11 License, or (at your option) any later version.
13 The Gnome Library is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Library General Public License for more details.
18 You should have received a copy of the GNU Library General Public
19 License along with the Gnome Library; see the file COPYING.LIB. If not,
20 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 Boston, MA 02111-1307, USA.
24 Ettore Perazzoli <ettore@gnu.org> (core HTTP)
25 Ian McKellar <yakk@yakk.net> (WebDAV/PUT)
26 Michael Fleming <mfleming@eazel.com> (Caching, Cleanup)
27 The friendly GNU Wget sources
32 - Handle persistent connections. */
35 #include "http-method.h"
37 #include "http-authn.h"
38 #include "http-cache.h"
39 /* Keep <sys/types.h> above any network includes for FreeBSD. */
40 #include <sys/types.h>
41 /* Keep <netinet/in.h> above <arpa/inet.h> for FreeBSD. */
42 #include <netinet/in.h>
43 #include <arpa/inet.h>
44 #include <gconf/gconf-client.h>
45 #include <libgnomevfs/gnome-vfs-inet-connection.h>
46 #include <libgnomevfs/gnome-vfs-mime-sniff-buffer.h>
47 #include <libgnomevfs/gnome-vfs-mime.h>
48 #include <libgnomevfs/gnome-vfs-module-callback-module-api.h>
49 #include <libgnomevfs/gnome-vfs-module.h>
50 #include <libgnomevfs/gnome-vfs-private-utils.h>
51 #include <libgnomevfs/gnome-vfs-socket-buffer.h>
52 #include <libgnomevfs/gnome-vfs-socket.h>
53 #include <libgnomevfs/gnome-vfs-ssl.h>
54 #include <libgnomevfs/gnome-vfs-standard-callbacks.h>
55 #include <libxml/parser.h>
56 #include <libxml/tree.h>
57 #include <libxml/xmlmemory.h>
60 #include <stdlib.h> /* for atoi */
62 #include <sys/socket.h>
67 #ifdef DEBUG_HTTP_ENABLE
69 http_debug_printf (char *fmt, ...)
78 out = g_strdup_vprintf (fmt, args);
80 fprintf (stderr, "HTTP: [0x%08x] [%p] %s\n",
81 (unsigned int) http_util_get_utime (),
82 g_thread_self (), out);
87 #endif /* DEBUG_HTTP_ENABLE */
89 /* What do we qualify ourselves as? */
90 /* FIXME bugzilla.gnome.org 41160: "gnome-vfs/1.0.0" may not be good. */
91 #define USER_AGENT_STRING "gnome-vfs/" VERSION
93 /* Custom User-Agent environment variable */
94 #define CUSTOM_USER_AGENT_VARIABLE "GNOME_VFS_HTTP_USER_AGENT"
96 /* Standard HTTP[S] port. */
97 #define DEFAULT_HTTP_PORT 80
98 #define DEFAULT_HTTPS_PORT 443
100 /* Standard HTTP proxy port */
101 #define DEFAULT_HTTP_PROXY_PORT 8080
103 /* GConf paths and keys */
104 #define PATH_GCONF_GNOME_VFS "/system/http_proxy"
105 #define ITEM_GCONF_HTTP_PROXY_PORT "port"
106 #define ITEM_GCONF_HTTP_PROXY_HOST "host"
107 #define KEY_GCONF_HTTP_PROXY_PORT (PATH_GCONF_GNOME_VFS "/" ITEM_GCONF_HTTP_PROXY_PORT)
108 #define KEY_GCONF_HTTP_PROXY_HOST (PATH_GCONF_GNOME_VFS "/" ITEM_GCONF_HTTP_PROXY_HOST)
110 #define ITEM_GCONF_USE_HTTP_PROXY "use_http_proxy"
111 #define KEY_GCONF_USE_HTTP_PROXY (PATH_GCONF_GNOME_VFS "/" ITEM_GCONF_USE_HTTP_PROXY)
113 #define KEY_GCONF_HTTP_AUTH_USER (PATH_GCONF_GNOME_VFS "/" "authentication_user")
114 #define KEY_GCONF_HTTP_AUTH_PW (PATH_GCONF_GNOME_VFS "/" "authentication_password")
115 #define KEY_GCONF_HTTP_USE_AUTH (PATH_GCONF_GNOME_VFS "/" "use_authentication")
117 #define KEY_GCONF_HTTP_PROXY_IGNORE_HOSTS (PATH_GCONF_GNOME_VFS "/" "ignore_hosts")
120 /* Some status code validation macros. */
121 #define HTTP_20X(x) (((x) >= 200) && ((x) < 300))
122 #define HTTP_PARTIAL(x) ((x) == HTTP_STATUS_PARTIAL_CONTENTS)
123 #define HTTP_REDIRECTED(x) (((x) == HTTP_STATUS_MOVED_PERMANENTLY) \
124 || ((x) == HTTP_STATUS_MOVED_TEMPORARILY))
126 /* HTTP/1.1 status codes from RFC2068, provided for reference. */
127 /* Successful 2xx. */
128 #define HTTP_STATUS_OK 200
129 #define HTTP_STATUS_CREATED 201
130 #define HTTP_STATUS_ACCEPTED 202
131 #define HTTP_STATUS_NON_AUTHORITATIVE 203
132 #define HTTP_STATUS_NO_CONTENT 204
133 #define HTTP_STATUS_RESET_CONTENT 205
134 #define HTTP_STATUS_PARTIAL_CONTENTS 206
136 /* Redirection 3xx. */
137 #define HTTP_STATUS_MULTIPLE_CHOICES 300
138 #define HTTP_STATUS_MOVED_PERMANENTLY 301
139 #define HTTP_STATUS_MOVED_TEMPORARILY 302
140 #define HTTP_STATUS_SEE_OTHER 303
141 #define HTTP_STATUS_NOT_MODIFIED 304
142 #define HTTP_STATUS_USE_PROXY 305
144 /* Client error 4xx. */
145 #define HTTP_STATUS_BAD_REQUEST 400
146 #define HTTP_STATUS_UNAUTHORIZED 401
147 #define HTTP_STATUS_PAYMENT_REQUIRED 402
148 #define HTTP_STATUS_FORBIDDEN 403
149 #define HTTP_STATUS_NOT_FOUND 404
150 #define HTTP_STATUS_METHOD_NOT_ALLOWED 405
151 #define HTTP_STATUS_NOT_ACCEPTABLE 406
152 #define HTTP_STATUS_PROXY_AUTH_REQUIRED 407
153 #define HTTP_STATUS_REQUEST_TIMEOUT 408
154 #define HTTP_STATUS_CONFLICT 409
155 #define HTTP_STATUS_GONE 410
156 #define HTTP_STATUS_LENGTH_REQUIRED 411
157 #define HTTP_STATUS_PRECONDITION_FAILED 412
158 #define HTTP_STATUS_REQENTITY_TOO_LARGE 413
159 #define HTTP_STATUS_REQURI_TOO_LARGE 414
160 #define HTTP_STATUS_UNSUPPORTED_MEDIA 415
161 #define HTTP_STATUS_LOCKED 423
163 /* Server errors 5xx. */
164 #define HTTP_STATUS_INTERNAL 500
165 #define HTTP_STATUS_NOT_IMPLEMENTED 501
166 #define HTTP_STATUS_BAD_GATEWAY 502
167 #define HTTP_STATUS_UNAVAILABLE 503
168 #define HTTP_STATUS_GATEWAY_TIMEOUT 504
169 #define HTTP_STATUS_UNSUPPORTED_VERSION 505
170 #define HTTP_STATUS_INSUFFICIENT_STORAGE 507
176 /* Global variables used by the HTTP proxy config */
177 static GConfClient * gl_client = NULL;
178 static GMutex *gl_mutex = NULL; /* This mutex protects preference values
179 * and ensures serialization of authentication
182 static gchar *gl_http_proxy = NULL;
183 static gchar *gl_http_proxy_auth = NULL;
184 static GSList *gl_ignore_hosts = NULL; /* Elements are strings. */
185 static GSList *gl_ignore_addrs = NULL; /* Elements are ProxyHostAddrs */
187 /* Store IP addresses that may represent network or host addresses and may be
199 struct in6_addr addr6;
200 struct in6_addr mask6;
205 GnomeVFSSocketBuffer *socket_buffer;
208 /* The list of headers returned with this response, newlines removed */
209 GList *response_headers;
211 /* File info for this file */
212 GnomeVFSFileInfo *file_info;
214 /* Bytes read so far. */
215 GnomeVFSFileSize bytes_read;
217 /* Bytes to be written... */
218 GByteArray *to_be_written;
220 /* List of GnomeVFSFileInfo from a directory listing */
223 /* The last HTTP status code returned */
227 static GnomeVFSResult resolve_409 (GnomeVFSMethod *method,
229 GnomeVFSContext *context);
230 static void proxy_set_authn (const char *username,
231 const char *password);
232 static void proxy_unset_authn (void);
233 static gboolean invoke_callback_send_additional_headers (GnomeVFSURI *uri,
235 static gboolean invoke_callback_headers_received (HttpFileHandle *handle);
236 static gboolean invoke_callback_basic_authn (HttpFileHandle *handle,
237 enum AuthnHeaderType authn_which,
238 gboolean previous_attempt_failed);
239 static gboolean check_authn_retry_request (HttpFileHandle * http_handle,
240 enum AuthnHeaderType authn_which,
241 const char *prev_authn_header);
242 static void parse_ignore_host (gpointer data,
245 static void ipv6_network_addr (const struct in6_addr *addr,
246 const struct in6_addr *mask,
247 struct in6_addr *res);
249 /*Check whether the node is IPv6 enabled.*/
255 s = socket (AF_INET6, SOCK_STREAM, 0);
265 static GnomeVFSFileInfo *
266 defaults_file_info_new (void)
268 GnomeVFSFileInfo *ret;
270 /* Fill up the file info structure with default values */
271 /* Default to REGULAR unless we find out later via a PROPFIND that it's a collection */
273 ret = gnome_vfs_file_info_new();
275 ret->type = GNOME_VFS_FILE_TYPE_REGULAR;
276 ret->flags = GNOME_VFS_FILE_FLAGS_NONE;
279 GNOME_VFS_FILE_INFO_FIELDS_TYPE
280 | GNOME_VFS_FILE_INFO_FIELDS_FLAGS;
286 /* Does not allocate the 'handle' memory. */
288 http_file_handle_new (HttpFileHandle *handle,
289 GnomeVFSSocketBuffer *socket_buffer,
292 memset (handle, 0, sizeof (*handle));
294 handle->socket_buffer = socket_buffer;
295 handle->uri_string = gnome_vfs_uri_to_string (uri, GNOME_VFS_URI_HIDE_NONE );
297 gnome_vfs_uri_ref(handle->uri);
299 handle->file_info = defaults_file_info_new();
300 handle->file_info->name = gnome_vfs_uri_extract_short_name (uri);
303 /* Does not free the 'handle' memory. */
305 http_file_handle_destroy (HttpFileHandle *handle)
307 if (handle == NULL) {
311 gnome_vfs_uri_unref(handle->uri);
312 gnome_vfs_file_info_unref (handle->file_info);
313 g_free (handle->uri_string);
314 if (handle->to_be_written) {
315 g_byte_array_free(handle->to_be_written, TRUE);
318 g_list_foreach (handle->response_headers, (GFunc) g_free, NULL);
319 g_list_free (handle->response_headers);
321 g_list_foreach(handle->files, (GFunc)gnome_vfs_file_info_unref, NULL);
322 g_list_free(handle->files);
325 /* The following comes from GNU Wget with minor changes by myself.
326 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
327 /* Parse the HTTP status line, which is of format:
329 HTTP-Version SP Status-Code SP Reason-Phrase
331 The function returns the status-code, or -1 if the status line is
332 malformed. The pointer to reason-phrase is returned in RP. */
334 parse_status (const char *cline,
335 guint *status_return)
337 /* (the variables must not be named `major' and `minor', because
338 that breaks compilation with SunOS4 cc.) */
341 const guchar *p, *line;
343 line = (const guchar *)cline;
345 /* The standard format of HTTP-Version is: `HTTP/X.Y', where X is
346 major version, and Y is minor version. */
347 if (strncmp (line, "HTTP/", 5) == 0) {
350 /* Calculate major HTTP version. */
352 for (mjr = 0; g_ascii_isdigit (*line); line++)
353 mjr = 10 * mjr + (*line - '0');
354 if (*line != '.' || p == line)
358 /* Calculate minor HTTP version. */
360 for (mnr = 0; g_ascii_isdigit (*line); line++)
361 mnr = 10 * mnr + (*line - '0');
362 if (*line != ' ' || p == line)
364 /* Wget will accept only 1.0 and higher HTTP-versions. The value of
365 minor version can be safely ignored. */
369 } else if (strncmp (line, "ICY ", 4) == 0) {
370 /* FIXME: workaround for broken ShoutCast and IceCast status replies.
371 * They send things like "ICY 200 OK" instead of "HTTP/1.0 200 OK".
372 * Is there a better way to handle this?
381 /* Calculate status code. */
382 if (!(g_ascii_isdigit (*line) && g_ascii_isdigit (line[1]) && g_ascii_isdigit (line[2])))
384 statcode = 100 * (*line - '0') + 10 * (line[1] - '0') + (line[2] - '0');
386 *status_return = statcode;
390 static GnomeVFSResult
391 http_status_to_vfs_result (guint status)
393 if (HTTP_20X (status))
396 /* FIXME bugzilla.gnome.org 41163 */
397 /* mfleming--I've improved the situation slightly, but more
398 * test cases need to be written to ensure that HTTP (esp DAV) does compatibile
399 * things with the normal file method
403 case HTTP_STATUS_PRECONDITION_FAILED:
404 /* This mapping is certainly true for MOVE with Overwrite: F, otherwise not so true */
405 return GNOME_VFS_ERROR_FILE_EXISTS;
406 case HTTP_STATUS_UNAUTHORIZED:
407 case HTTP_STATUS_PROXY_AUTH_REQUIRED:
408 case HTTP_STATUS_FORBIDDEN:
409 /* Note that FORBIDDEN can also be returned on a MOVE in a case which
410 * should be VFS_ERROR_BAD_PARAMETERS
412 return GNOME_VFS_ERROR_ACCESS_DENIED;
413 case HTTP_STATUS_NOT_FOUND:
414 return GNOME_VFS_ERROR_NOT_FOUND;
415 case HTTP_STATUS_METHOD_NOT_ALLOWED:
416 /* Note that METHOD_NOT_ALLOWED is also returned in a PROPFIND in a case which
417 * should be FILE_EXISTS. This is handled in do_make_directory
419 case HTTP_STATUS_BAD_REQUEST:
420 case HTTP_STATUS_NOT_IMPLEMENTED:
421 case HTTP_STATUS_UNSUPPORTED_VERSION:
422 return GNOME_VFS_ERROR_NOT_SUPPORTED;
423 case HTTP_STATUS_CONFLICT:
424 /* _CONFLICT's usually happen when collection paths don't exist */
425 return GNOME_VFS_ERROR_NOT_FOUND;
426 case HTTP_STATUS_LOCKED:
427 /* Maybe we need a separate GNOME_VFS_ERROR_LOCKED? */
428 return GNOME_VFS_ERROR_DIRECTORY_BUSY;
429 case HTTP_STATUS_INSUFFICIENT_STORAGE:
430 return GNOME_VFS_ERROR_NO_SPACE;
432 return GNOME_VFS_ERROR_GENERIC;
436 /* Header parsing routines. */
439 header_value_to_number (const char *header_value,
447 for (result = 0; g_ascii_isdigit (*p); p++)
448 result = 10 * result + (*p - '0');
458 set_content_length (HttpFileHandle *handle,
464 result = header_value_to_number (value, &size);
468 DEBUG_HTTP (("Expected size is %lu.", size));
469 handle->file_info->size = size;
470 handle->file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_SIZE;
475 strip_semicolon (const char *value)
479 p = strchr (value, ';');
482 return g_strndup (value, p - value);
485 return g_strdup (value);
490 set_content_type (HttpFileHandle *handle,
493 g_free (handle->file_info->mime_type);
495 handle->file_info->mime_type = strip_semicolon (value);
496 handle->file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE;
502 set_last_modified (HttpFileHandle *handle,
507 if (! gnome_vfs_atotm (value, &time))
510 handle->file_info->mtime = time;
511 handle->file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_MTIME;
516 set_access_time (HttpFileHandle *handle,
521 if (! gnome_vfs_atotm (value, &time))
524 handle->file_info->atime = time;
525 handle->file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_ATIME;
531 gboolean (* set_func) (HttpFileHandle *handle, const char *value);
533 typedef struct _Header Header;
535 static Header headers[] = {
536 { "Content-Length", set_content_length },
537 { "Content-Type", set_content_type },
538 { "Last-Modified", set_last_modified },
539 { "Date", set_access_time },
544 check_header (const char *header,
549 for (p = header, q = name; *p != '\0' && *q != '\0'; p++, q++) {
550 if (g_ascii_tolower (*p) != g_ascii_tolower (*q))
554 if (*q != '\0' || *p != ':')
558 while (*p == ' ' || *p == '\t')
565 parse_header (HttpFileHandle *handle,
570 for (i = 0; headers[i].name != NULL; i++) {
573 value = check_header (header, headers[i].name);
575 return (* headers[i].set_func) (handle, value);
578 /* Simply ignore headers we don't know. */
582 /* Header/status reading. */
584 static GnomeVFSResult
585 get_header (GnomeVFSSocketBuffer *socket_buffer,
588 GnomeVFSResult result;
589 GnomeVFSFileSize bytes_read;
592 ANALYZE_HTTP ("==> +get_header");
594 g_string_truncate (s, 0);
600 /* ANALYZE_HTTP ("==> +get_header read"); */
601 result = gnome_vfs_socket_buffer_read (socket_buffer, &c, 1,
603 /* ANALYZE_HTTP ("==> -get_header read"); */
605 if (result != GNOME_VFS_OK) {
608 if (bytes_read == 0) {
609 return GNOME_VFS_ERROR_EOF;
613 /* Handle continuation lines. */
614 if (count != 0 && (count != 1 || s->str[0] != '\r')) {
617 result = gnome_vfs_socket_buffer_peekc (
618 socket_buffer, &next);
619 if (result != GNOME_VFS_OK) {
623 if (next == '\t' || next == ' ') {
625 && s->str[count - 1] == '\r')
626 s->str[count - 1] = '\0';
631 if (count > 0 && s->str[count - 1] == '\r')
632 s->str[count - 1] = '\0';
635 g_string_append_c (s, c);
642 ANALYZE_HTTP ("==> -get_header");
647 /* rename this function? */
648 static GnomeVFSResult
649 create_handle (GnomeVFSURI *uri,
650 GnomeVFSSocketBuffer *socket_buffer,
651 GnomeVFSContext *context,
652 /* OUT */ HttpFileHandle *handle)
654 GString *header_string;
655 GnomeVFSResult result;
658 g_return_val_if_fail (handle != NULL, GNOME_VFS_ERROR_INTERNAL);
660 http_file_handle_new (handle, socket_buffer, uri);
662 header_string = g_string_new (NULL);
664 ANALYZE_HTTP ("==> +create_handle");
666 /* This is the status report string, which is the first header. */
667 result = get_header (socket_buffer, header_string);
668 if (result != GNOME_VFS_OK) {
672 if (!parse_status (header_string->str, &server_status)) {
673 /* An unparsable status line is fatal */
674 result = GNOME_VFS_ERROR_GENERIC;
678 handle->server_status = server_status;
680 ANALYZE_HTTP ("==> +create_handle: fetching headers");
682 /* Header fetching loop. */
684 result = get_header (socket_buffer, header_string);
685 if (result != GNOME_VFS_OK) {
689 /* Empty header ends header section. */
690 if (header_string->str[0] == '\0') {
694 handle->response_headers = g_list_prepend (handle->response_headers,
695 g_strdup (header_string->str));
697 /* We don't really care if we successfully parse the
698 * header or not. It might be nice to tell someone we
699 * found a header we can't parse, but it's not clear
700 * who would be interested or how we tell them. In the
701 * past we would return NOT_FOUND if any header could
702 * not be parsed, but that seems wrong.
704 parse_header (handle, header_string->str);
707 invoke_callback_headers_received (handle);
709 ANALYZE_HTTP ("==> -create_handle: fetching headers");
711 if (result != GNOME_VFS_OK) {
715 if (! HTTP_20X (server_status) && !HTTP_REDIRECTED(server_status)) {
716 result = http_status_to_vfs_result (server_status);
720 result = GNOME_VFS_OK;
722 g_string_free (header_string, TRUE);
724 ANALYZE_HTTP ("==> -create_handle");
729 * Here's how the gconf gnome-vfs HTTP proxy variables
730 * are intended to be used
732 * /system/http_proxy/use_http_proxy
734 * If set to TRUE, the client should use an HTTP proxy to connect to all
735 * servers (except those specified in the ignore_hosts key -- see below).
736 * The proxy is specified in other gconf variables below.
738 * /system/http_proxy/host
740 * The hostname of the HTTP proxy this client should use. If
741 * use-http-proxy is TRUE, this should be set. If it is not set, the
742 * application should behave as if use-http-proxy is was set to FALSE.
744 * /system/http_proxy/port
746 * The port number on the HTTP proxy host that the client should connect to
747 * If use_http_proxy and host are set but this is not set, the application
748 * should use a default port value of 8080
750 * /system/http_proxy/authentication-user
752 * Username to pass to an authenticating HTTP proxy.
754 * /system/http_proxy/authentication_password
756 * Password to pass to an authenticating HTTP proxy.
758 * /system/http_proxy/use-authentication
760 * TRUE if the client should pass http-proxy-authorization-user and
761 * http-proxy-authorization-password an HTTP proxy
763 * /system/http_proxy/ignore_hosts
764 * Type: list of strings
765 * A list of hosts (hostnames, wildcard domains, IP addresses, and CIDR
766 * network addresses) that should be accessed directly.
770 construct_gl_http_proxy (gboolean use_proxy)
772 g_free (gl_http_proxy);
773 gl_http_proxy = NULL;
775 g_slist_foreach (gl_ignore_hosts, (GFunc) g_free, NULL);
776 g_slist_free (gl_ignore_hosts);
777 gl_ignore_hosts = NULL;
778 g_slist_foreach (gl_ignore_addrs, (GFunc) g_free, NULL);
779 g_slist_free (gl_ignore_addrs);
780 gl_ignore_addrs = NULL;
787 proxy_host = gconf_client_get_string (gl_client, KEY_GCONF_HTTP_PROXY_HOST, NULL);
788 proxy_port = gconf_client_get_int (gl_client, KEY_GCONF_HTTP_PROXY_PORT, NULL);
791 if (0 != proxy_port && 0xffff >= (unsigned) proxy_port) {
792 gl_http_proxy = g_strdup_printf ("%s:%u", proxy_host, (unsigned)proxy_port);
794 gl_http_proxy = g_strdup_printf ("%s:%u", proxy_host, (unsigned)DEFAULT_HTTP_PROXY_PORT);
796 DEBUG_HTTP (("New HTTP proxy: '%s'", gl_http_proxy));
798 DEBUG_HTTP (("HTTP proxy unset"));
804 ignore = gconf_client_get_list (gl_client, KEY_GCONF_HTTP_PROXY_IGNORE_HOSTS, GCONF_VALUE_STRING, NULL);
805 g_slist_foreach (ignore, (GFunc) parse_ignore_host, NULL);
806 g_slist_foreach (ignore, (GFunc) g_free, NULL);
807 g_slist_free (ignore);
813 parse_ignore_host (gpointer data, gpointer user_data)
815 gchar *hostname, *input, *netmask;
816 gboolean ip_addr = FALSE, has_error = FALSE;
817 struct in_addr host, mask;
819 struct in6_addr host6, mask6;
824 input = (gchar*) data;
825 elt = g_new0 (ProxyHostAddr, 1);
826 if ((netmask = strchr (input, '/')) != NULL) {
827 hostname = g_strndup (input, netmask - input);
831 hostname = g_ascii_strdown (input, -1);
833 if (inet_pton (AF_INET, hostname, &host) > 0) {
835 elt->type = PROXY_IPv4;
836 elt->addr.s_addr = host.s_addr;
839 gint width = strtol (netmask, &endptr, 10);
841 if (*endptr != '\0' || width < 0 || width > 32) {
844 elt->mask.s_addr = htonl(~0 << width);
845 elt->addr.s_addr &= mask.s_addr;
848 elt->mask.s_addr = 0xffffffff;
852 else if (have_ipv6 () && inet_pton (AF_INET6, hostname, &host6) > 0) {
854 elt->type = PROXY_IPv6;
855 for (i = 0; i < 16; ++i) {
856 elt->addr6.s6_addr[i] = host6.s6_addr[i];
860 gint width = strtol (netmask, &endptr, 10);
862 if (*endptr != '\0' || width < 0 || width > 128) {
865 for (i = 0; i < 16; ++i) {
866 elt->mask6.s6_addr[i] = 0;
868 for (i=0; i < width/8; i++) {
869 elt->mask6.s6_addr[i] = 0xff;
871 elt->mask6.s6_addr[i] = (0xff << (8 - width % 8)) & 0xff;
872 ipv6_network_addr (&elt->addr6, &mask6, &elt->addr6);
875 for (i = 0; i < 16; ++i) {
876 elt->mask6.s6_addr[i] = 0xff;
884 gchar *dst = g_new0 (gchar, INET_ADDRSTRLEN);
886 gl_ignore_addrs = g_slist_append (gl_ignore_addrs, elt);
887 DEBUG_HTTP (("Host %s/%s does not go through proxy.",
889 inet_ntop(AF_INET, &elt->mask, dst, INET_ADDRSTRLEN)));
894 /* It is a hostname. */
895 gl_ignore_hosts = g_slist_append (gl_ignore_hosts, hostname);
896 DEBUG_HTTP (("Host %s does not go through proxy.", hostname));
901 set_proxy_auth (gboolean use_proxy_auth)
906 auth_user = gconf_client_get_string (gl_client, KEY_GCONF_HTTP_AUTH_USER, NULL);
907 auth_pw = gconf_client_get_string (gl_client, KEY_GCONF_HTTP_AUTH_PW, NULL);
909 if (use_proxy_auth) {
910 proxy_set_authn (auth_user, auth_pw);
911 DEBUG_HTTP (("New HTTP proxy auth user: '%s'", auth_user));
913 proxy_unset_authn ();
914 DEBUG_HTTP (("HTTP proxy auth unset"));
922 * sig_gconf_value_changed
923 * GGconf notify function for when HTTP proxy GConf key has changed.
926 notify_gconf_value_changed (GConfClient *client,
933 key = gconf_entry_get_key (entry);
935 if (strcmp (key, KEY_GCONF_USE_HTTP_PROXY) == 0
936 || strcmp (key, KEY_GCONF_HTTP_PROXY_IGNORE_HOSTS) == 0
937 || strcmp (key, KEY_GCONF_HTTP_PROXY_HOST) == 0
938 || strcmp (key, KEY_GCONF_HTTP_PROXY_PORT) == 0) {
939 gboolean use_proxy_value;
941 g_mutex_lock (gl_mutex);
943 /* Check and see if we are using the proxy */
944 use_proxy_value = gconf_client_get_bool (gl_client, KEY_GCONF_USE_HTTP_PROXY, NULL);
945 construct_gl_http_proxy (use_proxy_value);
947 g_mutex_unlock (gl_mutex);
948 } else if (strcmp (key, KEY_GCONF_HTTP_AUTH_USER) == 0
949 || strcmp (key, KEY_GCONF_HTTP_AUTH_PW) == 0
950 || strcmp (key, KEY_GCONF_HTTP_USE_AUTH) == 0) {
951 gboolean use_proxy_auth;
953 g_mutex_lock (gl_mutex);
955 use_proxy_auth = gconf_client_get_bool (gl_client, KEY_GCONF_HTTP_USE_AUTH, NULL);
956 set_proxy_auth (use_proxy_auth);
958 g_mutex_unlock (gl_mutex);
963 * host_port_from_string
964 * splits a <host>:<port> formatted string into its separate components
967 host_port_from_string (const char *http_proxy,
973 port_part = strchr (http_proxy, ':');
975 if (port_part && '\0' != ++port_part && p_proxy_port) {
976 *p_proxy_port = (guint) strtoul (port_part, NULL, 10);
977 } else if (p_proxy_port) {
978 *p_proxy_port = DEFAULT_HTTP_PROXY_PORT;
982 if ( port_part != http_proxy ) {
983 *p_proxy_host = g_strndup (http_proxy, port_part - http_proxy - 1);
992 /* FIXME: should be done using AC_REPLACE_FUNCS */
993 #ifndef HAVE_INET_PTON
995 inet_pton(int af, const char *hostname, void *pton)
998 if (!inet_aton(hostname, &in))
1000 memcpy(pton, &in, sizeof(in));
1007 ipv6_network_addr (const struct in6_addr *addr, const struct in6_addr *mask, struct in6_addr *res)
1011 for (i = 0; i < 16; ++i) {
1012 res->s6_addr[i] = addr->s6_addr[i] & mask->s6_addr[i];
1018 proxy_should_for_hostname (const char *hostname)
1021 struct in6_addr in6, net6;
1025 ProxyHostAddr *addr;
1029 if (inet_pton (AF_INET, hostname, &in) > 0) {
1030 for (elt = gl_ignore_addrs; elt; elt = g_slist_next (elt)) {
1031 addr = (ProxyHostAddr*) (elt->data);
1032 if (addr->type == PROXY_IPv4
1033 && (in.s_addr & addr->mask.s_addr) == addr->addr.s_addr) {
1034 DEBUG_HTTP (("Host %s using direct connection.", hostname));
1040 else if (have_ipv6 () && inet_pton (AF_INET6, hostname, &in6)) {
1041 for (elt = gl_ignore_addrs; elt; elt = g_slist_next (elt)) {
1042 addr = (ProxyHostAddr*) (elt->data);
1043 ipv6_network_addr (&in6, &addr->mask6, &net6);
1044 if (addr->type == PROXY_IPv6
1045 && IN6_ARE_ADDR_EQUAL (&net6, &addr->addr6)) {
1046 DEBUG_HTTP (("Host %s using direct connection.", hostname));
1049 /* Handle IPv6-wrapped IPv4 addresses. */
1050 else if (addr->type == PROXY_IPv4
1051 && IN6_IS_ADDR_V4MAPPED (&net6)) {
1054 v4addr = net6.s6_addr[12] << 24 | net6.s6_addr[13] << 16 | net6.s6_addr[14] << 8 | net6.s6_addr[15];
1055 if ((v4addr & addr->mask.s_addr) != addr->addr.s_addr) {
1056 DEBUG_HTTP (("Host %s using direct connection.", hostname));
1063 /* All hostnames (foo.bar.com) -- independent of IPv4 or IPv6 */
1065 /* If there are IPv6 addresses in the ignore_hosts list but we do not
1066 * have IPv6 available at runtime, then those addresses will also fall
1067 * through to here (and harmlessly fail to match). */
1069 gchar *hn = g_ascii_strdown (hostname, -1);
1071 for (elt = gl_ignore_hosts; elt; elt = g_slist_next (elt)) {
1072 if (*(gchar*) (elt->data) == '*' ) {
1073 if (g_str_has_suffix (hn,
1074 (gchar*) (elt->data) + 1)) {
1075 DEBUG_HTTP (("Host %s using direct connection.", hn));
1080 else if (strcmp (hn, elt->data) == 0) {
1081 DEBUG_HTTP (("Host %s using direct connection.", hn));
1092 proxy_get_authn_header_for_uri_nolock (GnomeVFSURI * uri)
1098 /* FIXME this needs to be atomic */
1099 if (gl_http_proxy_auth != NULL) {
1100 ret = g_strdup_printf ("Proxy-Authorization: Basic %s\r\n", gl_http_proxy_auth);
1107 proxy_get_authn_header_for_uri (GnomeVFSURI * uri)
1111 g_mutex_lock (gl_mutex);
1113 ret = proxy_get_authn_header_for_uri_nolock (uri);
1115 g_mutex_unlock (gl_mutex);
1122 * Retrives an appropriate HTTP proxy for a given toplevel uri
1123 * Currently, only a single HTTP proxy is implemented (there's no way for
1124 * specifying non-proxy domain names's). Returns FALSE if the connect should
1125 * take place directly
1129 GnomeVFSToplevelURI * toplevel_uri,
1130 gchar **p_proxy_host, /* Callee must free */
1131 guint *p_proxy_port) /* Callee must free */
1135 ret = proxy_should_for_hostname (toplevel_uri->host_name);
1137 g_mutex_lock (gl_mutex);
1139 if (ret && gl_http_proxy != NULL) {
1140 ret = host_port_from_string (gl_http_proxy, p_proxy_host, p_proxy_port);
1142 p_proxy_host = NULL;
1143 p_proxy_port = NULL;
1147 g_mutex_unlock (gl_mutex);
1153 proxy_set_authn (const char *username, const char *password)
1157 g_free (gl_http_proxy_auth);
1158 gl_http_proxy_auth = NULL;
1160 credentials = g_strdup_printf ("%s:%s",
1161 username == NULL ? "" : username,
1162 password == NULL ? "" : password);
1164 gl_http_proxy_auth = http_util_base64 (credentials);
1166 g_free (credentials);
1170 proxy_unset_authn (void)
1172 g_free (gl_http_proxy_auth);
1173 gl_http_proxy_auth = NULL;
1177 static GnomeVFSResult
1178 https_proxy (GnomeVFSSocket **socket_return,
1184 /* use CONNECT to do https proxying. It goes something like this:
1185 * >CONNECT server:port HTTP/1.0
1187 * <HTTP/1.0 200 Connection-established
1188 * <Proxy-agent: Apache/1.3.19 (Unix) Debian/GNU
1190 * and then we've got an open connection.
1192 * So we sent "CONNECT server:port HTTP/1.0\r\n\r\n"
1193 * Check the HTTP status.
1194 * Wait for "\r\n\r\n"
1195 * Start doing the SSL dance.
1198 GnomeVFSResult result;
1199 GnomeVFSInetConnection *http_connection;
1200 GnomeVFSSocket *http_socket;
1201 GnomeVFSSocket *https_socket;
1204 GnomeVFSFileSize bytes;
1208 result = gnome_vfs_inet_connection_create (&http_connection,
1209 proxy_host, proxy_port, NULL);
1211 if (result != GNOME_VFS_OK) {
1215 fd = gnome_vfs_inet_connection_get_fd (http_connection);
1217 http_socket = gnome_vfs_inet_connection_to_socket (http_connection);
1219 buffer = g_strdup_printf ("CONNECT %s:%d HTTP/1.0\r\n\r\n",
1220 server_host, server_port);
1221 result = gnome_vfs_socket_write (http_socket, buffer, strlen(buffer),
1225 if (result != GNOME_VFS_OK) {
1226 gnome_vfs_socket_close (http_socket);
1230 buffer = proxy_get_authn_header_for_uri (NULL); /* FIXME need uri */
1231 if (buffer != NULL) {
1232 result = gnome_vfs_socket_write (http_socket, buffer,
1233 strlen(buffer), &bytes);
1237 if (result != GNOME_VFS_OK) {
1238 gnome_vfs_socket_close (http_socket);
1243 buffer = g_malloc0 (bytes);
1245 result = gnome_vfs_socket_read (http_socket, buffer, bytes-1, &bytes);
1247 if (result != GNOME_VFS_OK) {
1248 gnome_vfs_socket_close (http_socket);
1253 if (!parse_status (buffer, &status_code)) {
1254 gnome_vfs_socket_close (http_socket);
1256 return GNOME_VFS_ERROR_PROTOCOL_ERROR;
1259 result = http_status_to_vfs_result (status_code);
1261 if (result != GNOME_VFS_OK) {
1262 gnome_vfs_socket_close (http_socket);
1267 /* okay - at this point we've read some stuff from the socket.. */
1268 /* FIXME: for now we'll assume thats all the headers and nothing but. */
1272 result = gnome_vfs_ssl_create_from_fd (&ssl, fd);
1274 if (result != GNOME_VFS_OK) {
1275 gnome_vfs_socket_close (http_socket);
1279 https_socket = gnome_vfs_ssl_to_socket (ssl);
1281 *socket_return = https_socket;
1283 return GNOME_VFS_OK;
1288 static GnomeVFSResult
1290 GnomeVFSToplevelURI *toplevel_uri,
1291 /* OUT */ GnomeVFSSocketBuffer **p_socket_buffer,
1292 /* OUT */ gboolean * p_proxy_connect)
1297 GnomeVFSResult result;
1298 GnomeVFSCancellation * cancellation;
1299 GnomeVFSInetConnection *connection;
1301 GnomeVFSSocket *socket;
1302 gboolean https = FALSE;
1304 cancellation = gnome_vfs_context_get_cancellation (
1305 gnome_vfs_context_peek_current ());
1307 g_return_val_if_fail (p_socket_buffer != NULL, GNOME_VFS_ERROR_INTERNAL);
1308 g_return_val_if_fail (p_proxy_connect != NULL, GNOME_VFS_ERROR_INTERNAL);
1309 g_return_val_if_fail (toplevel_uri != NULL, GNOME_VFS_ERROR_INTERNAL);
1311 if (!g_ascii_strcasecmp (gnome_vfs_uri_get_scheme (&toplevel_uri->uri),
1313 if (!gnome_vfs_ssl_enabled ()) {
1314 return GNOME_VFS_ERROR_NOT_SUPPORTED;
1319 if (toplevel_uri->host_port == 0) {
1321 host_port = DEFAULT_HTTPS_PORT;
1323 host_port = DEFAULT_HTTP_PORT;
1326 host_port = toplevel_uri->host_port;
1329 ANALYZE_HTTP ("==> +Making connection");
1331 if (toplevel_uri->host_name == NULL) {
1332 result = GNOME_VFS_ERROR_INVALID_URI;
1336 if (proxy_for_uri (toplevel_uri, &proxy_host, &proxy_port)) {
1338 *p_proxy_connect = FALSE;
1340 result = https_proxy (&socket, proxy_host, proxy_port,
1341 toplevel_uri->host_name, host_port);
1343 g_free (proxy_host);
1346 if (result != GNOME_VFS_OK) {
1351 *p_proxy_connect = TRUE;
1353 result = gnome_vfs_inet_connection_create (&connection,
1357 if (result != GNOME_VFS_OK) {
1360 socket = gnome_vfs_inet_connection_to_socket
1363 g_free (proxy_host);
1367 *p_proxy_connect = FALSE;
1370 result = gnome_vfs_ssl_create (&ssl,
1371 toplevel_uri->host_name, host_port);
1373 if (result != GNOME_VFS_OK) {
1376 socket = gnome_vfs_ssl_to_socket (ssl);
1378 result = gnome_vfs_inet_connection_create (&connection,
1379 toplevel_uri->host_name,
1382 if (result != GNOME_VFS_OK) {
1385 socket = gnome_vfs_inet_connection_to_socket
1390 *p_socket_buffer = gnome_vfs_socket_buffer_new (socket);
1392 if (*p_socket_buffer == NULL) {
1393 gnome_vfs_socket_close (socket);
1394 return GNOME_VFS_ERROR_INTERNAL;
1397 ANALYZE_HTTP ("==> -Making connection");
1404 build_request (const char * method, GnomeVFSToplevelURI * toplevel_uri, gboolean proxy_connect)
1406 gchar *uri_string = NULL;
1411 uri = (GnomeVFSURI *)toplevel_uri;
1413 if (proxy_connect) {
1414 uri_string = gnome_vfs_uri_to_string (uri,
1415 GNOME_VFS_URI_HIDE_USER_NAME
1416 | GNOME_VFS_URI_HIDE_PASSWORD);
1419 uri_string = gnome_vfs_uri_to_string (uri,
1420 GNOME_VFS_URI_HIDE_USER_NAME
1421 | GNOME_VFS_URI_HIDE_PASSWORD
1422 | GNOME_VFS_URI_HIDE_HOST_NAME
1423 | GNOME_VFS_URI_HIDE_HOST_PORT
1424 | GNOME_VFS_URI_HIDE_TOPLEVEL_METHOD);
1428 request = g_string_new ("");
1430 g_string_append_printf (request, "%s %s%s HTTP/1.0\r\n", method, uri_string,
1431 gnome_vfs_uri_get_path (uri)[0] == '\0' ? "/" : "" );
1433 DEBUG_HTTP (("-->Making request '%s %s'", method, uri_string));
1435 g_free (uri_string);
1438 /* `Host:' header. */
1439 if(toplevel_uri->host_port && toplevel_uri->host_port != 0) {
1440 g_string_append_printf (request, "Host: %s:%d\r\n",
1441 toplevel_uri->host_name, toplevel_uri->host_port);
1443 g_string_append_printf (request, "Host: %s:80\r\n",
1444 toplevel_uri->host_name);
1447 /* `Accept:' header. */
1448 g_string_append (request, "Accept: */*\r\n");
1450 /* `User-Agent:' header. */
1451 user_agent = getenv (CUSTOM_USER_AGENT_VARIABLE);
1453 if(user_agent == NULL) {
1454 user_agent = USER_AGENT_STRING;
1457 g_string_append_printf (request, "User-Agent: %s\r\n", user_agent);
1462 static GnomeVFSResult
1463 xmit_request (GnomeVFSSocketBuffer *socket_buffer,
1467 GnomeVFSResult result;
1468 GnomeVFSFileSize bytes_written;
1470 ANALYZE_HTTP ("==> Writing request and header");
1472 /* Transmit the request headers. */
1473 result = gnome_vfs_socket_buffer_write (socket_buffer, request->str,
1474 request->len, &bytes_written);
1476 if (result != GNOME_VFS_OK) {
1480 /* Transmit the body */
1481 if(data && data->data) {
1482 ANALYZE_HTTP ("==> Writing data");
1484 result = gnome_vfs_socket_buffer_write (socket_buffer,
1485 data->data, data->len, &bytes_written);
1488 if (result != GNOME_VFS_OK) {
1492 result = gnome_vfs_socket_buffer_flush (socket_buffer);
1498 static GnomeVFSResult
1499 make_request (HttpFileHandle *handle,
1501 const gchar *method,
1503 gchar *extra_headers,
1504 GnomeVFSContext *context)
1506 GnomeVFSSocketBuffer *socket_buffer;
1507 GnomeVFSResult result;
1508 GnomeVFSToplevelURI *toplevel_uri;
1510 gboolean proxy_connect;
1511 char *authn_header_request;
1512 char *authn_header_proxy;
1514 g_return_val_if_fail (handle != NULL, GNOME_VFS_ERROR_INTERNAL);
1516 ANALYZE_HTTP ("==> +make_request");
1519 proxy_connect = FALSE;
1520 authn_header_request = NULL;
1521 authn_header_proxy = NULL;
1523 toplevel_uri = (GnomeVFSToplevelURI *) uri;
1528 g_free (authn_header_request);
1529 g_free (authn_header_proxy);
1531 socket_buffer = NULL;
1532 result = connect_to_uri (toplevel_uri, &socket_buffer,
1535 if (result != GNOME_VFS_OK) {
1539 request = build_request (method, toplevel_uri, proxy_connect);
1541 authn_header_request = http_authn_get_header_for_uri (uri);
1543 if (authn_header_request != NULL) {
1544 g_string_append (request, authn_header_request);
1547 if (proxy_connect) {
1548 authn_header_proxy = proxy_get_authn_header_for_uri (uri);
1550 if (authn_header_proxy != NULL) {
1551 g_string_append (request, authn_header_proxy);
1555 /* `Content-Length' header. */
1557 g_string_append_printf (request, "Content-Length: %d\r\n", data->len);
1560 /* Extra headers. */
1561 if (extra_headers != NULL) {
1562 g_string_append (request, extra_headers);
1565 /* Extra headers from user */
1568 if (invoke_callback_send_additional_headers (uri, &list)) {
1571 for (i = list; i; i = i->next) {
1572 g_string_append (request, i->data);
1580 /* Empty line ends header section. */
1581 g_string_append (request, "\r\n");
1583 result = xmit_request (socket_buffer, request, data);
1584 g_string_free (request, TRUE);
1587 if (result != GNOME_VFS_OK) {
1591 /* Read the headers and create our internal HTTP file handle. */
1592 result = create_handle (uri, socket_buffer, context, handle);
1594 if (result == GNOME_VFS_OK) {
1595 socket_buffer = NULL;
1598 if (handle->server_status == HTTP_STATUS_UNAUTHORIZED) {
1599 if (! check_authn_retry_request (handle, AuthnHeader_WWW, authn_header_request)) {
1602 } else if (handle->server_status == HTTP_STATUS_PROXY_AUTH_REQUIRED) {
1603 if (! check_authn_retry_request (handle, AuthnHeader_WWW, authn_header_proxy)) {
1609 http_file_handle_destroy (handle);
1613 g_free (authn_header_request);
1614 g_free (authn_header_proxy);
1616 if (result != GNOME_VFS_OK && handle != NULL) {
1617 http_file_handle_destroy (handle);
1621 if (request != NULL) {
1622 g_string_free (request, TRUE);
1625 if (socket_buffer != NULL) {
1626 gnome_vfs_socket_buffer_destroy (socket_buffer, TRUE);
1629 ANALYZE_HTTP ("==> -make_request");
1634 http_handle_close (HttpFileHandle *handle,
1635 GnomeVFSContext *context)
1637 ANALYZE_HTTP ("==> +http_handle_close");
1639 if (handle != NULL) {
1640 if (handle->socket_buffer) {
1641 gnome_vfs_socket_buffer_flush (handle->socket_buffer);
1642 gnome_vfs_socket_buffer_destroy (handle->socket_buffer,
1644 handle->socket_buffer = NULL;
1647 http_file_handle_destroy (handle);
1650 ANALYZE_HTTP ("==> -http_handle_close");
1653 static GnomeVFSResult
1654 do_open (GnomeVFSMethod *method,
1655 GnomeVFSMethodHandle **method_handle,
1657 GnomeVFSOpenMode mode,
1658 GnomeVFSContext *context)
1660 HttpFileHandle *handle;
1661 GnomeVFSResult result = GNOME_VFS_OK;
1663 g_return_val_if_fail (uri->parent == NULL, GNOME_VFS_ERROR_INVALID_URI);
1664 g_return_val_if_fail (!(mode & GNOME_VFS_OPEN_READ &&
1665 mode & GNOME_VFS_OPEN_WRITE),
1666 GNOME_VFS_ERROR_INVALID_OPEN_MODE);
1668 ANALYZE_HTTP ("==> +do_open");
1669 DEBUG_HTTP (("+Open URI: '%s' mode:'%c'", gnome_vfs_uri_to_string(uri, 0),
1670 mode & GNOME_VFS_OPEN_READ ? 'R' : 'W'));
1672 handle = g_new (HttpFileHandle, 1);
1673 if (mode & GNOME_VFS_OPEN_READ) {
1674 result = make_request (handle, uri, "GET", NULL, NULL,
1677 http_file_handle_new(handle, NULL, uri); /* shrug */
1679 if (result == GNOME_VFS_OK) {
1680 *method_handle = (GnomeVFSMethodHandle *) handle;
1682 *method_handle = NULL;
1685 DEBUG_HTTP (("-Open (%d) handle:0x%08x", result, (unsigned int)handle));
1686 ANALYZE_HTTP ("==> -do_open");
1691 static GnomeVFSResult
1692 do_create (GnomeVFSMethod *method,
1693 GnomeVFSMethodHandle **method_handle,
1695 GnomeVFSOpenMode mode,
1698 GnomeVFSContext *context)
1700 /* try to write a zero length file - this appears to be the
1701 * only reliable way of testing if a put will succeed.
1702 * Xythos can apparently tell us if we have write permission by
1703 * playing with LOCK, but mod_dav cannot. */
1704 HttpFileHandle *handle;
1705 GnomeVFSResult result;
1706 GByteArray *bytes = g_byte_array_new();
1708 ANALYZE_HTTP ("==> +do_create");
1709 DEBUG_HTTP (("+Create URI: '%s'", gnome_vfs_uri_get_path (uri)));
1711 http_cache_invalidate_uri_parent (uri);
1713 /* Don't ignore exclusive; it should check first whether
1714 the file exists, since the http protocol default is to
1715 overwrite by default */
1716 /* FIXME we've stopped using HEAD -- we should use GET instead */
1717 /* FIXME we should check the cache here */
1720 ANALYZE_HTTP ("==> Checking to see if file exists");
1722 handle = g_new (HttpFileHandle, 1);
1723 result = make_request (handle, uri, "HEAD", NULL, NULL,
1725 http_handle_close (handle, context);
1728 if (result != GNOME_VFS_OK &&
1729 result != GNOME_VFS_ERROR_NOT_FOUND) {
1732 if (result == GNOME_VFS_OK) {
1733 return GNOME_VFS_ERROR_FILE_EXISTS;
1737 ANALYZE_HTTP ("==> Creating initial file");
1739 handle = g_new (HttpFileHandle, 1);
1740 result = make_request (handle, uri, "PUT", bytes, NULL, context);
1741 http_handle_close(handle, context);
1744 if (result != GNOME_VFS_OK) {
1745 /* the PUT failed */
1747 /* FIXME bugzilla.gnome.org 45131
1748 * If you PUT a file with an invalid name to Xythos, it
1749 * returns a 403 Forbidden, which is different from the behaviour
1750 * in MKCOL or MOVE. Unfortunately, it is not possible to discern whether
1751 * that 403 Forbidden is being returned because of invalid characters in the name
1752 * or because of permissions problems
1755 if (result == GNOME_VFS_ERROR_NOT_FOUND) {
1756 result = resolve_409 (method, uri, context);
1763 g_byte_array_free (bytes, TRUE);
1765 /* FIXME bugzilla.gnome.org 41159: do we need to do something more intelligent here? */
1766 result = do_open (method, method_handle, uri, GNOME_VFS_OPEN_WRITE, context);
1768 DEBUG_HTTP (("-Create (%d) handle:0x%08x", result, (unsigned int)handle));
1769 ANALYZE_HTTP ("==> -do_create");
1774 static GnomeVFSResult
1775 do_close (GnomeVFSMethod *method,
1776 GnomeVFSMethodHandle *method_handle,
1777 GnomeVFSContext *context)
1779 HttpFileHandle *old_handle;
1780 HttpFileHandle *new_handle;
1781 GnomeVFSResult result;
1783 ANALYZE_HTTP ("==> +do_close");
1784 DEBUG_HTTP (("+Close handle:0x%08x", (unsigned int)method_handle));
1786 old_handle = (HttpFileHandle *) method_handle;
1788 /* if the handle was opened in write mode then:
1789 * 1) there won't be a connection open, and
1790 * 2) there will be data to_be_written...
1792 if (old_handle->to_be_written != NULL) {
1793 GnomeVFSURI *uri = old_handle->uri;
1794 GByteArray *bytes = old_handle->to_be_written;
1795 GnomeVFSMimeSniffBuffer *sniff_buffer;
1796 char *extraheader = NULL;
1797 const char *mime_type = NULL;
1800 gnome_vfs_mime_sniff_buffer_new_from_existing_data (bytes->data,
1803 if (sniff_buffer != NULL) {
1805 gnome_vfs_get_mime_type_for_buffer (
1807 if (mime_type != NULL) {
1808 extraheader = g_strdup_printf(
1809 "Content-type: %s\r\n",
1812 gnome_vfs_mime_sniff_buffer_free (sniff_buffer);
1816 http_cache_invalidate_uri (uri);
1818 ANALYZE_HTTP ("==> doing PUT");
1819 new_handle = g_new (HttpFileHandle, 1);
1820 result = make_request (new_handle, uri, "PUT", bytes,
1821 extraheader, context);
1822 g_free (extraheader);
1823 http_handle_close (new_handle, context);
1824 g_free (new_handle);
1826 result = GNOME_VFS_OK;
1829 http_handle_close (old_handle, context);
1830 g_free (old_handle);
1832 DEBUG_HTTP (("-Close (%d)", result));
1833 ANALYZE_HTTP ("==> -do_close");
1838 static GnomeVFSResult
1839 do_write (GnomeVFSMethod *method,
1840 GnomeVFSMethodHandle *method_handle,
1841 gconstpointer buffer,
1842 GnomeVFSFileSize num_bytes,
1843 GnomeVFSFileSize *bytes_read,
1844 GnomeVFSContext *context)
1846 HttpFileHandle *handle;
1848 DEBUG_HTTP (("+Write handle:0x%08x", (unsigned int)method_handle));
1850 handle = (HttpFileHandle *) method_handle;
1852 if(handle->to_be_written == NULL) {
1853 handle->to_be_written = g_byte_array_new();
1855 handle->to_be_written = g_byte_array_append(handle->to_be_written, buffer, num_bytes);
1856 *bytes_read = num_bytes;
1858 DEBUG_HTTP (("-Write (0)"));
1860 return GNOME_VFS_OK;
1864 static GnomeVFSResult
1865 do_read (GnomeVFSMethod *method,
1866 GnomeVFSMethodHandle *method_handle,
1868 GnomeVFSFileSize num_bytes,
1869 GnomeVFSFileSize *bytes_read,
1870 GnomeVFSContext *context)
1872 HttpFileHandle *handle;
1873 GnomeVFSResult result;
1875 ANALYZE_HTTP ("==> +do_read");
1876 DEBUG_HTTP (("+Read handle=0x%08x", (unsigned int) method_handle));
1878 handle = (HttpFileHandle *) method_handle;
1880 if (handle->file_info->flags & GNOME_VFS_FILE_INFO_FIELDS_SIZE) {
1881 GnomeVFSFileSize max_bytes;
1883 max_bytes = handle->file_info->size - handle->bytes_read;
1884 num_bytes = MIN (max_bytes, num_bytes);
1887 result = gnome_vfs_socket_buffer_read (handle->socket_buffer, buffer,
1888 num_bytes, bytes_read);
1890 if (*bytes_read == 0) {
1891 return GNOME_VFS_ERROR_EOF;
1894 handle->bytes_read += *bytes_read;
1896 DEBUG_HTTP (("-Read (%d)", result));
1897 ANALYZE_HTTP ("==> -do_read");
1902 /* Directory handling - WebDAV servers only */
1905 process_propfind_propstat (xmlNodePtr node,
1906 GnomeVFSFileInfo *file_info)
1909 gboolean treat_as_directory;
1911 treat_as_directory = FALSE;
1913 while (node != NULL) {
1914 if (strcmp ((char *)node->name, "prop") != 0) {
1915 /* node name != "prop" - prop is all we care about */
1919 /* properties of the file */
1920 l = node->xmlChildrenNode;
1922 char *node_content_xml = xmlNodeGetContent(l);
1923 if (node_content_xml) {
1924 if (strcmp ((char *)l->name, "getcontenttype") == 0) {
1926 file_info->valid_fields |=
1927 GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE;
1929 if (!file_info->mime_type) {
1930 file_info->mime_type = strip_semicolon (node_content_xml);
1932 } else if (strcmp ((char *)l->name, "getcontentlength") == 0){
1933 file_info->valid_fields |=
1934 GNOME_VFS_FILE_INFO_FIELDS_SIZE;
1935 file_info->size = atoi(node_content_xml);
1936 } else if (strcmp((char *)l->name, "getlastmodified") == 0) {
1937 if (gnome_vfs_atotm (node_content_xml, &(file_info->mtime))) {
1938 file_info->ctime = file_info->mtime;
1939 file_info->valid_fields |=
1940 GNOME_VFS_FILE_INFO_FIELDS_MTIME
1941 | GNOME_VFS_FILE_INFO_FIELDS_CTIME;
1944 /* Unfortunately, we don't have a mapping for "creationdate" */
1946 xmlFree (node_content_xml);
1947 node_content_xml = NULL;
1949 if (strcmp ((char *)l->name, "resourcetype") == 0) {
1950 file_info->valid_fields |=
1951 GNOME_VFS_FILE_INFO_FIELDS_TYPE;
1952 file_info->type = GNOME_VFS_FILE_TYPE_REGULAR;
1954 if (l->xmlChildrenNode && l->xmlChildrenNode->name
1955 && strcmp ((char *)l->xmlChildrenNode->name, "collection") == 0) {
1956 file_info->type = GNOME_VFS_FILE_TYPE_DIRECTORY;
1964 /* If this is a DAV collection, do we tell nautilus to treat it
1965 * as a directory or as a web page?
1967 if (file_info->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_TYPE
1968 && file_info->type == GNOME_VFS_FILE_TYPE_DIRECTORY) {
1969 g_free (file_info->mime_type);
1970 if (treat_as_directory) {
1971 file_info->mime_type = g_strdup ("x-directory/webdav-prefer-directory");
1972 file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE;
1974 file_info->mime_type = g_strdup ("x-directory/webdav");
1975 file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE;
1980 if ((file_info->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE) == 0) {
1981 file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE;
1982 file_info->mime_type = g_strdup (gnome_vfs_mime_type_from_name_or_default (file_info->name, "text/plain"));
1985 if ((file_info->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_TYPE) == 0) {
1986 /* Is this a reasonable assumption ? */
1987 file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_TYPE;
1988 file_info->type = GNOME_VFS_FILE_TYPE_REGULAR;
1992 /* a strcmp that doesn't barf on NULLs */
1994 null_handling_strcmp (const char *a, const char *b)
1996 if ((a == NULL) != (b == NULL)) {
2000 if (a == NULL && b == NULL) {
2004 return strcmp (a, b);
2009 unescape_unreserved_chars (const char *in_string)
2011 /* RFC 2396 section 2.2 */
2012 static const char * reserved_chars = "%;/?:@&=+$,";
2014 char *ret, *write_char;
2015 const char * read_char;
2017 if (in_string == NULL) {
2021 ret = g_new (char, strlen (in_string) + 1);
2023 for (read_char = in_string, write_char = ret ; *read_char != '\0' ; read_char++) {
2024 if (read_char[0] == '%'
2025 && g_ascii_isxdigit (read_char[1])
2026 && g_ascii_isxdigit (read_char[2])) {
2029 unescaped = (g_ascii_xdigit_value (read_char[1]) << 4) | g_ascii_xdigit_value (read_char[2]);
2031 if (strchr (reserved_chars, unescaped)) {
2032 *write_char++ = *read_char++;
2033 *write_char++ = *read_char++;
2034 *write_char++ = *read_char; /*The last ++ is done in the for statement */
2036 *write_char++ = unescaped;
2037 read_char += 2; /*The last ++ is done in the for statement */
2040 *write_char++ = *read_char;
2043 *write_char++ = '\0';
2050 find_child_node_named (xmlNodePtr node,
2051 const char *child_node_name)
2055 child = node->xmlChildrenNode;
2057 for (child = node->xmlChildrenNode; child != NULL; child = child->next) {
2058 if (0 == strcmp (child->name, child_node_name)) {
2066 /* Look for a <status> tag in the children of node, and returns
2067 * the corresponding (HTTP) error code
2070 get_status_node (xmlNodePtr node, guint *status_code)
2072 xmlNodePtr status_node;
2073 char *status_string;
2076 status_node = find_child_node_named (node, "status");
2078 if (status_node != NULL) {
2079 status_string = xmlNodeGetContent (status_node);
2080 ret = parse_status (status_string, status_code);
2081 xmlFree (status_string);
2089 static GnomeVFSFileInfo *
2090 process_propfind_response(xmlNodePtr n,
2091 GnomeVFSURI *base_uri)
2093 GnomeVFSFileInfo *file_info = defaults_file_info_new ();
2094 GnomeVFSURI *second_base = gnome_vfs_uri_append_path (base_uri, "/");
2097 file_info->valid_fields = GNOME_VFS_FILE_INFO_FIELDS_NONE;
2100 if (strcmp ((char *)n->name, "href") == 0) {
2101 char *nodecontent = xmlNodeGetContent (n);
2104 rv = gnome_vfs_remove_optional_escapes (nodecontent);
2106 if (nodecontent != NULL && *nodecontent != '\0' && rv == GNOME_VFS_OK) {
2108 GnomeVFSURI *uri = gnome_vfs_uri_new (nodecontent);
2111 if ((0 == null_handling_strcmp (base_uri->text, uri->text)) ||
2112 (0 == null_handling_strcmp (second_base->text, uri->text))) {
2113 file_info->name = NULL; /* this file is the . directory */
2115 if (file_info->name != NULL) {
2116 /* Don't leak if a (potentially malicious)
2117 * server returns several href in its answer
2119 g_free (file_info->name);
2121 file_info->name = gnome_vfs_uri_extract_short_name (uri);
2122 if (file_info->name != NULL) {
2123 len = strlen (file_info->name) -1;
2124 if (file_info->name[len] == '/') {
2125 /* trim trailing `/` - it confuses stuff */
2126 file_info->name[len] = '\0';
2129 g_warning ("Invalid filename in PROPFIND '%s'; silently skipping", nodecontent);
2132 gnome_vfs_uri_unref (uri);
2134 g_warning ("Can't make URI from href in PROPFIND '%s'; silently skipping", nodecontent);
2137 g_warning ("got href without contents in PROPFIND response");
2140 xmlFree (nodecontent);
2141 } else if (strcmp ((char *)n->name, "propstat") == 0) {
2142 if (get_status_node (n, &status_code) && status_code == 200) {
2143 process_propfind_propstat (n->xmlChildrenNode, file_info);
2149 gnome_vfs_uri_unref (second_base);
2156 static GnomeVFSResult
2157 make_propfind_request (HttpFileHandle *handle,
2160 GnomeVFSContext *context)
2162 GnomeVFSResult result = GNOME_VFS_OK;
2163 GnomeVFSFileSize bytes_read, num_bytes=(64*1024);
2164 char *buffer = g_malloc(num_bytes);
2165 xmlParserCtxtPtr parserContext;
2166 xmlDocPtr doc = NULL;
2167 xmlNodePtr cur = NULL;
2168 char *extraheaders = g_strdup_printf("Depth: %d\r\n", depth);
2169 gboolean found_root_node_props;
2171 GByteArray *request = g_byte_array_new();
2172 char *request_str = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
2173 "<D:propfind xmlns:D=\"DAV:\" >"
2176 "<D:getcontentlength/>"
2177 "<D:getcontenttype/>"
2178 "<D:getlastmodified/>"
2183 ANALYZE_HTTP ("==> +make_propfind_request");
2185 request = g_byte_array_append(request, request_str,
2186 strlen(request_str));
2188 parserContext = xmlCreatePushParserCtxt(NULL, NULL, "", 0, "PROPFIND");
2191 http_cache_invalidate_uri_and_children (uri);
2194 result = make_request (handle, uri, "PROPFIND", request,
2195 extraheaders, context);
2197 /* FIXME bugzilla.gnome.org 43834: It looks like some http
2198 * servers (eg, www.yahoo.com) treat PROPFIND as a GET and
2199 * return a 200 OK. Others may return access denied errors or
2200 * redirects or any other legal response. This case probably
2201 * needs to be made more robust.
2203 if (result == GNOME_VFS_OK && handle->server_status != 207) { /* Multi-Status */
2204 DEBUG_HTTP (("HTTP server returned an invalid PROPFIND response: %d", handle->server_status));
2205 result = GNOME_VFS_ERROR_NOT_SUPPORTED;
2208 if (result == GNOME_VFS_OK) {
2210 result = do_read (NULL, (GnomeVFSMethodHandle *) handle,
2211 buffer, num_bytes, &bytes_read, context);
2213 if (result != GNOME_VFS_OK ) {
2216 xmlParseChunk (parserContext, buffer, bytes_read, 0);
2217 buffer[bytes_read]=0;
2218 } while (bytes_read > 0);
2221 if (result == GNOME_VFS_ERROR_EOF) {
2222 result = GNOME_VFS_OK;
2225 if (result != GNOME_VFS_OK) {
2229 xmlParseChunk (parserContext, "", 0, 1);
2231 doc = parserContext->myDoc;
2233 result = GNOME_VFS_ERROR_GENERIC;
2237 cur = doc->xmlRootNode;
2238 if (strcmp ((char *)cur->name, "multistatus") != 0) {
2239 DEBUG_HTTP (("Couldn't find <multistatus>.\n"));
2240 result = GNOME_VFS_ERROR_GENERIC;
2243 cur = cur->xmlChildrenNode;
2245 found_root_node_props = FALSE;
2246 while (cur != NULL) {
2247 if (strcmp ((char *)cur->name, "response") == 0) {
2248 GnomeVFSFileInfo *file_info;
2251 /* Some webdav servers (eg resin) put the HTTP status
2252 * code for PROPFIND request in the xml answer instead
2253 * of directly sending a 404
2255 if (get_status_node (cur, &status) && !HTTP_20X(status)) {
2256 result = http_status_to_vfs_result (status);
2261 process_propfind_response (cur->xmlChildrenNode, uri);
2263 if (file_info->name != NULL) {
2264 handle->files = g_list_append (handle->files, file_info);
2266 /* This response refers to the root node */
2267 /* Abandon the old information that came from create_handle*/
2269 file_info->name = handle->file_info->name;
2270 handle->file_info->name = NULL;
2271 gnome_vfs_file_info_unref (handle->file_info);
2272 handle->file_info = file_info;
2273 found_root_node_props = TRUE;
2277 DEBUG_HTTP(("expecting <response> got <%s>\n", cur->name));
2282 if (!found_root_node_props) {
2283 DEBUG_HTTP (("Failed to find root request node properties during propfind"));
2284 result = GNOME_VFS_ERROR_GENERIC;
2290 * Section 8.1, final line
2291 * "The results of this method [PROPFIND] SHOULD NOT be cached"
2292 * Well, at least its not "MUST NOT"
2296 http_cache_add_uri (uri, handle->file_info, TRUE);
2298 http_cache_add_uri_and_children (uri, handle->file_info, handle->files);
2303 g_free(extraheaders);
2304 xmlFreeParserCtxt(parserContext);
2306 if (result != GNOME_VFS_OK) {
2307 http_handle_close (handle, context);
2311 ANALYZE_HTTP ("==> -make_propfind_request");
2316 static GnomeVFSResult
2317 do_open_directory(GnomeVFSMethod *method,
2318 GnomeVFSMethodHandle **method_handle,
2320 GnomeVFSFileInfoOptions options,
2321 GnomeVFSContext *context)
2323 /* TODO move to using the gnome_vfs_file_info_list family of functions */
2324 GnomeVFSResult result;
2325 HttpFileHandle *handle = NULL;
2326 GnomeVFSFileInfo * file_info_cached;
2327 GList *child_file_info_cached_list = NULL;
2329 ANALYZE_HTTP ("==> +do_open_directory");
2330 DEBUG_HTTP (("+Open_Directory options: %d URI: '%s'", options, gnome_vfs_uri_to_string (uri, 0)));
2332 /* Check the cache--is this even a directory?
2333 * (Nautilus, in particular, seems to like to make this call on non directories
2336 file_info_cached = http_cache_check_uri (uri);
2338 if (file_info_cached) {
2339 if (GNOME_VFS_FILE_TYPE_DIRECTORY != file_info_cached->type) {
2340 ANALYZE_HTTP ("==> Cache Hit (Negative)");
2341 gnome_vfs_file_info_unref (file_info_cached);
2342 result = GNOME_VFS_ERROR_NOT_A_DIRECTORY;
2345 gnome_vfs_file_info_unref (file_info_cached);
2346 file_info_cached = NULL;
2350 /* The check for directory contents is more stringent */
2351 file_info_cached = http_cache_check_directory_uri (uri, &child_file_info_cached_list);
2353 if (file_info_cached) {
2354 handle = g_new (HttpFileHandle, 1);
2355 http_file_handle_new (handle, NULL, uri);
2356 gnome_vfs_file_info_unref (handle->file_info);
2357 handle->file_info = file_info_cached;
2358 handle->files = child_file_info_cached_list;
2359 result = GNOME_VFS_OK;
2361 handle = g_new (HttpFileHandle, 1);
2362 result = make_propfind_request(handle, uri, 1, context);
2363 /* mfleming -- is this necessary? Most DAV server's I've seen don't have the horrible
2364 * lack-of-trailing-/-is-a-301 problem for PROPFIND's
2366 if (result == GNOME_VFS_ERROR_NOT_FOUND) { /* 404 not found */
2367 if (uri->text != NULL && *uri->text != '\0'
2368 && uri->text[strlen (uri->text) - 1] != '/') {
2369 GnomeVFSURI *tmpuri = gnome_vfs_uri_append_path (uri, "/");
2370 result = do_open_directory (method, (GnomeVFSMethodHandle **)&handle, tmpuri, options, context);
2371 gnome_vfs_uri_unref (tmpuri);
2376 if (result == GNOME_VFS_OK
2377 && handle->file_info->type != GNOME_VFS_FILE_TYPE_DIRECTORY) {
2378 result = GNOME_VFS_ERROR_NOT_A_DIRECTORY;
2379 http_handle_close (handle, context);
2385 *method_handle = (GnomeVFSMethodHandle *)handle;
2388 DEBUG_HTTP (("-Open_Directory (%d) handle:0x%08x", result, (unsigned int)handle));
2389 ANALYZE_HTTP ("==> -do_open_directory");
2394 static GnomeVFSResult
2395 do_close_directory (GnomeVFSMethod *method,
2396 GnomeVFSMethodHandle *method_handle,
2397 GnomeVFSContext *context)
2399 HttpFileHandle *handle;
2401 DEBUG_HTTP (("+Close_Directory"));
2403 handle = (HttpFileHandle *) method_handle;
2405 http_handle_close(handle, context);
2408 DEBUG_HTTP (("-Close_Directory (0) handle:0x%08x", (unsigned int) method_handle));
2410 return GNOME_VFS_OK;
2413 static GnomeVFSResult
2414 do_read_directory (GnomeVFSMethod *method,
2415 GnomeVFSMethodHandle *method_handle,
2416 GnomeVFSFileInfo *file_info,
2417 GnomeVFSContext *context)
2419 HttpFileHandle *handle;
2420 GnomeVFSResult result;
2422 DEBUG_HTTP (("+Read_Directory handle:0x%08x", (unsigned int) method_handle));
2424 handle = (HttpFileHandle *) method_handle;
2426 if (handle->files && g_list_length (handle->files)) {
2427 GnomeVFSFileInfo *original_info = g_list_nth_data (handle->files, 0);
2428 gboolean found_entry = FALSE;
2430 /* mfleming -- Why is this check here? Does anyone set original_info->name to NULL? */
2431 if (original_info->name != NULL && original_info->name[0]) {
2432 gnome_vfs_file_info_copy (file_info, original_info);
2436 /* remove our GnomeVFSFileInfo from the list */
2437 handle->files = g_list_remove (handle->files, original_info);
2438 gnome_vfs_file_info_unref (original_info);
2440 /* mfleming -- Is this necessary? */
2442 result = GNOME_VFS_OK;
2444 result = do_read_directory (method, method_handle, file_info, context);
2447 result = GNOME_VFS_ERROR_EOF;
2450 DEBUG_HTTP (("-Read_Directory (%d)", result));
2455 static GnomeVFSResult
2456 do_get_file_info (GnomeVFSMethod *method,
2458 GnomeVFSFileInfo *file_info,
2459 GnomeVFSFileInfoOptions options,
2460 GnomeVFSContext *context)
2462 HttpFileHandle *handle;
2463 GnomeVFSResult result;
2464 GnomeVFSFileInfo * file_info_cached;
2466 ANALYZE_HTTP ("==> +do_get_file_info");
2467 DEBUG_HTTP (("+Get_File_Info options: %d URI: '%s'", options, gnome_vfs_uri_to_string( uri, 0)));
2469 file_info_cached = http_cache_check_uri (uri);
2471 if (file_info_cached != NULL) {
2472 gnome_vfs_file_info_copy (file_info, file_info_cached);
2473 gnome_vfs_file_info_unref (file_info_cached);
2474 ANALYZE_HTTP ("==> Cache Hit");
2475 result = GNOME_VFS_OK;
2478 * Start off by making a PROPFIND request. Fall back to a HEAD if it fails
2481 handle = g_new (HttpFileHandle, 1);
2482 result = make_propfind_request (handle, uri, 0, context);
2484 /* Note that theoretically we could not bother with this request if we get a 404 back,
2485 * but since some servers seem to return wierd things on PROPFIND (mostly 200 OK's...)
2486 * I'm not going to count on the PROPFIND response....
2488 if (result == GNOME_VFS_OK) {
2489 gnome_vfs_file_info_copy (file_info, handle->file_info);
2490 http_handle_close (handle, context);
2494 g_assert (handle == NULL); /* Make sure we're not leaking some old one */
2496 /* Lame buggy servers (eg: www.mozilla.org,
2497 * www.corel.com)) return an HTTP error for a
2498 * HEAD where a GET would succeed. In these
2499 * cases lets try to do a GET.
2501 if (result != GNOME_VFS_OK) {
2502 g_assert (handle == NULL); /* Make sure we're not leaking some old one */
2504 ANALYZE_HTTP ("==> do_get_file_info: do GET ");
2506 handle = g_new (HttpFileHandle, 1);
2507 result = make_request (handle, uri, "GET", NULL, NULL, context);
2508 if (result == GNOME_VFS_OK) {
2509 gnome_vfs_file_info_copy (file_info, handle->file_info);
2510 http_cache_add_uri (uri, handle->file_info, FALSE);
2511 http_handle_close (handle, context);
2515 /* If we get a redirect, we should be
2516 * basing the MIME type on the type of
2517 * the page we'll be redirected
2518 * too. Maybe we even want to take the
2519 * "follow_links" setting into account.
2521 /* FIXME: For now we treat all
2522 * redirects as if they lead to a
2523 * text/html. That works pretty well,
2524 * but it's not correct.
2526 if (handle != NULL && HTTP_REDIRECTED (handle->server_status)) {
2527 g_free (file_info->mime_type);
2528 file_info->mime_type = g_strdup ("text/html");
2532 if (result == GNOME_VFS_ERROR_NOT_FOUND) { /* 404 not found */
2533 /* FIXME bugzilla.gnome.org 43835: mfleming: Is this code really appropriate?
2534 * In any case, it doesn't seem to be appropriate for a DAV-enabled
2535 * server, since they don't seem to send 301's when you PROPFIND collections
2536 * without a trailing '/'.
2538 if (uri->text != NULL && *uri->text != '\0'
2539 && uri->text[strlen(uri->text)-1] != '/') {
2540 GnomeVFSURI *tmpuri = gnome_vfs_uri_append_path (uri, "/");
2542 result = do_get_file_info (method, tmpuri, file_info, options, context);
2543 gnome_vfs_uri_unref (tmpuri);
2549 DEBUG_HTTP (("-Get_File_Info (%d)", result));
2550 ANALYZE_HTTP ("==> -do_get_file_info");
2555 static GnomeVFSResult
2556 do_get_file_info_from_handle (GnomeVFSMethod *method,
2557 GnomeVFSMethodHandle *method_handle,
2558 GnomeVFSFileInfo *file_info,
2559 GnomeVFSFileInfoOptions options,
2560 GnomeVFSContext *context)
2562 HttpFileHandle *handle;
2564 DEBUG_HTTP (("+Get_File_Info_From_Handle"));
2566 handle = (HttpFileHandle *) method_handle;
2568 gnome_vfs_file_info_copy (file_info, handle->file_info);
2570 DEBUG_HTTP (("-Get_File_Info_From_Handle"));
2572 return GNOME_VFS_OK;
2576 do_is_local (GnomeVFSMethod *method,
2577 const GnomeVFSURI *uri)
2579 DEBUG_HTTP (("+Is_Local"));
2583 static GnomeVFSResult
2584 do_make_directory (GnomeVFSMethod *method,
2587 GnomeVFSContext *context)
2589 /* MKCOL /path HTTP/1.0 */
2591 HttpFileHandle *handle;
2592 GnomeVFSResult result;
2594 DEBUG_HTTP (("+Make_Directory URI: '%s'", gnome_vfs_uri_to_string (uri, 0)));
2595 ANALYZE_HTTP ("==> +do_make_directory");
2598 * MKCOL returns a 405 if you try to MKCOL on something that
2599 * already exists. Of course, we don't know whether that means that
2600 * the server doesn't support DAV or the collection already exists.
2601 * So we do a PROPFIND first to find out
2603 /* FIXME check cache here */
2604 handle = g_new (HttpFileHandle, 1);
2605 result = make_propfind_request(handle, uri, 0, context);
2607 if (result == GNOME_VFS_OK) {
2608 result = GNOME_VFS_ERROR_FILE_EXISTS;
2610 /* Make sure we're not leaking an old one */
2611 g_assert (handle == NULL);
2613 if (result == GNOME_VFS_ERROR_NOT_FOUND) {
2614 http_cache_invalidate_uri_parent (uri);
2615 handle = g_new (HttpFileHandle, 1);
2616 result = make_request (handle, uri, "MKCOL", NULL, NULL, context);
2619 http_handle_close (handle, context);
2622 if (result == GNOME_VFS_ERROR_NOT_FOUND) {
2623 result = resolve_409 (method, uri, context);
2626 ANALYZE_HTTP ("==> -do_make_directory");
2627 DEBUG_HTTP (("-Make_Directory (%d)", result));
2632 static GnomeVFSResult
2633 do_remove_directory(GnomeVFSMethod *method,
2635 GnomeVFSContext *context)
2637 /* DELETE /path HTTP/1.0 */
2638 HttpFileHandle *handle;
2639 GnomeVFSResult result;
2641 ANALYZE_HTTP ("==> +do_remove_directory");
2642 DEBUG_HTTP (("+Remove_Directory URI: '%s'", gnome_vfs_uri_to_string (uri, 0)));
2644 http_cache_invalidate_uri_parent (uri);
2646 /* FIXME this should return GNOME_VFS_ERROR_DIRECTORY_NOT_EMPTY if the
2647 * directory is not empty
2649 handle = g_new (HttpFileHandle, 1);
2650 result = make_request (handle, uri, "DELETE", NULL, NULL,
2652 http_handle_close (handle, context);
2655 DEBUG_HTTP (("-Remove_Directory (%d)", result));
2656 ANALYZE_HTTP ("==> -do_remove_directory");
2662 is_same_fs (const GnomeVFSURI *a,
2663 const GnomeVFSURI *b)
2665 return null_handling_strcmp (gnome_vfs_uri_get_scheme (a), gnome_vfs_uri_get_scheme (b)) == 0
2666 && null_handling_strcmp (gnome_vfs_uri_get_host_name (a), gnome_vfs_uri_get_host_name (b)) == 0
2667 && null_handling_strcmp (gnome_vfs_uri_get_user_name (a), gnome_vfs_uri_get_user_name (b)) == 0
2668 && null_handling_strcmp (gnome_vfs_uri_get_password (a), gnome_vfs_uri_get_password (b)) == 0
2669 && (gnome_vfs_uri_get_host_port (a) == gnome_vfs_uri_get_host_port (b));
2672 static GnomeVFSResult
2673 do_move (GnomeVFSMethod *method,
2674 GnomeVFSURI *old_uri,
2675 GnomeVFSURI *new_uri,
2676 gboolean force_replace,
2677 GnomeVFSContext *context)
2681 * MOVE /path1 HTTP/1.0
2682 * Destination: /path2
2686 HttpFileHandle *handle;
2687 GnomeVFSResult result;
2689 char *destpath, *destheader;
2691 ANALYZE_HTTP ("==> +do_move");
2692 DEBUG_HTTP (("+Move URI: '%s' Dest: '%s'",
2693 gnome_vfs_uri_to_string (old_uri, 0),
2694 gnome_vfs_uri_to_string (new_uri, 0)));
2696 if (!is_same_fs (old_uri, new_uri)) {
2697 return GNOME_VFS_ERROR_NOT_SAME_FILE_SYSTEM;
2700 destpath = gnome_vfs_uri_to_string (new_uri, GNOME_VFS_URI_HIDE_USER_NAME|GNOME_VFS_URI_HIDE_PASSWORD);
2701 destheader = g_strdup_printf ("Destination: %s\r\nOverwrite: %c\r\n", destpath, force_replace ? 'T' : 'F' );
2703 handle = g_new (HttpFileHandle, 1);
2704 result = make_request (handle, old_uri, "MOVE", NULL, destheader, context);
2705 http_handle_close (handle, context);
2709 if (result == GNOME_VFS_ERROR_NOT_FOUND) {
2710 result = resolve_409 (method, new_uri, context);
2713 http_cache_invalidate_uri_parent (old_uri);
2714 http_cache_invalidate_uri_parent (new_uri);
2716 DEBUG_HTTP (("-Move (%d)", result));
2717 ANALYZE_HTTP ("==> -do_move");
2723 static GnomeVFSResult
2724 do_unlink(GnomeVFSMethod *method,
2726 GnomeVFSContext *context)
2728 GnomeVFSResult result;
2730 /* FIXME need to make sure this fails on directories */
2731 ANALYZE_HTTP ("==> +do_unlink");
2732 DEBUG_HTTP (("+Unlink URI: '%s'", gnome_vfs_uri_to_string (uri, 0)));
2733 result = do_remove_directory (method, uri, context);
2734 DEBUG_HTTP (("-Unlink (%d)", result));
2735 ANALYZE_HTTP ("==> -do_unlink");
2740 static GnomeVFSResult
2741 do_check_same_fs (GnomeVFSMethod *method,
2744 gboolean *same_fs_return,
2745 GnomeVFSContext *context)
2747 *same_fs_return = is_same_fs (a, b);
2749 return GNOME_VFS_OK;
2752 static GnomeVFSResult
2753 do_set_file_info (GnomeVFSMethod *method,
2755 const GnomeVFSFileInfo *info,
2756 GnomeVFSSetFileInfoMask mask,
2757 GnomeVFSContext *context)
2759 GnomeVFSURI *parent_uri, *new_uri;
2760 GnomeVFSResult result;
2762 /* FIXME: For now, we only support changing the name. */
2763 if ((mask & ~(GNOME_VFS_SET_FILE_INFO_NAME)) != 0) {
2764 return GNOME_VFS_ERROR_NOT_SUPPORTED;
2767 /* FIXME bugzillagnome.org 40645: Make sure this returns an
2768 * error for incoming names with "/" characters in them,
2769 * instead of moving the file.
2772 /* Share code with do_move. */
2773 parent_uri = gnome_vfs_uri_get_parent (uri);
2774 if (parent_uri == NULL) {
2775 return GNOME_VFS_ERROR_NOT_FOUND;
2777 new_uri = gnome_vfs_uri_append_file_name (parent_uri, info->name);
2778 gnome_vfs_uri_unref (parent_uri);
2779 result = do_move (method, uri, new_uri, FALSE, context);
2780 gnome_vfs_uri_unref (new_uri);
2784 static GnomeVFSMethod method = {
2785 sizeof (GnomeVFSMethod),
2793 NULL, /* truncate_handle */
2798 do_get_file_info_from_handle,
2801 do_remove_directory,
2806 NULL, /* truncate */
2807 NULL, /* find_directory */
2808 NULL /* create_symbolic_link */
2812 vfs_module_init (const char *method_name,
2815 GError *gconf_error = NULL;
2817 gboolean use_proxy_auth;
2821 gl_client = gconf_client_get_default ();
2823 gl_mutex = g_mutex_new ();
2825 gconf_client_add_dir (gl_client, PATH_GCONF_GNOME_VFS, GCONF_CLIENT_PRELOAD_ONELEVEL, &gconf_error);
2827 DEBUG_HTTP (("GConf error during client_add_dir '%s'", gconf_error->message));
2828 g_error_free (gconf_error);
2832 gconf_client_notify_add (gl_client, PATH_GCONF_GNOME_VFS, notify_gconf_value_changed, NULL, NULL, &gconf_error);
2834 DEBUG_HTTP (("GConf error during notify_error '%s'", gconf_error->message));
2835 g_error_free (gconf_error);
2839 /* Load the http proxy setting */
2840 use_proxy = gconf_client_get_bool (gl_client, KEY_GCONF_USE_HTTP_PROXY, &gconf_error);
2842 if (gconf_error != NULL) {
2843 DEBUG_HTTP (("GConf error during client_get_bool '%s'", gconf_error->message));
2844 g_error_free (gconf_error);
2847 construct_gl_http_proxy (use_proxy);
2850 use_proxy_auth = gconf_client_get_bool (gl_client, KEY_GCONF_HTTP_USE_AUTH, &gconf_error);
2852 if (gconf_error != NULL) {
2853 DEBUG_HTTP (("GConf error during client_get_bool '%s'", gconf_error->message));
2854 g_error_free (gconf_error);
2857 set_proxy_auth (use_proxy_auth);
2867 vfs_module_shutdown (GnomeVFSMethod *method)
2869 g_object_unref (G_OBJECT (gl_client));
2871 http_authn_shutdown ();
2873 http_cache_shutdown();
2875 g_mutex_free (gl_mutex);
2880 /* A "409 Conflict" currently maps to GNOME_VFS_ERROR_NOT_FOUND because it can be returned
2881 * when the parent collection/directory does not exist. Unfortunately, Xythos also returns
2882 * this code when the destination filename of a PUT, MKCOL, or MOVE contains illegal characters,
2883 * eg "my*file:name".
2885 * The only way to resolve this is to ask...
2888 static GnomeVFSResult
2889 resolve_409 (GnomeVFSMethod *method, GnomeVFSURI *uri, GnomeVFSContext *context)
2891 GnomeVFSFileInfo *file_info;
2892 GnomeVFSURI *parent_dest_uri;
2893 GnomeVFSResult result;
2896 ANALYZE_HTTP ("==> +resolving 409");
2898 file_info = gnome_vfs_file_info_new ();
2899 parent_dest_uri = gnome_vfs_uri_get_parent (uri);
2901 if (parent_dest_uri != NULL) {
2902 result = do_get_file_info (method,
2905 GNOME_VFS_FILE_INFO_DEFAULT,
2908 gnome_vfs_file_info_unref (file_info);
2911 gnome_vfs_uri_unref (parent_dest_uri);
2912 parent_dest_uri = NULL;
2914 result = GNOME_VFS_ERROR_NOT_FOUND;
2917 if (result == GNOME_VFS_OK) {
2918 /* The destination filename contains characters that are not allowed
2919 * by the server. This is a bummer mapping, but EINVAL is what
2920 * the Linux FAT filesystems return on bad filenames, so at least
2921 * its not without precedent...
2923 result = GNOME_VFS_ERROR_BAD_PARAMETERS;
2925 /* The destination's parent path does not exist */
2926 result = GNOME_VFS_ERROR_NOT_FOUND;
2929 ANALYZE_HTTP ("==> -resolving 409");
2935 invoke_callback_headers_received (HttpFileHandle *handle)
2937 GnomeVFSModuleCallbackReceivedHeadersIn in_args;
2938 GnomeVFSModuleCallbackReceivedHeadersOut out_args;
2939 gboolean ret = FALSE;
2941 memset (&in_args, 0, sizeof (in_args));
2942 memset (&out_args, 0, sizeof (out_args));
2944 in_args.uri = handle->uri;
2945 in_args.headers = handle->response_headers;
2947 ret = gnome_vfs_module_callback_invoke (GNOME_VFS_MODULE_CALLBACK_HTTP_RECEIVED_HEADERS,
2948 &in_args, sizeof (in_args),
2949 &out_args, sizeof (out_args));
2955 invoke_callback_send_additional_headers (GnomeVFSURI *uri,
2958 GnomeVFSModuleCallbackAdditionalHeadersIn in_args;
2959 GnomeVFSModuleCallbackAdditionalHeadersOut out_args;
2960 gboolean ret = FALSE;
2962 memset (&in_args, 0, sizeof (in_args));
2963 memset (&out_args, 0, sizeof (out_args));
2967 ret = gnome_vfs_module_callback_invoke (GNOME_VFS_MODULE_CALLBACK_HTTP_SEND_ADDITIONAL_HEADERS,
2968 &in_args, sizeof (in_args),
2969 &out_args, sizeof (out_args));
2972 *headers = out_args.headers;
2976 if (out_args.headers) {
2977 g_list_foreach (out_args.headers, (GFunc)g_free, NULL);
2978 g_list_free (out_args.headers);
2987 invoke_callback_basic_authn (HttpFileHandle *handle,
2988 enum AuthnHeaderType authn_which,
2989 gboolean previous_attempt_failed)
2991 GnomeVFSModuleCallbackAuthenticationIn in_args;
2992 GnomeVFSModuleCallbackAuthenticationOut out_args;
2997 memset (&in_args, 0, sizeof (in_args));
2998 memset (&out_args, 0, sizeof (out_args));
3000 in_args.previous_attempt_failed = previous_attempt_failed;
3002 in_args.uri = gnome_vfs_uri_to_string (handle->uri, GNOME_VFS_URI_HIDE_NONE);
3004 ret = http_authn_parse_response_header_basic (authn_which, handle->response_headers, &in_args.realm);
3010 DEBUG_HTTP (("Invoking %s authentication callback for uri %s",
3011 authn_which == AuthnHeader_WWW ? "basic" : "proxy", in_args.uri));
3013 in_args.auth_type = AuthTypeBasic;
3015 ret = gnome_vfs_module_callback_invoke (authn_which == AuthnHeader_WWW
3016 ? GNOME_VFS_MODULE_CALLBACK_AUTHENTICATION
3017 : GNOME_VFS_MODULE_CALLBACK_HTTP_PROXY_AUTHENTICATION,
3018 &in_args, sizeof (in_args),
3019 &out_args, sizeof (out_args));
3022 DEBUG_HTTP (("No callback registered"));
3026 ret = (out_args.username != NULL);
3029 DEBUG_HTTP (("No username provided by callback"));
3033 DEBUG_HTTP (("Back from authentication callback, adding credentials"));
3035 if (authn_which == AuthnHeader_WWW) {
3036 http_authn_session_add_credentials (handle->uri, out_args.username, out_args.password);
3037 } else /* if (authn_which == AuthnHeader_Proxy) */ {
3038 proxy_set_authn (out_args.username, out_args.password);
3041 g_free (in_args.uri);
3042 g_free (in_args.realm);
3043 g_free (out_args.username);
3044 g_free (out_args.password);
3050 strcmp_allow_nulls (const char *s1, const char *s2)
3052 return strcmp (s1 == NULL ? "" : s1, s2 == NULL ? "" : s2);
3056 /* Returns TRUE if the given URL has changed authentication credentials
3057 * from the last request (eg, another thread updated the authn information)
3058 * or if the application provided new credentials via a callback
3060 * prev_authn_header is NULL if the previous request contained no authn information.
3064 check_authn_retry_request (HttpFileHandle * http_handle,
3065 enum AuthnHeaderType authn_which,
3066 const char *prev_authn_header)
3069 char *current_authn_header;
3071 current_authn_header = NULL;
3073 g_mutex_lock (gl_mutex);
3075 if (authn_which == AuthnHeader_WWW) {
3076 current_authn_header = http_authn_get_header_for_uri (http_handle->uri);
3077 } else if (authn_which == AuthnHeader_Proxy) {
3078 current_authn_header = proxy_get_authn_header_for_uri_nolock (http_handle->uri);
3080 g_assert_not_reached ();
3084 if (0 == strcmp_allow_nulls (current_authn_header, prev_authn_header)) {
3085 ret = invoke_callback_basic_authn (http_handle, authn_which, prev_authn_header == NULL);
3090 g_mutex_unlock (gl_mutex);
3092 g_free (current_authn_header);
3099 http_util_get_utime (void)
3102 gettimeofday (&tmp, NULL);
3103 return (utime_t)tmp.tv_usec + ((gint64)tmp.tv_sec) * 1000000LL;
3107 /* BASE64 code ported from neon (http://www.webdav.org/neon) */
3108 static const gchar b64_alphabet[65] = {
3109 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3110 "abcdefghijklmnopqrstuvwxyz"
3114 http_util_base64 (const gchar *text)
3116 /* The tricky thing about this is doing the padding at the end,
3117 * doing the bit manipulation requires a bit of concentration only */
3118 gchar *buffer, *point;
3121 /* Use 'buffer' to store the output. Work out how big it should be...
3122 * This must be a multiple of 4 bytes
3125 inlen = strlen (text);
3126 outlen = (inlen*4)/3;
3127 if ((inlen % 3) > 0) { /* got to pad */
3128 outlen += 4 - (inlen % 3);
3131 buffer = g_malloc (outlen + 1); /* +1 for the \0 */
3133 /* now do the main stage of conversion, 3 bytes at a time,
3134 * leave the trailing bytes (if there are any) for later
3137 for (point=buffer; inlen>=3; inlen-=3, text+=3) {
3138 *(point++) = b64_alphabet[ (*text)>>2 ];
3139 *(point++) = b64_alphabet[ ((*text)<<4 & 0x30) | (*(text+1))>>4 ];
3140 *(point++) = b64_alphabet[ ((*(text+1))<<2 & 0x3c) | (*(text+2))>>6 ];
3141 *(point++) = b64_alphabet[ (*(text+2)) & 0x3f ];
3144 /* Now deal with the trailing bytes */
3146 /* We always have one trailing byte */
3147 *(point++) = b64_alphabet[ (*text)>>2 ];
3148 *(point++) = b64_alphabet[ ( ((*text)<<4 & 0x30) |
3149 (inlen==2?(*(text+1))>>4:0) ) ];
3150 *(point++) = (inlen==1?'=':b64_alphabet[ (*(text+1))<<2 & 0x3c ] );
3154 /* Null-terminate */
3160 static gboolean at_least_one_test_failed = FALSE;
3163 test_failed (const char *format, ...)
3168 va_start (arguments, format);
3169 message = g_strdup_vprintf (format, arguments);
3172 g_message ("test failed: %s", message);
3173 at_least_one_test_failed = TRUE;
3176 #define VERIFY_BOOLEAN_RESULT(function, expected) \
3178 gboolean result = function; \
3179 if (! ((result && expected) || (!result && !expected))) { \
3180 test_failed ("%s: returned '%d' expected '%d'", #function, (int)result, (int)expected); \
3186 http_self_test (void)
3188 g_message ("self-test: http\n");
3190 VERIFY_BOOLEAN_RESULT (proxy_should_for_hostname ("localhost"), FALSE);
3191 VERIFY_BOOLEAN_RESULT (proxy_should_for_hostname ("LocalHost"), FALSE);
3192 VERIFY_BOOLEAN_RESULT (proxy_should_for_hostname ("127.0.0.1"), FALSE);
3193 VERIFY_BOOLEAN_RESULT (proxy_should_for_hostname ("127.127.0.1"), FALSE);
3194 VERIFY_BOOLEAN_RESULT (proxy_should_for_hostname ("www.yahoo.com"), TRUE);
3196 return !at_least_one_test_failed;
3199 gboolean vfs_module_self_test (void);
3202 vfs_module_self_test (void)
3208 ret = http_authn_self_test () && ret;
3210 ret = http_self_test () && ret;