Fixed do_read() 'offset' corruption.
[gnome-vfs-httpcaptive.git] / modules / http-method.c
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
3    System.
4
5    Copyright (C) 1999 Free Software Foundation
6    Copyright (C) 2000-2001 Eazel, Inc
7
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.
12
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.
17
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.
22
23    Authors: 
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
28         */
29
30 /* TODO:
31    - Handle redirection.
32    - Handle persistent connections.  */
33
34 #include <config.h>
35 #include "http-method.h"
36
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>
58 #include <stdarg.h>
59 #include <stdio.h>
60 #include <stdlib.h> /* for atoi */
61 #include <string.h>
62 #include <sys/socket.h>
63 #include <sys/time.h>
64 #include <unistd.h>
65 #include <netdb.h>
66
67 #ifdef DEBUG_HTTP_ENABLE
68 void
69 http_debug_printf (char *fmt, ...)
70 {
71         va_list args;
72         gchar * out;
73
74         g_assert (fmt);
75
76         va_start (args, fmt);
77
78         out = g_strdup_vprintf (fmt, args);
79
80         fprintf (stderr, "HTTP: [0x%08x] [%p] %s\n",
81                  (unsigned int) http_util_get_utime (),
82                  g_thread_self (), out);
83
84         g_free (out);
85         va_end (args);
86 }
87 #endif /* DEBUG_HTTP_ENABLE */
88
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
92
93 /* Custom User-Agent environment variable */
94 #define CUSTOM_USER_AGENT_VARIABLE "GNOME_VFS_HTTP_USER_AGENT"
95
96 /* Standard HTTP[S] port.  */
97 #define DEFAULT_HTTP_PORT       80
98 #define DEFAULT_HTTPS_PORT      443
99
100 /* Standard HTTP proxy port */
101 #define DEFAULT_HTTP_PROXY_PORT 8080
102
103 /* Maximum amount of data to read if seek()ed forward. Otherwise make a new connection. */
104 #define MAX_BUFFER_SEEK_SKIP_READ       0x10000
105
106 /* GConf paths and keys */
107 #define PATH_GCONF_GNOME_VFS "/system/http_proxy"
108 #define ITEM_GCONF_HTTP_PROXY_PORT "port"
109 #define ITEM_GCONF_HTTP_PROXY_HOST "host"
110 #define KEY_GCONF_HTTP_PROXY_PORT (PATH_GCONF_GNOME_VFS "/" ITEM_GCONF_HTTP_PROXY_PORT)
111 #define KEY_GCONF_HTTP_PROXY_HOST (PATH_GCONF_GNOME_VFS "/" ITEM_GCONF_HTTP_PROXY_HOST)
112
113 #define ITEM_GCONF_USE_HTTP_PROXY "use_http_proxy"
114 #define KEY_GCONF_USE_HTTP_PROXY (PATH_GCONF_GNOME_VFS "/" ITEM_GCONF_USE_HTTP_PROXY)
115
116 #define KEY_GCONF_HTTP_AUTH_USER (PATH_GCONF_GNOME_VFS "/" "authentication_user")
117 #define KEY_GCONF_HTTP_AUTH_PW (PATH_GCONF_GNOME_VFS "/" "authentication_password")
118 #define KEY_GCONF_HTTP_USE_AUTH (PATH_GCONF_GNOME_VFS "/" "use_authentication")
119
120 #define KEY_GCONF_HTTP_PROXY_IGNORE_HOSTS (PATH_GCONF_GNOME_VFS "/" "ignore_hosts")
121
122
123 /* Some status code validation macros.  */
124 #define HTTP_20X(x)        (((x) >= 200) && ((x) < 300))
125 #define HTTP_PARTIAL(x)    ((x) == HTTP_STATUS_PARTIAL_CONTENTS)
126 #define HTTP_REDIRECTED(x) (((x) == HTTP_STATUS_MOVED_PERMANENTLY)      \
127                             || ((x) == HTTP_STATUS_MOVED_TEMPORARILY))
128
129 /* HTTP/1.1 status codes from RFC2068, provided for reference.  */
130 /* Successful 2xx.  */
131 #define HTTP_STATUS_OK                  200
132 #define HTTP_STATUS_CREATED             201
133 #define HTTP_STATUS_ACCEPTED            202
134 #define HTTP_STATUS_NON_AUTHORITATIVE   203
135 #define HTTP_STATUS_NO_CONTENT          204
136 #define HTTP_STATUS_RESET_CONTENT       205
137 #define HTTP_STATUS_PARTIAL_CONTENTS    206
138
139 /* Redirection 3xx.  */
140 #define HTTP_STATUS_MULTIPLE_CHOICES    300
141 #define HTTP_STATUS_MOVED_PERMANENTLY   301
142 #define HTTP_STATUS_MOVED_TEMPORARILY   302
143 #define HTTP_STATUS_SEE_OTHER           303
144 #define HTTP_STATUS_NOT_MODIFIED        304
145 #define HTTP_STATUS_USE_PROXY           305
146
147 /* Client error 4xx.  */
148 #define HTTP_STATUS_BAD_REQUEST         400
149 #define HTTP_STATUS_UNAUTHORIZED        401
150 #define HTTP_STATUS_PAYMENT_REQUIRED    402
151 #define HTTP_STATUS_FORBIDDEN           403
152 #define HTTP_STATUS_NOT_FOUND           404
153 #define HTTP_STATUS_METHOD_NOT_ALLOWED  405
154 #define HTTP_STATUS_NOT_ACCEPTABLE      406
155 #define HTTP_STATUS_PROXY_AUTH_REQUIRED 407
156 #define HTTP_STATUS_REQUEST_TIMEOUT     408
157 #define HTTP_STATUS_CONFLICT            409
158 #define HTTP_STATUS_GONE                410
159 #define HTTP_STATUS_LENGTH_REQUIRED     411
160 #define HTTP_STATUS_PRECONDITION_FAILED 412
161 #define HTTP_STATUS_REQENTITY_TOO_LARGE 413
162 #define HTTP_STATUS_REQURI_TOO_LARGE    414
163 #define HTTP_STATUS_UNSUPPORTED_MEDIA   415
164 #define HTTP_STATUS_LOCKED              423
165
166 /* Server errors 5xx.  */
167 #define HTTP_STATUS_INTERNAL            500
168 #define HTTP_STATUS_NOT_IMPLEMENTED     501
169 #define HTTP_STATUS_BAD_GATEWAY         502
170 #define HTTP_STATUS_UNAVAILABLE         503
171 #define HTTP_STATUS_GATEWAY_TIMEOUT     504
172 #define HTTP_STATUS_UNSUPPORTED_VERSION 505
173 #define HTTP_STATUS_INSUFFICIENT_STORAGE 507
174
175 /*
176  * Static Variables
177  */
178
179 /* Global variables used by the HTTP proxy config */ 
180 static GConfClient * gl_client = NULL;
181 static GMutex *gl_mutex = NULL;         /* This mutex protects preference values
182                                          * and ensures serialization of authentication
183                                          * hook callbacks
184                                          */
185 static gchar *gl_http_proxy = NULL;
186 static gchar *gl_http_proxy_auth = NULL;
187 static GSList *gl_ignore_hosts = NULL;  /* Elements are strings. */
188 static GSList *gl_ignore_addrs = NULL;  /* Elements are ProxyHostAddrs */
189
190 /* Store IP addresses that may represent network or host addresses and may be
191  * IPv4 or IPv6. */
192 typedef enum {
193         PROXY_IPv4 = 4,
194         PROXY_IPv6 = 6
195 } ProxyAddrType;
196
197 typedef struct {
198         ProxyAddrType type;
199         struct in_addr addr;
200         struct in_addr mask;
201 #ifdef ENABLE_IPV6
202         struct in6_addr addr6;
203         struct in6_addr mask6;
204 #endif
205 } ProxyHostAddr;
206
207 typedef struct {
208         GnomeVFSSocketBuffer *socket_buffer;
209         char *uri_string;
210         GnomeVFSURI *uri;
211         /* The list of headers returned with this response, newlines removed */
212         GList *response_headers;
213
214         /* File info for this file */
215         GnomeVFSFileInfo *file_info;
216
217         /* File offset of current pointer of 'socket_buffer'. */
218         GnomeVFSFileOffset socket_buffer_offset;
219
220         /* Offset; Current file position. */
221         GnomeVFSFileOffset offset;
222
223         /* Bytes to be written... */
224         GByteArray *to_be_written;
225
226         /* List of GnomeVFSFileInfo from a directory listing */
227         GList *files;
228
229         /* The last HTTP status code returned */
230         guint server_status;
231 } HttpFileHandle;
232
233 static GnomeVFSResult resolve_409                (GnomeVFSMethod *method,
234                                                   GnomeVFSURI *uri,
235                                                   GnomeVFSContext *context);
236 static void     proxy_set_authn                  (const char *username,
237                                                   const char *password);
238 static void     proxy_unset_authn                (void);
239 static gboolean invoke_callback_send_additional_headers (GnomeVFSURI *uri,
240                                                          GList **list);
241 static gboolean invoke_callback_headers_received (HttpFileHandle *handle);
242 static gboolean invoke_callback_basic_authn      (HttpFileHandle *handle, 
243                                                   enum AuthnHeaderType authn_which,
244                                                   gboolean previous_attempt_failed);
245 static gboolean check_authn_retry_request        (HttpFileHandle * http_handle,
246                                                   enum AuthnHeaderType authn_which,
247                                                   const char *prev_authn_header);
248 static void parse_ignore_host                    (gpointer data,
249                                                   gpointer user_data);
250 #ifdef ENABLE_IPV6
251 static void ipv6_network_addr                    (const struct in6_addr *addr,
252                                                   const struct in6_addr *mask,
253                                                   struct in6_addr *res);
254
255 /*Check whether the node is IPv6 enabled.*/
256 static gboolean
257 have_ipv6 (void)
258 {
259         int s;
260
261         s = socket (AF_INET6, SOCK_STREAM, 0);
262         if (s != -1) {
263                 close (s);
264                 return TRUE;
265         }
266
267         return FALSE;
268 }
269 #endif
270
271 static GnomeVFSFileInfo *
272 defaults_file_info_new (void)
273 {
274         GnomeVFSFileInfo *ret;
275
276         /* Fill up the file info structure with default values */
277         /* Default to REGULAR unless we find out later via a PROPFIND that it's a collection */
278
279         ret = gnome_vfs_file_info_new();
280
281         ret->type = GNOME_VFS_FILE_TYPE_REGULAR;
282         ret->flags = GNOME_VFS_FILE_FLAGS_NONE;
283
284         ret->valid_fields |= 
285                 GNOME_VFS_FILE_INFO_FIELDS_TYPE
286                         | GNOME_VFS_FILE_INFO_FIELDS_FLAGS;
287
288
289         return ret;
290 }
291
292 /* Does not allocate the 'handle' memory. */
293 static void
294 http_file_handle_new (HttpFileHandle *handle,
295                       GnomeVFSSocketBuffer *socket_buffer,
296                       GnomeVFSURI *uri)
297 {
298         memset (handle, 0, sizeof (*handle));
299
300         handle->socket_buffer = socket_buffer;
301         handle->uri_string = gnome_vfs_uri_to_string (uri, GNOME_VFS_URI_HIDE_NONE );
302         handle->uri = uri;
303         gnome_vfs_uri_ref(handle->uri);
304
305         handle->file_info = defaults_file_info_new();
306         handle->file_info->name = gnome_vfs_uri_extract_short_name (uri);
307 }
308
309 /* Does not free the 'handle' memory. */
310 static void
311 http_file_handle_destroy (HttpFileHandle *handle)
312 {
313         if (handle == NULL) {
314                 return;
315         }
316
317         gnome_vfs_uri_unref(handle->uri);
318         gnome_vfs_file_info_unref (handle->file_info);
319         g_free (handle->uri_string);
320         if (handle->to_be_written) {
321                 g_byte_array_free(handle->to_be_written, TRUE);
322         }
323
324         g_list_foreach (handle->response_headers, (GFunc) g_free, NULL);
325         g_list_free (handle->response_headers);
326
327         g_list_foreach(handle->files, (GFunc)gnome_vfs_file_info_unref, NULL);
328         g_list_free(handle->files);
329 }
330
331 /* The following comes from GNU Wget with minor changes by myself.
332    Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc.  */
333 /* Parse the HTTP status line, which is of format:
334
335    HTTP-Version SP Status-Code SP Reason-Phrase
336
337    The function returns the status-code, or -1 if the status line is
338    malformed.  The pointer to reason-phrase is returned in RP.  */
339 static gboolean
340 parse_status (const char *cline,
341               guint *status_return)
342 {
343         /* (the variables must not be named `major' and `minor', because
344            that breaks compilation with SunOS4 cc.)  */
345         guint mjr, mnr;
346         guint statcode;
347         const guchar *p, *line;
348
349         line = (const guchar *)cline;
350
351         /* The standard format of HTTP-Version is: `HTTP/X.Y', where X is
352            major version, and Y is minor version.  */
353         if (strncmp (line, "HTTP/", 5) == 0) {
354                 line += 5;
355                 
356                 /* Calculate major HTTP version.  */
357                 p = line;
358                 for (mjr = 0; g_ascii_isdigit (*line); line++)
359                         mjr = 10 * mjr + (*line - '0');
360                 if (*line != '.' || p == line)
361                         return FALSE;
362                 ++line;
363                 
364                 /* Calculate minor HTTP version.  */
365                 p = line;
366                 for (mnr = 0; g_ascii_isdigit (*line); line++)
367                         mnr = 10 * mnr + (*line - '0');
368                 if (*line != ' ' || p == line)
369                         return -1;
370                 /* Wget will accept only 1.0 and higher HTTP-versions.  The value of
371                    minor version can be safely ignored.  */
372                 if (mjr < 1)
373                         return FALSE;
374                 ++line;
375         } else if (strncmp (line, "ICY ", 4) == 0) {
376                 /* FIXME: workaround for broken ShoutCast and IceCast status replies.
377                  * They send things like "ICY 200 OK" instead of "HTTP/1.0 200 OK".
378                  * Is there a better way to handle this? 
379                  */
380                 mjr = 1;
381                 mnr = 0;
382                 line += 4;
383         } else {
384                 return FALSE;
385         }
386         
387         /* Calculate status code.  */
388         if (!(g_ascii_isdigit (*line) && g_ascii_isdigit (line[1]) && g_ascii_isdigit (line[2])))
389                 return -1;
390         statcode = 100 * (*line - '0') + 10 * (line[1] - '0') + (line[2] - '0');
391
392         *status_return = statcode;
393         return TRUE;
394 }
395
396 static GnomeVFSResult
397 http_status_to_vfs_result (guint status)
398 {
399         if (HTTP_20X (status))
400                 return GNOME_VFS_OK;
401
402         /* FIXME bugzilla.gnome.org 41163 */
403         /* mfleming--I've improved the situation slightly, but more
404          * test cases need to be written to ensure that HTTP (esp DAV) does compatibile
405          * things with the normal file method
406          */
407
408         switch (status) {
409         case HTTP_STATUS_PRECONDITION_FAILED:
410                 /* This mapping is certainly true for MOVE with Overwrite: F, otherwise not so true */
411                 return GNOME_VFS_ERROR_FILE_EXISTS;
412         case HTTP_STATUS_UNAUTHORIZED:
413         case HTTP_STATUS_PROXY_AUTH_REQUIRED:
414         case HTTP_STATUS_FORBIDDEN:
415                 /* Note that FORBIDDEN can also be returned on a MOVE in a case which
416                  * should be VFS_ERROR_BAD_PARAMETERS
417                  */
418                 return GNOME_VFS_ERROR_ACCESS_DENIED;
419         case HTTP_STATUS_NOT_FOUND:
420                 return GNOME_VFS_ERROR_NOT_FOUND;
421         case HTTP_STATUS_METHOD_NOT_ALLOWED:
422                 /* Note that METHOD_NOT_ALLOWED is also returned in a PROPFIND in a case which
423                  * should be FILE_EXISTS.  This is handled in do_make_directory
424                  */
425         case HTTP_STATUS_BAD_REQUEST:
426         case HTTP_STATUS_NOT_IMPLEMENTED:
427         case HTTP_STATUS_UNSUPPORTED_VERSION:
428                 return GNOME_VFS_ERROR_NOT_SUPPORTED;
429         case HTTP_STATUS_CONFLICT:
430                 /* _CONFLICT's usually happen when collection paths don't exist */
431                 return GNOME_VFS_ERROR_NOT_FOUND;
432         case HTTP_STATUS_LOCKED:
433                 /* Maybe we need a separate GNOME_VFS_ERROR_LOCKED? */
434                 return GNOME_VFS_ERROR_DIRECTORY_BUSY;
435         case HTTP_STATUS_INSUFFICIENT_STORAGE:
436                 return GNOME_VFS_ERROR_NO_SPACE;
437         default:
438                 return GNOME_VFS_ERROR_GENERIC;
439         }
440 }
441
442 /* Header parsing routines.  */
443
444 static gboolean
445 header_value_to_number (const char *header_value,
446                         gulong *number)
447 {
448         const char *p;
449         gulong result;
450
451         p = header_value;
452
453         for (result = 0; g_ascii_isdigit (*p); p++)
454                 result = 10 * result + (*p - '0');
455         if (*p)
456                 return FALSE;
457
458         *number = result;
459
460         return TRUE;
461 }
462
463 static gboolean
464 set_content_length (HttpFileHandle *handle,
465                     const char *value)
466 {
467         gboolean result;
468         gulong size;
469
470         result = header_value_to_number (value, &size);
471         if (! result)
472                 return FALSE;
473
474         DEBUG_HTTP (("Expected size is %lu.", size));
475         handle->file_info->size = size;
476         handle->file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_SIZE;
477         return TRUE;
478 }
479
480 static char *
481 strip_semicolon (const char *value)
482 {
483         char *p;
484
485         p = strchr (value, ';');
486
487         if (p != NULL) {
488                 return g_strndup (value, p - value);
489         }
490         else {
491                 return g_strdup (value);
492         }
493 }
494
495 static gboolean
496 set_content_type (HttpFileHandle *handle,
497                   const char *value)
498 {
499         g_free (handle->file_info->mime_type);
500
501         handle->file_info->mime_type = strip_semicolon (value);
502         handle->file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE;
503         
504         return TRUE;
505 }
506
507 static gboolean
508 set_last_modified (HttpFileHandle *handle,
509                    const char *value)
510 {
511         time_t time;
512
513         if (! gnome_vfs_atotm (value, &time))
514                 return FALSE;
515
516         handle->file_info->mtime = time;
517         handle->file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_MTIME;
518         return TRUE;
519 }
520
521 static gboolean
522 set_access_time (HttpFileHandle *handle,
523                  const char *value)
524 {
525         time_t time;
526
527         if (! gnome_vfs_atotm (value, &time))
528                 return FALSE;
529
530         handle->file_info->atime = time;
531         handle->file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_ATIME;
532         return TRUE;
533 }
534
535 struct _Header {
536         const char *name;
537         gboolean (* set_func) (HttpFileHandle *handle, const char *value);
538 };
539 typedef struct _Header Header;
540
541 static Header headers[] = {
542         { "Content-Length", set_content_length },
543         { "Content-Type", set_content_type },
544         { "Last-Modified", set_last_modified },
545         { "Date", set_access_time },
546         { NULL, NULL }
547 };
548
549 static const char *
550 check_header (const char *header,
551               const char *name)
552 {
553         const char *p, *q;
554
555         for (p = header, q = name; *p != '\0' && *q != '\0'; p++, q++) {
556                 if (g_ascii_tolower (*p) != g_ascii_tolower (*q))
557                         break;
558         }
559
560         if (*q != '\0' || *p != ':')
561                 return NULL;
562
563         p++;                    /* Skip ':'.  */
564         while (*p == ' ' || *p == '\t')
565                 p++;
566
567         return p;
568 }
569
570 static gboolean
571 parse_header (HttpFileHandle *handle,
572               const char *header)
573 {
574         guint i;
575
576         for (i = 0; headers[i].name != NULL; i++) {
577                 const char *value;
578
579                 value = check_header (header, headers[i].name);
580                 if (value != NULL)
581                         return (* headers[i].set_func) (handle, value);
582         }
583
584         /* Simply ignore headers we don't know.  */
585         return TRUE;
586 }
587
588 /* Header/status reading.  */
589
590 static GnomeVFSResult
591 get_header (GnomeVFSSocketBuffer *socket_buffer,
592             GString *s)
593 {
594         GnomeVFSResult result;
595         GnomeVFSFileSize bytes_read;
596         guint count;
597
598         ANALYZE_HTTP ("==> +get_header");
599
600         g_string_truncate (s, 0);
601
602         count = 0;
603         while (1) {
604                 char c;
605
606                 /* ANALYZE_HTTP ("==> +get_header read"); */
607                 result = gnome_vfs_socket_buffer_read (socket_buffer, &c, 1,
608                                 &bytes_read);
609                 /* ANALYZE_HTTP ("==> -get_header read"); */
610
611                 if (result != GNOME_VFS_OK) {
612                         return result;
613                 }
614                 if (bytes_read == 0) {
615                         return GNOME_VFS_ERROR_EOF;
616                 }
617
618                 if (c == '\n') {
619                         /* Handle continuation lines.  */
620                         if (count != 0 && (count != 1 || s->str[0] != '\r')) {
621                                 char next;
622
623                                 result = gnome_vfs_socket_buffer_peekc (
624                                                 socket_buffer, &next);
625                                 if (result != GNOME_VFS_OK) {
626                                         return result;
627                                 }
628                                 
629                                 if (next == '\t' || next == ' ') {
630                                         if (count > 0
631                                             && s->str[count - 1] == '\r')
632                                                 s->str[count - 1] = '\0';
633                                         continue;
634                                 }
635                         }
636
637                         if (count > 0 && s->str[count - 1] == '\r')
638                                 s->str[count - 1] = '\0';
639                         break;
640                 } else {
641                         g_string_append_c (s, c);
642                 }
643
644                 count++;
645         }
646         
647
648         ANALYZE_HTTP ("==> -get_header");
649
650         return GNOME_VFS_OK;
651 }
652
653 /* rename this function? */
654 static GnomeVFSResult
655 create_handle (GnomeVFSURI *uri,
656                GnomeVFSSocketBuffer *socket_buffer,
657                GnomeVFSContext *context,
658                /* OUT */ HttpFileHandle *handle)
659 {
660         GString *header_string;
661         GnomeVFSResult result;
662         guint server_status;
663
664         g_return_val_if_fail (handle != NULL, GNOME_VFS_ERROR_INTERNAL);
665
666         http_file_handle_new (handle, socket_buffer, uri);
667
668         header_string = g_string_new (NULL);
669
670         ANALYZE_HTTP ("==> +create_handle");
671
672         /* This is the status report string, which is the first header.  */
673         result = get_header (socket_buffer, header_string);
674         if (result != GNOME_VFS_OK) {
675                 goto error;
676         }
677
678         if (!parse_status (header_string->str, &server_status)) {
679                 /* An unparsable status line is fatal */
680                 result = GNOME_VFS_ERROR_GENERIC;
681                 goto error;
682         }
683
684         handle->server_status = server_status;
685
686         ANALYZE_HTTP ("==> +create_handle: fetching headers");
687
688         /* Header fetching loop.  */
689         for (;;) {
690                 result = get_header (socket_buffer, header_string);
691                 if (result != GNOME_VFS_OK) {
692                         break;
693                 }
694
695                 /* Empty header ends header section.  */
696                 if (header_string->str[0] == '\0') {
697                         break;
698                 }
699
700                 handle->response_headers = g_list_prepend (handle->response_headers, 
701                                                         g_strdup (header_string->str));
702
703                 /* We don't really care if we successfully parse the
704                  * header or not. It might be nice to tell someone we
705                  * found a header we can't parse, but it's not clear
706                  * who would be interested or how we tell them. In the
707                  * past we would return NOT_FOUND if any header could
708                  * not be parsed, but that seems wrong.
709                  */
710                 parse_header (handle, header_string->str);
711         }
712
713         invoke_callback_headers_received (handle);
714
715         ANALYZE_HTTP ("==> -create_handle: fetching headers");
716
717         if (result != GNOME_VFS_OK) {
718                 goto error;
719         }
720
721         if (! HTTP_20X (server_status) && !HTTP_REDIRECTED(server_status)) {
722                 result = http_status_to_vfs_result (server_status);
723                 goto error;
724         }
725
726         result = GNOME_VFS_OK;
727  error:
728         g_string_free (header_string, TRUE);
729
730         ANALYZE_HTTP ("==> -create_handle");
731         return result;
732 }
733
734 /*
735  * Here's how the gconf gnome-vfs HTTP proxy variables
736  * are intended to be used
737  *
738  * /system/http_proxy/use_http_proxy    
739  *      Type: boolean
740  *      If set to TRUE, the client should use an HTTP proxy to connect to all
741  *      servers (except those specified in the ignore_hosts key -- see below).
742  *      The proxy is specified in other gconf variables below.
743  *
744  * /system/http_proxy/host
745  *      Type: string
746  *      The hostname of the HTTP proxy this client should use.  If
747  *      use-http-proxy is TRUE, this should be set.  If it is not set, the
748  *      application should behave as if use-http-proxy is was set to FALSE.
749  *
750  * /system/http_proxy/port
751  *      Type: int
752  *      The port number on the HTTP proxy host that the client should connect to
753  *      If use_http_proxy and host are set but this is not set, the application
754  *      should use a default port value of 8080
755  *
756  * /system/http_proxy/authentication-user
757  *      Type: string
758  *      Username to pass to an authenticating HTTP proxy.
759  *
760  * /system/http_proxy/authentication_password
761  *      Type: string
762  *      Password to pass to an authenticating HTTP proxy.
763  *  
764  * /system/http_proxy/use-authentication
765  *      Type: boolean
766  *      TRUE if the client should pass http-proxy-authorization-user and
767  *      http-proxy-authorization-password an HTTP proxy
768  *
769  * /system/http_proxy/ignore_hosts
770  *      Type: list of strings
771  *      A list of hosts (hostnames, wildcard domains, IP addresses, and CIDR
772  *      network addresses) that should be accessed directly.
773  */
774
775 static void
776 construct_gl_http_proxy (gboolean use_proxy)
777 {
778         g_free (gl_http_proxy);
779         gl_http_proxy = NULL;
780
781         g_slist_foreach (gl_ignore_hosts, (GFunc) g_free, NULL);
782         g_slist_free (gl_ignore_hosts);
783         gl_ignore_hosts = NULL;
784         g_slist_foreach (gl_ignore_addrs, (GFunc) g_free, NULL);
785         g_slist_free (gl_ignore_addrs);
786         gl_ignore_addrs = NULL;
787
788         if (use_proxy) {
789                 char *proxy_host;
790                 int   proxy_port;
791                 GSList *ignore;
792
793                 proxy_host = gconf_client_get_string (gl_client, KEY_GCONF_HTTP_PROXY_HOST, NULL);
794                 proxy_port = gconf_client_get_int (gl_client, KEY_GCONF_HTTP_PROXY_PORT, NULL);
795
796                 if (proxy_host) {
797                         if (0 != proxy_port && 0xffff >= (unsigned) proxy_port) {
798                                 gl_http_proxy = g_strdup_printf ("%s:%u", proxy_host, (unsigned)proxy_port);
799                         } else {
800                                 gl_http_proxy = g_strdup_printf ("%s:%u", proxy_host, (unsigned)DEFAULT_HTTP_PROXY_PORT);
801                         }
802                         DEBUG_HTTP (("New HTTP proxy: '%s'", gl_http_proxy));
803                 } else {
804                         DEBUG_HTTP (("HTTP proxy unset"));
805                 }
806                 
807                 g_free (proxy_host);
808                 proxy_host = NULL;
809
810                 ignore = gconf_client_get_list (gl_client, KEY_GCONF_HTTP_PROXY_IGNORE_HOSTS, GCONF_VALUE_STRING, NULL);
811                 g_slist_foreach (ignore, (GFunc) parse_ignore_host, NULL);
812                 g_slist_foreach (ignore, (GFunc) g_free, NULL);
813                 g_slist_free (ignore);
814                 ignore = NULL;
815         }
816 }
817
818 static void
819 parse_ignore_host (gpointer data, gpointer user_data)
820 {
821         gchar *hostname, *input, *netmask;
822         gboolean ip_addr = FALSE, has_error = FALSE;
823         struct in_addr host, mask;
824 #ifdef ENABLE_IPV6
825         struct in6_addr host6, mask6;
826 #endif
827         ProxyHostAddr *elt;
828         gint i;
829
830         input = (gchar*) data;
831         elt = g_new0 (ProxyHostAddr, 1);
832         if ((netmask = strchr (input, '/')) != NULL) {
833                 hostname = g_strndup (input, netmask - input);
834                 ++netmask;
835         }
836         else {
837                 hostname = g_ascii_strdown (input, -1);
838         }
839         if (inet_pton (AF_INET, hostname, &host) > 0) {
840                 ip_addr = TRUE;
841                 elt->type = PROXY_IPv4;
842                 elt->addr.s_addr = host.s_addr;
843                 if (netmask) {
844                         gchar *endptr;
845                         gint width = strtol (netmask, &endptr, 10);
846
847                         if (*endptr != '\0' || width < 0 || width > 32) {
848                                 has_error = TRUE;
849                         }
850                         elt->mask.s_addr = htonl(~0 << width);
851                         elt->addr.s_addr &= mask.s_addr;
852                 }
853                 else {
854                         elt->mask.s_addr = 0xffffffff;
855                 }
856         }
857 #ifdef ENABLE_IPV6
858         else if (have_ipv6 () && inet_pton (AF_INET6, hostname, &host6) > 0) {
859                 ip_addr = TRUE;
860                 elt->type = PROXY_IPv6;
861                 for (i = 0; i < 16; ++i) {
862                         elt->addr6.s6_addr[i] = host6.s6_addr[i];
863                 }
864                 if (netmask) {
865                         gchar *endptr;
866                         gint width = strtol (netmask, &endptr, 10);
867
868                         if (*endptr != '\0' || width < 0 || width > 128) {
869                                 has_error = TRUE;
870                         }
871                         for (i = 0; i < 16; ++i) {
872                                 elt->mask6.s6_addr[i] = 0;
873                         }
874                         for (i=0; i < width/8; i++) {
875                                 elt->mask6.s6_addr[i] = 0xff;
876                         }
877                         elt->mask6.s6_addr[i] = (0xff << (8 - width % 8)) & 0xff;
878                         ipv6_network_addr (&elt->addr6, &mask6, &elt->addr6);
879                 }
880                 else {
881                         for (i = 0; i < 16; ++i) {
882                                 elt->mask6.s6_addr[i] = 0xff;
883                         }
884                 }
885         }
886 #endif
887
888         if (ip_addr) {
889                 if (!has_error) {
890                         gchar *dst = g_new0 (gchar, INET_ADDRSTRLEN);
891         
892                         gl_ignore_addrs = g_slist_append (gl_ignore_addrs, elt);
893                         DEBUG_HTTP (("Host %s/%s does not go through proxy.",
894                                         hostname,
895                                         inet_ntop(AF_INET, &elt->mask, dst, INET_ADDRSTRLEN)));
896                         g_free (dst);
897                 }
898         }
899         else {
900                 /* It is a hostname. */
901                 gl_ignore_hosts = g_slist_append (gl_ignore_hosts, hostname);
902                 DEBUG_HTTP (("Host %s does not go through proxy.", hostname));
903         }
904 }
905
906 static void
907 set_proxy_auth (gboolean use_proxy_auth)
908 {
909         char *auth_user;
910         char *auth_pw;
911
912         auth_user = gconf_client_get_string (gl_client, KEY_GCONF_HTTP_AUTH_USER, NULL);
913         auth_pw = gconf_client_get_string (gl_client, KEY_GCONF_HTTP_AUTH_PW, NULL);
914
915         if (use_proxy_auth) {
916                 proxy_set_authn (auth_user, auth_pw);
917                 DEBUG_HTTP (("New HTTP proxy auth user: '%s'", auth_user));
918         } else {
919                 proxy_unset_authn ();
920                 DEBUG_HTTP (("HTTP proxy auth unset"));
921         }
922
923         g_free (auth_user);
924         g_free (auth_pw);
925 }
926
927 /**
928  * sig_gconf_value_changed 
929  * GGconf notify function for when HTTP proxy GConf key has changed.
930  */
931 static void
932 notify_gconf_value_changed (GConfClient *client,
933                             guint        cnxn_id,
934                             GConfEntry  *entry,
935                             gpointer     data)
936 {
937         const char *key;
938
939         key = gconf_entry_get_key (entry);
940
941         if (strcmp (key, KEY_GCONF_USE_HTTP_PROXY) == 0
942             || strcmp (key, KEY_GCONF_HTTP_PROXY_IGNORE_HOSTS) == 0
943             || strcmp (key, KEY_GCONF_HTTP_PROXY_HOST) == 0
944             || strcmp (key, KEY_GCONF_HTTP_PROXY_PORT) == 0) {
945                 gboolean use_proxy_value;
946                 
947                 g_mutex_lock (gl_mutex);
948                 
949                 /* Check and see if we are using the proxy */
950                 use_proxy_value = gconf_client_get_bool (gl_client, KEY_GCONF_USE_HTTP_PROXY, NULL);
951                 construct_gl_http_proxy (use_proxy_value);
952                 
953                 g_mutex_unlock (gl_mutex);
954         } else if (strcmp (key, KEY_GCONF_HTTP_AUTH_USER) == 0
955             || strcmp (key, KEY_GCONF_HTTP_AUTH_PW) == 0
956             || strcmp (key, KEY_GCONF_HTTP_USE_AUTH) == 0) {
957                 gboolean use_proxy_auth;
958
959                 g_mutex_lock (gl_mutex);
960                 
961                 use_proxy_auth = gconf_client_get_bool (gl_client, KEY_GCONF_HTTP_USE_AUTH, NULL);
962                 set_proxy_auth (use_proxy_auth);
963
964                 g_mutex_unlock (gl_mutex);
965         }
966 }
967
968 /**
969  * host_port_from_string
970  * splits a <host>:<port> formatted string into its separate components
971  */
972 static gboolean
973 host_port_from_string (const char *http_proxy,
974                        char **p_proxy_host, 
975                        guint *p_proxy_port)
976 {
977         char *port_part;
978         
979         port_part = strchr (http_proxy, ':');
980         
981         if (port_part && '\0' != ++port_part && p_proxy_port) {
982                 *p_proxy_port = (guint) strtoul (port_part, NULL, 10);
983         } else if (p_proxy_port) {
984                 *p_proxy_port = DEFAULT_HTTP_PROXY_PORT;
985         }
986         
987         if (p_proxy_host) {
988                 if ( port_part != http_proxy ) {
989                         *p_proxy_host = g_strndup (http_proxy, port_part - http_proxy - 1);
990                 } else {
991                         return FALSE;
992                 }
993         }
994
995         return TRUE;
996 }
997
998 /* FIXME: should be done using AC_REPLACE_FUNCS */
999 #ifndef HAVE_INET_PTON
1000 static int
1001 inet_pton(int af, const char *hostname, void *pton)
1002 {
1003         struct in_addr in;
1004         if (!inet_aton(hostname, &in))
1005             return 0;
1006         memcpy(pton, &in, sizeof(in));
1007         return 1;
1008 }
1009 #endif
1010
1011 #ifdef ENABLE_IPV6
1012 static void
1013 ipv6_network_addr (const struct in6_addr *addr, const struct in6_addr *mask, struct in6_addr *res)
1014 {
1015         gint i;
1016
1017         for (i = 0; i < 16; ++i) {
1018                 res->s6_addr[i] = addr->s6_addr[i] & mask->s6_addr[i];
1019         }
1020 }
1021 #endif
1022
1023 static gboolean
1024 proxy_should_for_hostname (const char *hostname)
1025 {
1026 #ifdef ENABLE_IPV6
1027         struct in6_addr in6, net6;
1028 #endif
1029         struct in_addr in;
1030         GSList *elt;
1031         ProxyHostAddr *addr;
1032
1033
1034         /* IPv4 address */
1035         if (inet_pton (AF_INET, hostname, &in) > 0) {
1036                 for (elt = gl_ignore_addrs; elt; elt = g_slist_next (elt)) {
1037                         addr = (ProxyHostAddr*) (elt->data);
1038                         if (addr->type == PROXY_IPv4
1039                             && (in.s_addr & addr->mask.s_addr) == addr->addr.s_addr) {
1040                                 DEBUG_HTTP (("Host %s using direct connection.", hostname)); 
1041                                 return FALSE;
1042                         }
1043                 }
1044         }
1045 #ifdef ENABLE_IPV6
1046         else if (have_ipv6 () && inet_pton (AF_INET6, hostname, &in6)) {
1047                 for (elt = gl_ignore_addrs; elt; elt = g_slist_next (elt)) {
1048                         addr = (ProxyHostAddr*) (elt->data);
1049                         ipv6_network_addr (&in6, &addr->mask6, &net6);
1050                         if (addr->type == PROXY_IPv6 
1051                             && IN6_ARE_ADDR_EQUAL (&net6, &addr->addr6)) {
1052                                 DEBUG_HTTP (("Host %s using direct connection.", hostname)); 
1053                                 return FALSE;
1054                         }
1055                         /* Handle IPv6-wrapped IPv4 addresses. */
1056                         else if (addr->type == PROXY_IPv4
1057                                  && IN6_IS_ADDR_V4MAPPED (&net6)) {
1058                                 guint32 v4addr;
1059
1060                                 v4addr = net6.s6_addr[12] << 24 | net6.s6_addr[13] << 16 | net6.s6_addr[14] << 8 | net6.s6_addr[15];
1061                                 if ((v4addr & addr->mask.s_addr) != addr->addr.s_addr) {
1062                                         DEBUG_HTTP (("Host %s using direct connection.", hostname)); 
1063                                         return FALSE;
1064                                 }
1065                         }
1066                 }
1067         }
1068 #endif
1069         /* All hostnames (foo.bar.com) -- independent of IPv4 or IPv6 */
1070
1071         /* If there are IPv6 addresses in the ignore_hosts list but we do not
1072          * have IPv6 available at runtime, then those addresses will also fall
1073          * through to here (and harmlessly fail to match). */
1074         else {
1075                 gchar *hn = g_ascii_strdown (hostname, -1);
1076
1077                 for (elt = gl_ignore_hosts; elt; elt = g_slist_next (elt)) {
1078                         if (*(gchar*) (elt->data) == '*' ) {
1079                                 if (g_str_has_suffix (hn,
1080                                                 (gchar*) (elt->data) + 1)) {
1081                                         DEBUG_HTTP (("Host %s using direct connection.", hn));
1082                                         g_free (hn);
1083                                         return FALSE;
1084                                 }
1085                         }
1086                         else if (strcmp (hn, elt->data) == 0) {
1087                                 DEBUG_HTTP (("Host %s using direct connection.", hn));
1088                                 g_free (hn);
1089                                 return FALSE;
1090                         }
1091                 }
1092         }
1093
1094         return TRUE;
1095 }
1096
1097 static char *
1098 proxy_get_authn_header_for_uri_nolock (GnomeVFSURI * uri)
1099 {
1100         char * ret;
1101
1102         ret = NULL;
1103
1104         /* FIXME this needs to be atomic */     
1105         if (gl_http_proxy_auth != NULL) {
1106                 ret = g_strdup_printf ("Proxy-Authorization: Basic %s\r\n", gl_http_proxy_auth);
1107         }
1108
1109         return ret;
1110 }
1111
1112 static char *
1113 proxy_get_authn_header_for_uri (GnomeVFSURI * uri)
1114 {
1115         char * ret;
1116
1117         g_mutex_lock (gl_mutex);
1118
1119         ret = proxy_get_authn_header_for_uri_nolock (uri);
1120
1121         g_mutex_unlock (gl_mutex);
1122         
1123         return ret;
1124 }
1125
1126 /**
1127  * proxy_for_uri
1128  * Retrives an appropriate HTTP proxy for a given toplevel uri
1129  * Currently, only a single HTTP proxy is implemented (there's no way for
1130  * specifying non-proxy domain names's).  Returns FALSE if the connect should
1131  * take place directly
1132  */
1133 static gboolean
1134 proxy_for_uri (
1135         GnomeVFSToplevelURI * toplevel_uri,
1136         gchar **p_proxy_host,           /* Callee must free */
1137         guint *p_proxy_port)            /* Callee must free */
1138 {
1139         gboolean ret;
1140         
1141         ret = proxy_should_for_hostname (toplevel_uri->host_name);
1142
1143         g_mutex_lock (gl_mutex);
1144
1145         if (ret && gl_http_proxy != NULL) {
1146                 ret = host_port_from_string (gl_http_proxy, p_proxy_host, p_proxy_port);
1147         } else {
1148                 p_proxy_host = NULL;
1149                 p_proxy_port = NULL;
1150                 ret = FALSE;
1151         }
1152
1153         g_mutex_unlock (gl_mutex);
1154
1155         return ret;
1156 }
1157
1158 static void
1159 proxy_set_authn (const char *username, const char *password)
1160 {
1161         char * credentials;
1162
1163         g_free (gl_http_proxy_auth);
1164         gl_http_proxy_auth = NULL;
1165
1166         credentials = g_strdup_printf ("%s:%s", 
1167                         username == NULL ? "" : username, 
1168                         password == NULL ? "" : password);
1169
1170         gl_http_proxy_auth = http_util_base64 (credentials);
1171
1172         g_free (credentials);
1173 }
1174
1175 static void
1176 proxy_unset_authn (void)
1177 {
1178         g_free (gl_http_proxy_auth);
1179         gl_http_proxy_auth = NULL;
1180 }
1181
1182
1183 static GnomeVFSResult
1184 https_proxy (GnomeVFSSocket **socket_return,
1185              gchar *proxy_host,
1186              gint proxy_port,
1187              gchar *server_host,
1188              gint server_port)
1189 {
1190         /* use CONNECT to do https proxying. It goes something like this:
1191          * >CONNECT server:port HTTP/1.0
1192          * >
1193          * <HTTP/1.0 200 Connection-established
1194          * <Proxy-agent: Apache/1.3.19 (Unix) Debian/GNU
1195          * <
1196          * and then we've got an open connection.
1197          *
1198          * So we sent "CONNECT server:port HTTP/1.0\r\n\r\n"
1199          * Check the HTTP status.
1200          * Wait for "\r\n\r\n"
1201          * Start doing the SSL dance.
1202          */
1203
1204         GnomeVFSResult result;
1205         GnomeVFSInetConnection *http_connection;
1206         GnomeVFSSocket *http_socket;
1207         GnomeVFSSocket *https_socket;
1208         GnomeVFSSSL *ssl;
1209         char *buffer;
1210         GnomeVFSFileSize bytes;
1211         guint status_code;
1212         gint fd;
1213
1214         result = gnome_vfs_inet_connection_create (&http_connection, 
1215                         proxy_host, proxy_port, NULL);
1216
1217         if (result != GNOME_VFS_OK) {
1218                 return result;
1219         }
1220
1221         fd = gnome_vfs_inet_connection_get_fd (http_connection);
1222
1223         http_socket = gnome_vfs_inet_connection_to_socket (http_connection);
1224
1225         buffer = g_strdup_printf ("CONNECT %s:%d HTTP/1.0\r\n\r\n",
1226                         server_host, server_port);
1227         result = gnome_vfs_socket_write (http_socket, buffer, strlen(buffer),
1228                         &bytes);
1229         g_free (buffer);
1230
1231         if (result != GNOME_VFS_OK) {
1232                 gnome_vfs_socket_close (http_socket);
1233                 return result;
1234         }
1235
1236         buffer = proxy_get_authn_header_for_uri (NULL); /* FIXME need uri */
1237         if (buffer != NULL) {
1238                 result = gnome_vfs_socket_write (http_socket, buffer, 
1239                                 strlen(buffer), &bytes);
1240                 g_free (buffer);
1241         }
1242
1243         if (result != GNOME_VFS_OK) {
1244                 gnome_vfs_socket_close (http_socket);
1245                 return result;
1246         }
1247
1248         bytes = 8192;
1249         buffer = g_malloc0 (bytes);
1250
1251         result = gnome_vfs_socket_read (http_socket, buffer, bytes-1, &bytes);
1252
1253         if (result != GNOME_VFS_OK) {
1254                 gnome_vfs_socket_close (http_socket);
1255                 g_free (buffer);
1256                 return result;
1257         }
1258
1259         if (!parse_status (buffer, &status_code)) {
1260                 gnome_vfs_socket_close (http_socket);
1261                 g_free (buffer);
1262                 return GNOME_VFS_ERROR_PROTOCOL_ERROR;
1263         }
1264
1265         result = http_status_to_vfs_result (status_code);
1266
1267         if (result != GNOME_VFS_OK) {
1268                 gnome_vfs_socket_close (http_socket);
1269                 g_free (buffer);
1270                 return result;
1271         }
1272
1273         /* okay - at this point we've read some stuff from the socket.. */
1274         /* FIXME: for now we'll assume thats all the headers and nothing but. */
1275
1276         g_free (buffer);
1277
1278         result = gnome_vfs_ssl_create_from_fd (&ssl, fd);
1279
1280         if (result != GNOME_VFS_OK) {
1281                 gnome_vfs_socket_close (http_socket);
1282                 return result;
1283         }
1284
1285         https_socket = gnome_vfs_ssl_to_socket (ssl);
1286
1287         *socket_return = https_socket;
1288
1289         return GNOME_VFS_OK;
1290 }
1291
1292
1293
1294 static GnomeVFSResult
1295 connect_to_uri (
1296         GnomeVFSToplevelURI *toplevel_uri, 
1297         /* OUT */ GnomeVFSSocketBuffer **p_socket_buffer,
1298         /* OUT */ gboolean * p_proxy_connect)
1299 {
1300         guint host_port;
1301         char *proxy_host;
1302         guint proxy_port;
1303         GnomeVFSResult result;
1304         GnomeVFSCancellation * cancellation;
1305         GnomeVFSInetConnection *connection;
1306         GnomeVFSSSL *ssl;
1307         GnomeVFSSocket *socket;
1308         gboolean https = FALSE;
1309
1310         cancellation = gnome_vfs_context_get_cancellation (
1311                                 gnome_vfs_context_peek_current ());
1312
1313         g_return_val_if_fail (p_socket_buffer != NULL, GNOME_VFS_ERROR_INTERNAL);
1314         g_return_val_if_fail (p_proxy_connect != NULL, GNOME_VFS_ERROR_INTERNAL);
1315         g_return_val_if_fail (toplevel_uri != NULL, GNOME_VFS_ERROR_INTERNAL);
1316
1317         if (!g_ascii_strcasecmp (gnome_vfs_uri_get_scheme (&toplevel_uri->uri), 
1318                                 "https")) {
1319                 if (!gnome_vfs_ssl_enabled ()) {
1320                         return GNOME_VFS_ERROR_NOT_SUPPORTED;
1321                 }
1322                 https = TRUE;
1323         }
1324
1325         if (toplevel_uri->host_port == 0) {
1326                 if (https) {
1327                         host_port = DEFAULT_HTTPS_PORT;
1328                 } else {
1329                         host_port = DEFAULT_HTTP_PORT;
1330                 }
1331         } else {
1332                 host_port = toplevel_uri->host_port;
1333         }
1334
1335         ANALYZE_HTTP ("==> +Making connection");
1336
1337         if (toplevel_uri->host_name == NULL) {
1338                 result = GNOME_VFS_ERROR_INVALID_URI;
1339                 goto error;
1340         }
1341
1342         if (proxy_for_uri (toplevel_uri, &proxy_host, &proxy_port)) {
1343                 if (https) {
1344                         *p_proxy_connect = FALSE;
1345
1346                         result = https_proxy (&socket, proxy_host, proxy_port,
1347                                         toplevel_uri->host_name, host_port);
1348
1349                         g_free (proxy_host);
1350                         proxy_host = NULL;
1351
1352                         if (result != GNOME_VFS_OK) {
1353                                 return result;
1354                         }
1355
1356                 } else {
1357                         *p_proxy_connect = TRUE;
1358
1359                         result = gnome_vfs_inet_connection_create (&connection,
1360                                                         proxy_host,
1361                                                         proxy_port, 
1362                                                         cancellation);
1363                         if (result != GNOME_VFS_OK) {
1364                                 return result;
1365                         }
1366                         socket = gnome_vfs_inet_connection_to_socket 
1367                                                                 (connection);
1368
1369                         g_free (proxy_host);
1370                         proxy_host = NULL;
1371                 }
1372         } else {
1373                 *p_proxy_connect = FALSE;
1374
1375                 if (https) {
1376                         result = gnome_vfs_ssl_create (&ssl, 
1377                                         toplevel_uri->host_name, host_port);
1378
1379                         if (result != GNOME_VFS_OK) {
1380                                 return result;
1381                         }
1382                         socket = gnome_vfs_ssl_to_socket (ssl);
1383                 } else {
1384                         result = gnome_vfs_inet_connection_create (&connection,
1385                                                    toplevel_uri->host_name,
1386                                                    host_port,
1387                                                    cancellation);
1388                         if (result != GNOME_VFS_OK) {
1389                                 return result;
1390                         }
1391                         socket = gnome_vfs_inet_connection_to_socket 
1392                                                                 (connection);
1393                 }
1394         }
1395
1396         *p_socket_buffer = gnome_vfs_socket_buffer_new (socket);
1397
1398         if (*p_socket_buffer == NULL) {
1399                 gnome_vfs_socket_close (socket);
1400                 return GNOME_VFS_ERROR_INTERNAL;
1401         }
1402
1403         ANALYZE_HTTP ("==> -Making connection");
1404
1405 error:
1406         return result;
1407 }
1408
1409 static GString *
1410 build_request (const char * method, GnomeVFSToplevelURI * toplevel_uri, gboolean proxy_connect)
1411 {
1412         gchar *uri_string = NULL;
1413         GString *request;
1414         GnomeVFSURI *uri;
1415         gchar *user_agent;
1416
1417         uri = (GnomeVFSURI *)toplevel_uri;
1418
1419         if (proxy_connect) {
1420                 uri_string = gnome_vfs_uri_to_string (uri,
1421                                                       GNOME_VFS_URI_HIDE_USER_NAME
1422                                                       | GNOME_VFS_URI_HIDE_PASSWORD);
1423
1424         } else {
1425                 uri_string = gnome_vfs_uri_to_string (uri,
1426                                                       GNOME_VFS_URI_HIDE_USER_NAME
1427                                                       | GNOME_VFS_URI_HIDE_PASSWORD
1428                                                       | GNOME_VFS_URI_HIDE_HOST_NAME
1429                                                       | GNOME_VFS_URI_HIDE_HOST_PORT
1430                                                       | GNOME_VFS_URI_HIDE_TOPLEVEL_METHOD);
1431         }
1432
1433         /* Request line.  */
1434         request = g_string_new ("");
1435
1436         g_string_append_printf (request, "%s %s%s HTTP/1.0\r\n", method, uri_string,
1437                                 gnome_vfs_uri_get_path (uri)[0] == '\0' ? "/" : "" );
1438
1439         DEBUG_HTTP (("-->Making request '%s %s'", method, uri_string));
1440         
1441         g_free (uri_string);
1442         uri_string = NULL;
1443
1444         /* `Host:' header.  */
1445         if(toplevel_uri->host_port && toplevel_uri->host_port != 0) {
1446                 g_string_append_printf (request, "Host: %s:%d\r\n",
1447                                         toplevel_uri->host_name, toplevel_uri->host_port);
1448         } else {
1449                 g_string_append_printf (request, "Host: %s:80\r\n",
1450                                         toplevel_uri->host_name);
1451         }
1452
1453         /* `Accept:' header.  */
1454         g_string_append (request, "Accept: */*\r\n");
1455
1456         /* `User-Agent:' header.  */
1457         user_agent = getenv (CUSTOM_USER_AGENT_VARIABLE);
1458
1459         if(user_agent == NULL) {
1460                 user_agent = USER_AGENT_STRING;
1461         }
1462
1463         g_string_append_printf (request, "User-Agent: %s\r\n", user_agent);
1464
1465         return request;
1466 }
1467
1468 static GnomeVFSResult
1469 xmit_request (GnomeVFSSocketBuffer *socket_buffer, 
1470               GString *request, 
1471               GByteArray *data)
1472 {
1473         GnomeVFSResult result;
1474         GnomeVFSFileSize bytes_written;
1475
1476         ANALYZE_HTTP ("==> Writing request and header");
1477
1478         /* Transmit the request headers.  */
1479         result = gnome_vfs_socket_buffer_write (socket_buffer, request->str, 
1480                         request->len, &bytes_written);
1481
1482         if (result != GNOME_VFS_OK) {
1483                 goto error;
1484         }
1485
1486         /* Transmit the body */
1487         if(data && data->data) {
1488                 ANALYZE_HTTP ("==> Writing data");
1489                 
1490                 result = gnome_vfs_socket_buffer_write (socket_buffer, 
1491                                 data->data, data->len, &bytes_written);
1492         }
1493
1494         if (result != GNOME_VFS_OK) {
1495                 goto error;
1496         }
1497
1498         result = gnome_vfs_socket_buffer_flush (socket_buffer); 
1499
1500 error:
1501         return result;
1502 }
1503
1504 static GnomeVFSResult
1505 make_request (HttpFileHandle *handle,
1506               GnomeVFSURI *uri,
1507               const gchar *method,
1508               GByteArray *data,
1509               gchar *extra_headers,
1510               GnomeVFSContext *context)
1511 {
1512         GnomeVFSSocketBuffer *socket_buffer;
1513         GnomeVFSResult result;
1514         GnomeVFSToplevelURI *toplevel_uri;
1515         GString *request;
1516         gboolean proxy_connect;
1517         char *authn_header_request;
1518         char *authn_header_proxy;
1519
1520         g_return_val_if_fail (handle != NULL, GNOME_VFS_ERROR_INTERNAL);
1521
1522         ANALYZE_HTTP ("==> +make_request");
1523
1524         request                 = NULL;
1525         proxy_connect           = FALSE;
1526         authn_header_request    = NULL;
1527         authn_header_proxy      = NULL;
1528         
1529         toplevel_uri = (GnomeVFSToplevelURI *) uri;
1530
1531         for (;;) {
1532                 GList *list;
1533
1534                 g_free (authn_header_request);
1535                 g_free (authn_header_proxy);
1536
1537                 socket_buffer = NULL;
1538                 result = connect_to_uri (toplevel_uri, &socket_buffer, 
1539                                 &proxy_connect);
1540                 
1541                 if (result != GNOME_VFS_OK) {
1542                         break;
1543                 }
1544                 
1545                 request = build_request (method, toplevel_uri, proxy_connect);
1546
1547                 authn_header_request = http_authn_get_header_for_uri (uri);
1548
1549                 if (authn_header_request != NULL) {
1550                         g_string_append (request, authn_header_request);
1551                 }
1552
1553                 if (proxy_connect) {
1554                         authn_header_proxy = proxy_get_authn_header_for_uri (uri);
1555
1556                         if (authn_header_proxy != NULL) {
1557                                 g_string_append (request, authn_header_proxy);
1558                         }
1559                 }
1560                 
1561                 /* `Content-Length' header.  */
1562                 if (data != NULL) {
1563                         g_string_append_printf (request, "Content-Length: %d\r\n", data->len);
1564                 }
1565                 
1566                 /* Extra headers. */
1567                 if (extra_headers != NULL) {
1568                         g_string_append (request, extra_headers);
1569                 }
1570
1571                 /* Extra headers from user */
1572                 list = NULL;
1573
1574                 if (invoke_callback_send_additional_headers (uri, &list)) {
1575                         GList *i;
1576
1577                         for (i = list; i; i = i->next) {
1578                                 g_string_append (request, i->data);
1579                                 g_free (i->data);
1580                                 i->data = NULL;
1581                         }
1582
1583                         g_list_free (list);
1584                 }
1585
1586                 /* Empty line ends header section.  */
1587                 g_string_append (request, "\r\n");
1588
1589                 result = xmit_request (socket_buffer, request, data);
1590                 g_string_free (request, TRUE);
1591                 request = NULL;
1592
1593                 if (result != GNOME_VFS_OK) {
1594                         break;
1595                 }
1596
1597                 /* Read the headers and create our internal HTTP file handle.  */
1598                 result = create_handle (uri, socket_buffer, context, handle);
1599
1600                 if (result == GNOME_VFS_OK) {
1601                         socket_buffer = NULL;
1602                         break;
1603                 }
1604                 if (handle->server_status == HTTP_STATUS_UNAUTHORIZED) {
1605                         if (! check_authn_retry_request (handle, AuthnHeader_WWW, authn_header_request)) {
1606                                 break;
1607                         }
1608                 } else if (handle->server_status == HTTP_STATUS_PROXY_AUTH_REQUIRED) {
1609                         if (! check_authn_retry_request (handle, AuthnHeader_WWW, authn_header_proxy)) {
1610                                 break;
1611                         }
1612                 } else {
1613                         break;
1614                 }
1615                 http_file_handle_destroy (handle);
1616                 handle = NULL;
1617         }
1618
1619         g_free (authn_header_request);
1620         g_free (authn_header_proxy);
1621
1622         if (result != GNOME_VFS_OK && handle != NULL) {
1623                 http_file_handle_destroy (handle);
1624                 handle = NULL;
1625         }
1626
1627         if (request != NULL) {
1628                 g_string_free (request, TRUE);
1629         }
1630         
1631         if (socket_buffer != NULL) {
1632                 gnome_vfs_socket_buffer_destroy (socket_buffer, TRUE);
1633         }
1634         
1635         ANALYZE_HTTP ("==> -make_request");
1636         return result;
1637 }
1638
1639 static void
1640 http_handle_close (HttpFileHandle *handle, 
1641                    GnomeVFSContext *context)
1642 {
1643         ANALYZE_HTTP ("==> +http_handle_close");
1644         
1645         if (handle != NULL) {
1646                 if (handle->socket_buffer) {
1647                         gnome_vfs_socket_buffer_flush (handle->socket_buffer);
1648                         gnome_vfs_socket_buffer_destroy (handle->socket_buffer,
1649                                                          TRUE);
1650                         handle->socket_buffer = NULL;
1651                 }
1652
1653                 http_file_handle_destroy (handle);
1654         }
1655         
1656         ANALYZE_HTTP ("==> -http_handle_close");
1657 }
1658
1659 static GnomeVFSResult
1660 do_open (GnomeVFSMethod *method,
1661          GnomeVFSMethodHandle **method_handle,
1662          GnomeVFSURI *uri,
1663          GnomeVFSOpenMode mode,
1664          GnomeVFSContext *context)
1665 {
1666         HttpFileHandle *handle;
1667         GnomeVFSResult result = GNOME_VFS_OK;
1668         
1669         g_return_val_if_fail (uri->parent == NULL, GNOME_VFS_ERROR_INVALID_URI);
1670         g_return_val_if_fail (!(mode & GNOME_VFS_OPEN_READ && 
1671                                 mode & GNOME_VFS_OPEN_WRITE),
1672                               GNOME_VFS_ERROR_INVALID_OPEN_MODE);
1673
1674         ANALYZE_HTTP ("==> +do_open");
1675         DEBUG_HTTP (("+Open URI: '%s' mode:'%c'", gnome_vfs_uri_to_string(uri, 0), 
1676                      mode & GNOME_VFS_OPEN_READ ? 'R' : 'W'));
1677
1678         handle = g_new (HttpFileHandle, 1);
1679         if (mode & GNOME_VFS_OPEN_READ) {
1680                 result = make_request (handle, uri, "GET", NULL, NULL,
1681                                        context);
1682         } else {
1683                 http_file_handle_new(handle, NULL, uri); /* shrug */
1684         }
1685         if (result == GNOME_VFS_OK) {
1686                 *method_handle = (GnomeVFSMethodHandle *) handle;
1687         } else {
1688                 *method_handle = NULL;
1689         }
1690
1691         DEBUG_HTTP (("-Open (%d) handle:0x%08x", result, (unsigned int)handle));
1692         ANALYZE_HTTP ("==> -do_open");
1693         
1694         return result;
1695 }
1696
1697 static GnomeVFSResult
1698 do_create (GnomeVFSMethod *method,
1699            GnomeVFSMethodHandle **method_handle,
1700            GnomeVFSURI *uri,
1701            GnomeVFSOpenMode mode,
1702            gboolean exclusive,
1703            guint perm,
1704            GnomeVFSContext *context)
1705 {
1706         /* try to write a zero length file - this appears to be the 
1707          * only reliable way of testing if a put will succeed. 
1708          * Xythos can apparently tell us if we have write permission by
1709          * playing with LOCK, but mod_dav cannot. */
1710         HttpFileHandle *handle;
1711         GnomeVFSResult result;
1712         GByteArray *bytes = g_byte_array_new();
1713         
1714         ANALYZE_HTTP ("==> +do_create");
1715         DEBUG_HTTP (("+Create URI: '%s'", gnome_vfs_uri_get_path (uri)));
1716
1717         http_cache_invalidate_uri_parent (uri);
1718
1719         /* Don't ignore exclusive; it should check first whether
1720            the file exists, since the http protocol default is to 
1721            overwrite by default */
1722         /* FIXME we've stopped using HEAD -- we should use GET instead  */
1723         /* FIXME we should check the cache here */
1724         if (exclusive) {
1725                 
1726                 ANALYZE_HTTP ("==> Checking to see if file exists");
1727                 
1728                 handle = g_new (HttpFileHandle, 1);
1729                 result = make_request (handle, uri, "HEAD", NULL, NULL,
1730                                        context);
1731                 http_handle_close (handle, context);
1732                 g_free (handle);
1733                 
1734                 if (result != GNOME_VFS_OK &&
1735                     result != GNOME_VFS_ERROR_NOT_FOUND) {
1736                         return result;
1737                 }
1738                 if (result == GNOME_VFS_OK) {
1739                         return GNOME_VFS_ERROR_FILE_EXISTS;
1740                 }
1741         }
1742         
1743         ANALYZE_HTTP ("==> Creating initial file");
1744         
1745         handle = g_new (HttpFileHandle, 1);
1746         result = make_request (handle, uri, "PUT", bytes, NULL, context);
1747         http_handle_close(handle, context);
1748         g_free (handle);
1749         
1750         if (result != GNOME_VFS_OK) {
1751                 /* the PUT failed */
1752                 
1753                 /* FIXME bugzilla.gnome.org 45131
1754                  * If you PUT a file with an invalid name to Xythos, it 
1755                  * returns a 403 Forbidden, which is different from the behaviour
1756                  * in MKCOL or MOVE.  Unfortunately, it is not possible to discern whether 
1757                  * that 403 Forbidden is being returned because of invalid characters in the name
1758                  * or because of permissions problems
1759                  */  
1760
1761                 if (result == GNOME_VFS_ERROR_NOT_FOUND) {
1762                         result = resolve_409 (method, uri, context);
1763                 }
1764
1765                 return result;
1766         }
1767
1768         /* clean up */
1769         g_byte_array_free (bytes, TRUE);
1770         
1771         /* FIXME bugzilla.gnome.org 41159: do we need to do something more intelligent here? */
1772         result = do_open (method, method_handle, uri, GNOME_VFS_OPEN_WRITE, context);
1773
1774         DEBUG_HTTP (("-Create (%d) handle:0x%08x", result, (unsigned int)handle));
1775         ANALYZE_HTTP ("==> -do_create");
1776
1777         return result;
1778 }
1779
1780 static GnomeVFSResult
1781 do_close (GnomeVFSMethod *method,
1782           GnomeVFSMethodHandle *method_handle,
1783           GnomeVFSContext *context)
1784 {
1785         HttpFileHandle *old_handle;
1786         HttpFileHandle *new_handle;
1787         GnomeVFSResult result;
1788         
1789         ANALYZE_HTTP ("==> +do_close");
1790         DEBUG_HTTP (("+Close handle:0x%08x", (unsigned int)method_handle));
1791
1792         old_handle = (HttpFileHandle *) method_handle;
1793         
1794         /* if the handle was opened in write mode then:
1795          * 1) there won't be a connection open, and
1796          * 2) there will be data to_be_written...
1797          */
1798         if (old_handle->to_be_written != NULL) {
1799                 GnomeVFSURI *uri = old_handle->uri;
1800                 GByteArray *bytes = old_handle->to_be_written;
1801                 GnomeVFSMimeSniffBuffer *sniff_buffer;
1802                 char *extraheader = NULL;
1803                 const char *mime_type = NULL;
1804                 
1805                 sniff_buffer = 
1806                         gnome_vfs_mime_sniff_buffer_new_from_existing_data (bytes->data, 
1807                                                                             bytes->len);
1808
1809                 if (sniff_buffer != NULL) {
1810                         mime_type = 
1811                                 gnome_vfs_get_mime_type_for_buffer (
1812                                                 sniff_buffer);
1813                         if (mime_type != NULL) {
1814                                 extraheader = g_strdup_printf(
1815                                                 "Content-type: %s\r\n", 
1816                                                 mime_type);
1817                         }
1818                         gnome_vfs_mime_sniff_buffer_free (sniff_buffer);
1819
1820                 }
1821
1822                 http_cache_invalidate_uri (uri);
1823
1824                 ANALYZE_HTTP ("==> doing PUT");
1825                 new_handle = g_new (HttpFileHandle, 1);
1826                 result = make_request (new_handle, uri, "PUT", bytes, 
1827                                        extraheader, context);
1828                 g_free (extraheader);
1829                 http_handle_close (new_handle, context);
1830                 g_free (new_handle);
1831         } else {
1832                 result = GNOME_VFS_OK;
1833         }
1834
1835         http_handle_close (old_handle, context);
1836         g_free (old_handle);
1837         
1838         DEBUG_HTTP (("-Close (%d)", result));
1839         ANALYZE_HTTP ("==> -do_close");
1840         
1841         return result;
1842 }
1843         
1844 static GnomeVFSResult
1845 do_write (GnomeVFSMethod *method,
1846           GnomeVFSMethodHandle *method_handle,
1847           gconstpointer buffer,
1848           GnomeVFSFileSize num_bytes,
1849           GnomeVFSFileSize *bytes_written,
1850           GnomeVFSContext *context)
1851 {
1852         HttpFileHandle *handle;
1853
1854         DEBUG_HTTP (("+Write handle:0x%08x", (unsigned int)method_handle));
1855
1856         handle = (HttpFileHandle *) method_handle;
1857
1858         if (handle->offset != 0)
1859                 return GNOME_VFS_ERROR_NOT_SUPPORTED;
1860
1861         if(handle->to_be_written == NULL) {
1862                 handle->to_be_written = g_byte_array_new();
1863         }
1864         handle->to_be_written = g_byte_array_append(handle->to_be_written, buffer, num_bytes);
1865         *bytes_written = num_bytes;
1866         
1867         DEBUG_HTTP (("-Write (0)"));
1868         
1869         return GNOME_VFS_OK;
1870 }
1871
1872
1873 static GnomeVFSResult
1874 do_read (GnomeVFSMethod *method,
1875          GnomeVFSMethodHandle *method_handle,
1876          gpointer buffer,
1877          GnomeVFSFileSize num_bytes,
1878          GnomeVFSFileSize *bytes_read,
1879          GnomeVFSContext *context)
1880 {
1881         HttpFileHandle *handle;
1882         GnomeVFSResult result;
1883
1884         ANALYZE_HTTP ("==> +do_read");
1885         DEBUG_HTTP (("+Read handle=0x%08x", (unsigned int) method_handle));
1886
1887         handle = (HttpFileHandle *) method_handle;
1888
1889         if (handle->file_info->flags & GNOME_VFS_FILE_INFO_FIELDS_SIZE) {
1890                 GnomeVFSFileSize max_bytes;
1891
1892                 max_bytes = MAX (0, handle->file_info->size - handle->offset);
1893                 num_bytes = MIN (max_bytes, num_bytes);
1894         }
1895
1896         if (!num_bytes) {
1897                 *bytes_read = 0;
1898                 return GNOME_VFS_ERROR_EOF;
1899         }
1900
1901         if (1
1902             && handle->offset >  handle->socket_buffer_offset
1903             && handle->offset <= handle->socket_buffer_offset+MAX_BUFFER_SEEK_SKIP_READ) {
1904 static char drop_buffer[0x1000];
1905 GnomeVFSFileSize bytes, bytes_read;
1906 GnomeVFSResult result;
1907
1908                 while ((bytes=MIN(sizeof(drop_buffer), handle->offset - handle->socket_buffer_offset))) {
1909                         result = gnome_vfs_socket_buffer_read (handle->socket_buffer, drop_buffer, 
1910                                         bytes, &bytes_read);
1911                         if (result != GNOME_VFS_OK)
1912                                 return result;
1913                         handle->socket_buffer_offset += bytes_read;
1914                 }
1915         }
1916
1917         if (handle->offset != handle->socket_buffer_offset) {
1918                 GnomeVFSURI *uri = handle->uri;
1919                 gchar *extra_headers;
1920                 GnomeVFSFileOffset offset_save;
1921
1922                 offset_save = handle->offset;
1923                 gnome_vfs_uri_ref(uri);
1924                 http_handle_close (handle, context);
1925                 extra_headers = g_strdup_printf("Range: bytes=%" G_GINT64_FORMAT "-\r\n",(gint64)handle->offset);
1926                 result = make_request (handle, uri, "GET", NULL, extra_headers,
1927                                        context);
1928                 g_free (extra_headers);
1929                 gnome_vfs_uri_unref(uri);
1930                 handle->offset = offset_save;
1931                 if (result != GNOME_VFS_OK) {
1932                         /* FIXME: 'method_handle' is now broken! */
1933                         memset(handle, 0, sizeof (*handle));
1934                         return result;
1935                 }
1936                 handle->socket_buffer_offset = handle->offset;
1937         }
1938
1939         result = gnome_vfs_socket_buffer_read (handle->socket_buffer, buffer, 
1940                         num_bytes, bytes_read);
1941         
1942         if (*bytes_read == 0) {
1943                 return GNOME_VFS_ERROR_EOF;
1944         }                                      
1945
1946         handle->socket_buffer_offset += *bytes_read;
1947         handle->offset += *bytes_read;
1948
1949         DEBUG_HTTP (("-Read (%d)", result));
1950         ANALYZE_HTTP ("==> -do_read");
1951
1952         return result;
1953 }
1954
1955 static GnomeVFSResult
1956 do_seek (GnomeVFSMethod *method,
1957          GnomeVFSMethodHandle *method_handle,
1958          GnomeVFSSeekPosition  whence,
1959          GnomeVFSFileOffset    offset,
1960          GnomeVFSContext *context)
1961 {
1962         HttpFileHandle *handle;
1963
1964         handle = (HttpFileHandle *) method_handle;
1965
1966         if (handle->to_be_written != NULL)
1967                 return GNOME_VFS_ERROR_NOT_SUPPORTED;
1968
1969         switch (whence) {
1970         case GNOME_VFS_SEEK_START:
1971                 handle->offset = offset;
1972                 break;
1973         case GNOME_VFS_SEEK_CURRENT:
1974                 handle->offset += offset;
1975                 break;
1976         case GNOME_VFS_SEEK_END:
1977                 if (!(handle->file_info->flags & GNOME_VFS_FILE_INFO_FIELDS_SIZE))
1978                         return GNOME_VFS_ERROR_NOT_SUPPORTED;
1979                 handle->offset = handle->file_info->size + offset;
1980                 break;
1981         default:
1982                 g_return_val_if_reached(GNOME_VFS_ERROR_NOT_SUPPORTED);
1983         }
1984
1985         return GNOME_VFS_OK;
1986 }
1987
1988 static GnomeVFSResult
1989 do_tell (GnomeVFSMethod *method,
1990          GnomeVFSMethodHandle *method_handle,
1991          GnomeVFSFileOffset *offset_return)
1992 {
1993         HttpFileHandle *handle;
1994
1995         handle = (HttpFileHandle *) method_handle;
1996
1997         *offset_return = handle->offset;
1998
1999         return GNOME_VFS_OK;
2000 }
2001
2002 /* Directory handling - WebDAV servers only */
2003
2004 static void
2005 process_propfind_propstat (xmlNodePtr node, 
2006                            GnomeVFSFileInfo *file_info)
2007 {
2008         xmlNodePtr l;
2009         gboolean treat_as_directory;
2010
2011         treat_as_directory = FALSE;
2012
2013         while (node != NULL) {
2014                 if (strcmp ((char *)node->name, "prop") != 0) {
2015                         /* node name != "prop" - prop is all we care about */
2016                         node = node->next;
2017                         continue;
2018                 }
2019                 /* properties of the file */
2020                 l = node->xmlChildrenNode;
2021                 while (l != NULL) {
2022                         char *node_content_xml = xmlNodeGetContent(l);
2023                         if (node_content_xml) {
2024                                 if (strcmp ((char *)l->name, "getcontenttype") == 0) {
2025
2026                                         file_info->valid_fields |= 
2027                                                 GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE;
2028                                         
2029                                         if (!file_info->mime_type) {
2030                                                 file_info->mime_type = strip_semicolon (node_content_xml);
2031                                         }
2032                                 } else if (strcmp ((char *)l->name, "getcontentlength") == 0){
2033                                         file_info->valid_fields |= 
2034                                                 GNOME_VFS_FILE_INFO_FIELDS_SIZE;
2035                                         file_info->size = atoi(node_content_xml);
2036                                 } else if (strcmp((char *)l->name, "getlastmodified") == 0) {
2037                                         if (gnome_vfs_atotm (node_content_xml, &(file_info->mtime))) {
2038                                                 file_info->ctime = file_info->mtime;
2039                                                 file_info->valid_fields |= 
2040                                                         GNOME_VFS_FILE_INFO_FIELDS_MTIME 
2041                                                         | GNOME_VFS_FILE_INFO_FIELDS_CTIME;
2042                                         }
2043                                 } 
2044                                 /* Unfortunately, we don't have a mapping for "creationdate" */
2045
2046                                 xmlFree (node_content_xml);
2047                                 node_content_xml = NULL;
2048                         }
2049                         if (strcmp ((char *)l->name, "resourcetype") == 0) {
2050                                 file_info->valid_fields |= 
2051                                         GNOME_VFS_FILE_INFO_FIELDS_TYPE;
2052                                 file_info->type = GNOME_VFS_FILE_TYPE_REGULAR;
2053                                 
2054                                 if (l->xmlChildrenNode && l->xmlChildrenNode->name 
2055                                     && strcmp ((char *)l->xmlChildrenNode->name, "collection") == 0) {
2056                                         file_info->type = GNOME_VFS_FILE_TYPE_DIRECTORY;
2057                                 }
2058                         }
2059                         l = l->next;
2060                 }
2061                 node = node->next;
2062         }
2063         
2064         /* If this is a DAV collection, do we tell nautilus to treat it
2065          * as a directory or as a web page?
2066          */
2067         if (file_info->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_TYPE
2068             && file_info->type == GNOME_VFS_FILE_TYPE_DIRECTORY) {
2069                 g_free (file_info->mime_type);
2070                 if (treat_as_directory) {
2071                         file_info->mime_type = g_strdup ("x-directory/webdav-prefer-directory");
2072                         file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE;
2073                 } else {
2074                         file_info->mime_type = g_strdup ("x-directory/webdav");
2075                         file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE;
2076                 }
2077         }
2078         
2079         
2080         if ((file_info->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE) == 0) {
2081                 file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE;
2082                 file_info->mime_type = g_strdup (gnome_vfs_mime_type_from_name_or_default (file_info->name, "text/plain"));
2083         }
2084
2085         if ((file_info->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_TYPE) == 0) {
2086                 /* Is this a reasonable assumption ? */
2087                 file_info->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_TYPE;
2088                 file_info->type = GNOME_VFS_FILE_TYPE_REGULAR;
2089         }
2090 }
2091
2092 /* a strcmp that doesn't barf on NULLs */
2093 static gint
2094 null_handling_strcmp (const char *a, const char *b) 
2095 {
2096         if ((a == NULL) != (b == NULL)) {
2097                 return 1;
2098         }
2099         
2100         if (a == NULL && b == NULL) {
2101                 return 0;
2102         }
2103         
2104         return strcmp (a, b);
2105 }
2106
2107 #if 0
2108 static char *
2109 unescape_unreserved_chars (const char *in_string)
2110 {
2111         /* RFC 2396 section 2.2 */
2112         static const char * reserved_chars = "%;/?:@&=+$,";
2113
2114         char *ret, *write_char;
2115         const char * read_char;
2116
2117         if (in_string == NULL) {
2118                 return NULL;
2119         }
2120         
2121         ret = g_new (char, strlen (in_string) + 1);
2122
2123         for (read_char = in_string, write_char = ret ; *read_char != '\0' ; read_char++) {
2124                 if (read_char[0] == '%' 
2125                     && g_ascii_isxdigit (read_char[1]) 
2126                     && g_ascii_isxdigit (read_char[2])) {
2127                         char unescaped;
2128                         
2129                         unescaped = (g_ascii_xdigit_value (read_char[1]) << 4) | g_ascii_xdigit_value (read_char[2]);
2130                         
2131                         if (strchr (reserved_chars, unescaped)) {
2132                                 *write_char++ = *read_char++;
2133                                 *write_char++ = *read_char++;
2134                                 *write_char++ = *read_char; /*The last ++ is done in the for statement */
2135                         } else {
2136                                 *write_char++ = unescaped;
2137                                 read_char += 2; /*The last ++ is done in the for statement */ 
2138                         }
2139                 } else {
2140                         *write_char++ = *read_char;
2141                 }
2142         }
2143         *write_char++ = '\0';           
2144         
2145         return ret;
2146 }
2147 #endif /* 0 */
2148
2149 static xmlNodePtr
2150 find_child_node_named (xmlNodePtr node, 
2151                        const char *child_node_name)
2152 {
2153         xmlNodePtr child;
2154
2155         child = node->xmlChildrenNode;
2156
2157         for (child = node->xmlChildrenNode; child != NULL; child = child->next) {
2158                 if (0 == strcmp (child->name, child_node_name)) {
2159                         return child;
2160                 }
2161         }
2162
2163         return NULL;
2164 }
2165
2166 /* Look for a <status> tag in the children of node, and returns
2167  * the corresponding (HTTP) error code
2168  */
2169 static gboolean
2170 get_status_node (xmlNodePtr node, guint *status_code)
2171 {
2172         xmlNodePtr status_node;
2173         char *status_string;
2174         gboolean ret;
2175
2176         status_node = find_child_node_named (node, "status");
2177
2178         if (status_node != NULL) {
2179                 status_string = xmlNodeGetContent (status_node);
2180                 ret = parse_status (status_string, status_code);
2181                 xmlFree (status_string);
2182         } else {
2183                 ret = FALSE;
2184         }
2185         
2186         return ret;
2187 }
2188
2189 static GnomeVFSFileInfo *
2190 process_propfind_response(xmlNodePtr n,
2191                           GnomeVFSURI *base_uri)
2192 {
2193         GnomeVFSFileInfo *file_info = defaults_file_info_new ();
2194         GnomeVFSURI *second_base = gnome_vfs_uri_append_path (base_uri, "/");
2195         guint status_code;
2196         
2197         file_info->valid_fields = GNOME_VFS_FILE_INFO_FIELDS_NONE;
2198         
2199         while (n != NULL) {
2200                 if (strcmp ((char *)n->name, "href") == 0) {
2201                         char *nodecontent = xmlNodeGetContent (n);
2202                         GnomeVFSResult rv;
2203                         
2204                         rv = gnome_vfs_remove_optional_escapes (nodecontent);
2205                         
2206                         if (nodecontent != NULL && *nodecontent != '\0' && rv == GNOME_VFS_OK) {
2207                                 gint len;
2208                                 GnomeVFSURI *uri = gnome_vfs_uri_new (nodecontent);
2209                                 
2210                                 if (uri != NULL) {
2211                                         if ((0 == null_handling_strcmp (base_uri->text, uri->text)) ||
2212                                             (0 == null_handling_strcmp (second_base->text, uri->text))) {
2213                                                 file_info->name = NULL; /* this file is the . directory */
2214                                         } else {
2215                                                 if (file_info->name != NULL) {
2216                                                         /* Don't leak if a (potentially malicious)
2217                                                          * server returns several href in its answer
2218                                                          */
2219                                                         g_free (file_info->name);
2220                                                 }
2221                                                 file_info->name = gnome_vfs_uri_extract_short_name (uri);
2222                                                 if (file_info->name != NULL) {
2223                                                         len = strlen (file_info->name) -1;
2224                                                         if (file_info->name[len] == '/') {
2225                                                                 /* trim trailing `/` - it confuses stuff */
2226                                                                 file_info->name[len] = '\0';
2227                                                         }
2228                                                 } else {
2229                                                         g_warning ("Invalid filename in PROPFIND '%s'; silently skipping", nodecontent);
2230                                                 }
2231                                         }
2232                                         gnome_vfs_uri_unref (uri);
2233                                 } else {
2234                                         g_warning ("Can't make URI from href in PROPFIND '%s'; silently skipping", nodecontent);
2235                                 }
2236                         } else {
2237                                 g_warning ("got href without contents in PROPFIND response");
2238                         }
2239
2240                         xmlFree (nodecontent);
2241                 } else if (strcmp ((char *)n->name, "propstat") == 0) {
2242                         if (get_status_node (n, &status_code) && status_code == 200) {
2243                                 process_propfind_propstat (n->xmlChildrenNode, file_info);
2244                         }
2245                 }
2246                 n = n->next;
2247         }
2248
2249         gnome_vfs_uri_unref (second_base);
2250
2251         return file_info;
2252 }
2253
2254
2255
2256 static GnomeVFSResult
2257 make_propfind_request (HttpFileHandle *handle,
2258         GnomeVFSURI *uri,
2259         gint depth,
2260         GnomeVFSContext *context)
2261 {
2262         GnomeVFSResult result = GNOME_VFS_OK;
2263         GnomeVFSFileSize bytes_read, num_bytes=(64*1024);
2264         char *buffer = g_malloc(num_bytes);
2265         xmlParserCtxtPtr parserContext;
2266         xmlDocPtr doc = NULL;
2267         xmlNodePtr cur = NULL;
2268         char *extraheaders = g_strdup_printf("Depth: %d\r\n", depth);
2269         gboolean found_root_node_props;
2270         gboolean handle_valid = FALSE;
2271
2272         GByteArray *request = g_byte_array_new();
2273         char *request_str = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
2274                 "<D:propfind xmlns:D=\"DAV:\" >"
2275                 "<D:prop>"
2276                 "<D:creationdate/>"
2277                 "<D:getcontentlength/>"
2278                 "<D:getcontenttype/>"
2279                 "<D:getlastmodified/>"
2280                 "<D:resourcetype/>"
2281                 "</D:prop>"
2282                 "</D:propfind>";
2283
2284         ANALYZE_HTTP ("==> +make_propfind_request");
2285
2286         request = g_byte_array_append(request, request_str, 
2287                         strlen(request_str));
2288
2289         parserContext = xmlCreatePushParserCtxt(NULL, NULL, "", 0, "PROPFIND");
2290
2291         if (depth > 0) {
2292                 http_cache_invalidate_uri_and_children (uri);
2293         }
2294
2295         result = make_request (handle, uri, "PROPFIND", request, 
2296                                extraheaders, context);
2297         if (result == GNOME_VFS_OK)
2298                 handle_valid = TRUE;
2299         
2300         /* FIXME bugzilla.gnome.org 43834: It looks like some http
2301          * servers (eg, www.yahoo.com) treat PROPFIND as a GET and
2302          * return a 200 OK. Others may return access denied errors or
2303          * redirects or any other legal response. This case probably
2304          * needs to be made more robust.
2305          */
2306         if (result == GNOME_VFS_OK && handle->server_status != 207) { /* Multi-Status */
2307                 DEBUG_HTTP (("HTTP server returned an invalid PROPFIND response: %d", handle->server_status));
2308                 result = GNOME_VFS_ERROR_NOT_SUPPORTED;
2309         }
2310         
2311         if (result == GNOME_VFS_OK) {
2312                 do {
2313                         result = do_read (NULL, (GnomeVFSMethodHandle *) handle,
2314                                           buffer, num_bytes, &bytes_read, context);
2315                         
2316                         if (result != GNOME_VFS_OK ) {
2317                                 break;
2318                         }
2319                         xmlParseChunk (parserContext, buffer, bytes_read, 0);
2320                         buffer[bytes_read]=0;
2321                 } while (bytes_read > 0);
2322         }
2323
2324         if (result == GNOME_VFS_ERROR_EOF) {
2325                 result = GNOME_VFS_OK;
2326         }
2327         
2328         if (result != GNOME_VFS_OK) {
2329                 goto cleanup;
2330         }
2331         
2332         xmlParseChunk (parserContext, "", 0, 1);
2333
2334         doc = parserContext->myDoc;
2335         if (doc == NULL) {
2336                 result = GNOME_VFS_ERROR_GENERIC;
2337                 goto cleanup;
2338         }
2339         
2340         cur = doc->xmlRootNode;
2341         if (strcmp ((char *)cur->name, "multistatus") != 0) {
2342                 DEBUG_HTTP (("Couldn't find <multistatus>.\n"));
2343                 result = GNOME_VFS_ERROR_GENERIC;
2344                 goto cleanup;
2345         }
2346         cur = cur->xmlChildrenNode;
2347         
2348         found_root_node_props = FALSE;
2349         while (cur != NULL) {
2350                 if (strcmp ((char *)cur->name, "response") == 0) {
2351                         GnomeVFSFileInfo *file_info;
2352                         guint status;
2353                         
2354                         /* Some webdav servers (eg resin) put the HTTP status
2355                          * code for PROPFIND request in the xml answer instead
2356                          * of directly sending a 404 
2357                          */
2358                         if (get_status_node (cur, &status) && !HTTP_20X(status)) {
2359                                 result = http_status_to_vfs_result (status);
2360                                 goto cleanup;
2361                         }
2362                         
2363                         file_info = 
2364                                 process_propfind_response (cur->xmlChildrenNode, uri);
2365                         
2366                         if (file_info->name != NULL) { 
2367                                 handle->files = g_list_append (handle->files, file_info);
2368                         } else {
2369                                 /* This response refers to the root node */
2370                                 /* Abandon the old information that came from create_handle*/
2371                                 
2372                                 file_info->name = handle->file_info->name;
2373                                 handle->file_info->name = NULL;
2374                                 gnome_vfs_file_info_unref (handle->file_info);
2375                                 handle->file_info = file_info;
2376                                 found_root_node_props = TRUE;
2377                         }
2378                         
2379                 } else {
2380                         DEBUG_HTTP(("expecting <response> got <%s>\n", cur->name));
2381                 }
2382                 cur = cur->next;
2383         }
2384         
2385         if (!found_root_node_props) {
2386                 DEBUG_HTTP (("Failed to find root request node properties during propfind"));
2387                 result = GNOME_VFS_ERROR_GENERIC;
2388                 goto cleanup;
2389         }
2390
2391         /*
2392          * RFC 2518
2393          * Section 8.1, final line
2394          * "The results of this method [PROPFIND] SHOULD NOT be cached"
2395          * Well, at least its not "MUST NOT"
2396          */
2397         
2398         if (depth == 0) {
2399                 http_cache_add_uri (uri, handle->file_info, TRUE);
2400         } else {
2401                 http_cache_add_uri_and_children (uri, handle->file_info, handle->files);
2402         }
2403
2404 cleanup:
2405         g_free(buffer);
2406         g_free(extraheaders);
2407         xmlFreeParserCtxt(parserContext);
2408         
2409         if (result != GNOME_VFS_OK && handle_valid) {
2410                 http_handle_close (handle, context);
2411         }
2412         
2413         ANALYZE_HTTP ("==> -make_propfind_request");
2414         
2415         return result;
2416 }
2417
2418 static GnomeVFSResult
2419 do_open_directory(GnomeVFSMethod *method,
2420                   GnomeVFSMethodHandle **method_handle,
2421                   GnomeVFSURI *uri,
2422                   GnomeVFSFileInfoOptions options,
2423                   GnomeVFSContext *context) 
2424 {
2425         /* TODO move to using the gnome_vfs_file_info_list family of functions */
2426         GnomeVFSResult result;
2427         HttpFileHandle *handle = NULL;
2428         GnomeVFSFileInfo * file_info_cached;
2429         GList *child_file_info_cached_list = NULL;
2430
2431         ANALYZE_HTTP ("==> +do_open_directory");
2432         DEBUG_HTTP (("+Open_Directory options: %d URI: '%s'", options, gnome_vfs_uri_to_string (uri, 0)));
2433
2434         /* Check the cache--is this even a directory?  
2435          * (Nautilus, in particular, seems to like to make this call on non directories
2436          */
2437
2438         file_info_cached = http_cache_check_uri (uri);
2439
2440         if (file_info_cached) {
2441                 if (GNOME_VFS_FILE_TYPE_DIRECTORY != file_info_cached->type) {
2442                         ANALYZE_HTTP ("==> Cache Hit (Negative)");      
2443                         gnome_vfs_file_info_unref (file_info_cached);
2444                         result = GNOME_VFS_ERROR_NOT_A_DIRECTORY;
2445                         goto error;
2446                 }
2447                 gnome_vfs_file_info_unref (file_info_cached);
2448                 file_info_cached = NULL;
2449         }
2450
2451         
2452         /* The check for directory contents is more stringent */
2453         file_info_cached = http_cache_check_directory_uri (uri, &child_file_info_cached_list);
2454
2455         if (file_info_cached) {
2456                 handle = g_new (HttpFileHandle, 1);
2457                 http_file_handle_new (handle, NULL, uri);
2458                 gnome_vfs_file_info_unref (handle->file_info);
2459                 handle->file_info = file_info_cached;
2460                 handle->files = child_file_info_cached_list;
2461                 result = GNOME_VFS_OK;
2462         } else {
2463                 handle = g_new (HttpFileHandle, 1);
2464                 result = make_propfind_request(handle, uri, 1, context);
2465                 /* mfleming -- is this necessary?  Most DAV server's I've seen don't have the horrible
2466                  * lack-of-trailing-/-is-a-301 problem for PROPFIND's
2467                  */
2468                 if (result == GNOME_VFS_ERROR_NOT_FOUND) { /* 404 not found */
2469                         if (uri->text != NULL && *uri->text != '\0'
2470                            && uri->text[strlen (uri->text) - 1] != '/') {
2471                                 GnomeVFSURI *tmpuri = gnome_vfs_uri_append_path (uri, "/");
2472                                 result = do_open_directory (method, (GnomeVFSMethodHandle **)&handle, tmpuri, options, context);
2473                                 gnome_vfs_uri_unref (tmpuri);
2474
2475                         }
2476                 }
2477
2478                 if (result == GNOME_VFS_OK
2479                     && handle->file_info->type != GNOME_VFS_FILE_TYPE_DIRECTORY) {
2480                         result = GNOME_VFS_ERROR_NOT_A_DIRECTORY;
2481                         http_handle_close (handle, context);
2482                         g_free (handle);
2483                         handle = NULL;
2484                 }
2485         }
2486         
2487         *method_handle = (GnomeVFSMethodHandle *)handle;
2488
2489 error:
2490         DEBUG_HTTP (("-Open_Directory (%d) handle:0x%08x", result, (unsigned int)handle));
2491         ANALYZE_HTTP ("==> -do_open_directory");
2492         
2493         return result;
2494 }
2495
2496 static GnomeVFSResult
2497 do_close_directory (GnomeVFSMethod *method,
2498                     GnomeVFSMethodHandle *method_handle,
2499                     GnomeVFSContext *context) 
2500 {
2501         HttpFileHandle *handle;
2502         
2503         DEBUG_HTTP (("+Close_Directory"));
2504         
2505         handle = (HttpFileHandle *) method_handle;
2506         
2507         http_handle_close(handle, context);
2508         g_free (handle);
2509
2510         DEBUG_HTTP (("-Close_Directory (0) handle:0x%08x", (unsigned int) method_handle));
2511
2512         return GNOME_VFS_OK;
2513 }
2514        
2515 static GnomeVFSResult
2516 do_read_directory (GnomeVFSMethod *method,
2517        GnomeVFSMethodHandle *method_handle,
2518        GnomeVFSFileInfo *file_info,
2519        GnomeVFSContext *context)
2520 {
2521         HttpFileHandle *handle;
2522         GnomeVFSResult result;
2523
2524         DEBUG_HTTP (("+Read_Directory handle:0x%08x", (unsigned int) method_handle));
2525
2526         handle = (HttpFileHandle *) method_handle;
2527         
2528         if (handle->files && g_list_length (handle->files)) {
2529                 GnomeVFSFileInfo *original_info = g_list_nth_data (handle->files, 0);
2530                 gboolean found_entry = FALSE;
2531                 
2532                 /* mfleming -- Why is this check here?  Does anyone set original_info->name to NULL? */
2533                 if (original_info->name != NULL && original_info->name[0]) {
2534                         gnome_vfs_file_info_copy (file_info, original_info); 
2535                         found_entry = TRUE;
2536                 }
2537                 
2538                 /* remove our GnomeVFSFileInfo from the list */
2539                 handle->files = g_list_remove (handle->files, original_info);
2540                 gnome_vfs_file_info_unref (original_info);
2541         
2542                 /* mfleming -- Is this necessary? */
2543                 if (found_entry) {
2544                         result = GNOME_VFS_OK;
2545                 } else {
2546                         result = do_read_directory (method, method_handle, file_info, context);
2547                 }
2548         } else {
2549                 result = GNOME_VFS_ERROR_EOF;
2550         }
2551
2552         DEBUG_HTTP (("-Read_Directory (%d)", result));
2553         return result;
2554 }
2555  
2556
2557 static GnomeVFSResult
2558 do_get_file_info (GnomeVFSMethod *method,
2559                   GnomeVFSURI *uri,
2560                   GnomeVFSFileInfo *file_info,
2561                   GnomeVFSFileInfoOptions options,
2562                   GnomeVFSContext *context)
2563 {
2564         HttpFileHandle *handle;
2565         GnomeVFSResult result;
2566         GnomeVFSFileInfo * file_info_cached;
2567
2568         ANALYZE_HTTP ("==> +do_get_file_info");
2569         DEBUG_HTTP (("+Get_File_Info options: %d URI: '%s'", options, gnome_vfs_uri_to_string( uri, 0)));
2570
2571         file_info_cached = http_cache_check_uri (uri);
2572
2573         if (file_info_cached != NULL) {
2574                 gnome_vfs_file_info_copy (file_info, file_info_cached);
2575                 gnome_vfs_file_info_unref (file_info_cached);
2576                 ANALYZE_HTTP ("==> Cache Hit"); 
2577                 result = GNOME_VFS_OK;
2578         } else {
2579                 /*
2580                  * Start off by making a PROPFIND request.  Fall back to a HEAD if it fails
2581                  */
2582                 
2583                 handle = g_new (HttpFileHandle, 1);
2584                 result = make_propfind_request (handle, uri, 0, context);
2585                 
2586                 /* Note that theoretically we could not bother with this request if we get a 404 back,
2587                  * but since some servers seem to return wierd things on PROPFIND (mostly 200 OK's...)
2588                  * I'm not going to count on the PROPFIND response....
2589                  */ 
2590                 if (result == GNOME_VFS_OK) {
2591                         gnome_vfs_file_info_copy (file_info, handle->file_info);
2592                         http_handle_close (handle, context);
2593                         g_free (handle);
2594                         handle = NULL;
2595                 } else {
2596                         g_free (handle);
2597                         handle = NULL;
2598                         g_assert (handle == NULL); /* Make sure we're not leaking some old one */
2599                         
2600                         /* Lame buggy servers (eg: www.mozilla.org,
2601                          * www.corel.com)) return an HTTP error for a
2602                          * HEAD where a GET would succeed. In these
2603                          * cases lets try to do a GET.
2604                          */
2605                         if (result != GNOME_VFS_OK) {
2606                                 g_assert (handle == NULL); /* Make sure we're not leaking some old one */
2607
2608                                 ANALYZE_HTTP ("==> do_get_file_info: do GET ");
2609
2610                                 handle = g_new (HttpFileHandle, 1);
2611                                 result = make_request (handle, uri, "GET", NULL, NULL, context);
2612                                 if (result == GNOME_VFS_OK) {
2613                                         gnome_vfs_file_info_copy (file_info, handle->file_info);
2614                                         http_cache_add_uri (uri, handle->file_info, FALSE);
2615                                         http_handle_close (handle, context);
2616                                 }
2617                                 g_free (handle);
2618                                 handle = NULL;
2619
2620                                 /* If we get a redirect, we should be
2621                                  * basing the MIME type on the type of
2622                                  * the page we'll be redirected
2623                                  * too. Maybe we even want to take the
2624                                  * "follow_links" setting into account.
2625                                  */
2626                                 /* FIXME: For now we treat all
2627                                  * redirects as if they lead to a
2628                                  * text/html. That works pretty well,
2629                                  * but it's not correct.
2630                                  */
2631                                 if (handle != NULL && HTTP_REDIRECTED (handle->server_status)) {
2632                                         g_free (file_info->mime_type);
2633                                         file_info->mime_type = g_strdup ("text/html");
2634                                 }
2635                         }
2636                         
2637                         if (result == GNOME_VFS_ERROR_NOT_FOUND) { /* 404 not found */
2638                                 /* FIXME bugzilla.gnome.org 43835: mfleming: Is this code really appropriate?
2639                                  * In any case, it doesn't seem to be appropriate for a DAV-enabled
2640                                  * server, since they don't seem to send 301's when you PROPFIND collections
2641                                  * without a trailing '/'.
2642                                  */
2643                                 if (uri->text != NULL && *uri->text != '\0' 
2644                                     && uri->text[strlen(uri->text)-1] != '/') {
2645                                         GnomeVFSURI *tmpuri = gnome_vfs_uri_append_path (uri, "/");
2646                                         
2647                                         result = do_get_file_info (method, tmpuri, file_info, options, context);
2648                                         gnome_vfs_uri_unref (tmpuri);
2649                                 }
2650                         }
2651                 }
2652         }
2653         
2654         DEBUG_HTTP (("-Get_File_Info (%d)", result));
2655         ANALYZE_HTTP ("==> -do_get_file_info");
2656         
2657         return result;
2658 }
2659
2660 static GnomeVFSResult
2661 do_get_file_info_from_handle (GnomeVFSMethod *method,
2662                               GnomeVFSMethodHandle *method_handle,
2663                               GnomeVFSFileInfo *file_info,
2664                               GnomeVFSFileInfoOptions options,
2665                               GnomeVFSContext *context)
2666 {
2667         HttpFileHandle *handle;
2668         
2669         DEBUG_HTTP (("+Get_File_Info_From_Handle"));
2670         
2671         handle = (HttpFileHandle *) method_handle;
2672         
2673         gnome_vfs_file_info_copy (file_info, handle->file_info);
2674         
2675         DEBUG_HTTP (("-Get_File_Info_From_Handle"));
2676         
2677         return GNOME_VFS_OK;
2678 }
2679
2680 static gboolean
2681 do_is_local (GnomeVFSMethod *method,
2682              const GnomeVFSURI *uri)
2683 {
2684         DEBUG_HTTP (("+Is_Local"));
2685         return FALSE;
2686 }
2687
2688 static GnomeVFSResult 
2689 do_make_directory (GnomeVFSMethod *method, 
2690                    GnomeVFSURI *uri,
2691                    guint perm, 
2692                    GnomeVFSContext *context) 
2693 {
2694         /* MKCOL /path HTTP/1.0 */
2695
2696         HttpFileHandle *handle;
2697         GnomeVFSResult result;
2698
2699         DEBUG_HTTP (("+Make_Directory URI: '%s'", gnome_vfs_uri_to_string (uri, 0)));
2700         ANALYZE_HTTP ("==> +do_make_directory");
2701
2702         /*
2703          * MKCOL returns a 405 if you try to MKCOL on something that
2704          * already exists.  Of course, we don't know whether that means that 
2705          * the server doesn't support DAV or the collection already exists.
2706          * So we do a PROPFIND first to find out
2707          */
2708         /* FIXME check cache here */
2709         handle = g_new (HttpFileHandle, 1);
2710         result = make_propfind_request(handle, uri, 0, context);
2711
2712         if (result == GNOME_VFS_OK) {
2713                 result = GNOME_VFS_ERROR_FILE_EXISTS;
2714         } else {
2715                 /* Make sure we're not leaking an old one */
2716                 g_assert (handle == NULL);
2717                 
2718                 if (result == GNOME_VFS_ERROR_NOT_FOUND) {
2719                         http_cache_invalidate_uri_parent (uri);
2720                         handle = g_new (HttpFileHandle, 1);
2721                         result = make_request (handle, uri, "MKCOL", NULL, NULL, context);
2722                 }
2723         }
2724         http_handle_close (handle, context);
2725         g_free (handle);
2726         
2727         if (result == GNOME_VFS_ERROR_NOT_FOUND) {
2728                 result = resolve_409 (method, uri, context);
2729         }
2730
2731         ANALYZE_HTTP ("==> -do_make_directory");
2732         DEBUG_HTTP (("-Make_Directory (%d)", result));
2733
2734         return result;
2735 }
2736
2737 static GnomeVFSResult 
2738 do_remove_directory(GnomeVFSMethod *method, 
2739                     GnomeVFSURI *uri, 
2740                     GnomeVFSContext *context) 
2741 {
2742         /* DELETE /path HTTP/1.0 */
2743         HttpFileHandle *handle;
2744         GnomeVFSResult result;
2745
2746         ANALYZE_HTTP ("==> +do_remove_directory");
2747         DEBUG_HTTP (("+Remove_Directory URI: '%s'", gnome_vfs_uri_to_string (uri, 0)));
2748
2749         http_cache_invalidate_uri_parent (uri);
2750
2751         /* FIXME this should return GNOME_VFS_ERROR_DIRECTORY_NOT_EMPTY if the
2752          * directory is not empty
2753          */
2754         handle = g_new (HttpFileHandle, 1);
2755         result = make_request (handle, uri, "DELETE", NULL, NULL,
2756                                context);
2757         http_handle_close (handle, context);
2758         g_free (handle);
2759         
2760         DEBUG_HTTP (("-Remove_Directory (%d)", result));
2761         ANALYZE_HTTP ("==> -do_remove_directory");
2762         
2763         return result;
2764 }
2765
2766 static gboolean 
2767 is_same_fs (const GnomeVFSURI *a, 
2768             const GnomeVFSURI *b)
2769 {
2770         return null_handling_strcmp (gnome_vfs_uri_get_scheme (a), gnome_vfs_uri_get_scheme (b)) == 0
2771                 && null_handling_strcmp (gnome_vfs_uri_get_host_name (a), gnome_vfs_uri_get_host_name (b)) == 0
2772                 && null_handling_strcmp (gnome_vfs_uri_get_user_name (a), gnome_vfs_uri_get_user_name (b)) == 0
2773                 && null_handling_strcmp (gnome_vfs_uri_get_password (a), gnome_vfs_uri_get_password (b)) == 0
2774                 && (gnome_vfs_uri_get_host_port (a) == gnome_vfs_uri_get_host_port (b));
2775 }
2776
2777 static GnomeVFSResult
2778 do_move (GnomeVFSMethod *method,
2779          GnomeVFSURI *old_uri,
2780          GnomeVFSURI *new_uri,
2781          gboolean force_replace,
2782          GnomeVFSContext *context)
2783 {
2784
2785         /*
2786          * MOVE /path1 HTTP/1.0
2787          * Destination: /path2
2788          * Overwrite: (T|F)
2789          */
2790
2791         HttpFileHandle *handle;
2792         GnomeVFSResult result;
2793
2794         char *destpath, *destheader;
2795
2796         ANALYZE_HTTP ("==> +do_move");
2797         DEBUG_HTTP (("+Move URI: '%s' Dest: '%s'", 
2798                 gnome_vfs_uri_to_string (old_uri, 0), 
2799                 gnome_vfs_uri_to_string (new_uri, 0)));
2800
2801         if (!is_same_fs (old_uri, new_uri)) {
2802                 return GNOME_VFS_ERROR_NOT_SAME_FILE_SYSTEM;
2803         }       
2804         
2805         destpath = gnome_vfs_uri_to_string (new_uri, GNOME_VFS_URI_HIDE_USER_NAME|GNOME_VFS_URI_HIDE_PASSWORD);
2806         destheader = g_strdup_printf ("Destination: %s\r\nOverwrite: %c\r\n", destpath, force_replace ? 'T' : 'F' );
2807
2808         handle = g_new (HttpFileHandle, 1);
2809         result = make_request (handle, old_uri, "MOVE", NULL, destheader, context);
2810         http_handle_close (handle, context);
2811         g_free (handle);
2812         handle = NULL;
2813
2814         if (result == GNOME_VFS_ERROR_NOT_FOUND) {
2815                 result = resolve_409 (method, new_uri, context);
2816         }
2817
2818         http_cache_invalidate_uri_parent (old_uri);
2819         http_cache_invalidate_uri_parent (new_uri);
2820
2821         DEBUG_HTTP (("-Move (%d)", result));
2822         ANALYZE_HTTP ("==> -do_move");
2823
2824         return result;
2825 }
2826
2827
2828 static GnomeVFSResult 
2829 do_unlink(GnomeVFSMethod *method,
2830         GnomeVFSURI *uri,
2831           GnomeVFSContext *context)
2832 {
2833         GnomeVFSResult result;
2834
2835         /* FIXME need to make sure this fails on directories */
2836         ANALYZE_HTTP ("==> +do_unlink");
2837         DEBUG_HTTP (("+Unlink URI: '%s'", gnome_vfs_uri_to_string (uri, 0)));
2838         result = do_remove_directory (method, uri, context);
2839         DEBUG_HTTP (("-Unlink (%d)", result));
2840         ANALYZE_HTTP ("==> -do_unlink");
2841         
2842         return result;
2843 }
2844
2845 static GnomeVFSResult 
2846 do_check_same_fs (GnomeVFSMethod *method,
2847                   GnomeVFSURI *a,
2848                   GnomeVFSURI *b,
2849                   gboolean *same_fs_return,
2850                   GnomeVFSContext *context)
2851 {
2852         *same_fs_return = is_same_fs (a, b);
2853         
2854         return GNOME_VFS_OK;
2855 }
2856
2857 static GnomeVFSResult
2858 do_set_file_info (GnomeVFSMethod *method,
2859                   GnomeVFSURI *uri,
2860                   const GnomeVFSFileInfo *info,
2861                   GnomeVFSSetFileInfoMask mask,
2862                   GnomeVFSContext *context)
2863 {
2864         GnomeVFSURI *parent_uri, *new_uri;
2865         GnomeVFSResult result;
2866         
2867         /* FIXME: For now, we only support changing the name. */
2868         if ((mask & ~(GNOME_VFS_SET_FILE_INFO_NAME)) != 0) {
2869                 return GNOME_VFS_ERROR_NOT_SUPPORTED;
2870         }
2871         
2872         /* FIXME bugzillagnome.org 40645: Make sure this returns an
2873          * error for incoming names with "/" characters in them,
2874          * instead of moving the file.
2875          */
2876         
2877         /* Share code with do_move. */
2878         parent_uri = gnome_vfs_uri_get_parent (uri);
2879         if (parent_uri == NULL) {
2880                 return GNOME_VFS_ERROR_NOT_FOUND;
2881         }
2882         new_uri = gnome_vfs_uri_append_file_name (parent_uri, info->name);
2883         gnome_vfs_uri_unref (parent_uri);
2884         result = do_move (method, uri, new_uri, FALSE, context);
2885         gnome_vfs_uri_unref (new_uri);
2886         return result;
2887 }
2888
2889 static GnomeVFSMethod method = {
2890         sizeof (GnomeVFSMethod),
2891         do_open,
2892         do_create,
2893         do_close,
2894         do_read,
2895         do_write,
2896         do_seek,
2897         do_tell,
2898         NULL, /* truncate_handle */
2899         do_open_directory,
2900         do_close_directory,
2901         do_read_directory,
2902         do_get_file_info,
2903         do_get_file_info_from_handle,
2904         do_is_local,
2905         do_make_directory,
2906         do_remove_directory,
2907         do_move,
2908         do_unlink,
2909         do_check_same_fs,
2910         do_set_file_info,
2911         NULL, /* truncate */
2912         NULL, /* find_directory */
2913         NULL  /* create_symbolic_link */
2914 };
2915
2916 GnomeVFSMethod *
2917 vfs_module_init (const char *method_name, 
2918                  const char *args)
2919 {
2920         GError *gconf_error = NULL;
2921         gboolean use_proxy;
2922         gboolean use_proxy_auth;
2923
2924         LIBXML_TEST_VERSION
2925                 
2926         gl_client = gconf_client_get_default ();
2927
2928         gl_mutex = g_mutex_new ();
2929         
2930         gconf_client_add_dir (gl_client, PATH_GCONF_GNOME_VFS, GCONF_CLIENT_PRELOAD_ONELEVEL, &gconf_error);
2931         if (gconf_error) {
2932                 DEBUG_HTTP (("GConf error during client_add_dir '%s'", gconf_error->message));
2933                 g_error_free (gconf_error);
2934                 gconf_error = NULL;
2935         }
2936
2937         gconf_client_notify_add (gl_client, PATH_GCONF_GNOME_VFS, notify_gconf_value_changed, NULL, NULL, &gconf_error);
2938         if (gconf_error) {
2939                 DEBUG_HTTP (("GConf error during notify_error '%s'", gconf_error->message));
2940                 g_error_free (gconf_error);
2941                 gconf_error = NULL;
2942         }
2943
2944         /* Load the http proxy setting */       
2945         use_proxy = gconf_client_get_bool (gl_client, KEY_GCONF_USE_HTTP_PROXY, &gconf_error);
2946
2947         if (gconf_error != NULL) {
2948                 DEBUG_HTTP (("GConf error during client_get_bool '%s'", gconf_error->message));
2949                 g_error_free (gconf_error);
2950                 gconf_error = NULL;
2951         } else {
2952                 construct_gl_http_proxy (use_proxy);
2953         }
2954
2955         use_proxy_auth = gconf_client_get_bool (gl_client, KEY_GCONF_HTTP_USE_AUTH, &gconf_error);
2956
2957         if (gconf_error != NULL) {
2958                 DEBUG_HTTP (("GConf error during client_get_bool '%s'", gconf_error->message));
2959                 g_error_free (gconf_error);
2960                 gconf_error = NULL;
2961         } else {
2962                 set_proxy_auth (use_proxy_auth);
2963         }
2964
2965         http_authn_init ();
2966         http_cache_init ();
2967
2968         return &method;
2969 }
2970
2971 void
2972 vfs_module_shutdown (GnomeVFSMethod *method)
2973 {
2974         g_object_unref (G_OBJECT (gl_client));
2975
2976         http_authn_shutdown ();
2977         
2978         http_cache_shutdown();
2979
2980         g_mutex_free (gl_mutex);
2981
2982         gl_client = NULL;
2983 }
2984
2985 /* A "409 Conflict" currently maps to GNOME_VFS_ERROR_NOT_FOUND because it can be returned
2986  * when the parent collection/directory does not exist.  Unfortunately, Xythos also returns
2987  * this code when the destination filename of a PUT, MKCOL, or MOVE contains illegal characters, 
2988  * eg "my*file:name".
2989  * 
2990  * The only way to resolve this is to ask...
2991  */
2992
2993 static GnomeVFSResult
2994 resolve_409 (GnomeVFSMethod *method, GnomeVFSURI *uri, GnomeVFSContext *context)
2995 {
2996         GnomeVFSFileInfo *file_info;
2997         GnomeVFSURI *parent_dest_uri;
2998         GnomeVFSResult result;
2999
3000
3001         ANALYZE_HTTP ("==> +resolving 409");
3002
3003         file_info = gnome_vfs_file_info_new ();
3004         parent_dest_uri = gnome_vfs_uri_get_parent (uri);
3005
3006         if (parent_dest_uri != NULL) {
3007                 result = do_get_file_info (method,
3008                                            parent_dest_uri,
3009                                            file_info,
3010                                            GNOME_VFS_FILE_INFO_DEFAULT,
3011                                            context);
3012
3013                 gnome_vfs_file_info_unref (file_info);
3014                 file_info = NULL;
3015                 
3016                 gnome_vfs_uri_unref (parent_dest_uri);
3017                 parent_dest_uri = NULL;
3018         } else {
3019                 result = GNOME_VFS_ERROR_NOT_FOUND;
3020         }
3021         
3022         if (result == GNOME_VFS_OK) {
3023                 /* The destination filename contains characters that are not allowed
3024                  * by the server.  This is a bummer mapping, but EINVAL is what
3025                  * the Linux FAT filesystems return on bad filenames, so at least
3026                  * its not without precedent...
3027                  */ 
3028                 result = GNOME_VFS_ERROR_BAD_PARAMETERS;
3029         } else {
3030                 /* The destination's parent path does not exist */
3031                 result = GNOME_VFS_ERROR_NOT_FOUND;
3032         }
3033
3034         ANALYZE_HTTP ("==> -resolving 409");
3035
3036         return result;
3037 }
3038
3039 static gboolean
3040 invoke_callback_headers_received (HttpFileHandle *handle)
3041 {
3042         GnomeVFSModuleCallbackReceivedHeadersIn in_args;
3043         GnomeVFSModuleCallbackReceivedHeadersOut out_args;
3044         gboolean ret = FALSE;
3045
3046         memset (&in_args, 0, sizeof (in_args));
3047         memset (&out_args, 0, sizeof (out_args));
3048
3049         in_args.uri = handle->uri;
3050         in_args.headers = handle->response_headers;
3051
3052         ret = gnome_vfs_module_callback_invoke (GNOME_VFS_MODULE_CALLBACK_HTTP_RECEIVED_HEADERS,
3053                                                 &in_args, sizeof (in_args),
3054                                                 &out_args, sizeof (out_args));
3055
3056         return ret;
3057 }
3058
3059 static gboolean
3060 invoke_callback_send_additional_headers (GnomeVFSURI  *uri,
3061                                          GList       **headers)
3062 {
3063         GnomeVFSModuleCallbackAdditionalHeadersIn in_args;
3064         GnomeVFSModuleCallbackAdditionalHeadersOut out_args;
3065         gboolean ret = FALSE;
3066
3067         memset (&in_args, 0, sizeof (in_args));
3068         memset (&out_args, 0, sizeof (out_args));
3069
3070         in_args.uri = uri;
3071
3072         ret = gnome_vfs_module_callback_invoke (GNOME_VFS_MODULE_CALLBACK_HTTP_SEND_ADDITIONAL_HEADERS,
3073                                                 &in_args, sizeof (in_args),
3074                                                 &out_args, sizeof (out_args));
3075
3076         if (ret) {
3077                 *headers = out_args.headers;
3078                 return TRUE;
3079         }
3080
3081         if (out_args.headers) {
3082                 g_list_foreach (out_args.headers, (GFunc)g_free, NULL);
3083                 g_list_free (out_args.headers);
3084         }
3085
3086         *headers = NULL;
3087
3088         return FALSE;
3089 }
3090
3091 static gboolean
3092 invoke_callback_basic_authn (HttpFileHandle *handle, 
3093                              enum AuthnHeaderType authn_which,
3094                              gboolean previous_attempt_failed)
3095 {
3096         GnomeVFSModuleCallbackAuthenticationIn in_args;
3097         GnomeVFSModuleCallbackAuthenticationOut out_args;
3098         gboolean ret;
3099
3100         ret = FALSE;
3101         
3102         memset (&in_args, 0, sizeof (in_args));
3103         memset (&out_args, 0, sizeof (out_args));
3104
3105         in_args.previous_attempt_failed = previous_attempt_failed;
3106                 
3107         in_args.uri = gnome_vfs_uri_to_string (handle->uri, GNOME_VFS_URI_HIDE_NONE);
3108
3109         ret = http_authn_parse_response_header_basic (authn_which, handle->response_headers, &in_args.realm);
3110                 
3111         if (!ret) {
3112                 goto error;
3113         }
3114
3115         DEBUG_HTTP (("Invoking %s authentication callback for uri %s",
3116                 authn_which == AuthnHeader_WWW ? "basic" : "proxy", in_args.uri));
3117
3118         in_args.auth_type = AuthTypeBasic;
3119
3120         ret = gnome_vfs_module_callback_invoke (authn_which == AuthnHeader_WWW 
3121                                                 ? GNOME_VFS_MODULE_CALLBACK_AUTHENTICATION
3122                                                 : GNOME_VFS_MODULE_CALLBACK_HTTP_PROXY_AUTHENTICATION, 
3123                                                 &in_args, sizeof (in_args), 
3124                                                 &out_args, sizeof (out_args)); 
3125
3126         if (!ret) {
3127                 DEBUG_HTTP (("No callback registered"));
3128                 goto error;
3129         }
3130
3131         ret = (out_args.username != NULL);
3132
3133         if (!ret) {
3134                 DEBUG_HTTP (("No username provided by callback"));
3135                 goto error;
3136         }
3137
3138         DEBUG_HTTP (("Back from authentication callback, adding credentials"));
3139
3140         if (authn_which == AuthnHeader_WWW) {
3141                 http_authn_session_add_credentials (handle->uri, out_args.username, out_args.password);
3142         } else /* if (authn_which == AuthnHeader_Proxy) */ {
3143                 proxy_set_authn (out_args.username, out_args.password);
3144         }
3145 error:
3146         g_free (in_args.uri);
3147         g_free (in_args.realm);
3148         g_free (out_args.username);
3149         g_free (out_args.password);
3150
3151         return ret;
3152 }
3153
3154 static int
3155 strcmp_allow_nulls (const char *s1, const char *s2)
3156 {
3157         return strcmp (s1 == NULL ? "" : s1, s2 == NULL ? "" : s2);
3158 }
3159
3160
3161 /* Returns TRUE if the given URL has changed authentication credentials
3162  * from the last request (eg, another thread updated the authn information) 
3163  * or if the application provided new credentials via a callback
3164  *
3165  * prev_authn_header is NULL if the previous request contained no authn information.
3166  */
3167
3168 gboolean
3169 check_authn_retry_request (HttpFileHandle * http_handle,
3170                            enum AuthnHeaderType authn_which,
3171                            const char *prev_authn_header)
3172 {
3173         gboolean ret;
3174         char *current_authn_header;
3175
3176         current_authn_header = NULL;
3177         
3178         g_mutex_lock (gl_mutex);
3179
3180         if (authn_which == AuthnHeader_WWW) {
3181                 current_authn_header = http_authn_get_header_for_uri (http_handle->uri);
3182         } else if (authn_which == AuthnHeader_Proxy) {
3183                 current_authn_header = proxy_get_authn_header_for_uri_nolock (http_handle->uri);
3184         } else {
3185                 g_assert_not_reached ();
3186         }
3187
3188         ret = FALSE;
3189         if (0 == strcmp_allow_nulls (current_authn_header, prev_authn_header)) {
3190                 ret = invoke_callback_basic_authn (http_handle, authn_which, prev_authn_header == NULL);
3191         } else {
3192                 ret = TRUE;
3193         }
3194
3195         g_mutex_unlock (gl_mutex);
3196
3197         g_free (current_authn_header);
3198
3199         return ret;
3200
3201
3202
3203 utime_t
3204 http_util_get_utime (void)
3205 {
3206     struct timeval tmp;
3207     gettimeofday (&tmp, NULL);
3208     return (utime_t)tmp.tv_usec + ((gint64)tmp.tv_sec) * 1000000LL;
3209 }
3210
3211
3212 /* BASE64 code ported from neon (http://www.webdav.org/neon) */
3213 static const gchar b64_alphabet[65] = {
3214         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3215         "abcdefghijklmnopqrstuvwxyz"
3216         "0123456789+/=" };
3217
3218 gchar *
3219 http_util_base64 (const gchar *text)
3220 {
3221         /* The tricky thing about this is doing the padding at the end,
3222          * doing the bit manipulation requires a bit of concentration only */
3223         gchar *buffer, *point;
3224         gint inlen, outlen;
3225
3226         /* Use 'buffer' to store the output. Work out how big it should be...
3227          * This must be a multiple of 4 bytes 
3228          */
3229
3230         inlen = strlen (text);
3231         outlen = (inlen*4)/3;
3232         if ((inlen % 3) > 0) { /* got to pad */
3233                 outlen += 4 - (inlen % 3);
3234         }
3235
3236         buffer = g_malloc (outlen + 1); /* +1 for the \0 */
3237
3238         /* now do the main stage of conversion, 3 bytes at a time,
3239          * leave the trailing bytes (if there are any) for later
3240          */
3241
3242         for (point=buffer; inlen>=3; inlen-=3, text+=3) {
3243                 *(point++) = b64_alphabet[ (*text)>>2 ];
3244                 *(point++) = b64_alphabet[ ((*text)<<4 & 0x30) | (*(text+1))>>4 ];
3245                 *(point++) = b64_alphabet[ ((*(text+1))<<2 & 0x3c) | (*(text+2))>>6 ];
3246                 *(point++) = b64_alphabet[ (*(text+2)) & 0x3f ];
3247         }
3248
3249         /* Now deal with the trailing bytes */
3250         if (inlen) {
3251                 /* We always have one trailing byte */
3252                 *(point++) = b64_alphabet[ (*text)>>2 ];
3253                 *(point++) = b64_alphabet[ ( ((*text)<<4 & 0x30) |
3254                                                                          (inlen==2?(*(text+1))>>4:0) ) ];
3255                 *(point++) = (inlen==1?'=':b64_alphabet[ (*(text+1))<<2 & 0x3c ] );
3256                 *(point++) = '=';
3257         }
3258
3259         /* Null-terminate */
3260         *point = '\0';
3261
3262         return buffer;
3263 }
3264
3265 static gboolean at_least_one_test_failed = FALSE;
3266
3267 static void
3268 test_failed (const char *format, ...)
3269 {
3270         va_list arguments;
3271         char *message;
3272
3273         va_start (arguments, format);
3274         message = g_strdup_vprintf (format, arguments);
3275         va_end (arguments);
3276
3277         g_message ("test failed: %s", message);
3278         at_least_one_test_failed = TRUE;
3279 }
3280
3281 #define VERIFY_BOOLEAN_RESULT(function, expected) \
3282         G_STMT_START {                                                                                  \
3283                 gboolean result = function;                                                             \
3284                 if (! ((result && expected) || (!result && !expected))) {                               \
3285                         test_failed ("%s: returned '%d' expected '%d'", #function, (int)result, (int)expected); \
3286                 }                                                                                       \
3287         } G_STMT_END
3288
3289
3290 static gboolean
3291 http_self_test (void)
3292 {
3293         g_message ("self-test: http\n");
3294
3295         VERIFY_BOOLEAN_RESULT (proxy_should_for_hostname ("localhost"), FALSE);
3296         VERIFY_BOOLEAN_RESULT (proxy_should_for_hostname ("LocalHost"), FALSE);
3297         VERIFY_BOOLEAN_RESULT (proxy_should_for_hostname ("127.0.0.1"), FALSE);
3298         VERIFY_BOOLEAN_RESULT (proxy_should_for_hostname ("127.127.0.1"), FALSE);
3299         VERIFY_BOOLEAN_RESULT (proxy_should_for_hostname ("www.yahoo.com"), TRUE);
3300
3301         return !at_least_one_test_failed;
3302 }
3303
3304 gboolean vfs_module_self_test (void);
3305
3306 gboolean
3307 vfs_module_self_test (void)
3308 {
3309         gboolean ret;
3310
3311         ret = TRUE;
3312
3313         ret = http_authn_self_test () && ret;
3314
3315         ret = http_self_test () && ret;
3316
3317         return ret;
3318 }
3319