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 static HttpFileHandle *
287 http_file_handle_new (GnomeVFSSocketBuffer *socket_buffer,
290 HttpFileHandle *result;
292 result = g_new0 (HttpFileHandle, 1);
294 result->socket_buffer = socket_buffer;
295 result->uri_string = gnome_vfs_uri_to_string (uri, GNOME_VFS_URI_HIDE_NONE );
297 gnome_vfs_uri_ref(result->uri);
299 result->file_info = defaults_file_info_new();
300 result->file_info->name = gnome_vfs_uri_extract_short_name (uri);
306 http_file_handle_destroy (HttpFileHandle *handle)
308 if (handle == NULL) {
312 gnome_vfs_uri_unref(handle->uri);
313 gnome_vfs_file_info_unref (handle->file_info);
314 g_free (handle->uri_string);
315 if (handle->to_be_written) {
316 g_byte_array_free(handle->to_be_written, TRUE);
319 g_list_foreach (handle->response_headers, (GFunc) g_free, NULL);
320 g_list_free (handle->response_headers);
322 g_list_foreach(handle->files, (GFunc)gnome_vfs_file_info_unref, NULL);
323 g_list_free(handle->files);
328 /* The following comes from GNU Wget with minor changes by myself.
329 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
330 /* Parse the HTTP status line, which is of format:
332 HTTP-Version SP Status-Code SP Reason-Phrase
334 The function returns the status-code, or -1 if the status line is
335 malformed. The pointer to reason-phrase is returned in RP. */
337 parse_status (const char *cline,
338 guint *status_return)
340 /* (the variables must not be named `major' and `minor', because
341 that breaks compilation with SunOS4 cc.) */
344 const guchar *p, *line;
346 line = (const guchar *)cline;
348 /* The standard format of HTTP-Version is: `HTTP/X.Y', where X is
349 major version, and Y is minor version. */
350 if (strncmp (line, "HTTP/", 5) == 0) {
353 /* Calculate major HTTP version. */
355 for (mjr = 0; g_ascii_isdigit (*line); line++)
356 mjr = 10 * mjr + (*line - '0');
357 if (*line != '.' || p == line)
361 /* Calculate minor HTTP version. */
363 for (mnr = 0; g_ascii_isdigit (*line); line++)
364 mnr = 10 * mnr + (*line - '0');
365 if (*line != ' ' || p == line)
367 /* Wget will accept only 1.0 and higher HTTP-versions. The value of
368 minor version can be safely ignored. */
372 } else if (strncmp (line, "ICY ", 4) == 0) {
373 /* FIXME: workaround for broken ShoutCast and IceCast status replies.
374 * They send things like "ICY 200 OK" instead of "HTTP/1.0 200 OK".
375 * Is there a better way to handle this?
384 /* Calculate status code. */
385 if (!(g_ascii_isdigit (*line) && g_ascii_isdigit (line[1]) && g_ascii_isdigit (line[2])))
387 statcode = 100 * (*line - '0') + 10 * (line[1] - '0') + (line[2] - '0');
389 *status_return = statcode;
393 static GnomeVFSResult
394 http_status_to_vfs_result (guint status)
396 if (HTTP_20X (status))
399 /* FIXME bugzilla.gnome.org 41163 */
400 /* mfleming--I've improved the situation slightly, but more
401 * test cases need to be written to ensure that HTTP (esp DAV) does compatibile
402 * things with the normal file method
406 case HTTP_STATUS_PRECONDITION_FAILED:
407 /* This mapping is certainly true for MOVE with Overwrite: F, otherwise not so true */
408 return GNOME_VFS_ERROR_FILE_EXISTS;
409 case HTTP_STATUS_UNAUTHORIZED:
410 case HTTP_STATUS_PROXY_AUTH_REQUIRED:
411 case HTTP_STATUS_FORBIDDEN:
412 /* Note that FORBIDDEN can also be returned on a MOVE in a case which
413 * should be VFS_ERROR_BAD_PARAMETERS
415 return GNOME_VFS_ERROR_ACCESS_DENIED;
416 case HTTP_STATUS_NOT_FOUND:
417 return GNOME_VFS_ERROR_NOT_FOUND;
418 case HTTP_STATUS_METHOD_NOT_ALLOWED:
419 /* Note that METHOD_NOT_ALLOWED is also returned in a PROPFIND in a case which
420 * should be FILE_EXISTS. This is handled in do_make_directory
422 case HTTP_STATUS_BAD_REQUEST:
423 case HTTP_STATUS_NOT_IMPLEMENTED:
424 case HTTP_STATUS_UNSUPPORTED_VERSION:
425 return GNOME_VFS_ERROR_NOT_SUPPORTED;
426 case HTTP_STATUS_CONFLICT:
427 /* _CONFLICT's usually happen when collection paths don't exist */
428 return GNOME_VFS_ERROR_NOT_FOUND;
429 case HTTP_STATUS_LOCKED:
430 /* Maybe we need a separate GNOME_VFS_ERROR_LOCKED? */
431 return GNOME_VFS_ERROR_DIRECTORY_BUSY;
432 case HTTP_STATUS_INSUFFICIENT_STORAGE:
433 return GNOME_VFS_ERROR_NO_SPACE;
435 return GNOME_VFS_ERROR_GENERIC;
439 /* Header parsing routines. */
442 header_value_to_number (const char *header_value,
450 for (result = 0; g_ascii_isdigit (*p); p++)
451 result = 10 * result + (*p - '0');
461 set_content_length (HttpFileHandle *handle,
467 result = header_value_to_number (value, &size);
471 DEBUG_HTTP (("Expected size is %lu.", size));
472 handle->file_info->size = size;
473 handle->file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_SIZE;
478 strip_semicolon (const char *value)
482 p = strchr (value, ';');
485 return g_strndup (value, p - value);
488 return g_strdup (value);
493 set_content_type (HttpFileHandle *handle,
496 g_free (handle->file_info->mime_type);
498 handle->file_info->mime_type = strip_semicolon (value);
499 handle->file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE;
505 set_last_modified (HttpFileHandle *handle,
510 if (! gnome_vfs_atotm (value, &time))
513 handle->file_info->mtime = time;
514 handle->file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_MTIME;
519 set_access_time (HttpFileHandle *handle,
524 if (! gnome_vfs_atotm (value, &time))
527 handle->file_info->atime = time;
528 handle->file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_ATIME;
534 gboolean (* set_func) (HttpFileHandle *handle, const char *value);
536 typedef struct _Header Header;
538 static Header headers[] = {
539 { "Content-Length", set_content_length },
540 { "Content-Type", set_content_type },
541 { "Last-Modified", set_last_modified },
542 { "Date", set_access_time },
547 check_header (const char *header,
552 for (p = header, q = name; *p != '\0' && *q != '\0'; p++, q++) {
553 if (g_ascii_tolower (*p) != g_ascii_tolower (*q))
557 if (*q != '\0' || *p != ':')
561 while (*p == ' ' || *p == '\t')
568 parse_header (HttpFileHandle *handle,
573 for (i = 0; headers[i].name != NULL; i++) {
576 value = check_header (header, headers[i].name);
578 return (* headers[i].set_func) (handle, value);
581 /* Simply ignore headers we don't know. */
585 /* Header/status reading. */
587 static GnomeVFSResult
588 get_header (GnomeVFSSocketBuffer *socket_buffer,
591 GnomeVFSResult result;
592 GnomeVFSFileSize bytes_read;
595 ANALYZE_HTTP ("==> +get_header");
597 g_string_truncate (s, 0);
603 /* ANALYZE_HTTP ("==> +get_header read"); */
604 result = gnome_vfs_socket_buffer_read (socket_buffer, &c, 1,
606 /* ANALYZE_HTTP ("==> -get_header read"); */
608 if (result != GNOME_VFS_OK) {
611 if (bytes_read == 0) {
612 return GNOME_VFS_ERROR_EOF;
616 /* Handle continuation lines. */
617 if (count != 0 && (count != 1 || s->str[0] != '\r')) {
620 result = gnome_vfs_socket_buffer_peekc (
621 socket_buffer, &next);
622 if (result != GNOME_VFS_OK) {
626 if (next == '\t' || next == ' ') {
628 && s->str[count - 1] == '\r')
629 s->str[count - 1] = '\0';
634 if (count > 0 && s->str[count - 1] == '\r')
635 s->str[count - 1] = '\0';
638 g_string_append_c (s, c);
645 ANALYZE_HTTP ("==> -get_header");
650 /* rename this function? */
651 static GnomeVFSResult
652 create_handle (GnomeVFSURI *uri,
653 GnomeVFSSocketBuffer *socket_buffer,
654 GnomeVFSContext *context,
655 /* OUT */ HttpFileHandle **p_handle)
657 GString *header_string;
658 GnomeVFSResult result;
661 g_return_val_if_fail (p_handle != NULL, GNOME_VFS_ERROR_INTERNAL);
663 *p_handle = http_file_handle_new (socket_buffer, uri);
665 header_string = g_string_new (NULL);
667 ANALYZE_HTTP ("==> +create_handle");
669 /* This is the status report string, which is the first header. */
670 result = get_header (socket_buffer, header_string);
671 if (result != GNOME_VFS_OK) {
675 if (!parse_status (header_string->str, &server_status)) {
676 /* An unparsable status line is fatal */
677 result = GNOME_VFS_ERROR_GENERIC;
681 (*p_handle)->server_status = server_status;
683 ANALYZE_HTTP ("==> +create_handle: fetching headers");
685 /* Header fetching loop. */
687 result = get_header (socket_buffer, header_string);
688 if (result != GNOME_VFS_OK) {
692 /* Empty header ends header section. */
693 if (header_string->str[0] == '\0') {
697 (*p_handle)->response_headers = g_list_prepend ((*p_handle)->response_headers,
698 g_strdup (header_string->str));
700 /* We don't really care if we successfully parse the
701 * header or not. It might be nice to tell someone we
702 * found a header we can't parse, but it's not clear
703 * who would be interested or how we tell them. In the
704 * past we would return NOT_FOUND if any header could
705 * not be parsed, but that seems wrong.
707 parse_header (*p_handle, header_string->str);
710 invoke_callback_headers_received (*p_handle);
712 ANALYZE_HTTP ("==> -create_handle: fetching headers");
714 if (result != GNOME_VFS_OK) {
718 if (! HTTP_20X (server_status) && !HTTP_REDIRECTED(server_status)) {
719 result = http_status_to_vfs_result (server_status);
723 result = GNOME_VFS_OK;
725 g_string_free (header_string, TRUE);
727 ANALYZE_HTTP ("==> -create_handle");
732 * Here's how the gconf gnome-vfs HTTP proxy variables
733 * are intended to be used
735 * /system/http_proxy/use_http_proxy
737 * If set to TRUE, the client should use an HTTP proxy to connect to all
738 * servers (except those specified in the ignore_hosts key -- see below).
739 * The proxy is specified in other gconf variables below.
741 * /system/http_proxy/host
743 * The hostname of the HTTP proxy this client should use. If
744 * use-http-proxy is TRUE, this should be set. If it is not set, the
745 * application should behave as if use-http-proxy is was set to FALSE.
747 * /system/http_proxy/port
749 * The port number on the HTTP proxy host that the client should connect to
750 * If use_http_proxy and host are set but this is not set, the application
751 * should use a default port value of 8080
753 * /system/http_proxy/authentication-user
755 * Username to pass to an authenticating HTTP proxy.
757 * /system/http_proxy/authentication_password
759 * Password to pass to an authenticating HTTP proxy.
761 * /system/http_proxy/use-authentication
763 * TRUE if the client should pass http-proxy-authorization-user and
764 * http-proxy-authorization-password an HTTP proxy
766 * /system/http_proxy/ignore_hosts
767 * Type: list of strings
768 * A list of hosts (hostnames, wildcard domains, IP addresses, and CIDR
769 * network addresses) that should be accessed directly.
773 construct_gl_http_proxy (gboolean use_proxy)
775 g_free (gl_http_proxy);
776 gl_http_proxy = NULL;
778 g_slist_foreach (gl_ignore_hosts, (GFunc) g_free, NULL);
779 g_slist_free (gl_ignore_hosts);
780 gl_ignore_hosts = NULL;
781 g_slist_foreach (gl_ignore_addrs, (GFunc) g_free, NULL);
782 g_slist_free (gl_ignore_addrs);
783 gl_ignore_addrs = NULL;
790 proxy_host = gconf_client_get_string (gl_client, KEY_GCONF_HTTP_PROXY_HOST, NULL);
791 proxy_port = gconf_client_get_int (gl_client, KEY_GCONF_HTTP_PROXY_PORT, NULL);
794 if (0 != proxy_port && 0xffff >= (unsigned) proxy_port) {
795 gl_http_proxy = g_strdup_printf ("%s:%u", proxy_host, (unsigned)proxy_port);
797 gl_http_proxy = g_strdup_printf ("%s:%u", proxy_host, (unsigned)DEFAULT_HTTP_PROXY_PORT);
799 DEBUG_HTTP (("New HTTP proxy: '%s'", gl_http_proxy));
801 DEBUG_HTTP (("HTTP proxy unset"));
807 ignore = gconf_client_get_list (gl_client, KEY_GCONF_HTTP_PROXY_IGNORE_HOSTS, GCONF_VALUE_STRING, NULL);
808 g_slist_foreach (ignore, (GFunc) parse_ignore_host, NULL);
809 g_slist_foreach (ignore, (GFunc) g_free, NULL);
810 g_slist_free (ignore);
816 parse_ignore_host (gpointer data, gpointer user_data)
818 gchar *hostname, *input, *netmask;
819 gboolean ip_addr = FALSE, has_error = FALSE;
820 struct in_addr host, mask;
822 struct in6_addr host6, mask6;
827 input = (gchar*) data;
828 elt = g_new0 (ProxyHostAddr, 1);
829 if ((netmask = strchr (input, '/')) != NULL) {
830 hostname = g_strndup (input, netmask - input);
834 hostname = g_ascii_strdown (input, -1);
836 if (inet_pton (AF_INET, hostname, &host) > 0) {
838 elt->type = PROXY_IPv4;
839 elt->addr.s_addr = host.s_addr;
842 gint width = strtol (netmask, &endptr, 10);
844 if (*endptr != '\0' || width < 0 || width > 32) {
847 elt->mask.s_addr = htonl(~0 << width);
848 elt->addr.s_addr &= mask.s_addr;
851 elt->mask.s_addr = 0xffffffff;
855 else if (have_ipv6 () && inet_pton (AF_INET6, hostname, &host6) > 0) {
857 elt->type = PROXY_IPv6;
858 for (i = 0; i < 16; ++i) {
859 elt->addr6.s6_addr[i] = host6.s6_addr[i];
863 gint width = strtol (netmask, &endptr, 10);
865 if (*endptr != '\0' || width < 0 || width > 128) {
868 for (i = 0; i < 16; ++i) {
869 elt->mask6.s6_addr[i] = 0;
871 for (i=0; i < width/8; i++) {
872 elt->mask6.s6_addr[i] = 0xff;
874 elt->mask6.s6_addr[i] = (0xff << (8 - width % 8)) & 0xff;
875 ipv6_network_addr (&elt->addr6, &mask6, &elt->addr6);
878 for (i = 0; i < 16; ++i) {
879 elt->mask6.s6_addr[i] = 0xff;
887 gchar *dst = g_new0 (gchar, INET_ADDRSTRLEN);
889 gl_ignore_addrs = g_slist_append (gl_ignore_addrs, elt);
890 DEBUG_HTTP (("Host %s/%s does not go through proxy.",
892 inet_ntop(AF_INET, &elt->mask, dst, INET_ADDRSTRLEN)));
897 /* It is a hostname. */
898 gl_ignore_hosts = g_slist_append (gl_ignore_hosts, hostname);
899 DEBUG_HTTP (("Host %s does not go through proxy.", hostname));
904 set_proxy_auth (gboolean use_proxy_auth)
909 auth_user = gconf_client_get_string (gl_client, KEY_GCONF_HTTP_AUTH_USER, NULL);
910 auth_pw = gconf_client_get_string (gl_client, KEY_GCONF_HTTP_AUTH_PW, NULL);
912 if (use_proxy_auth) {
913 proxy_set_authn (auth_user, auth_pw);
914 DEBUG_HTTP (("New HTTP proxy auth user: '%s'", auth_user));
916 proxy_unset_authn ();
917 DEBUG_HTTP (("HTTP proxy auth unset"));
925 * sig_gconf_value_changed
926 * GGconf notify function for when HTTP proxy GConf key has changed.
929 notify_gconf_value_changed (GConfClient *client,
936 key = gconf_entry_get_key (entry);
938 if (strcmp (key, KEY_GCONF_USE_HTTP_PROXY) == 0
939 || strcmp (key, KEY_GCONF_HTTP_PROXY_IGNORE_HOSTS) == 0
940 || strcmp (key, KEY_GCONF_HTTP_PROXY_HOST) == 0
941 || strcmp (key, KEY_GCONF_HTTP_PROXY_PORT) == 0) {
942 gboolean use_proxy_value;
944 g_mutex_lock (gl_mutex);
946 /* Check and see if we are using the proxy */
947 use_proxy_value = gconf_client_get_bool (gl_client, KEY_GCONF_USE_HTTP_PROXY, NULL);
948 construct_gl_http_proxy (use_proxy_value);
950 g_mutex_unlock (gl_mutex);
951 } else if (strcmp (key, KEY_GCONF_HTTP_AUTH_USER) == 0
952 || strcmp (key, KEY_GCONF_HTTP_AUTH_PW) == 0
953 || strcmp (key, KEY_GCONF_HTTP_USE_AUTH) == 0) {
954 gboolean use_proxy_auth;
956 g_mutex_lock (gl_mutex);
958 use_proxy_auth = gconf_client_get_bool (gl_client, KEY_GCONF_HTTP_USE_AUTH, NULL);
959 set_proxy_auth (use_proxy_auth);
961 g_mutex_unlock (gl_mutex);
966 * host_port_from_string
967 * splits a <host>:<port> formatted string into its separate components
970 host_port_from_string (const char *http_proxy,
976 port_part = strchr (http_proxy, ':');
978 if (port_part && '\0' != ++port_part && p_proxy_port) {
979 *p_proxy_port = (guint) strtoul (port_part, NULL, 10);
980 } else if (p_proxy_port) {
981 *p_proxy_port = DEFAULT_HTTP_PROXY_PORT;
985 if ( port_part != http_proxy ) {
986 *p_proxy_host = g_strndup (http_proxy, port_part - http_proxy - 1);
995 /* FIXME: should be done using AC_REPLACE_FUNCS */
996 #ifndef HAVE_INET_PTON
998 inet_pton(int af, const char *hostname, void *pton)
1001 if (!inet_aton(hostname, &in))
1003 memcpy(pton, &in, sizeof(in));
1010 ipv6_network_addr (const struct in6_addr *addr, const struct in6_addr *mask, struct in6_addr *res)
1014 for (i = 0; i < 16; ++i) {
1015 res->s6_addr[i] = addr->s6_addr[i] & mask->s6_addr[i];
1021 proxy_should_for_hostname (const char *hostname)
1024 struct in6_addr in6, net6;
1028 ProxyHostAddr *addr;
1032 if (inet_pton (AF_INET, hostname, &in) > 0) {
1033 for (elt = gl_ignore_addrs; elt; elt = g_slist_next (elt)) {
1034 addr = (ProxyHostAddr*) (elt->data);
1035 if (addr->type == PROXY_IPv4
1036 && (in.s_addr & addr->mask.s_addr) == addr->addr.s_addr) {
1037 DEBUG_HTTP (("Host %s using direct connection.", hostname));
1043 else if (have_ipv6 () && inet_pton (AF_INET6, hostname, &in6)) {
1044 for (elt = gl_ignore_addrs; elt; elt = g_slist_next (elt)) {
1045 addr = (ProxyHostAddr*) (elt->data);
1046 ipv6_network_addr (&in6, &addr->mask6, &net6);
1047 if (addr->type == PROXY_IPv6
1048 && IN6_ARE_ADDR_EQUAL (&net6, &addr->addr6)) {
1049 DEBUG_HTTP (("Host %s using direct connection.", hostname));
1052 /* Handle IPv6-wrapped IPv4 addresses. */
1053 else if (addr->type == PROXY_IPv4
1054 && IN6_IS_ADDR_V4MAPPED (&net6)) {
1057 v4addr = net6.s6_addr[12] << 24 | net6.s6_addr[13] << 16 | net6.s6_addr[14] << 8 | net6.s6_addr[15];
1058 if ((v4addr & addr->mask.s_addr) != addr->addr.s_addr) {
1059 DEBUG_HTTP (("Host %s using direct connection.", hostname));
1066 /* All hostnames (foo.bar.com) -- independent of IPv4 or IPv6 */
1068 /* If there are IPv6 addresses in the ignore_hosts list but we do not
1069 * have IPv6 available at runtime, then those addresses will also fall
1070 * through to here (and harmlessly fail to match). */
1072 gchar *hn = g_ascii_strdown (hostname, -1);
1074 for (elt = gl_ignore_hosts; elt; elt = g_slist_next (elt)) {
1075 if (*(gchar*) (elt->data) == '*' ) {
1076 if (g_str_has_suffix (hn,
1077 (gchar*) (elt->data) + 1)) {
1078 DEBUG_HTTP (("Host %s using direct connection.", hn));
1083 else if (strcmp (hn, elt->data) == 0) {
1084 DEBUG_HTTP (("Host %s using direct connection.", hn));
1095 proxy_get_authn_header_for_uri_nolock (GnomeVFSURI * uri)
1101 /* FIXME this needs to be atomic */
1102 if (gl_http_proxy_auth != NULL) {
1103 ret = g_strdup_printf ("Proxy-Authorization: Basic %s\r\n", gl_http_proxy_auth);
1110 proxy_get_authn_header_for_uri (GnomeVFSURI * uri)
1114 g_mutex_lock (gl_mutex);
1116 ret = proxy_get_authn_header_for_uri_nolock (uri);
1118 g_mutex_unlock (gl_mutex);
1125 * Retrives an appropriate HTTP proxy for a given toplevel uri
1126 * Currently, only a single HTTP proxy is implemented (there's no way for
1127 * specifying non-proxy domain names's). Returns FALSE if the connect should
1128 * take place directly
1132 GnomeVFSToplevelURI * toplevel_uri,
1133 gchar **p_proxy_host, /* Callee must free */
1134 guint *p_proxy_port) /* Callee must free */
1138 ret = proxy_should_for_hostname (toplevel_uri->host_name);
1140 g_mutex_lock (gl_mutex);
1142 if (ret && gl_http_proxy != NULL) {
1143 ret = host_port_from_string (gl_http_proxy, p_proxy_host, p_proxy_port);
1145 p_proxy_host = NULL;
1146 p_proxy_port = NULL;
1150 g_mutex_unlock (gl_mutex);
1156 proxy_set_authn (const char *username, const char *password)
1160 g_free (gl_http_proxy_auth);
1161 gl_http_proxy_auth = NULL;
1163 credentials = g_strdup_printf ("%s:%s",
1164 username == NULL ? "" : username,
1165 password == NULL ? "" : password);
1167 gl_http_proxy_auth = http_util_base64 (credentials);
1169 g_free (credentials);
1173 proxy_unset_authn (void)
1175 g_free (gl_http_proxy_auth);
1176 gl_http_proxy_auth = NULL;
1180 static GnomeVFSResult
1181 https_proxy (GnomeVFSSocket **socket_return,
1187 /* use CONNECT to do https proxying. It goes something like this:
1188 * >CONNECT server:port HTTP/1.0
1190 * <HTTP/1.0 200 Connection-established
1191 * <Proxy-agent: Apache/1.3.19 (Unix) Debian/GNU
1193 * and then we've got an open connection.
1195 * So we sent "CONNECT server:port HTTP/1.0\r\n\r\n"
1196 * Check the HTTP status.
1197 * Wait for "\r\n\r\n"
1198 * Start doing the SSL dance.
1201 GnomeVFSResult result;
1202 GnomeVFSInetConnection *http_connection;
1203 GnomeVFSSocket *http_socket;
1204 GnomeVFSSocket *https_socket;
1207 GnomeVFSFileSize bytes;
1211 result = gnome_vfs_inet_connection_create (&http_connection,
1212 proxy_host, proxy_port, NULL);
1214 if (result != GNOME_VFS_OK) {
1218 fd = gnome_vfs_inet_connection_get_fd (http_connection);
1220 http_socket = gnome_vfs_inet_connection_to_socket (http_connection);
1222 buffer = g_strdup_printf ("CONNECT %s:%d HTTP/1.0\r\n\r\n",
1223 server_host, server_port);
1224 result = gnome_vfs_socket_write (http_socket, buffer, strlen(buffer),
1228 if (result != GNOME_VFS_OK) {
1229 gnome_vfs_socket_close (http_socket);
1233 buffer = proxy_get_authn_header_for_uri (NULL); /* FIXME need uri */
1234 if (buffer != NULL) {
1235 result = gnome_vfs_socket_write (http_socket, buffer,
1236 strlen(buffer), &bytes);
1240 if (result != GNOME_VFS_OK) {
1241 gnome_vfs_socket_close (http_socket);
1246 buffer = g_malloc0 (bytes);
1248 result = gnome_vfs_socket_read (http_socket, buffer, bytes-1, &bytes);
1250 if (result != GNOME_VFS_OK) {
1251 gnome_vfs_socket_close (http_socket);
1256 if (!parse_status (buffer, &status_code)) {
1257 gnome_vfs_socket_close (http_socket);
1259 return GNOME_VFS_ERROR_PROTOCOL_ERROR;
1262 result = http_status_to_vfs_result (status_code);
1264 if (result != GNOME_VFS_OK) {
1265 gnome_vfs_socket_close (http_socket);
1270 /* okay - at this point we've read some stuff from the socket.. */
1271 /* FIXME: for now we'll assume thats all the headers and nothing but. */
1275 result = gnome_vfs_ssl_create_from_fd (&ssl, fd);
1277 if (result != GNOME_VFS_OK) {
1278 gnome_vfs_socket_close (http_socket);
1282 https_socket = gnome_vfs_ssl_to_socket (ssl);
1284 *socket_return = https_socket;
1286 return GNOME_VFS_OK;
1291 static GnomeVFSResult
1293 GnomeVFSToplevelURI *toplevel_uri,
1294 /* OUT */ GnomeVFSSocketBuffer **p_socket_buffer,
1295 /* OUT */ gboolean * p_proxy_connect)
1300 GnomeVFSResult result;
1301 GnomeVFSCancellation * cancellation;
1302 GnomeVFSInetConnection *connection;
1304 GnomeVFSSocket *socket;
1305 gboolean https = FALSE;
1307 cancellation = gnome_vfs_context_get_cancellation (
1308 gnome_vfs_context_peek_current ());
1310 g_return_val_if_fail (p_socket_buffer != NULL, GNOME_VFS_ERROR_INTERNAL);
1311 g_return_val_if_fail (p_proxy_connect != NULL, GNOME_VFS_ERROR_INTERNAL);
1312 g_return_val_if_fail (toplevel_uri != NULL, GNOME_VFS_ERROR_INTERNAL);
1314 if (!g_ascii_strcasecmp (gnome_vfs_uri_get_scheme (&toplevel_uri->uri),
1316 if (!gnome_vfs_ssl_enabled ()) {
1317 return GNOME_VFS_ERROR_NOT_SUPPORTED;
1322 if (toplevel_uri->host_port == 0) {
1324 host_port = DEFAULT_HTTPS_PORT;
1326 host_port = DEFAULT_HTTP_PORT;
1329 host_port = toplevel_uri->host_port;
1332 ANALYZE_HTTP ("==> +Making connection");
1334 if (toplevel_uri->host_name == NULL) {
1335 result = GNOME_VFS_ERROR_INVALID_URI;
1339 if (proxy_for_uri (toplevel_uri, &proxy_host, &proxy_port)) {
1341 *p_proxy_connect = FALSE;
1343 result = https_proxy (&socket, proxy_host, proxy_port,
1344 toplevel_uri->host_name, host_port);
1346 g_free (proxy_host);
1349 if (result != GNOME_VFS_OK) {
1354 *p_proxy_connect = TRUE;
1356 result = gnome_vfs_inet_connection_create (&connection,
1360 if (result != GNOME_VFS_OK) {
1363 socket = gnome_vfs_inet_connection_to_socket
1366 g_free (proxy_host);
1370 *p_proxy_connect = FALSE;
1373 result = gnome_vfs_ssl_create (&ssl,
1374 toplevel_uri->host_name, host_port);
1376 if (result != GNOME_VFS_OK) {
1379 socket = gnome_vfs_ssl_to_socket (ssl);
1381 result = gnome_vfs_inet_connection_create (&connection,
1382 toplevel_uri->host_name,
1385 if (result != GNOME_VFS_OK) {
1388 socket = gnome_vfs_inet_connection_to_socket
1393 *p_socket_buffer = gnome_vfs_socket_buffer_new (socket);
1395 if (*p_socket_buffer == NULL) {
1396 gnome_vfs_socket_close (socket);
1397 return GNOME_VFS_ERROR_INTERNAL;
1400 ANALYZE_HTTP ("==> -Making connection");
1407 build_request (const char * method, GnomeVFSToplevelURI * toplevel_uri, gboolean proxy_connect)
1409 gchar *uri_string = NULL;
1414 uri = (GnomeVFSURI *)toplevel_uri;
1416 if (proxy_connect) {
1417 uri_string = gnome_vfs_uri_to_string (uri,
1418 GNOME_VFS_URI_HIDE_USER_NAME
1419 | GNOME_VFS_URI_HIDE_PASSWORD);
1422 uri_string = gnome_vfs_uri_to_string (uri,
1423 GNOME_VFS_URI_HIDE_USER_NAME
1424 | GNOME_VFS_URI_HIDE_PASSWORD
1425 | GNOME_VFS_URI_HIDE_HOST_NAME
1426 | GNOME_VFS_URI_HIDE_HOST_PORT
1427 | GNOME_VFS_URI_HIDE_TOPLEVEL_METHOD);
1431 request = g_string_new ("");
1433 g_string_append_printf (request, "%s %s%s HTTP/1.0\r\n", method, uri_string,
1434 gnome_vfs_uri_get_path (uri)[0] == '\0' ? "/" : "" );
1436 DEBUG_HTTP (("-->Making request '%s %s'", method, uri_string));
1438 g_free (uri_string);
1441 /* `Host:' header. */
1442 if(toplevel_uri->host_port && toplevel_uri->host_port != 0) {
1443 g_string_append_printf (request, "Host: %s:%d\r\n",
1444 toplevel_uri->host_name, toplevel_uri->host_port);
1446 g_string_append_printf (request, "Host: %s:80\r\n",
1447 toplevel_uri->host_name);
1450 /* `Accept:' header. */
1451 g_string_append (request, "Accept: */*\r\n");
1453 /* `User-Agent:' header. */
1454 user_agent = getenv (CUSTOM_USER_AGENT_VARIABLE);
1456 if(user_agent == NULL) {
1457 user_agent = USER_AGENT_STRING;
1460 g_string_append_printf (request, "User-Agent: %s\r\n", user_agent);
1465 static GnomeVFSResult
1466 xmit_request (GnomeVFSSocketBuffer *socket_buffer,
1470 GnomeVFSResult result;
1471 GnomeVFSFileSize bytes_written;
1473 ANALYZE_HTTP ("==> Writing request and header");
1475 /* Transmit the request headers. */
1476 result = gnome_vfs_socket_buffer_write (socket_buffer, request->str,
1477 request->len, &bytes_written);
1479 if (result != GNOME_VFS_OK) {
1483 /* Transmit the body */
1484 if(data && data->data) {
1485 ANALYZE_HTTP ("==> Writing data");
1487 result = gnome_vfs_socket_buffer_write (socket_buffer,
1488 data->data, data->len, &bytes_written);
1491 if (result != GNOME_VFS_OK) {
1495 result = gnome_vfs_socket_buffer_flush (socket_buffer);
1501 static GnomeVFSResult
1502 make_request (HttpFileHandle **handle_return,
1504 const gchar *method,
1506 gchar *extra_headers,
1507 GnomeVFSContext *context)
1509 GnomeVFSSocketBuffer *socket_buffer;
1510 GnomeVFSResult result;
1511 GnomeVFSToplevelURI *toplevel_uri;
1513 gboolean proxy_connect;
1514 char *authn_header_request;
1515 char *authn_header_proxy;
1517 g_return_val_if_fail (handle_return != NULL, GNOME_VFS_ERROR_INTERNAL);
1518 *handle_return = NULL;
1520 ANALYZE_HTTP ("==> +make_request");
1523 proxy_connect = FALSE;
1524 authn_header_request = NULL;
1525 authn_header_proxy = NULL;
1527 toplevel_uri = (GnomeVFSToplevelURI *) uri;
1532 g_free (authn_header_request);
1533 g_free (authn_header_proxy);
1535 socket_buffer = NULL;
1536 result = connect_to_uri (toplevel_uri, &socket_buffer,
1539 if (result != GNOME_VFS_OK) {
1543 request = build_request (method, toplevel_uri, proxy_connect);
1545 authn_header_request = http_authn_get_header_for_uri (uri);
1547 if (authn_header_request != NULL) {
1548 g_string_append (request, authn_header_request);
1551 if (proxy_connect) {
1552 authn_header_proxy = proxy_get_authn_header_for_uri (uri);
1554 if (authn_header_proxy != NULL) {
1555 g_string_append (request, authn_header_proxy);
1559 /* `Content-Length' header. */
1561 g_string_append_printf (request, "Content-Length: %d\r\n", data->len);
1564 /* Extra headers. */
1565 if (extra_headers != NULL) {
1566 g_string_append (request, extra_headers);
1569 /* Extra headers from user */
1572 if (invoke_callback_send_additional_headers (uri, &list)) {
1575 for (i = list; i; i = i->next) {
1576 g_string_append (request, i->data);
1584 /* Empty line ends header section. */
1585 g_string_append (request, "\r\n");
1587 result = xmit_request (socket_buffer, request, data);
1588 g_string_free (request, TRUE);
1591 if (result != GNOME_VFS_OK) {
1595 /* Read the headers and create our internal HTTP file handle. */
1596 result = create_handle (uri, socket_buffer, context, handle_return);
1598 if (result == GNOME_VFS_OK) {
1599 socket_buffer = NULL;
1602 if ((*handle_return)->server_status == HTTP_STATUS_UNAUTHORIZED) {
1603 if (! check_authn_retry_request (*handle_return, AuthnHeader_WWW, authn_header_request)) {
1606 } else if ((*handle_return)->server_status == HTTP_STATUS_PROXY_AUTH_REQUIRED) {
1607 if (! check_authn_retry_request (*handle_return, AuthnHeader_WWW, authn_header_proxy)) {
1613 http_file_handle_destroy (*handle_return);
1614 *handle_return = NULL;
1617 g_free (authn_header_request);
1618 g_free (authn_header_proxy);
1620 if (result != GNOME_VFS_OK && *handle_return != NULL) {
1621 http_file_handle_destroy (*handle_return);
1622 *handle_return = NULL;
1625 if (request != NULL) {
1626 g_string_free (request, TRUE);
1629 if (socket_buffer != NULL) {
1630 gnome_vfs_socket_buffer_destroy (socket_buffer, TRUE);
1633 ANALYZE_HTTP ("==> -make_request");
1638 http_handle_close (HttpFileHandle *handle,
1639 GnomeVFSContext *context)
1641 ANALYZE_HTTP ("==> +http_handle_close");
1643 if (handle != NULL) {
1644 if (handle->socket_buffer) {
1645 gnome_vfs_socket_buffer_flush (handle->socket_buffer);
1646 gnome_vfs_socket_buffer_destroy (handle->socket_buffer,
1648 handle->socket_buffer = NULL;
1651 http_file_handle_destroy (handle);
1654 ANALYZE_HTTP ("==> -http_handle_close");
1657 static GnomeVFSResult
1658 do_open (GnomeVFSMethod *method,
1659 GnomeVFSMethodHandle **method_handle,
1661 GnomeVFSOpenMode mode,
1662 GnomeVFSContext *context)
1664 HttpFileHandle *handle;
1665 GnomeVFSResult result = GNOME_VFS_OK;
1667 g_return_val_if_fail (uri->parent == NULL, GNOME_VFS_ERROR_INVALID_URI);
1668 g_return_val_if_fail (!(mode & GNOME_VFS_OPEN_READ &&
1669 mode & GNOME_VFS_OPEN_WRITE),
1670 GNOME_VFS_ERROR_INVALID_OPEN_MODE);
1672 ANALYZE_HTTP ("==> +do_open");
1673 DEBUG_HTTP (("+Open URI: '%s' mode:'%c'", gnome_vfs_uri_to_string(uri, 0),
1674 mode & GNOME_VFS_OPEN_READ ? 'R' : 'W'));
1676 if (mode & GNOME_VFS_OPEN_READ) {
1677 result = make_request (&handle, uri, "GET", NULL, NULL,
1680 handle = http_file_handle_new(NULL, uri); /* shrug */
1682 if (result == GNOME_VFS_OK) {
1683 *method_handle = (GnomeVFSMethodHandle *) handle;
1685 *method_handle = NULL;
1688 DEBUG_HTTP (("-Open (%d) handle:0x%08x", result, (unsigned int)handle));
1689 ANALYZE_HTTP ("==> -do_open");
1694 static GnomeVFSResult
1695 do_create (GnomeVFSMethod *method,
1696 GnomeVFSMethodHandle **method_handle,
1698 GnomeVFSOpenMode mode,
1701 GnomeVFSContext *context)
1703 /* try to write a zero length file - this appears to be the
1704 * only reliable way of testing if a put will succeed.
1705 * Xythos can apparently tell us if we have write permission by
1706 * playing with LOCK, but mod_dav cannot. */
1707 HttpFileHandle *handle;
1708 GnomeVFSResult result;
1709 GByteArray *bytes = g_byte_array_new();
1711 ANALYZE_HTTP ("==> +do_create");
1712 DEBUG_HTTP (("+Create URI: '%s'", gnome_vfs_uri_get_path (uri)));
1714 http_cache_invalidate_uri_parent (uri);
1716 /* Don't ignore exclusive; it should check first whether
1717 the file exists, since the http protocol default is to
1718 overwrite by default */
1719 /* FIXME we've stopped using HEAD -- we should use GET instead */
1720 /* FIXME we should check the cache here */
1723 ANALYZE_HTTP ("==> Checking to see if file exists");
1725 result = make_request (&handle, uri, "HEAD", NULL, NULL,
1727 http_handle_close (handle, context);
1729 if (result != GNOME_VFS_OK &&
1730 result != GNOME_VFS_ERROR_NOT_FOUND) {
1733 if (result == GNOME_VFS_OK) {
1734 return GNOME_VFS_ERROR_FILE_EXISTS;
1738 ANALYZE_HTTP ("==> Creating initial file");
1740 result = make_request (&handle, uri, "PUT", bytes, NULL, context);
1741 http_handle_close(handle, context);
1743 if (result != GNOME_VFS_OK) {
1744 /* the PUT failed */
1746 /* FIXME bugzilla.gnome.org 45131
1747 * If you PUT a file with an invalid name to Xythos, it
1748 * returns a 403 Forbidden, which is different from the behaviour
1749 * in MKCOL or MOVE. Unfortunately, it is not possible to discern whether
1750 * that 403 Forbidden is being returned because of invalid characters in the name
1751 * or because of permissions problems
1754 if (result == GNOME_VFS_ERROR_NOT_FOUND) {
1755 result = resolve_409 (method, uri, context);
1762 g_byte_array_free (bytes, TRUE);
1764 /* FIXME bugzilla.gnome.org 41159: do we need to do something more intelligent here? */
1765 result = do_open (method, method_handle, uri, GNOME_VFS_OPEN_WRITE, context);
1767 DEBUG_HTTP (("-Create (%d) handle:0x%08x", result, (unsigned int)handle));
1768 ANALYZE_HTTP ("==> -do_create");
1773 static GnomeVFSResult
1774 do_close (GnomeVFSMethod *method,
1775 GnomeVFSMethodHandle *method_handle,
1776 GnomeVFSContext *context)
1778 HttpFileHandle *old_handle;
1779 HttpFileHandle *new_handle;
1780 GnomeVFSResult result;
1782 ANALYZE_HTTP ("==> +do_close");
1783 DEBUG_HTTP (("+Close handle:0x%08x", (unsigned int)method_handle));
1785 old_handle = (HttpFileHandle *) method_handle;
1787 /* if the handle was opened in write mode then:
1788 * 1) there won't be a connection open, and
1789 * 2) there will be data to_be_written...
1791 if (old_handle->to_be_written != NULL) {
1792 GnomeVFSURI *uri = old_handle->uri;
1793 GByteArray *bytes = old_handle->to_be_written;
1794 GnomeVFSMimeSniffBuffer *sniff_buffer;
1795 char *extraheader = NULL;
1796 const char *mime_type = NULL;
1799 gnome_vfs_mime_sniff_buffer_new_from_existing_data (bytes->data,
1802 if (sniff_buffer != NULL) {
1804 gnome_vfs_get_mime_type_for_buffer (
1806 if (mime_type != NULL) {
1807 extraheader = g_strdup_printf(
1808 "Content-type: %s\r\n",
1811 gnome_vfs_mime_sniff_buffer_free (sniff_buffer);
1815 http_cache_invalidate_uri (uri);
1817 ANALYZE_HTTP ("==> doing PUT");
1818 result = make_request (&new_handle, uri, "PUT", bytes,
1819 extraheader, context);
1820 g_free (extraheader);
1821 http_handle_close (new_handle, context);
1823 result = GNOME_VFS_OK;
1826 http_handle_close (old_handle, context);
1828 DEBUG_HTTP (("-Close (%d)", result));
1829 ANALYZE_HTTP ("==> -do_close");
1834 static GnomeVFSResult
1835 do_write (GnomeVFSMethod *method,
1836 GnomeVFSMethodHandle *method_handle,
1837 gconstpointer buffer,
1838 GnomeVFSFileSize num_bytes,
1839 GnomeVFSFileSize *bytes_read,
1840 GnomeVFSContext *context)
1842 HttpFileHandle *handle;
1844 DEBUG_HTTP (("+Write handle:0x%08x", (unsigned int)method_handle));
1846 handle = (HttpFileHandle *) method_handle;
1848 if(handle->to_be_written == NULL) {
1849 handle->to_be_written = g_byte_array_new();
1851 handle->to_be_written = g_byte_array_append(handle->to_be_written, buffer, num_bytes);
1852 *bytes_read = num_bytes;
1854 DEBUG_HTTP (("-Write (0)"));
1856 return GNOME_VFS_OK;
1860 static GnomeVFSResult
1861 do_read (GnomeVFSMethod *method,
1862 GnomeVFSMethodHandle *method_handle,
1864 GnomeVFSFileSize num_bytes,
1865 GnomeVFSFileSize *bytes_read,
1866 GnomeVFSContext *context)
1868 HttpFileHandle *handle;
1869 GnomeVFSResult result;
1871 ANALYZE_HTTP ("==> +do_read");
1872 DEBUG_HTTP (("+Read handle=0x%08x", (unsigned int) method_handle));
1874 handle = (HttpFileHandle *) method_handle;
1876 if (handle->file_info->flags & GNOME_VFS_FILE_INFO_FIELDS_SIZE) {
1877 GnomeVFSFileSize max_bytes;
1879 max_bytes = handle->file_info->size - handle->bytes_read;
1880 num_bytes = MIN (max_bytes, num_bytes);
1883 result = gnome_vfs_socket_buffer_read (handle->socket_buffer, buffer,
1884 num_bytes, bytes_read);
1886 if (*bytes_read == 0) {
1887 return GNOME_VFS_ERROR_EOF;
1890 handle->bytes_read += *bytes_read;
1892 DEBUG_HTTP (("-Read (%d)", result));
1893 ANALYZE_HTTP ("==> -do_read");
1898 /* Directory handling - WebDAV servers only */
1901 process_propfind_propstat (xmlNodePtr node,
1902 GnomeVFSFileInfo *file_info)
1905 gboolean treat_as_directory;
1907 treat_as_directory = FALSE;
1909 while (node != NULL) {
1910 if (strcmp ((char *)node->name, "prop") != 0) {
1911 /* node name != "prop" - prop is all we care about */
1915 /* properties of the file */
1916 l = node->xmlChildrenNode;
1918 char *node_content_xml = xmlNodeGetContent(l);
1919 if (node_content_xml) {
1920 if (strcmp ((char *)l->name, "getcontenttype") == 0) {
1922 file_info->valid_fields |=
1923 GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE;
1925 if (!file_info->mime_type) {
1926 file_info->mime_type = strip_semicolon (node_content_xml);
1928 } else if (strcmp ((char *)l->name, "getcontentlength") == 0){
1929 file_info->valid_fields |=
1930 GNOME_VFS_FILE_INFO_FIELDS_SIZE;
1931 file_info->size = atoi(node_content_xml);
1932 } else if (strcmp((char *)l->name, "getlastmodified") == 0) {
1933 if (gnome_vfs_atotm (node_content_xml, &(file_info->mtime))) {
1934 file_info->ctime = file_info->mtime;
1935 file_info->valid_fields |=
1936 GNOME_VFS_FILE_INFO_FIELDS_MTIME
1937 | GNOME_VFS_FILE_INFO_FIELDS_CTIME;
1940 /* Unfortunately, we don't have a mapping for "creationdate" */
1942 xmlFree (node_content_xml);
1943 node_content_xml = NULL;
1945 if (strcmp ((char *)l->name, "resourcetype") == 0) {
1946 file_info->valid_fields |=
1947 GNOME_VFS_FILE_INFO_FIELDS_TYPE;
1948 file_info->type = GNOME_VFS_FILE_TYPE_REGULAR;
1950 if (l->xmlChildrenNode && l->xmlChildrenNode->name
1951 && strcmp ((char *)l->xmlChildrenNode->name, "collection") == 0) {
1952 file_info->type = GNOME_VFS_FILE_TYPE_DIRECTORY;
1960 /* If this is a DAV collection, do we tell nautilus to treat it
1961 * as a directory or as a web page?
1963 if (file_info->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_TYPE
1964 && file_info->type == GNOME_VFS_FILE_TYPE_DIRECTORY) {
1965 g_free (file_info->mime_type);
1966 if (treat_as_directory) {
1967 file_info->mime_type = g_strdup ("x-directory/webdav-prefer-directory");
1968 file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE;
1970 file_info->mime_type = g_strdup ("x-directory/webdav");
1971 file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE;
1976 if ((file_info->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE) == 0) {
1977 file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE;
1978 file_info->mime_type = g_strdup (gnome_vfs_mime_type_from_name_or_default (file_info->name, "text/plain"));
1981 if ((file_info->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_TYPE) == 0) {
1982 /* Is this a reasonable assumption ? */
1983 file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_TYPE;
1984 file_info->type = GNOME_VFS_FILE_TYPE_REGULAR;
1988 /* a strcmp that doesn't barf on NULLs */
1990 null_handling_strcmp (const char *a, const char *b)
1992 if ((a == NULL) != (b == NULL)) {
1996 if (a == NULL && b == NULL) {
2000 return strcmp (a, b);
2005 unescape_unreserved_chars (const char *in_string)
2007 /* RFC 2396 section 2.2 */
2008 static const char * reserved_chars = "%;/?:@&=+$,";
2010 char *ret, *write_char;
2011 const char * read_char;
2013 if (in_string == NULL) {
2017 ret = g_new (char, strlen (in_string) + 1);
2019 for (read_char = in_string, write_char = ret ; *read_char != '\0' ; read_char++) {
2020 if (read_char[0] == '%'
2021 && g_ascii_isxdigit (read_char[1])
2022 && g_ascii_isxdigit (read_char[2])) {
2025 unescaped = (g_ascii_xdigit_value (read_char[1]) << 4) | g_ascii_xdigit_value (read_char[2]);
2027 if (strchr (reserved_chars, unescaped)) {
2028 *write_char++ = *read_char++;
2029 *write_char++ = *read_char++;
2030 *write_char++ = *read_char; /*The last ++ is done in the for statement */
2032 *write_char++ = unescaped;
2033 read_char += 2; /*The last ++ is done in the for statement */
2036 *write_char++ = *read_char;
2039 *write_char++ = '\0';
2046 find_child_node_named (xmlNodePtr node,
2047 const char *child_node_name)
2051 child = node->xmlChildrenNode;
2053 for (child = node->xmlChildrenNode; child != NULL; child = child->next) {
2054 if (0 == strcmp (child->name, child_node_name)) {
2062 /* Look for a <status> tag in the children of node, and returns
2063 * the corresponding (HTTP) error code
2066 get_status_node (xmlNodePtr node, guint *status_code)
2068 xmlNodePtr status_node;
2069 char *status_string;
2072 status_node = find_child_node_named (node, "status");
2074 if (status_node != NULL) {
2075 status_string = xmlNodeGetContent (status_node);
2076 ret = parse_status (status_string, status_code);
2077 xmlFree (status_string);
2085 static GnomeVFSFileInfo *
2086 process_propfind_response(xmlNodePtr n,
2087 GnomeVFSURI *base_uri)
2089 GnomeVFSFileInfo *file_info = defaults_file_info_new ();
2090 GnomeVFSURI *second_base = gnome_vfs_uri_append_path (base_uri, "/");
2093 file_info->valid_fields = GNOME_VFS_FILE_INFO_FIELDS_NONE;
2096 if (strcmp ((char *)n->name, "href") == 0) {
2097 char *nodecontent = xmlNodeGetContent (n);
2100 rv = gnome_vfs_remove_optional_escapes (nodecontent);
2102 if (nodecontent != NULL && *nodecontent != '\0' && rv == GNOME_VFS_OK) {
2104 GnomeVFSURI *uri = gnome_vfs_uri_new (nodecontent);
2107 if ((0 == null_handling_strcmp (base_uri->text, uri->text)) ||
2108 (0 == null_handling_strcmp (second_base->text, uri->text))) {
2109 file_info->name = NULL; /* this file is the . directory */
2111 if (file_info->name != NULL) {
2112 /* Don't leak if a (potentially malicious)
2113 * server returns several href in its answer
2115 g_free (file_info->name);
2117 file_info->name = gnome_vfs_uri_extract_short_name (uri);
2118 if (file_info->name != NULL) {
2119 len = strlen (file_info->name) -1;
2120 if (file_info->name[len] == '/') {
2121 /* trim trailing `/` - it confuses stuff */
2122 file_info->name[len] = '\0';
2125 g_warning ("Invalid filename in PROPFIND '%s'; silently skipping", nodecontent);
2128 gnome_vfs_uri_unref (uri);
2130 g_warning ("Can't make URI from href in PROPFIND '%s'; silently skipping", nodecontent);
2133 g_warning ("got href without contents in PROPFIND response");
2136 xmlFree (nodecontent);
2137 } else if (strcmp ((char *)n->name, "propstat") == 0) {
2138 if (get_status_node (n, &status_code) && status_code == 200) {
2139 process_propfind_propstat (n->xmlChildrenNode, file_info);
2145 gnome_vfs_uri_unref (second_base);
2152 static GnomeVFSResult
2153 make_propfind_request (HttpFileHandle **handle_return,
2156 GnomeVFSContext *context)
2158 GnomeVFSResult result = GNOME_VFS_OK;
2159 GnomeVFSFileSize bytes_read, num_bytes=(64*1024);
2160 char *buffer = g_malloc(num_bytes);
2161 xmlParserCtxtPtr parserContext;
2162 xmlDocPtr doc = NULL;
2163 xmlNodePtr cur = NULL;
2164 char *extraheaders = g_strdup_printf("Depth: %d\r\n", depth);
2165 gboolean found_root_node_props;
2167 GByteArray *request = g_byte_array_new();
2168 char *request_str = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
2169 "<D:propfind xmlns:D=\"DAV:\" >"
2172 "<D:getcontentlength/>"
2173 "<D:getcontenttype/>"
2174 "<D:getlastmodified/>"
2179 ANALYZE_HTTP ("==> +make_propfind_request");
2181 request = g_byte_array_append(request, request_str,
2182 strlen(request_str));
2184 parserContext = xmlCreatePushParserCtxt(NULL, NULL, "", 0, "PROPFIND");
2187 http_cache_invalidate_uri_and_children (uri);
2190 result = make_request (handle_return, uri, "PROPFIND", request,
2191 extraheaders, context);
2193 /* FIXME bugzilla.gnome.org 43834: It looks like some http
2194 * servers (eg, www.yahoo.com) treat PROPFIND as a GET and
2195 * return a 200 OK. Others may return access denied errors or
2196 * redirects or any other legal response. This case probably
2197 * needs to be made more robust.
2199 if (result == GNOME_VFS_OK && (*handle_return)->server_status != 207) { /* Multi-Status */
2200 DEBUG_HTTP (("HTTP server returned an invalid PROPFIND response: %d", (*handle_return)->server_status));
2201 result = GNOME_VFS_ERROR_NOT_SUPPORTED;
2204 if (result == GNOME_VFS_OK) {
2206 result = do_read (NULL, (GnomeVFSMethodHandle *) *handle_return,
2207 buffer, num_bytes, &bytes_read, context);
2209 if (result != GNOME_VFS_OK ) {
2212 xmlParseChunk (parserContext, buffer, bytes_read, 0);
2213 buffer[bytes_read]=0;
2214 } while (bytes_read > 0);
2217 if (result == GNOME_VFS_ERROR_EOF) {
2218 result = GNOME_VFS_OK;
2221 if (result != GNOME_VFS_OK) {
2225 xmlParseChunk (parserContext, "", 0, 1);
2227 doc = parserContext->myDoc;
2229 result = GNOME_VFS_ERROR_GENERIC;
2233 cur = doc->xmlRootNode;
2234 if (strcmp ((char *)cur->name, "multistatus") != 0) {
2235 DEBUG_HTTP (("Couldn't find <multistatus>.\n"));
2236 result = GNOME_VFS_ERROR_GENERIC;
2239 cur = cur->xmlChildrenNode;
2241 found_root_node_props = FALSE;
2242 while (cur != NULL) {
2243 if (strcmp ((char *)cur->name, "response") == 0) {
2244 GnomeVFSFileInfo *file_info;
2247 /* Some webdav servers (eg resin) put the HTTP status
2248 * code for PROPFIND request in the xml answer instead
2249 * of directly sending a 404
2251 if (get_status_node (cur, &status) && !HTTP_20X(status)) {
2252 result = http_status_to_vfs_result (status);
2257 process_propfind_response (cur->xmlChildrenNode, uri);
2259 if (file_info->name != NULL) {
2260 (*handle_return)->files = g_list_append ((*handle_return)->files, file_info);
2262 /* This response refers to the root node */
2263 /* Abandon the old information that came from create_handle*/
2265 file_info->name = (*handle_return)->file_info->name;
2266 (*handle_return)->file_info->name = NULL;
2267 gnome_vfs_file_info_unref ((*handle_return)->file_info);
2268 (*handle_return)->file_info = file_info;
2269 found_root_node_props = TRUE;
2273 DEBUG_HTTP(("expecting <response> got <%s>\n", cur->name));
2278 if (!found_root_node_props) {
2279 DEBUG_HTTP (("Failed to find root request node properties during propfind"));
2280 result = GNOME_VFS_ERROR_GENERIC;
2286 * Section 8.1, final line
2287 * "The results of this method [PROPFIND] SHOULD NOT be cached"
2288 * Well, at least its not "MUST NOT"
2292 http_cache_add_uri (uri, (*handle_return)->file_info, TRUE);
2294 http_cache_add_uri_and_children (uri, (*handle_return)->file_info, (*handle_return)->files);
2299 g_free(extraheaders);
2300 xmlFreeParserCtxt(parserContext);
2302 if (result != GNOME_VFS_OK) {
2303 http_handle_close (*handle_return, context);
2304 *handle_return = NULL;
2307 ANALYZE_HTTP ("==> -make_propfind_request");
2312 static GnomeVFSResult
2313 do_open_directory(GnomeVFSMethod *method,
2314 GnomeVFSMethodHandle **method_handle,
2316 GnomeVFSFileInfoOptions options,
2317 GnomeVFSContext *context)
2319 /* TODO move to using the gnome_vfs_file_info_list family of functions */
2320 GnomeVFSResult result;
2321 HttpFileHandle *handle = NULL;
2322 GnomeVFSFileInfo * file_info_cached;
2323 GList *child_file_info_cached_list = NULL;
2325 ANALYZE_HTTP ("==> +do_open_directory");
2326 DEBUG_HTTP (("+Open_Directory options: %d URI: '%s'", options, gnome_vfs_uri_to_string (uri, 0)));
2328 /* Check the cache--is this even a directory?
2329 * (Nautilus, in particular, seems to like to make this call on non directories
2332 file_info_cached = http_cache_check_uri (uri);
2334 if (file_info_cached) {
2335 if (GNOME_VFS_FILE_TYPE_DIRECTORY != file_info_cached->type) {
2336 ANALYZE_HTTP ("==> Cache Hit (Negative)");
2337 gnome_vfs_file_info_unref (file_info_cached);
2338 result = GNOME_VFS_ERROR_NOT_A_DIRECTORY;
2341 gnome_vfs_file_info_unref (file_info_cached);
2342 file_info_cached = NULL;
2346 /* The check for directory contents is more stringent */
2347 file_info_cached = http_cache_check_directory_uri (uri, &child_file_info_cached_list);
2349 if (file_info_cached) {
2350 handle = http_file_handle_new (NULL, uri);
2351 gnome_vfs_file_info_unref (handle->file_info);
2352 handle->file_info = file_info_cached;
2353 handle->files = child_file_info_cached_list;
2354 result = GNOME_VFS_OK;
2356 result = make_propfind_request(&handle, uri, 1, context);
2357 /* mfleming -- is this necessary? Most DAV server's I've seen don't have the horrible
2358 * lack-of-trailing-/-is-a-301 problem for PROPFIND's
2360 if (result == GNOME_VFS_ERROR_NOT_FOUND) { /* 404 not found */
2361 if (uri->text != NULL && *uri->text != '\0'
2362 && uri->text[strlen (uri->text) - 1] != '/') {
2363 GnomeVFSURI *tmpuri = gnome_vfs_uri_append_path (uri, "/");
2364 result = do_open_directory (method, (GnomeVFSMethodHandle **)&handle, tmpuri, options, context);
2365 gnome_vfs_uri_unref (tmpuri);
2370 if (result == GNOME_VFS_OK
2371 && handle->file_info->type != GNOME_VFS_FILE_TYPE_DIRECTORY) {
2372 result = GNOME_VFS_ERROR_NOT_A_DIRECTORY;
2373 http_handle_close (handle, context);
2378 *method_handle = (GnomeVFSMethodHandle *)handle;
2381 DEBUG_HTTP (("-Open_Directory (%d) handle:0x%08x", result, (unsigned int)handle));
2382 ANALYZE_HTTP ("==> -do_open_directory");
2387 static GnomeVFSResult
2388 do_close_directory (GnomeVFSMethod *method,
2389 GnomeVFSMethodHandle *method_handle,
2390 GnomeVFSContext *context)
2392 HttpFileHandle *handle;
2394 DEBUG_HTTP (("+Close_Directory"));
2396 handle = (HttpFileHandle *) method_handle;
2398 http_handle_close(handle, context);
2400 DEBUG_HTTP (("-Close_Directory (0) handle:0x%08x", (unsigned int) method_handle));
2402 return GNOME_VFS_OK;
2405 static GnomeVFSResult
2406 do_read_directory (GnomeVFSMethod *method,
2407 GnomeVFSMethodHandle *method_handle,
2408 GnomeVFSFileInfo *file_info,
2409 GnomeVFSContext *context)
2411 HttpFileHandle *handle;
2412 GnomeVFSResult result;
2414 DEBUG_HTTP (("+Read_Directory handle:0x%08x", (unsigned int) method_handle));
2416 handle = (HttpFileHandle *) method_handle;
2418 if (handle->files && g_list_length (handle->files)) {
2419 GnomeVFSFileInfo *original_info = g_list_nth_data (handle->files, 0);
2420 gboolean found_entry = FALSE;
2422 /* mfleming -- Why is this check here? Does anyone set original_info->name to NULL? */
2423 if (original_info->name != NULL && original_info->name[0]) {
2424 gnome_vfs_file_info_copy (file_info, original_info);
2428 /* remove our GnomeVFSFileInfo from the list */
2429 handle->files = g_list_remove (handle->files, original_info);
2430 gnome_vfs_file_info_unref (original_info);
2432 /* mfleming -- Is this necessary? */
2434 result = GNOME_VFS_OK;
2436 result = do_read_directory (method, method_handle, file_info, context);
2439 result = GNOME_VFS_ERROR_EOF;
2442 DEBUG_HTTP (("-Read_Directory (%d)", result));
2447 static GnomeVFSResult
2448 do_get_file_info (GnomeVFSMethod *method,
2450 GnomeVFSFileInfo *file_info,
2451 GnomeVFSFileInfoOptions options,
2452 GnomeVFSContext *context)
2454 HttpFileHandle *handle;
2455 GnomeVFSResult result;
2456 GnomeVFSFileInfo * file_info_cached;
2458 ANALYZE_HTTP ("==> +do_get_file_info");
2459 DEBUG_HTTP (("+Get_File_Info options: %d URI: '%s'", options, gnome_vfs_uri_to_string( uri, 0)));
2461 file_info_cached = http_cache_check_uri (uri);
2463 if (file_info_cached != NULL) {
2464 gnome_vfs_file_info_copy (file_info, file_info_cached);
2465 gnome_vfs_file_info_unref (file_info_cached);
2466 ANALYZE_HTTP ("==> Cache Hit");
2467 result = GNOME_VFS_OK;
2470 * Start off by making a PROPFIND request. Fall back to a HEAD if it fails
2473 result = make_propfind_request (&handle, uri, 0, context);
2475 /* Note that theoretically we could not bother with this request if we get a 404 back,
2476 * but since some servers seem to return wierd things on PROPFIND (mostly 200 OK's...)
2477 * I'm not going to count on the PROPFIND response....
2479 if (result == GNOME_VFS_OK) {
2480 gnome_vfs_file_info_copy (file_info, handle->file_info);
2481 http_handle_close (handle, context);
2484 g_assert (handle == NULL); /* Make sure we're not leaking some old one */
2486 /* Lame buggy servers (eg: www.mozilla.org,
2487 * www.corel.com)) return an HTTP error for a
2488 * HEAD where a GET would succeed. In these
2489 * cases lets try to do a GET.
2491 if (result != GNOME_VFS_OK) {
2492 g_assert (handle == NULL); /* Make sure we're not leaking some old one */
2494 ANALYZE_HTTP ("==> do_get_file_info: do GET ");
2496 result = make_request (&handle, uri, "GET", NULL, NULL, context);
2497 if (result == GNOME_VFS_OK) {
2498 gnome_vfs_file_info_copy (file_info, handle->file_info);
2499 http_cache_add_uri (uri, handle->file_info, FALSE);
2500 http_handle_close (handle, context);
2503 /* If we get a redirect, we should be
2504 * basing the MIME type on the type of
2505 * the page we'll be redirected
2506 * too. Maybe we even want to take the
2507 * "follow_links" setting into account.
2509 /* FIXME: For now we treat all
2510 * redirects as if they lead to a
2511 * text/html. That works pretty well,
2512 * but it's not correct.
2514 if (handle != NULL && HTTP_REDIRECTED (handle->server_status)) {
2515 g_free (file_info->mime_type);
2516 file_info->mime_type = g_strdup ("text/html");
2520 if (result == GNOME_VFS_ERROR_NOT_FOUND) { /* 404 not found */
2521 /* FIXME bugzilla.gnome.org 43835: mfleming: Is this code really appropriate?
2522 * In any case, it doesn't seem to be appropriate for a DAV-enabled
2523 * server, since they don't seem to send 301's when you PROPFIND collections
2524 * without a trailing '/'.
2526 if (uri->text != NULL && *uri->text != '\0'
2527 && uri->text[strlen(uri->text)-1] != '/') {
2528 GnomeVFSURI *tmpuri = gnome_vfs_uri_append_path (uri, "/");
2530 result = do_get_file_info (method, tmpuri, file_info, options, context);
2531 gnome_vfs_uri_unref (tmpuri);
2537 DEBUG_HTTP (("-Get_File_Info (%d)", result));
2538 ANALYZE_HTTP ("==> -do_get_file_info");
2543 static GnomeVFSResult
2544 do_get_file_info_from_handle (GnomeVFSMethod *method,
2545 GnomeVFSMethodHandle *method_handle,
2546 GnomeVFSFileInfo *file_info,
2547 GnomeVFSFileInfoOptions options,
2548 GnomeVFSContext *context)
2550 HttpFileHandle *handle;
2552 DEBUG_HTTP (("+Get_File_Info_From_Handle"));
2554 handle = (HttpFileHandle *) method_handle;
2556 gnome_vfs_file_info_copy (file_info, handle->file_info);
2558 DEBUG_HTTP (("-Get_File_Info_From_Handle"));
2560 return GNOME_VFS_OK;
2564 do_is_local (GnomeVFSMethod *method,
2565 const GnomeVFSURI *uri)
2567 DEBUG_HTTP (("+Is_Local"));
2571 static GnomeVFSResult
2572 do_make_directory (GnomeVFSMethod *method,
2575 GnomeVFSContext *context)
2577 /* MKCOL /path HTTP/1.0 */
2579 HttpFileHandle *handle;
2580 GnomeVFSResult result;
2582 DEBUG_HTTP (("+Make_Directory URI: '%s'", gnome_vfs_uri_to_string (uri, 0)));
2583 ANALYZE_HTTP ("==> +do_make_directory");
2586 * MKCOL returns a 405 if you try to MKCOL on something that
2587 * already exists. Of course, we don't know whether that means that
2588 * the server doesn't support DAV or the collection already exists.
2589 * So we do a PROPFIND first to find out
2591 /* FIXME check cache here */
2592 result = make_propfind_request(&handle, uri, 0, context);
2594 if (result == GNOME_VFS_OK) {
2595 result = GNOME_VFS_ERROR_FILE_EXISTS;
2597 /* Make sure we're not leaking an old one */
2598 g_assert (handle == NULL);
2600 if (result == GNOME_VFS_ERROR_NOT_FOUND) {
2601 http_cache_invalidate_uri_parent (uri);
2602 result = make_request (&handle, uri, "MKCOL", NULL, NULL, context);
2605 http_handle_close (handle, context);
2607 if (result == GNOME_VFS_ERROR_NOT_FOUND) {
2608 result = resolve_409 (method, uri, context);
2611 ANALYZE_HTTP ("==> -do_make_directory");
2612 DEBUG_HTTP (("-Make_Directory (%d)", result));
2617 static GnomeVFSResult
2618 do_remove_directory(GnomeVFSMethod *method,
2620 GnomeVFSContext *context)
2622 /* DELETE /path HTTP/1.0 */
2623 HttpFileHandle *handle;
2624 GnomeVFSResult result;
2626 ANALYZE_HTTP ("==> +do_remove_directory");
2627 DEBUG_HTTP (("+Remove_Directory URI: '%s'", gnome_vfs_uri_to_string (uri, 0)));
2629 http_cache_invalidate_uri_parent (uri);
2631 /* FIXME this should return GNOME_VFS_ERROR_DIRECTORY_NOT_EMPTY if the
2632 * directory is not empty
2634 result = make_request (&handle, uri, "DELETE", NULL, NULL,
2636 http_handle_close (handle, context);
2638 DEBUG_HTTP (("-Remove_Directory (%d)", result));
2639 ANALYZE_HTTP ("==> -do_remove_directory");
2645 is_same_fs (const GnomeVFSURI *a,
2646 const GnomeVFSURI *b)
2648 return null_handling_strcmp (gnome_vfs_uri_get_scheme (a), gnome_vfs_uri_get_scheme (b)) == 0
2649 && null_handling_strcmp (gnome_vfs_uri_get_host_name (a), gnome_vfs_uri_get_host_name (b)) == 0
2650 && null_handling_strcmp (gnome_vfs_uri_get_user_name (a), gnome_vfs_uri_get_user_name (b)) == 0
2651 && null_handling_strcmp (gnome_vfs_uri_get_password (a), gnome_vfs_uri_get_password (b)) == 0
2652 && (gnome_vfs_uri_get_host_port (a) == gnome_vfs_uri_get_host_port (b));
2655 static GnomeVFSResult
2656 do_move (GnomeVFSMethod *method,
2657 GnomeVFSURI *old_uri,
2658 GnomeVFSURI *new_uri,
2659 gboolean force_replace,
2660 GnomeVFSContext *context)
2664 * MOVE /path1 HTTP/1.0
2665 * Destination: /path2
2669 HttpFileHandle *handle;
2670 GnomeVFSResult result;
2672 char *destpath, *destheader;
2674 ANALYZE_HTTP ("==> +do_move");
2675 DEBUG_HTTP (("+Move URI: '%s' Dest: '%s'",
2676 gnome_vfs_uri_to_string (old_uri, 0),
2677 gnome_vfs_uri_to_string (new_uri, 0)));
2679 if (!is_same_fs (old_uri, new_uri)) {
2680 return GNOME_VFS_ERROR_NOT_SAME_FILE_SYSTEM;
2683 destpath = gnome_vfs_uri_to_string (new_uri, GNOME_VFS_URI_HIDE_USER_NAME|GNOME_VFS_URI_HIDE_PASSWORD);
2684 destheader = g_strdup_printf ("Destination: %s\r\nOverwrite: %c\r\n", destpath, force_replace ? 'T' : 'F' );
2686 result = make_request (&handle, old_uri, "MOVE", NULL, destheader, context);
2687 http_handle_close (handle, context);
2690 if (result == GNOME_VFS_ERROR_NOT_FOUND) {
2691 result = resolve_409 (method, new_uri, context);
2694 http_cache_invalidate_uri_parent (old_uri);
2695 http_cache_invalidate_uri_parent (new_uri);
2697 DEBUG_HTTP (("-Move (%d)", result));
2698 ANALYZE_HTTP ("==> -do_move");
2704 static GnomeVFSResult
2705 do_unlink(GnomeVFSMethod *method,
2707 GnomeVFSContext *context)
2709 GnomeVFSResult result;
2711 /* FIXME need to make sure this fails on directories */
2712 ANALYZE_HTTP ("==> +do_unlink");
2713 DEBUG_HTTP (("+Unlink URI: '%s'", gnome_vfs_uri_to_string (uri, 0)));
2714 result = do_remove_directory (method, uri, context);
2715 DEBUG_HTTP (("-Unlink (%d)", result));
2716 ANALYZE_HTTP ("==> -do_unlink");
2721 static GnomeVFSResult
2722 do_check_same_fs (GnomeVFSMethod *method,
2725 gboolean *same_fs_return,
2726 GnomeVFSContext *context)
2728 *same_fs_return = is_same_fs (a, b);
2730 return GNOME_VFS_OK;
2733 static GnomeVFSResult
2734 do_set_file_info (GnomeVFSMethod *method,
2736 const GnomeVFSFileInfo *info,
2737 GnomeVFSSetFileInfoMask mask,
2738 GnomeVFSContext *context)
2740 GnomeVFSURI *parent_uri, *new_uri;
2741 GnomeVFSResult result;
2743 /* FIXME: For now, we only support changing the name. */
2744 if ((mask & ~(GNOME_VFS_SET_FILE_INFO_NAME)) != 0) {
2745 return GNOME_VFS_ERROR_NOT_SUPPORTED;
2748 /* FIXME bugzillagnome.org 40645: Make sure this returns an
2749 * error for incoming names with "/" characters in them,
2750 * instead of moving the file.
2753 /* Share code with do_move. */
2754 parent_uri = gnome_vfs_uri_get_parent (uri);
2755 if (parent_uri == NULL) {
2756 return GNOME_VFS_ERROR_NOT_FOUND;
2758 new_uri = gnome_vfs_uri_append_file_name (parent_uri, info->name);
2759 gnome_vfs_uri_unref (parent_uri);
2760 result = do_move (method, uri, new_uri, FALSE, context);
2761 gnome_vfs_uri_unref (new_uri);
2765 static GnomeVFSMethod method = {
2766 sizeof (GnomeVFSMethod),
2774 NULL, /* truncate_handle */
2779 do_get_file_info_from_handle,
2782 do_remove_directory,
2787 NULL, /* truncate */
2788 NULL, /* find_directory */
2789 NULL /* create_symbolic_link */
2793 vfs_module_init (const char *method_name,
2796 GError *gconf_error = NULL;
2798 gboolean use_proxy_auth;
2802 gl_client = gconf_client_get_default ();
2804 gl_mutex = g_mutex_new ();
2806 gconf_client_add_dir (gl_client, PATH_GCONF_GNOME_VFS, GCONF_CLIENT_PRELOAD_ONELEVEL, &gconf_error);
2808 DEBUG_HTTP (("GConf error during client_add_dir '%s'", gconf_error->message));
2809 g_error_free (gconf_error);
2813 gconf_client_notify_add (gl_client, PATH_GCONF_GNOME_VFS, notify_gconf_value_changed, NULL, NULL, &gconf_error);
2815 DEBUG_HTTP (("GConf error during notify_error '%s'", gconf_error->message));
2816 g_error_free (gconf_error);
2820 /* Load the http proxy setting */
2821 use_proxy = gconf_client_get_bool (gl_client, KEY_GCONF_USE_HTTP_PROXY, &gconf_error);
2823 if (gconf_error != NULL) {
2824 DEBUG_HTTP (("GConf error during client_get_bool '%s'", gconf_error->message));
2825 g_error_free (gconf_error);
2828 construct_gl_http_proxy (use_proxy);
2831 use_proxy_auth = gconf_client_get_bool (gl_client, KEY_GCONF_HTTP_USE_AUTH, &gconf_error);
2833 if (gconf_error != NULL) {
2834 DEBUG_HTTP (("GConf error during client_get_bool '%s'", gconf_error->message));
2835 g_error_free (gconf_error);
2838 set_proxy_auth (use_proxy_auth);
2848 vfs_module_shutdown (GnomeVFSMethod *method)
2850 g_object_unref (G_OBJECT (gl_client));
2852 http_authn_shutdown ();
2854 http_cache_shutdown();
2856 g_mutex_free (gl_mutex);
2861 /* A "409 Conflict" currently maps to GNOME_VFS_ERROR_NOT_FOUND because it can be returned
2862 * when the parent collection/directory does not exist. Unfortunately, Xythos also returns
2863 * this code when the destination filename of a PUT, MKCOL, or MOVE contains illegal characters,
2864 * eg "my*file:name".
2866 * The only way to resolve this is to ask...
2869 static GnomeVFSResult
2870 resolve_409 (GnomeVFSMethod *method, GnomeVFSURI *uri, GnomeVFSContext *context)
2872 GnomeVFSFileInfo *file_info;
2873 GnomeVFSURI *parent_dest_uri;
2874 GnomeVFSResult result;
2877 ANALYZE_HTTP ("==> +resolving 409");
2879 file_info = gnome_vfs_file_info_new ();
2880 parent_dest_uri = gnome_vfs_uri_get_parent (uri);
2882 if (parent_dest_uri != NULL) {
2883 result = do_get_file_info (method,
2886 GNOME_VFS_FILE_INFO_DEFAULT,
2889 gnome_vfs_file_info_unref (file_info);
2892 gnome_vfs_uri_unref (parent_dest_uri);
2893 parent_dest_uri = NULL;
2895 result = GNOME_VFS_ERROR_NOT_FOUND;
2898 if (result == GNOME_VFS_OK) {
2899 /* The destination filename contains characters that are not allowed
2900 * by the server. This is a bummer mapping, but EINVAL is what
2901 * the Linux FAT filesystems return on bad filenames, so at least
2902 * its not without precedent...
2904 result = GNOME_VFS_ERROR_BAD_PARAMETERS;
2906 /* The destination's parent path does not exist */
2907 result = GNOME_VFS_ERROR_NOT_FOUND;
2910 ANALYZE_HTTP ("==> -resolving 409");
2916 invoke_callback_headers_received (HttpFileHandle *handle)
2918 GnomeVFSModuleCallbackReceivedHeadersIn in_args;
2919 GnomeVFSModuleCallbackReceivedHeadersOut out_args;
2920 gboolean ret = FALSE;
2922 memset (&in_args, 0, sizeof (in_args));
2923 memset (&out_args, 0, sizeof (out_args));
2925 in_args.uri = handle->uri;
2926 in_args.headers = handle->response_headers;
2928 ret = gnome_vfs_module_callback_invoke (GNOME_VFS_MODULE_CALLBACK_HTTP_RECEIVED_HEADERS,
2929 &in_args, sizeof (in_args),
2930 &out_args, sizeof (out_args));
2936 invoke_callback_send_additional_headers (GnomeVFSURI *uri,
2939 GnomeVFSModuleCallbackAdditionalHeadersIn in_args;
2940 GnomeVFSModuleCallbackAdditionalHeadersOut out_args;
2941 gboolean ret = FALSE;
2943 memset (&in_args, 0, sizeof (in_args));
2944 memset (&out_args, 0, sizeof (out_args));
2948 ret = gnome_vfs_module_callback_invoke (GNOME_VFS_MODULE_CALLBACK_HTTP_SEND_ADDITIONAL_HEADERS,
2949 &in_args, sizeof (in_args),
2950 &out_args, sizeof (out_args));
2953 *headers = out_args.headers;
2957 if (out_args.headers) {
2958 g_list_foreach (out_args.headers, (GFunc)g_free, NULL);
2959 g_list_free (out_args.headers);
2968 invoke_callback_basic_authn (HttpFileHandle *handle,
2969 enum AuthnHeaderType authn_which,
2970 gboolean previous_attempt_failed)
2972 GnomeVFSModuleCallbackAuthenticationIn in_args;
2973 GnomeVFSModuleCallbackAuthenticationOut out_args;
2978 memset (&in_args, 0, sizeof (in_args));
2979 memset (&out_args, 0, sizeof (out_args));
2981 in_args.previous_attempt_failed = previous_attempt_failed;
2983 in_args.uri = gnome_vfs_uri_to_string (handle->uri, GNOME_VFS_URI_HIDE_NONE);
2985 ret = http_authn_parse_response_header_basic (authn_which, handle->response_headers, &in_args.realm);
2991 DEBUG_HTTP (("Invoking %s authentication callback for uri %s",
2992 authn_which == AuthnHeader_WWW ? "basic" : "proxy", in_args.uri));
2994 in_args.auth_type = AuthTypeBasic;
2996 ret = gnome_vfs_module_callback_invoke (authn_which == AuthnHeader_WWW
2997 ? GNOME_VFS_MODULE_CALLBACK_AUTHENTICATION
2998 : GNOME_VFS_MODULE_CALLBACK_HTTP_PROXY_AUTHENTICATION,
2999 &in_args, sizeof (in_args),
3000 &out_args, sizeof (out_args));
3003 DEBUG_HTTP (("No callback registered"));
3007 ret = (out_args.username != NULL);
3010 DEBUG_HTTP (("No username provided by callback"));
3014 DEBUG_HTTP (("Back from authentication callback, adding credentials"));
3016 if (authn_which == AuthnHeader_WWW) {
3017 http_authn_session_add_credentials (handle->uri, out_args.username, out_args.password);
3018 } else /* if (authn_which == AuthnHeader_Proxy) */ {
3019 proxy_set_authn (out_args.username, out_args.password);
3022 g_free (in_args.uri);
3023 g_free (in_args.realm);
3024 g_free (out_args.username);
3025 g_free (out_args.password);
3031 strcmp_allow_nulls (const char *s1, const char *s2)
3033 return strcmp (s1 == NULL ? "" : s1, s2 == NULL ? "" : s2);
3037 /* Returns TRUE if the given URL has changed authentication credentials
3038 * from the last request (eg, another thread updated the authn information)
3039 * or if the application provided new credentials via a callback
3041 * prev_authn_header is NULL if the previous request contained no authn information.
3045 check_authn_retry_request (HttpFileHandle * http_handle,
3046 enum AuthnHeaderType authn_which,
3047 const char *prev_authn_header)
3050 char *current_authn_header;
3052 current_authn_header = NULL;
3054 g_mutex_lock (gl_mutex);
3056 if (authn_which == AuthnHeader_WWW) {
3057 current_authn_header = http_authn_get_header_for_uri (http_handle->uri);
3058 } else if (authn_which == AuthnHeader_Proxy) {
3059 current_authn_header = proxy_get_authn_header_for_uri_nolock (http_handle->uri);
3061 g_assert_not_reached ();
3065 if (0 == strcmp_allow_nulls (current_authn_header, prev_authn_header)) {
3066 ret = invoke_callback_basic_authn (http_handle, authn_which, prev_authn_header == NULL);
3071 g_mutex_unlock (gl_mutex);
3073 g_free (current_authn_header);
3080 http_util_get_utime (void)
3083 gettimeofday (&tmp, NULL);
3084 return (utime_t)tmp.tv_usec + ((gint64)tmp.tv_sec) * 1000000LL;
3088 /* BASE64 code ported from neon (http://www.webdav.org/neon) */
3089 static const gchar b64_alphabet[65] = {
3090 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3091 "abcdefghijklmnopqrstuvwxyz"
3095 http_util_base64 (const gchar *text)
3097 /* The tricky thing about this is doing the padding at the end,
3098 * doing the bit manipulation requires a bit of concentration only */
3099 gchar *buffer, *point;
3102 /* Use 'buffer' to store the output. Work out how big it should be...
3103 * This must be a multiple of 4 bytes
3106 inlen = strlen (text);
3107 outlen = (inlen*4)/3;
3108 if ((inlen % 3) > 0) { /* got to pad */
3109 outlen += 4 - (inlen % 3);
3112 buffer = g_malloc (outlen + 1); /* +1 for the \0 */
3114 /* now do the main stage of conversion, 3 bytes at a time,
3115 * leave the trailing bytes (if there are any) for later
3118 for (point=buffer; inlen>=3; inlen-=3, text+=3) {
3119 *(point++) = b64_alphabet[ (*text)>>2 ];
3120 *(point++) = b64_alphabet[ ((*text)<<4 & 0x30) | (*(text+1))>>4 ];
3121 *(point++) = b64_alphabet[ ((*(text+1))<<2 & 0x3c) | (*(text+2))>>6 ];
3122 *(point++) = b64_alphabet[ (*(text+2)) & 0x3f ];
3125 /* Now deal with the trailing bytes */
3127 /* We always have one trailing byte */
3128 *(point++) = b64_alphabet[ (*text)>>2 ];
3129 *(point++) = b64_alphabet[ ( ((*text)<<4 & 0x30) |
3130 (inlen==2?(*(text+1))>>4:0) ) ];
3131 *(point++) = (inlen==1?'=':b64_alphabet[ (*(text+1))<<2 & 0x3c ] );
3135 /* Null-terminate */
3141 static gboolean at_least_one_test_failed = FALSE;
3144 test_failed (const char *format, ...)
3149 va_start (arguments, format);
3150 message = g_strdup_vprintf (format, arguments);
3153 g_message ("test failed: %s", message);
3154 at_least_one_test_failed = TRUE;
3157 #define VERIFY_BOOLEAN_RESULT(function, expected) \
3159 gboolean result = function; \
3160 if (! ((result && expected) || (!result && !expected))) { \
3161 test_failed ("%s: returned '%d' expected '%d'", #function, (int)result, (int)expected); \
3167 http_self_test (void)
3169 g_message ("self-test: http\n");
3171 VERIFY_BOOLEAN_RESULT (proxy_should_for_hostname ("localhost"), FALSE);
3172 VERIFY_BOOLEAN_RESULT (proxy_should_for_hostname ("LocalHost"), FALSE);
3173 VERIFY_BOOLEAN_RESULT (proxy_should_for_hostname ("127.0.0.1"), FALSE);
3174 VERIFY_BOOLEAN_RESULT (proxy_should_for_hostname ("127.127.0.1"), FALSE);
3175 VERIFY_BOOLEAN_RESULT (proxy_should_for_hostname ("www.yahoo.com"), TRUE);
3177 return !at_least_one_test_failed;
3180 gboolean vfs_module_self_test (void);
3183 vfs_module_self_test (void)
3189 ret = http_authn_self_test () && ret;
3191 ret = http_self_test () && ret;