Bug 634734 - Fennec ASSERTION: mFUnitsConvFactor not valid: mFUnitsConvFactor > 0...
[mozilla-central.git] / extensions / gnomevfs / nsGnomeVFSProtocolHandler.cpp
blob3f38fc104e1911fcbae5a196b4e1cbd47ebf7d8c
1 /* vim:set ts=2 sw=2 et cindent: */
2 /* ***** BEGIN LICENSE BLOCK *****
3 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 * The contents of this file are subject to the Mozilla Public License Version
6 * 1.1 (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 * http://www.mozilla.org/MPL/
10 * Software distributed under the License is distributed on an "AS IS" basis,
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12 * for the specific language governing rights and limitations under the
13 * License.
15 * The Original Code is the Mozilla gnome-vfs extension.
17 * The Initial Developer of the Original Code is IBM Corporation.
18 * Portions created by IBM Corporation are Copyright (C) 2004
19 * IBM Corporation. All Rights Reserved.
21 * Contributor(s):
22 * Darin Fisher <darin@meer.net>
24 * Alternatively, the contents of this file may be used under the terms of
25 * either the GNU General Public License Version 2 or later (the "GPL"), or
26 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27 * in which case the provisions of the GPL or the LGPL are applicable instead
28 * of those above. If you wish to allow use of your version of this file only
29 * under the terms of either the GPL or the LGPL, and not to allow others to
30 * use your version of this file under the terms of the MPL, indicate your
31 * decision by deleting the provisions above and replace them with the notice
32 * and other provisions required by the GPL or the LGPL. If you do not delete
33 * the provisions above, a recipient may use your version of this file under
34 * the terms of any one of the MPL, the GPL or the LGPL.
36 * ***** END LICENSE BLOCK ***** */
38 // GnomeVFS v2.2.2 is missing G_BEGIN_DECLS in gnome-vfs-module-callback.h
39 extern "C" {
40 #include <libgnomevfs/gnome-vfs.h>
41 #include <libgnomevfs/gnome-vfs-standard-callbacks.h>
42 #include <libgnomevfs/gnome-vfs-mime-utils.h>
45 #include "nsServiceManagerUtils.h"
46 #include "nsComponentManagerUtils.h"
47 #include "mozilla/ModuleUtils.h"
48 #include "nsIInterfaceRequestorUtils.h"
49 #include "nsIPrefService.h"
50 #include "nsIPrefBranch2.h"
51 #include "nsIObserver.h"
52 #include "nsThreadUtils.h"
53 #include "nsProxyRelease.h"
54 #include "nsIAuthPrompt.h"
55 #include "nsIStringBundle.h"
56 #include "nsIStandardURL.h"
57 #include "nsIURL.h"
58 #include "nsMimeTypes.h"
59 #include "nsNetUtil.h"
60 #include "nsINetUtil.h"
61 #include "nsAutoPtr.h"
62 #include "nsError.h"
63 #include "prlog.h"
64 #include "prtime.h"
65 #include "prprf.h"
66 #include "plstr.h"
68 #define MOZ_GNOMEVFS_SCHEME "moz-gnomevfs"
69 #define MOZ_GNOMEVFS_SUPPORTED_PROTOCOLS "network.gnomevfs.supported-protocols"
71 //-----------------------------------------------------------------------------
73 // NSPR_LOG_MODULES=gnomevfs:5
74 #ifdef PR_LOGGING
75 static PRLogModuleInfo *sGnomeVFSLog;
76 #define LOG(args) PR_LOG(sGnomeVFSLog, PR_LOG_DEBUG, args)
77 #else
78 #define LOG(args)
79 #endif
81 //-----------------------------------------------------------------------------
83 static nsresult
84 MapGnomeVFSResult(GnomeVFSResult result)
86 switch (result)
88 case GNOME_VFS_OK: return NS_OK;
89 case GNOME_VFS_ERROR_NOT_FOUND: return NS_ERROR_FILE_NOT_FOUND;
90 case GNOME_VFS_ERROR_INTERNAL: return NS_ERROR_UNEXPECTED;
91 case GNOME_VFS_ERROR_BAD_PARAMETERS: return NS_ERROR_INVALID_ARG;
92 case GNOME_VFS_ERROR_NOT_SUPPORTED: return NS_ERROR_NOT_AVAILABLE;
93 case GNOME_VFS_ERROR_CORRUPTED_DATA: return NS_ERROR_FILE_CORRUPTED;
94 case GNOME_VFS_ERROR_TOO_BIG: return NS_ERROR_FILE_TOO_BIG;
95 case GNOME_VFS_ERROR_NO_SPACE: return NS_ERROR_FILE_NO_DEVICE_SPACE;
96 case GNOME_VFS_ERROR_READ_ONLY:
97 case GNOME_VFS_ERROR_READ_ONLY_FILE_SYSTEM: return NS_ERROR_FILE_READ_ONLY;
98 case GNOME_VFS_ERROR_INVALID_URI:
99 case GNOME_VFS_ERROR_INVALID_HOST_NAME: return NS_ERROR_MALFORMED_URI;
100 case GNOME_VFS_ERROR_ACCESS_DENIED:
101 case GNOME_VFS_ERROR_NOT_PERMITTED:
102 case GNOME_VFS_ERROR_LOGIN_FAILED: return NS_ERROR_FILE_ACCESS_DENIED;
103 case GNOME_VFS_ERROR_EOF: return NS_BASE_STREAM_CLOSED;
104 case GNOME_VFS_ERROR_NOT_A_DIRECTORY: return NS_ERROR_FILE_NOT_DIRECTORY;
105 case GNOME_VFS_ERROR_IN_PROGRESS: return NS_ERROR_IN_PROGRESS;
106 case GNOME_VFS_ERROR_FILE_EXISTS: return NS_ERROR_FILE_ALREADY_EXISTS;
107 case GNOME_VFS_ERROR_IS_DIRECTORY: return NS_ERROR_FILE_IS_DIRECTORY;
108 case GNOME_VFS_ERROR_NO_MEMORY: return NS_ERROR_OUT_OF_MEMORY;
109 case GNOME_VFS_ERROR_HOST_NOT_FOUND:
110 case GNOME_VFS_ERROR_HOST_HAS_NO_ADDRESS: return NS_ERROR_UNKNOWN_HOST;
111 case GNOME_VFS_ERROR_CANCELLED:
112 case GNOME_VFS_ERROR_INTERRUPTED: return NS_ERROR_ABORT;
113 case GNOME_VFS_ERROR_DIRECTORY_NOT_EMPTY: return NS_ERROR_FILE_DIR_NOT_EMPTY;
114 case GNOME_VFS_ERROR_NAME_TOO_LONG: return NS_ERROR_FILE_NAME_TOO_LONG;
115 case GNOME_VFS_ERROR_SERVICE_NOT_AVAILABLE: return NS_ERROR_UNKNOWN_PROTOCOL;
117 /* No special mapping for these error codes...
119 case GNOME_VFS_ERROR_GENERIC:
120 case GNOME_VFS_ERROR_IO:
121 case GNOME_VFS_ERROR_WRONG_FORMAT:
122 case GNOME_VFS_ERROR_BAD_FILE:
123 case GNOME_VFS_ERROR_NOT_OPEN:
124 case GNOME_VFS_ERROR_INVALID_OPEN_MODE:
125 case GNOME_VFS_ERROR_TOO_MANY_OPEN_FILES:
126 case GNOME_VFS_ERROR_LOOP:
127 case GNOME_VFS_ERROR_DIRECTORY_BUSY:
128 case GNOME_VFS_ERROR_TOO_MANY_LINKS:
129 case GNOME_VFS_ERROR_NOT_SAME_FILE_SYSTEM:
130 case GNOME_VFS_ERROR_SERVICE_OBSOLETE:
131 case GNOME_VFS_ERROR_PROTOCOL_ERROR:
132 case GNOME_VFS_ERROR_NO_MASTER_BROWSER:
136 // Make GCC happy
137 default:
138 return NS_ERROR_FAILURE;
141 return NS_ERROR_FAILURE;
144 //-----------------------------------------------------------------------------
146 static void
147 ProxiedAuthCallback(gconstpointer in,
148 gsize in_size,
149 gpointer out,
150 gsize out_size,
151 gpointer callback_data)
153 GnomeVFSModuleCallbackAuthenticationIn *authIn =
154 (GnomeVFSModuleCallbackAuthenticationIn *) in;
155 GnomeVFSModuleCallbackAuthenticationOut *authOut =
156 (GnomeVFSModuleCallbackAuthenticationOut *) out;
158 LOG(("gnomevfs: ProxiedAuthCallback [uri=%s]\n", authIn->uri));
160 // Without a channel, we have no way of getting a prompter.
161 nsIChannel *channel = (nsIChannel *) callback_data;
162 if (!channel)
163 return;
165 nsCOMPtr<nsIAuthPrompt> prompt;
166 NS_QueryNotificationCallbacks(channel, prompt);
168 // If no auth prompt, then give up. We could failover to using the
169 // WindowWatcher service, but that might defeat a consumer's purposeful
170 // attempt to disable authentication (for whatever reason).
171 if (!prompt)
172 return;
174 // Parse out the host and port...
175 nsCOMPtr<nsIURI> uri;
176 channel->GetURI(getter_AddRefs(uri));
177 if (!uri)
178 return;
180 #ifdef DEBUG
183 // Make sure authIn->uri is consistent with the channel's URI.
185 // XXX This check is probably not IDN safe, and it might incorrectly
186 // fire as a result of escaping differences. It's unclear what
187 // kind of transforms GnomeVFS might have applied to the URI spec
188 // that we originally gave to it. In spite of the likelihood of
189 // false hits, this check is probably still valuable.
191 nsCAutoString spec;
192 uri->GetSpec(spec);
193 int uriLen = strlen(authIn->uri);
194 if (!StringHead(spec, uriLen).Equals(nsDependentCString(authIn->uri, uriLen)))
196 LOG(("gnomevfs: [spec=%s authIn->uri=%s]\n", spec.get(), authIn->uri));
197 NS_ERROR("URI mismatch");
200 #endif
202 nsCAutoString scheme, hostPort;
203 uri->GetScheme(scheme);
204 uri->GetHostPort(hostPort);
206 // It doesn't make sense for either of these strings to be empty. What kind
207 // of funky URI is this?
208 if (scheme.IsEmpty() || hostPort.IsEmpty())
209 return;
211 // Construct the single signon key. Altering the value of this key will
212 // cause people's remembered passwords to be forgotten. Think carefully
213 // before changing the way this key is constructed.
214 nsAutoString key, realm;
216 NS_ConvertUTF8toUTF16 dispHost(scheme);
217 dispHost.Append(NS_LITERAL_STRING("://"));
218 dispHost.Append(NS_ConvertUTF8toUTF16(hostPort));
220 key = dispHost;
221 if (authIn->realm)
223 // We assume the realm string is ASCII. That might be a bogus assumption,
224 // but we have no idea what encoding GnomeVFS is using, so for now we'll
225 // limit ourselves to ISO-Latin-1. XXX What is a better solution?
226 realm.Append('"');
227 realm.Append(NS_ConvertASCIItoUTF16(authIn->realm));
228 realm.Append('"');
229 key.Append(' ');
230 key.Append(realm);
233 // Construct the message string...
235 // We use Necko's string bundle here. This code really should be encapsulated
236 // behind some Necko API, after all this code is based closely on the code in
237 // nsHttpChannel.cpp.
239 nsCOMPtr<nsIStringBundleService> bundleSvc =
240 do_GetService(NS_STRINGBUNDLE_CONTRACTID);
241 if (!bundleSvc)
242 return;
244 nsCOMPtr<nsIStringBundle> bundle;
245 bundleSvc->CreateBundle("chrome://global/locale/commonDialogs.properties",
246 getter_AddRefs(bundle));
247 if (!bundle)
248 return;
250 nsString message;
251 if (!realm.IsEmpty())
253 const PRUnichar *strings[] = { realm.get(), dispHost.get() };
254 bundle->FormatStringFromName(NS_LITERAL_STRING("EnterUserPasswordForRealm").get(),
255 strings, 2, getter_Copies(message));
257 else
259 const PRUnichar *strings[] = { dispHost.get() };
260 bundle->FormatStringFromName(NS_LITERAL_STRING("EnterUserPasswordFor").get(),
261 strings, 1, getter_Copies(message));
263 if (message.IsEmpty())
264 return;
266 // Prompt the user...
267 nsresult rv;
268 PRBool retval = PR_FALSE;
269 PRUnichar *user = nsnull, *pass = nsnull;
271 rv = prompt->PromptUsernameAndPassword(nsnull, message.get(),
272 key.get(),
273 nsIAuthPrompt::SAVE_PASSWORD_PERMANENTLY,
274 &user, &pass, &retval);
275 if (NS_FAILED(rv))
276 return;
277 if (!retval || !user || !pass)
278 return;
280 // XXX We need to convert the UTF-16 username and password from our dialog to
281 // strings that GnomeVFS can understand. It's unclear what encoding GnomeVFS
282 // expects, so for now we assume 7-bit ASCII. Hopefully, we can get a better
283 // solution at some point.
285 // One copy is never enough...
286 authOut->username = g_strdup(NS_LossyConvertUTF16toASCII(user).get());
287 authOut->password = g_strdup(NS_LossyConvertUTF16toASCII(pass).get());
289 nsMemory::Free(user);
290 nsMemory::Free(pass);
293 struct nsGnomeVFSAuthCallbackEvent : public nsRunnable
295 gconstpointer in;
296 gsize in_size;
297 gpointer out;
298 gsize out_size;
299 gpointer callback_data;
301 NS_IMETHOD Run() {
302 ProxiedAuthCallback(in, in_size, out, out_size, callback_data);
303 return NS_OK;
307 static void
308 AuthCallback(gconstpointer in,
309 gsize in_size,
310 gpointer out,
311 gsize out_size,
312 gpointer callback_data)
314 // Need to proxy this callback over to the main thread. Synchronous dispatch
315 // is required in order to provide data to the GnomeVFS callback.
317 nsRefPtr<nsGnomeVFSAuthCallbackEvent> ev = new nsGnomeVFSAuthCallbackEvent();
318 if (!ev)
319 return; // OOM
321 ev->in = in;
322 ev->in_size = in_size;
323 ev->out = out;
324 ev->out_size = out_size;
325 ev->callback_data = callback_data;
327 NS_DispatchToMainThread(ev, NS_DISPATCH_SYNC);
330 //-----------------------------------------------------------------------------
332 static gint
333 FileInfoComparator(gconstpointer a, gconstpointer b)
335 const GnomeVFSFileInfo *ia = (const GnomeVFSFileInfo *) a;
336 const GnomeVFSFileInfo *ib = (const GnomeVFSFileInfo *) b;
338 return strcasecmp(ia->name, ib->name);
341 //-----------------------------------------------------------------------------
343 class nsGnomeVFSInputStream : public nsIInputStream
345 public:
346 NS_DECL_ISUPPORTS
347 NS_DECL_NSIINPUTSTREAM
349 nsGnomeVFSInputStream(const nsCString &uriSpec)
350 : mSpec(uriSpec)
351 , mChannel(nsnull)
352 , mHandle(nsnull)
353 , mBytesRemaining(PR_UINT32_MAX)
354 , mStatus(NS_OK)
355 , mDirList(nsnull)
356 , mDirListPtr(nsnull)
357 , mDirBufCursor(0)
358 , mDirOpen(PR_FALSE) {}
360 ~nsGnomeVFSInputStream() { Close(); }
362 void SetChannel(nsIChannel *channel)
364 // We need to hold an owning reference to our channel. This is done
365 // so we can access the channel's notification callbacks to acquire
366 // a reference to a nsIAuthPrompt if we need to handle a GnomeVFS
367 // authentication callback.
369 // However, the channel can only be accessed on the main thread, so
370 // we have to be very careful with ownership. Moreover, it doesn't
371 // support threadsafe addref/release, so proxying is the answer.
373 // Also, it's important to note that this likely creates a reference
374 // cycle since the channel likely owns this stream. This reference
375 // cycle is broken in our Close method.
377 NS_ADDREF(mChannel = channel);
380 private:
381 GnomeVFSResult DoOpen();
382 GnomeVFSResult DoRead(char *aBuf, PRUint32 aCount, PRUint32 *aCountRead);
383 nsresult SetContentTypeOfChannel(const char *contentType);
385 private:
386 nsCString mSpec;
387 nsIChannel *mChannel; // manually refcounted
388 GnomeVFSHandle *mHandle;
389 PRUint32 mBytesRemaining;
390 nsresult mStatus;
391 GList *mDirList;
392 GList *mDirListPtr;
393 nsCString mDirBuf;
394 PRUint32 mDirBufCursor;
395 PRPackedBool mDirOpen;
398 GnomeVFSResult
399 nsGnomeVFSInputStream::DoOpen()
401 GnomeVFSResult rv;
403 NS_ASSERTION(mHandle == nsnull, "already open");
405 // Push a callback handler on the stack for this thread, so we can intercept
406 // authentication requests from GnomeVFS. We'll use the channel to get a
407 // nsIAuthPrompt instance.
409 gnome_vfs_module_callback_push(GNOME_VFS_MODULE_CALLBACK_AUTHENTICATION,
410 AuthCallback, mChannel, NULL);
412 // Query the mime type first (this could return NULL).
414 // XXX We need to do this up-front in order to determine how to open the URI.
415 // Unfortunately, the error code GNOME_VFS_ERROR_IS_DIRECTORY is not
416 // always returned by gnome_vfs_open when we pass it a URI to a directory!
417 // Otherwise, we could have used that as a way to failover to opening the
418 // URI as a directory. Also, it would have been ideal if
419 // gnome_vfs_get_file_info_from_handle were actually implemented by the
420 // smb:// module, since that would have allowed us to potentially save a
421 // round trip to the server to discover the mime type of the document in
422 // the case where gnome_vfs_open would have been used. (Oh well! /me
423 // throws hands up in the air and moves on...)
425 GnomeVFSFileInfo info = {0};
426 rv = gnome_vfs_get_file_info(mSpec.get(), &info, GnomeVFSFileInfoOptions(
427 GNOME_VFS_FILE_INFO_DEFAULT |
428 GNOME_VFS_FILE_INFO_FOLLOW_LINKS));
429 if (rv == GNOME_VFS_OK)
431 if (info.type == GNOME_VFS_FILE_TYPE_DIRECTORY)
433 rv = gnome_vfs_directory_list_load(&mDirList, mSpec.get(),
434 GNOME_VFS_FILE_INFO_DEFAULT);
436 LOG(("gnomevfs: gnome_vfs_directory_list_load returned %d (%s) [spec=\"%s\"]\n",
437 rv, gnome_vfs_result_to_string(rv), mSpec.get()));
439 else
441 rv = gnome_vfs_open(&mHandle, mSpec.get(), GNOME_VFS_OPEN_READ);
443 LOG(("gnomevfs: gnome_vfs_open returned %d (%s) [spec=\"%s\"]\n",
444 rv, gnome_vfs_result_to_string(rv), mSpec.get()));
448 gnome_vfs_module_callback_pop(GNOME_VFS_MODULE_CALLBACK_AUTHENTICATION);
450 if (rv == GNOME_VFS_OK)
452 if (mHandle)
454 // Here we set the content type of the channel to the value of the mime
455 // type determined by GnomeVFS. However, if GnomeVFS is telling us that
456 // the document is binary, we'll ignore that and keep the channel's
457 // content type unspecified. That will enable our content type sniffing
458 // algorithms. This should provide more consistent mime type handling.
460 if (info.mime_type && (strcmp(info.mime_type, APPLICATION_OCTET_STREAM) != 0))
461 SetContentTypeOfChannel(info.mime_type);
463 // XXX truncates size from 64-bit to 32-bit
464 mBytesRemaining = (PRUint32) info.size;
466 // Update the content length attribute on the channel. We do this
467 // synchronously without proxying. This hack is not as bad as it looks!
468 if (mBytesRemaining != PR_UINT32_MAX)
469 mChannel->SetContentLength(mBytesRemaining);
471 else
473 mDirOpen = PR_TRUE;
475 // Sort mDirList
476 mDirList = g_list_sort(mDirList, FileInfoComparator);
477 mDirListPtr = mDirList;
479 // Write base URL (make sure it ends with a '/')
480 mDirBuf.Append("300: ");
481 mDirBuf.Append(mSpec);
482 if (mSpec.get()[mSpec.Length() - 1] != '/')
483 mDirBuf.Append('/');
484 mDirBuf.Append('\n');
486 // Write column names
487 mDirBuf.Append("200: filename content-length last-modified file-type\n");
489 // Write charset (assume UTF-8)
490 // XXX is this correct?
491 mDirBuf.Append("301: UTF-8\n");
493 SetContentTypeOfChannel(APPLICATION_HTTP_INDEX_FORMAT);
497 gnome_vfs_file_info_clear(&info);
498 return rv;
501 GnomeVFSResult
502 nsGnomeVFSInputStream::DoRead(char *aBuf, PRUint32 aCount, PRUint32 *aCountRead)
504 GnomeVFSResult rv;
506 if (mHandle)
508 GnomeVFSFileSize bytesRead;
509 rv = gnome_vfs_read(mHandle, aBuf, aCount, &bytesRead);
510 if (rv == GNOME_VFS_OK)
512 *aCountRead = (PRUint32) bytesRead;
513 mBytesRemaining -= *aCountRead;
516 else if (mDirOpen)
518 rv = GNOME_VFS_OK;
520 while (aCount && rv != GNOME_VFS_ERROR_EOF)
522 // Copy data out of our buffer
523 PRUint32 bufLen = mDirBuf.Length() - mDirBufCursor;
524 if (bufLen)
526 PRUint32 n = PR_MIN(bufLen, aCount);
527 memcpy(aBuf, mDirBuf.get() + mDirBufCursor, n);
528 *aCountRead += n;
529 aBuf += n;
530 aCount -= n;
531 mDirBufCursor += n;
534 if (!mDirListPtr) // Are we at the end of the directory list?
536 rv = GNOME_VFS_ERROR_EOF;
538 else if (aCount) // Do we need more data?
540 GnomeVFSFileInfo *info = (GnomeVFSFileInfo *) mDirListPtr->data;
542 // Prune '.' and '..' from directory listing.
543 if (info->name[0] == '.' &&
544 (info->name[1] == '\0' ||
545 (info->name[1] == '.' && info->name[2] == '\0')))
547 mDirListPtr = mDirListPtr->next;
548 continue;
551 mDirBuf.Assign("201: ");
553 // The "filename" field
554 nsCString escName;
555 nsCOMPtr<nsINetUtil> nu = do_GetService(NS_NETUTIL_CONTRACTID);
556 if (nu) {
557 nu->EscapeString(nsDependentCString(info->name),
558 nsINetUtil::ESCAPE_URL_PATH, escName);
560 mDirBuf.Append(escName);
561 mDirBuf.Append(' ');
564 // The "content-length" field
565 // XXX truncates size from 64-bit to 32-bit
566 mDirBuf.AppendInt(PRInt32(info->size));
567 mDirBuf.Append(' ');
569 // The "last-modified" field
571 // NSPR promises: PRTime is compatible with time_t
572 // we just need to convert from seconds to microseconds
573 PRExplodedTime tm;
574 PRTime pt = ((PRTime) info->mtime) * 1000000;
575 PR_ExplodeTime(pt, PR_GMTParameters, &tm);
577 char buf[64];
578 PR_FormatTimeUSEnglish(buf, sizeof(buf),
579 "%a,%%20%d%%20%b%%20%Y%%20%H:%M:%S%%20GMT ", &tm);
580 mDirBuf.Append(buf);
583 // The "file-type" field
584 switch (info->type)
586 case GNOME_VFS_FILE_TYPE_REGULAR:
587 mDirBuf.Append("FILE ");
588 break;
589 case GNOME_VFS_FILE_TYPE_DIRECTORY:
590 mDirBuf.Append("DIRECTORY ");
591 break;
592 case GNOME_VFS_FILE_TYPE_SYMBOLIC_LINK:
593 mDirBuf.Append("SYMBOLIC-LINK ");
594 break;
595 default:
596 break;
599 mDirBuf.Append('\n');
601 mDirBufCursor = 0;
602 mDirListPtr = mDirListPtr->next;
606 else
608 NS_NOTREACHED("reading from what?");
609 rv = GNOME_VFS_ERROR_GENERIC;
612 return rv;
615 // This class is used to implement SetContentTypeOfChannel.
616 class nsGnomeVFSSetContentTypeEvent : public nsRunnable
618 public:
619 nsGnomeVFSSetContentTypeEvent(nsIChannel *channel, const char *contentType)
620 : mChannel(channel), mContentType(contentType)
622 // stash channel reference in mChannel. no AddRef here! see note
623 // in SetContentTypeOfchannel.
626 NS_IMETHOD Run()
628 mChannel->SetContentType(mContentType);
629 return NS_OK;
632 private:
633 nsIChannel *mChannel;
634 nsCString mContentType;
637 nsresult
638 nsGnomeVFSInputStream::SetContentTypeOfChannel(const char *contentType)
640 // We need to proxy this call over to the main thread. We post an
641 // asynchronous event in this case so that we don't delay reading data, and
642 // we know that this is safe to do since the channel's reference will be
643 // released asynchronously as well. We trust the ordering of the main
644 // thread's event queue to protect us against memory corruption.
646 nsresult rv;
647 nsCOMPtr<nsIRunnable> ev =
648 new nsGnomeVFSSetContentTypeEvent(mChannel, contentType);
649 if (!ev)
651 rv = NS_ERROR_OUT_OF_MEMORY;
653 else
655 rv = NS_DispatchToMainThread(ev);
657 return rv;
660 NS_IMPL_THREADSAFE_ISUPPORTS1(nsGnomeVFSInputStream, nsIInputStream)
662 NS_IMETHODIMP
663 nsGnomeVFSInputStream::Close()
665 if (mHandle)
667 gnome_vfs_close(mHandle);
668 mHandle = nsnull;
671 if (mDirList)
673 // Destroy the list of GnomeVFSFileInfo objects...
674 g_list_foreach(mDirList, (GFunc) gnome_vfs_file_info_unref, nsnull);
675 g_list_free(mDirList);
676 mDirList = nsnull;
677 mDirListPtr = nsnull;
680 if (mChannel)
682 nsresult rv = NS_OK;
684 nsCOMPtr<nsIThread> thread = do_GetMainThread();
685 if (thread)
686 rv = NS_ProxyRelease(thread, mChannel);
688 NS_ASSERTION(thread && NS_SUCCEEDED(rv), "leaking channel reference");
689 mChannel = nsnull;
692 mSpec.Truncate(); // free memory
694 // Prevent future reads from re-opening the handle.
695 if (NS_SUCCEEDED(mStatus))
696 mStatus = NS_BASE_STREAM_CLOSED;
698 return NS_OK;
701 NS_IMETHODIMP
702 nsGnomeVFSInputStream::Available(PRUint32 *aResult)
704 if (NS_FAILED(mStatus))
705 return mStatus;
707 *aResult = mBytesRemaining;
708 return NS_OK;
711 NS_IMETHODIMP
712 nsGnomeVFSInputStream::Read(char *aBuf,
713 PRUint32 aCount,
714 PRUint32 *aCountRead)
716 *aCountRead = 0;
718 if (mStatus == NS_BASE_STREAM_CLOSED)
719 return NS_OK;
720 if (NS_FAILED(mStatus))
721 return mStatus;
723 GnomeVFSResult rv = GNOME_VFS_OK;
725 // If this is our first-time through here, then open the URI.
726 if (!mHandle && !mDirOpen)
727 rv = DoOpen();
729 if (rv == GNOME_VFS_OK)
730 rv = DoRead(aBuf, aCount, aCountRead);
732 if (rv != GNOME_VFS_OK)
734 // If we reach here, we hit some kind of error. EOF is not an error.
735 mStatus = MapGnomeVFSResult(rv);
736 if (mStatus == NS_BASE_STREAM_CLOSED)
737 return NS_OK;
739 LOG(("gnomevfs: result %d [%s] mapped to 0x%x\n",
740 rv, gnome_vfs_result_to_string(rv), mStatus));
742 return mStatus;
745 NS_IMETHODIMP
746 nsGnomeVFSInputStream::ReadSegments(nsWriteSegmentFun aWriter,
747 void *aClosure,
748 PRUint32 aCount,
749 PRUint32 *aResult)
751 // There is no way to implement this using GnomeVFS, but fortunately
752 // that doesn't matter. Because we are a blocking input stream, Necko
753 // isn't going to call our ReadSegments method.
754 NS_NOTREACHED("nsGnomeVFSInputStream::ReadSegments");
755 return NS_ERROR_NOT_IMPLEMENTED;
758 NS_IMETHODIMP
759 nsGnomeVFSInputStream::IsNonBlocking(PRBool *aResult)
761 *aResult = PR_FALSE;
762 return NS_OK;
765 //-----------------------------------------------------------------------------
767 class nsGnomeVFSProtocolHandler : public nsIProtocolHandler
768 , public nsIObserver
770 public:
771 NS_DECL_ISUPPORTS
772 NS_DECL_NSIPROTOCOLHANDLER
773 NS_DECL_NSIOBSERVER
775 nsresult Init();
777 private:
778 void InitSupportedProtocolsPref(nsIPrefBranch *prefs);
779 PRBool IsSupportedProtocol(const nsCString &spec);
781 nsCString mSupportedProtocols;
784 NS_IMPL_ISUPPORTS2(nsGnomeVFSProtocolHandler, nsIProtocolHandler, nsIObserver)
786 nsresult
787 nsGnomeVFSProtocolHandler::Init()
789 #ifdef PR_LOGGING
790 sGnomeVFSLog = PR_NewLogModule("gnomevfs");
791 #endif
793 if (!gnome_vfs_initialized())
795 if (!gnome_vfs_init())
797 NS_WARNING("gnome_vfs_init failed");
798 return NS_ERROR_UNEXPECTED;
802 nsCOMPtr<nsIPrefBranch2> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
803 if (prefs)
805 InitSupportedProtocolsPref(prefs);
806 prefs->AddObserver(MOZ_GNOMEVFS_SUPPORTED_PROTOCOLS, this, PR_FALSE);
809 return NS_OK;
812 void
813 nsGnomeVFSProtocolHandler::InitSupportedProtocolsPref(nsIPrefBranch *prefs)
815 // read preferences
816 nsresult rv = prefs->GetCharPref(MOZ_GNOMEVFS_SUPPORTED_PROTOCOLS,
817 getter_Copies(mSupportedProtocols));
818 if (NS_SUCCEEDED(rv)) {
819 mSupportedProtocols.StripWhitespace();
820 ToLowerCase(mSupportedProtocols);
822 else
823 mSupportedProtocols.Assign("smb:,sftp:"); // use defaults
825 LOG(("gnomevfs: supported protocols \"%s\"\n", mSupportedProtocols.get()));
828 PRBool
829 nsGnomeVFSProtocolHandler::IsSupportedProtocol(const nsCString &aSpec)
831 const char *specString = aSpec.get();
832 const char *colon = strchr(specString, ':');
833 if (!colon)
834 return PR_FALSE;
836 PRUint32 length = colon - specString + 1;
838 // <scheme> + ':'
839 nsCString scheme(specString, length);
841 char *found = PL_strcasestr(mSupportedProtocols.get(), scheme.get());
842 if (!found)
843 return PR_FALSE;
845 if (found[length] != ',' && found[length] != '\0')
846 return PR_FALSE;
848 return PR_TRUE;
851 NS_IMETHODIMP
852 nsGnomeVFSProtocolHandler::GetScheme(nsACString &aScheme)
854 aScheme.Assign(MOZ_GNOMEVFS_SCHEME);
855 return NS_OK;
858 NS_IMETHODIMP
859 nsGnomeVFSProtocolHandler::GetDefaultPort(PRInt32 *aDefaultPort)
861 *aDefaultPort = -1;
862 return NS_OK;
865 NS_IMETHODIMP
866 nsGnomeVFSProtocolHandler::GetProtocolFlags(PRUint32 *aProtocolFlags)
868 // Is URI_STD true of all GnomeVFS URI types?
869 *aProtocolFlags = URI_STD | URI_DANGEROUS_TO_LOAD;
870 return NS_OK;
873 NS_IMETHODIMP
874 nsGnomeVFSProtocolHandler::NewURI(const nsACString &aSpec,
875 const char *aOriginCharset,
876 nsIURI *aBaseURI,
877 nsIURI **aResult)
879 const nsCString flatSpec(aSpec);
880 LOG(("gnomevfs: NewURI [spec=%s]\n", flatSpec.get()));
882 if (!aBaseURI)
885 // XXX This check is used to limit the gnome-vfs protocols we support. For
886 // security reasons, it is best that we limit the protocols we support to
887 // those with known characteristics. We might want to lessen this
888 // restriction if it proves to be too heavy handed. A black list of
889 // protocols we don't want to support might be better. For example, we
890 // probably don't want to try to load "start-here:" inside the browser.
891 // There are others that fall into this category, which are best handled
892 // externally by Nautilus (or another app like it).
894 if (!IsSupportedProtocol(flatSpec))
895 return NS_ERROR_UNKNOWN_PROTOCOL;
897 // Verify that GnomeVFS supports this URI scheme.
898 GnomeVFSURI *uri = gnome_vfs_uri_new(flatSpec.get());
899 if (!uri)
900 return NS_ERROR_UNKNOWN_PROTOCOL;
904 // XXX Can we really assume that all gnome-vfs URIs can be parsed using
905 // nsStandardURL? We probably really need to implement nsIURI/nsIURL
906 // in terms of the gnome_vfs_uri_XXX methods, but at least this works
907 // correctly for smb:// URLs ;-)
909 // Also, it might not be possible to fully implement nsIURI/nsIURL in
910 // terms of GnomeVFSURI since some Necko methods have no GnomeVFS
911 // equivalent.
913 nsresult rv;
914 nsCOMPtr<nsIStandardURL> url =
915 do_CreateInstance(NS_STANDARDURL_CONTRACTID, &rv);
916 if (NS_FAILED(rv))
917 return rv;
919 rv = url->Init(nsIStandardURL::URLTYPE_STANDARD, -1, flatSpec,
920 aOriginCharset, aBaseURI);
921 if (NS_SUCCEEDED(rv))
922 rv = CallQueryInterface(url, aResult);
924 return rv;
927 NS_IMETHODIMP
928 nsGnomeVFSProtocolHandler::NewChannel(nsIURI *aURI, nsIChannel **aResult)
930 NS_ENSURE_ARG_POINTER(aURI);
931 nsresult rv;
933 nsCAutoString spec;
934 rv = aURI->GetSpec(spec);
935 if (NS_FAILED(rv))
936 return rv;
938 nsRefPtr<nsGnomeVFSInputStream> stream = new nsGnomeVFSInputStream(spec);
939 if (!stream)
941 rv = NS_ERROR_OUT_OF_MEMORY;
943 else
945 // start out assuming an unknown content-type. we'll set the content-type
946 // to something better once we open the URI.
947 rv = NS_NewInputStreamChannel(aResult, aURI, stream,
948 NS_LITERAL_CSTRING(UNKNOWN_CONTENT_TYPE));
949 if (NS_SUCCEEDED(rv))
950 stream->SetChannel(*aResult);
952 return rv;
955 NS_IMETHODIMP
956 nsGnomeVFSProtocolHandler::AllowPort(PRInt32 aPort,
957 const char *aScheme,
958 PRBool *aResult)
960 // Don't override anything.
961 *aResult = PR_FALSE;
962 return NS_OK;
965 NS_IMETHODIMP
966 nsGnomeVFSProtocolHandler::Observe(nsISupports *aSubject,
967 const char *aTopic,
968 const PRUnichar *aData)
970 if (strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID) == 0) {
971 nsCOMPtr<nsIPrefBranch> prefs = do_QueryInterface(aSubject);
972 InitSupportedProtocolsPref(prefs);
974 return NS_OK;
977 //-----------------------------------------------------------------------------
979 #define NS_GNOMEVFSPROTOCOLHANDLER_CID \
980 { /* 9b6dc177-a2e4-49e1-9c98-0a8384de7f6c */ \
981 0x9b6dc177, \
982 0xa2e4, \
983 0x49e1, \
984 {0x9c, 0x98, 0x0a, 0x83, 0x84, 0xde, 0x7f, 0x6c} \
987 NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsGnomeVFSProtocolHandler, Init)
988 NS_DEFINE_NAMED_CID(NS_GNOMEVFSPROTOCOLHANDLER_CID);
990 static const mozilla::Module::CIDEntry kVFSCIDs[] = {
991 { &kNS_GNOMEVFSPROTOCOLHANDLER_CID, false, NULL, nsGnomeVFSProtocolHandlerConstructor },
992 { NULL }
995 static const mozilla::Module::ContractIDEntry kVFSContracts[] = {
996 { NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX MOZ_GNOMEVFS_SCHEME, &kNS_GNOMEVFSPROTOCOLHANDLER_CID },
997 { NULL }
1000 static const mozilla::Module kVFSModule = {
1001 mozilla::Module::kVersion,
1002 kVFSCIDs,
1003 kVFSContracts
1006 NSMODULE_DEFN(nsGnomeVFSModule) = &kVFSModule;