michael@0: /* vim:set ts=2 sw=2 et cindent: */ michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: /* michael@0: * This code is based on original Mozilla gnome-vfs extension. It implements michael@0: * input stream provided by GVFS/GIO. michael@0: */ michael@0: #include "mozilla/ModuleUtils.h" michael@0: #include "nsIPrefService.h" michael@0: #include "nsIPrefBranch.h" michael@0: #include "nsIObserver.h" michael@0: #include "nsThreadUtils.h" michael@0: #include "nsProxyRelease.h" michael@0: #include "nsIStringBundle.h" michael@0: #include "nsIStandardURL.h" michael@0: #include "nsMimeTypes.h" michael@0: #include "nsNetUtil.h" michael@0: #include "mozilla/Monitor.h" michael@0: #include michael@0: #include michael@0: michael@0: #define MOZ_GIO_SCHEME "moz-gio" michael@0: #define MOZ_GIO_SUPPORTED_PROTOCOLS "network.gio.supported-protocols" michael@0: michael@0: //----------------------------------------------------------------------------- michael@0: michael@0: // NSPR_LOG_MODULES=gio:5 michael@0: #ifdef PR_LOGGING michael@0: static PRLogModuleInfo *sGIOLog; michael@0: #define LOG(args) PR_LOG(sGIOLog, PR_LOG_DEBUG, args) michael@0: #else michael@0: #define LOG(args) michael@0: #endif michael@0: michael@0: michael@0: //----------------------------------------------------------------------------- michael@0: static nsresult michael@0: MapGIOResult(gint code) michael@0: { michael@0: switch (code) michael@0: { michael@0: case G_IO_ERROR_NOT_FOUND: return NS_ERROR_FILE_NOT_FOUND; // shows error michael@0: case G_IO_ERROR_INVALID_ARGUMENT: return NS_ERROR_INVALID_ARG; michael@0: case G_IO_ERROR_NOT_SUPPORTED: return NS_ERROR_NOT_AVAILABLE; michael@0: case G_IO_ERROR_NO_SPACE: return NS_ERROR_FILE_NO_DEVICE_SPACE; michael@0: case G_IO_ERROR_READ_ONLY: return NS_ERROR_FILE_READ_ONLY; michael@0: case G_IO_ERROR_PERMISSION_DENIED: return NS_ERROR_FILE_ACCESS_DENIED; // wrong password/login michael@0: case G_IO_ERROR_CLOSED: return NS_BASE_STREAM_CLOSED; // was EOF michael@0: case G_IO_ERROR_NOT_DIRECTORY: return NS_ERROR_FILE_NOT_DIRECTORY; michael@0: case G_IO_ERROR_PENDING: return NS_ERROR_IN_PROGRESS; michael@0: case G_IO_ERROR_EXISTS: return NS_ERROR_FILE_ALREADY_EXISTS; michael@0: case G_IO_ERROR_IS_DIRECTORY: return NS_ERROR_FILE_IS_DIRECTORY; michael@0: case G_IO_ERROR_NOT_MOUNTED: return NS_ERROR_NOT_CONNECTED; // shows error michael@0: case G_IO_ERROR_HOST_NOT_FOUND: return NS_ERROR_UNKNOWN_HOST; // shows error michael@0: case G_IO_ERROR_CANCELLED: return NS_ERROR_ABORT; michael@0: case G_IO_ERROR_NOT_EMPTY: return NS_ERROR_FILE_DIR_NOT_EMPTY; michael@0: case G_IO_ERROR_FILENAME_TOO_LONG: return NS_ERROR_FILE_NAME_TOO_LONG; michael@0: case G_IO_ERROR_INVALID_FILENAME: return NS_ERROR_FILE_INVALID_PATH; michael@0: case G_IO_ERROR_TIMED_OUT: return NS_ERROR_NET_TIMEOUT; // shows error michael@0: case G_IO_ERROR_WOULD_BLOCK: return NS_BASE_STREAM_WOULD_BLOCK; michael@0: case G_IO_ERROR_FAILED_HANDLED: return NS_ERROR_ABORT; // Cancel on login dialog michael@0: michael@0: /* unhandled: michael@0: G_IO_ERROR_NOT_REGULAR_FILE, michael@0: G_IO_ERROR_NOT_SYMBOLIC_LINK, michael@0: G_IO_ERROR_NOT_MOUNTABLE_FILE, michael@0: G_IO_ERROR_TOO_MANY_LINKS, michael@0: G_IO_ERROR_ALREADY_MOUNTED, michael@0: G_IO_ERROR_CANT_CREATE_BACKUP, michael@0: G_IO_ERROR_WRONG_ETAG, michael@0: G_IO_ERROR_WOULD_RECURSE, michael@0: G_IO_ERROR_BUSY, michael@0: G_IO_ERROR_WOULD_MERGE, michael@0: G_IO_ERROR_TOO_MANY_OPEN_FILES michael@0: */ michael@0: // Make GCC happy michael@0: default: michael@0: return NS_ERROR_FAILURE; michael@0: } michael@0: michael@0: return NS_ERROR_FAILURE; michael@0: } michael@0: michael@0: static nsresult michael@0: MapGIOResult(GError *result) michael@0: { michael@0: if (!result) michael@0: return NS_OK; michael@0: else michael@0: return MapGIOResult(result->code); michael@0: } michael@0: /** Return values for mount operation. michael@0: * These enums are used as mount operation return values. michael@0: */ michael@0: typedef enum { michael@0: MOUNT_OPERATION_IN_PROGRESS, /** \enum operation in progress */ michael@0: MOUNT_OPERATION_SUCCESS, /** \enum operation successful */ michael@0: MOUNT_OPERATION_FAILED /** \enum operation not successful */ michael@0: } MountOperationResult; michael@0: //----------------------------------------------------------------------------- michael@0: /** michael@0: * Sort function compares according to file type (directory/file) michael@0: * and alphabethical order michael@0: * @param a pointer to GFileInfo object to compare michael@0: * @param b pointer to GFileInfo object to compare michael@0: * @return -1 when first object should be before the second, 0 when equal, michael@0: * +1 when second object should be before the first michael@0: */ michael@0: static gint michael@0: FileInfoComparator(gconstpointer a, gconstpointer b) michael@0: { michael@0: GFileInfo *ia = ( GFileInfo *) a; michael@0: GFileInfo *ib = ( GFileInfo *) b; michael@0: if (g_file_info_get_file_type(ia) == G_FILE_TYPE_DIRECTORY michael@0: && g_file_info_get_file_type(ib) != G_FILE_TYPE_DIRECTORY) michael@0: return -1; michael@0: if (g_file_info_get_file_type(ib) == G_FILE_TYPE_DIRECTORY michael@0: && g_file_info_get_file_type(ia) != G_FILE_TYPE_DIRECTORY) michael@0: return 1; michael@0: michael@0: return strcasecmp(g_file_info_get_name(ia), g_file_info_get_name(ib)); michael@0: } michael@0: michael@0: /* Declaration of mount callback functions */ michael@0: static void mount_enclosing_volume_finished (GObject *source_object, michael@0: GAsyncResult *res, michael@0: gpointer user_data); michael@0: static void mount_operation_ask_password (GMountOperation *mount_op, michael@0: const char *message, michael@0: const char *default_user, michael@0: const char *default_domain, michael@0: GAskPasswordFlags flags, michael@0: gpointer user_data); michael@0: //----------------------------------------------------------------------------- michael@0: michael@0: class nsGIOInputStream MOZ_FINAL : public nsIInputStream michael@0: { michael@0: public: michael@0: NS_DECL_THREADSAFE_ISUPPORTS michael@0: NS_DECL_NSIINPUTSTREAM michael@0: michael@0: nsGIOInputStream(const nsCString &uriSpec) michael@0: : mSpec(uriSpec) michael@0: , mChannel(nullptr) michael@0: , mHandle(nullptr) michael@0: , mStream(nullptr) michael@0: , mBytesRemaining(UINT64_MAX) michael@0: , mStatus(NS_OK) michael@0: , mDirList(nullptr) michael@0: , mDirListPtr(nullptr) michael@0: , mDirBufCursor(0) michael@0: , mDirOpen(false) michael@0: , mMonitorMountInProgress("GIOInputStream::MountFinished") { } michael@0: michael@0: ~nsGIOInputStream() { Close(); } michael@0: michael@0: void SetChannel(nsIChannel *channel) michael@0: { michael@0: // We need to hold an owning reference to our channel. This is done michael@0: // so we can access the channel's notification callbacks to acquire michael@0: // a reference to a nsIAuthPrompt if we need to handle an interactive michael@0: // mount operation. michael@0: // michael@0: // However, the channel can only be accessed on the main thread, so michael@0: // we have to be very careful with ownership. Moreover, it doesn't michael@0: // support threadsafe addref/release, so proxying is the answer. michael@0: // michael@0: // Also, it's important to note that this likely creates a reference michael@0: // cycle since the channel likely owns this stream. This reference michael@0: // cycle is broken in our Close method. michael@0: michael@0: NS_ADDREF(mChannel = channel); michael@0: } michael@0: void SetMountResult(MountOperationResult result, gint error_code); michael@0: private: michael@0: nsresult DoOpen(); michael@0: nsresult DoRead(char *aBuf, uint32_t aCount, uint32_t *aCountRead); michael@0: nsresult SetContentTypeOfChannel(const char *contentType); michael@0: nsresult MountVolume(); michael@0: nsresult DoOpenDirectory(); michael@0: nsresult DoOpenFile(GFileInfo *info); michael@0: nsCString mSpec; michael@0: nsIChannel *mChannel; // manually refcounted michael@0: GFile *mHandle; michael@0: GFileInputStream *mStream; michael@0: uint64_t mBytesRemaining; michael@0: nsresult mStatus; michael@0: GList *mDirList; michael@0: GList *mDirListPtr; michael@0: nsCString mDirBuf; michael@0: uint32_t mDirBufCursor; michael@0: bool mDirOpen; michael@0: MountOperationResult mMountRes; michael@0: mozilla::Monitor mMonitorMountInProgress; michael@0: gint mMountErrorCode; michael@0: }; michael@0: /** michael@0: * Set result of mount operation and notify monitor waiting for results. michael@0: * This method is called in main thread as long as it is used only michael@0: * in mount_enclosing_volume_finished function. michael@0: * @param result Result of mount operation michael@0: */ michael@0: void michael@0: nsGIOInputStream::SetMountResult(MountOperationResult result, gint error_code) michael@0: { michael@0: mozilla::MonitorAutoLock mon(mMonitorMountInProgress); michael@0: mMountRes = result; michael@0: mMountErrorCode = error_code; michael@0: mon.Notify(); michael@0: } michael@0: michael@0: /** michael@0: * Start mount operation and wait in loop until it is finished. This method is michael@0: * called from thread which is trying to read from location. michael@0: */ michael@0: nsresult michael@0: nsGIOInputStream::MountVolume() { michael@0: GMountOperation* mount_op = g_mount_operation_new(); michael@0: g_signal_connect (mount_op, "ask-password", michael@0: G_CALLBACK (mount_operation_ask_password), mChannel); michael@0: mMountRes = MOUNT_OPERATION_IN_PROGRESS; michael@0: /* g_file_mount_enclosing_volume uses a dbus request to mount the volume. michael@0: Callback mount_enclosing_volume_finished is called in main thread michael@0: (not this thread on which this method is called). */ michael@0: g_file_mount_enclosing_volume(mHandle, michael@0: G_MOUNT_MOUNT_NONE, michael@0: mount_op, michael@0: nullptr, michael@0: mount_enclosing_volume_finished, michael@0: this); michael@0: mozilla::MonitorAutoLock mon(mMonitorMountInProgress); michael@0: /* Waiting for finish of mount operation thread */ michael@0: while (mMountRes == MOUNT_OPERATION_IN_PROGRESS) michael@0: mon.Wait(); michael@0: michael@0: g_object_unref(mount_op); michael@0: michael@0: if (mMountRes == MOUNT_OPERATION_FAILED) { michael@0: return MapGIOResult(mMountErrorCode); michael@0: } else { michael@0: return NS_OK; michael@0: } michael@0: } michael@0: michael@0: /** michael@0: * Create list of infos about objects in opened directory michael@0: * Return: NS_OK when list obtained, otherwise error code according michael@0: * to failed operation. michael@0: */ michael@0: nsresult michael@0: nsGIOInputStream::DoOpenDirectory() michael@0: { michael@0: GError *error = nullptr; michael@0: michael@0: GFileEnumerator *f_enum = g_file_enumerate_children(mHandle, michael@0: "standard::*,time::*", michael@0: G_FILE_QUERY_INFO_NONE, michael@0: nullptr, michael@0: &error); michael@0: if (!f_enum) { michael@0: nsresult rv = MapGIOResult(error); michael@0: g_warning("Cannot read from directory: %s", error->message); michael@0: g_error_free(error); michael@0: return rv; michael@0: } michael@0: // fill list of file infos michael@0: GFileInfo *info = g_file_enumerator_next_file(f_enum, nullptr, &error); michael@0: while (info) { michael@0: mDirList = g_list_append(mDirList, info); michael@0: info = g_file_enumerator_next_file(f_enum, nullptr, &error); michael@0: } michael@0: g_object_unref(f_enum); michael@0: if (error) { michael@0: g_warning("Error reading directory content: %s", error->message); michael@0: nsresult rv = MapGIOResult(error); michael@0: g_error_free(error); michael@0: return rv; michael@0: } michael@0: mDirOpen = true; michael@0: michael@0: // Sort list of file infos by using FileInfoComparator function michael@0: mDirList = g_list_sort(mDirList, FileInfoComparator); michael@0: mDirListPtr = mDirList; michael@0: michael@0: // Write base URL (make sure it ends with a '/') michael@0: mDirBuf.Append("300: "); michael@0: mDirBuf.Append(mSpec); michael@0: if (mSpec.get()[mSpec.Length() - 1] != '/') michael@0: mDirBuf.Append('/'); michael@0: mDirBuf.Append('\n'); michael@0: michael@0: // Write column names michael@0: mDirBuf.Append("200: filename content-length last-modified file-type\n"); michael@0: michael@0: // Write charset (assume UTF-8) michael@0: // XXX is this correct? michael@0: mDirBuf.Append("301: UTF-8\n"); michael@0: SetContentTypeOfChannel(APPLICATION_HTTP_INDEX_FORMAT); michael@0: return NS_OK; michael@0: } michael@0: michael@0: /** michael@0: * Create file stream and set mime type for channel michael@0: * @param info file info used to determine mime type michael@0: * @return NS_OK when file stream created successfuly, error code otherwise michael@0: */ michael@0: nsresult michael@0: nsGIOInputStream::DoOpenFile(GFileInfo *info) michael@0: { michael@0: GError *error = nullptr; michael@0: michael@0: mStream = g_file_read(mHandle, nullptr, &error); michael@0: if (!mStream) { michael@0: nsresult rv = MapGIOResult(error); michael@0: g_warning("Cannot read from file: %s", error->message); michael@0: g_error_free(error); michael@0: return rv; michael@0: } michael@0: michael@0: const char * content_type = g_file_info_get_content_type(info); michael@0: if (content_type) { michael@0: char *mime_type = g_content_type_get_mime_type(content_type); michael@0: if (mime_type) { michael@0: if (strcmp(mime_type, APPLICATION_OCTET_STREAM) != 0) { michael@0: SetContentTypeOfChannel(mime_type); michael@0: } michael@0: g_free(mime_type); michael@0: } michael@0: } else { michael@0: g_warning("Missing content type."); michael@0: } michael@0: michael@0: mBytesRemaining = g_file_info_get_size(info); michael@0: // Update the content length attribute on the channel. We do this michael@0: // synchronously without proxying. This hack is not as bad as it looks! michael@0: mChannel->SetContentLength(mBytesRemaining); michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: /** michael@0: * Start file open operation, mount volume when needed and according to file type michael@0: * create file output stream or read directory content. michael@0: * @return NS_OK when file or directory opened successfully, error code otherwise michael@0: */ michael@0: nsresult michael@0: nsGIOInputStream::DoOpen() michael@0: { michael@0: nsresult rv; michael@0: GError *error = nullptr; michael@0: michael@0: NS_ASSERTION(mHandle == nullptr, "already open"); michael@0: michael@0: mHandle = g_file_new_for_uri( mSpec.get() ); michael@0: michael@0: GFileInfo *info = g_file_query_info(mHandle, michael@0: "standard::*", michael@0: G_FILE_QUERY_INFO_NONE, michael@0: nullptr, michael@0: &error); michael@0: michael@0: if (error) { michael@0: if (error->domain == G_IO_ERROR && error->code == G_IO_ERROR_NOT_MOUNTED) { michael@0: // location is not yet mounted, try to mount michael@0: g_error_free(error); michael@0: if (NS_IsMainThread()) michael@0: return NS_ERROR_NOT_CONNECTED; michael@0: error = nullptr; michael@0: rv = MountVolume(); michael@0: if (rv != NS_OK) { michael@0: return rv; michael@0: } michael@0: // get info again michael@0: info = g_file_query_info(mHandle, michael@0: "standard::*", michael@0: G_FILE_QUERY_INFO_NONE, michael@0: nullptr, michael@0: &error); michael@0: // second try to get file info from remote files after media mount michael@0: if (!info) { michael@0: g_warning("Unable to get file info: %s", error->message); michael@0: rv = MapGIOResult(error); michael@0: g_error_free(error); michael@0: return rv; michael@0: } michael@0: } else { michael@0: g_warning("Unable to get file info: %s", error->message); michael@0: rv = MapGIOResult(error); michael@0: g_error_free(error); michael@0: return rv; michael@0: } michael@0: } michael@0: // Get file type to handle directories and file differently michael@0: GFileType f_type = g_file_info_get_file_type(info); michael@0: if (f_type == G_FILE_TYPE_DIRECTORY) { michael@0: // directory michael@0: rv = DoOpenDirectory(); michael@0: } else if (f_type != G_FILE_TYPE_UNKNOWN) { michael@0: // file michael@0: rv = DoOpenFile(info); michael@0: } else { michael@0: g_warning("Unable to get file type."); michael@0: rv = NS_ERROR_FILE_NOT_FOUND; michael@0: } michael@0: if (info) michael@0: g_object_unref(info); michael@0: return rv; michael@0: } michael@0: michael@0: /** michael@0: * Read content of file or create file list from directory michael@0: * @param aBuf read destination buffer michael@0: * @param aCount length of destination buffer michael@0: * @param aCountRead number of read characters michael@0: * @return NS_OK when read successfully, NS_BASE_STREAM_CLOSED when end of file, michael@0: * error code otherwise michael@0: */ michael@0: nsresult michael@0: nsGIOInputStream::DoRead(char *aBuf, uint32_t aCount, uint32_t *aCountRead) michael@0: { michael@0: nsresult rv = NS_ERROR_NOT_AVAILABLE; michael@0: if (mStream) { michael@0: // file read michael@0: GError *error = nullptr; michael@0: uint32_t bytes_read = g_input_stream_read(G_INPUT_STREAM(mStream), michael@0: aBuf, michael@0: aCount, michael@0: nullptr, michael@0: &error); michael@0: if (error) { michael@0: rv = MapGIOResult(error); michael@0: *aCountRead = 0; michael@0: g_warning("Cannot read from file: %s", error->message); michael@0: g_error_free(error); michael@0: return rv; michael@0: } michael@0: *aCountRead = bytes_read; michael@0: mBytesRemaining -= *aCountRead; michael@0: return NS_OK; michael@0: } michael@0: else if (mDirOpen) { michael@0: // directory read michael@0: while (aCount && rv != NS_BASE_STREAM_CLOSED) michael@0: { michael@0: // Copy data out of our buffer michael@0: uint32_t bufLen = mDirBuf.Length() - mDirBufCursor; michael@0: if (bufLen) michael@0: { michael@0: uint32_t n = std::min(bufLen, aCount); michael@0: memcpy(aBuf, mDirBuf.get() + mDirBufCursor, n); michael@0: *aCountRead += n; michael@0: aBuf += n; michael@0: aCount -= n; michael@0: mDirBufCursor += n; michael@0: } michael@0: michael@0: if (!mDirListPtr) // Are we at the end of the directory list? michael@0: { michael@0: rv = NS_BASE_STREAM_CLOSED; michael@0: } michael@0: else if (aCount) // Do we need more data? michael@0: { michael@0: GFileInfo *info = (GFileInfo *) mDirListPtr->data; michael@0: michael@0: // Prune '.' and '..' from directory listing. michael@0: const char * fname = g_file_info_get_name(info); michael@0: if (fname && fname[0] == '.' && michael@0: (fname[1] == '\0' || (fname[1] == '.' && fname[2] == '\0'))) michael@0: { michael@0: mDirListPtr = mDirListPtr->next; michael@0: continue; michael@0: } michael@0: michael@0: mDirBuf.Assign("201: "); michael@0: michael@0: // The "filename" field michael@0: nsCString escName; michael@0: nsCOMPtr nu = do_GetService(NS_NETUTIL_CONTRACTID); michael@0: if (nu && fname) { michael@0: nu->EscapeString(nsDependentCString(fname), michael@0: nsINetUtil::ESCAPE_URL_PATH, escName); michael@0: michael@0: mDirBuf.Append(escName); michael@0: mDirBuf.Append(' '); michael@0: } michael@0: michael@0: // The "content-length" field michael@0: // XXX truncates size from 64-bit to 32-bit michael@0: mDirBuf.AppendInt(int32_t(g_file_info_get_size(info))); michael@0: mDirBuf.Append(' '); michael@0: michael@0: // The "last-modified" field michael@0: // michael@0: // NSPR promises: PRTime is compatible with time_t michael@0: // we just need to convert from seconds to microseconds michael@0: GTimeVal gtime; michael@0: g_file_info_get_modification_time(info, >ime); michael@0: michael@0: PRExplodedTime tm; michael@0: PRTime pt = ((PRTime) gtime.tv_sec) * 1000000; michael@0: PR_ExplodeTime(pt, PR_GMTParameters, &tm); michael@0: { michael@0: char buf[64]; michael@0: PR_FormatTimeUSEnglish(buf, sizeof(buf), michael@0: "%a,%%20%d%%20%b%%20%Y%%20%H:%M:%S%%20GMT ", &tm); michael@0: mDirBuf.Append(buf); michael@0: } michael@0: michael@0: // The "file-type" field michael@0: switch (g_file_info_get_file_type(info)) michael@0: { michael@0: case G_FILE_TYPE_REGULAR: michael@0: mDirBuf.Append("FILE "); michael@0: break; michael@0: case G_FILE_TYPE_DIRECTORY: michael@0: mDirBuf.Append("DIRECTORY "); michael@0: break; michael@0: case G_FILE_TYPE_SYMBOLIC_LINK: michael@0: mDirBuf.Append("SYMBOLIC-LINK "); michael@0: break; michael@0: default: michael@0: break; michael@0: } michael@0: mDirBuf.Append('\n'); michael@0: michael@0: mDirBufCursor = 0; michael@0: mDirListPtr = mDirListPtr->next; michael@0: } michael@0: } michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: /** michael@0: * This class is used to implement SetContentTypeOfChannel. michael@0: */ michael@0: class nsGIOSetContentTypeEvent : public nsRunnable michael@0: { michael@0: public: michael@0: nsGIOSetContentTypeEvent(nsIChannel *channel, const char *contentType) michael@0: : mChannel(channel), mContentType(contentType) michael@0: { michael@0: // stash channel reference in mChannel. no AddRef here! see note michael@0: // in SetContentTypeOfchannel. michael@0: } michael@0: michael@0: NS_IMETHOD Run() michael@0: { michael@0: mChannel->SetContentType(mContentType); michael@0: return NS_OK; michael@0: } michael@0: michael@0: private: michael@0: nsIChannel *mChannel; michael@0: nsCString mContentType; michael@0: }; michael@0: michael@0: nsresult michael@0: nsGIOInputStream::SetContentTypeOfChannel(const char *contentType) michael@0: { michael@0: // We need to proxy this call over to the main thread. We post an michael@0: // asynchronous event in this case so that we don't delay reading data, and michael@0: // we know that this is safe to do since the channel's reference will be michael@0: // released asynchronously as well. We trust the ordering of the main michael@0: // thread's event queue to protect us against memory corruption. michael@0: michael@0: nsresult rv; michael@0: nsCOMPtr ev = michael@0: new nsGIOSetContentTypeEvent(mChannel, contentType); michael@0: if (!ev) michael@0: { michael@0: rv = NS_ERROR_OUT_OF_MEMORY; michael@0: } michael@0: else michael@0: { michael@0: rv = NS_DispatchToMainThread(ev); michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: NS_IMPL_ISUPPORTS(nsGIOInputStream, nsIInputStream) michael@0: michael@0: /** michael@0: * Free all used memory and close stream. michael@0: */ michael@0: NS_IMETHODIMP michael@0: nsGIOInputStream::Close() michael@0: { michael@0: if (mStream) michael@0: { michael@0: g_object_unref(mStream); michael@0: mStream = nullptr; michael@0: } michael@0: michael@0: if (mHandle) michael@0: { michael@0: g_object_unref(mHandle); michael@0: mHandle = nullptr; michael@0: } michael@0: michael@0: if (mDirList) michael@0: { michael@0: // Destroy the list of GIOFileInfo objects... michael@0: g_list_foreach(mDirList, (GFunc) g_object_unref, nullptr); michael@0: g_list_free(mDirList); michael@0: mDirList = nullptr; michael@0: mDirListPtr = nullptr; michael@0: } michael@0: michael@0: if (mChannel) michael@0: { michael@0: nsresult rv = NS_OK; michael@0: michael@0: nsCOMPtr thread = do_GetMainThread(); michael@0: if (thread) michael@0: rv = NS_ProxyRelease(thread, mChannel); michael@0: michael@0: NS_ASSERTION(thread && NS_SUCCEEDED(rv), "leaking channel reference"); michael@0: mChannel = nullptr; michael@0: (void) rv; michael@0: } michael@0: michael@0: mSpec.Truncate(); // free memory michael@0: michael@0: // Prevent future reads from re-opening the handle. michael@0: if (NS_SUCCEEDED(mStatus)) michael@0: mStatus = NS_BASE_STREAM_CLOSED; michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: /** michael@0: * Return number of remaining bytes available on input michael@0: * @param aResult remaining bytes michael@0: */ michael@0: NS_IMETHODIMP michael@0: nsGIOInputStream::Available(uint64_t *aResult) michael@0: { michael@0: if (NS_FAILED(mStatus)) michael@0: return mStatus; michael@0: michael@0: *aResult = mBytesRemaining; michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: /** michael@0: * Trying to read from stream. When location is not available it tries to mount it. michael@0: * @param aBuf buffer to put read data michael@0: * @param aCount length of aBuf michael@0: * @param aCountRead number of bytes actually read michael@0: */ michael@0: NS_IMETHODIMP michael@0: nsGIOInputStream::Read(char *aBuf, michael@0: uint32_t aCount, michael@0: uint32_t *aCountRead) michael@0: { michael@0: *aCountRead = 0; michael@0: // Check if file is already opened, otherwise open it michael@0: if (!mStream && !mDirOpen && mStatus == NS_OK) { michael@0: mStatus = DoOpen(); michael@0: if (NS_FAILED(mStatus)) { michael@0: return mStatus; michael@0: } michael@0: } michael@0: michael@0: mStatus = DoRead(aBuf, aCount, aCountRead); michael@0: // Check if all data has been read michael@0: if (mStatus == NS_BASE_STREAM_CLOSED) michael@0: return NS_OK; michael@0: michael@0: // Check whenever any error appears while reading michael@0: return mStatus; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsGIOInputStream::ReadSegments(nsWriteSegmentFun aWriter, michael@0: void *aClosure, michael@0: uint32_t aCount, michael@0: uint32_t *aResult) michael@0: { michael@0: // There is no way to implement this using GnomeVFS, but fortunately michael@0: // that doesn't matter. Because we are a blocking input stream, Necko michael@0: // isn't going to call our ReadSegments method. michael@0: NS_NOTREACHED("nsGIOInputStream::ReadSegments"); michael@0: return NS_ERROR_NOT_IMPLEMENTED; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsGIOInputStream::IsNonBlocking(bool *aResult) michael@0: { michael@0: *aResult = false; michael@0: return NS_OK; michael@0: } michael@0: michael@0: //----------------------------------------------------------------------------- michael@0: michael@0: /** michael@0: * Called when finishing mount operation. Result of operation is set in michael@0: * nsGIOInputStream. This function is called in main thread as an async request michael@0: * typically from dbus. michael@0: * @param source_object GFile object which requested the mount michael@0: * @param res result object michael@0: * @param user_data pointer to nsGIOInputStream michael@0: */ michael@0: static void michael@0: mount_enclosing_volume_finished (GObject *source_object, michael@0: GAsyncResult *res, michael@0: gpointer user_data) michael@0: { michael@0: GError *error = nullptr; michael@0: michael@0: nsGIOInputStream* istream = static_cast(user_data); michael@0: michael@0: g_file_mount_enclosing_volume_finish(G_FILE (source_object), res, &error); michael@0: michael@0: if (error) { michael@0: g_warning("Mount failed: %s %d", error->message, error->code); michael@0: istream->SetMountResult(MOUNT_OPERATION_FAILED, error->code); michael@0: g_error_free(error); michael@0: } else { michael@0: istream->SetMountResult(MOUNT_OPERATION_SUCCESS, 0); michael@0: } michael@0: } michael@0: michael@0: /** michael@0: * This function is called when username or password are requested from user. michael@0: * This function is called in main thread as async request from dbus. michael@0: * @param mount_op mount operation michael@0: * @param message message to show to user michael@0: * @param default_user preffered user michael@0: * @param default_domain domain name michael@0: * @param flags what type of information is required michael@0: * @param user_data nsIChannel michael@0: */ michael@0: static void michael@0: mount_operation_ask_password (GMountOperation *mount_op, michael@0: const char *message, michael@0: const char *default_user, michael@0: const char *default_domain, michael@0: GAskPasswordFlags flags, michael@0: gpointer user_data) michael@0: { michael@0: nsIChannel *channel = (nsIChannel *) user_data; michael@0: if (!channel) { michael@0: g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED); michael@0: return; michael@0: } michael@0: // We can't handle request for domain michael@0: if (flags & G_ASK_PASSWORD_NEED_DOMAIN) { michael@0: g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED); michael@0: return; michael@0: } michael@0: michael@0: nsCOMPtr prompt; michael@0: NS_QueryNotificationCallbacks(channel, prompt); michael@0: michael@0: // If no auth prompt, then give up. We could failover to using the michael@0: // WindowWatcher service, but that might defeat a consumer's purposeful michael@0: // attempt to disable authentication (for whatever reason). michael@0: if (!prompt) { michael@0: g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED); michael@0: return; michael@0: } michael@0: // Parse out the host and port... michael@0: nsCOMPtr uri; michael@0: channel->GetURI(getter_AddRefs(uri)); michael@0: if (!uri) { michael@0: g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED); michael@0: return; michael@0: } michael@0: michael@0: nsAutoCString scheme, hostPort; michael@0: uri->GetScheme(scheme); michael@0: uri->GetHostPort(hostPort); michael@0: michael@0: // It doesn't make sense for either of these strings to be empty. What kind michael@0: // of funky URI is this? michael@0: if (scheme.IsEmpty() || hostPort.IsEmpty()) { michael@0: g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED); michael@0: return; michael@0: } michael@0: // Construct the single signon key. Altering the value of this key will michael@0: // cause people's remembered passwords to be forgotten. Think carefully michael@0: // before changing the way this key is constructed. michael@0: nsAutoString key, realm; michael@0: michael@0: NS_ConvertUTF8toUTF16 dispHost(scheme); michael@0: dispHost.Append(NS_LITERAL_STRING("://")); michael@0: dispHost.Append(NS_ConvertUTF8toUTF16(hostPort)); michael@0: michael@0: key = dispHost; michael@0: if (*default_domain != '\0') michael@0: { michael@0: // We assume the realm string is ASCII. That might be a bogus assumption, michael@0: // but we have no idea what encoding GnomeVFS is using, so for now we'll michael@0: // limit ourselves to ISO-Latin-1. XXX What is a better solution? michael@0: realm.Append('"'); michael@0: realm.Append(NS_ConvertASCIItoUTF16(default_domain)); michael@0: realm.Append('"'); michael@0: key.Append(' '); michael@0: key.Append(realm); michael@0: } michael@0: // Construct the message string... michael@0: // michael@0: // We use Necko's string bundle here. This code really should be encapsulated michael@0: // behind some Necko API, after all this code is based closely on the code in michael@0: // nsHttpChannel.cpp. michael@0: nsCOMPtr bundleSvc = michael@0: do_GetService(NS_STRINGBUNDLE_CONTRACTID); michael@0: if (!bundleSvc) { michael@0: g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED); michael@0: return; michael@0: } michael@0: nsCOMPtr bundle; michael@0: bundleSvc->CreateBundle("chrome://global/locale/commonDialogs.properties", michael@0: getter_AddRefs(bundle)); michael@0: if (!bundle) { michael@0: g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED); michael@0: return; michael@0: } michael@0: nsAutoString nsmessage; michael@0: michael@0: if (flags & G_ASK_PASSWORD_NEED_PASSWORD) { michael@0: if (flags & G_ASK_PASSWORD_NEED_USERNAME) { michael@0: if (!realm.IsEmpty()) { michael@0: const char16_t *strings[] = { realm.get(), dispHost.get() }; michael@0: bundle->FormatStringFromName(MOZ_UTF16("EnterLoginForRealm"), michael@0: strings, 2, getter_Copies(nsmessage)); michael@0: } else { michael@0: const char16_t *strings[] = { dispHost.get() }; michael@0: bundle->FormatStringFromName(MOZ_UTF16("EnterUserPasswordFor"), michael@0: strings, 1, getter_Copies(nsmessage)); michael@0: } michael@0: } else { michael@0: NS_ConvertUTF8toUTF16 userName(default_user); michael@0: const char16_t *strings[] = { userName.get(), dispHost.get() }; michael@0: bundle->FormatStringFromName(MOZ_UTF16("EnterPasswordFor"), michael@0: strings, 2, getter_Copies(nsmessage)); michael@0: } michael@0: } else { michael@0: g_warning("Unknown mount operation request (flags: %x)", flags); michael@0: } michael@0: michael@0: if (nsmessage.IsEmpty()) { michael@0: g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED); michael@0: return; michael@0: } michael@0: // Prompt the user... michael@0: nsresult rv; michael@0: bool retval = false; michael@0: char16_t *user = nullptr, *pass = nullptr; michael@0: if (default_user) { michael@0: // user will be freed by PromptUsernameAndPassword michael@0: user = ToNewUnicode(NS_ConvertUTF8toUTF16(default_user)); michael@0: } michael@0: if (flags & G_ASK_PASSWORD_NEED_USERNAME) { michael@0: rv = prompt->PromptUsernameAndPassword(nullptr, nsmessage.get(), michael@0: key.get(), michael@0: nsIAuthPrompt::SAVE_PASSWORD_PERMANENTLY, michael@0: &user, &pass, &retval); michael@0: } else { michael@0: rv = prompt->PromptPassword(nullptr, nsmessage.get(), michael@0: key.get(), michael@0: nsIAuthPrompt::SAVE_PASSWORD_PERMANENTLY, michael@0: &pass, &retval); michael@0: } michael@0: if (NS_FAILED(rv) || !retval) { // was || user == '\0' || pass == '\0' michael@0: g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED); michael@0: return; michael@0: } michael@0: /* GIO should accept UTF8 */ michael@0: g_mount_operation_set_username(mount_op, NS_ConvertUTF16toUTF8(user).get()); michael@0: g_mount_operation_set_password(mount_op, NS_ConvertUTF16toUTF8(pass).get()); michael@0: nsMemory::Free(user); michael@0: nsMemory::Free(pass); michael@0: g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_HANDLED); michael@0: } michael@0: michael@0: //----------------------------------------------------------------------------- michael@0: michael@0: class nsGIOProtocolHandler MOZ_FINAL : public nsIProtocolHandler michael@0: , public nsIObserver michael@0: { michael@0: public: michael@0: NS_DECL_ISUPPORTS michael@0: NS_DECL_NSIPROTOCOLHANDLER michael@0: NS_DECL_NSIOBSERVER michael@0: michael@0: nsresult Init(); michael@0: michael@0: private: michael@0: void InitSupportedProtocolsPref(nsIPrefBranch *prefs); michael@0: bool IsSupportedProtocol(const nsCString &spec); michael@0: michael@0: nsCString mSupportedProtocols; michael@0: }; michael@0: michael@0: NS_IMPL_ISUPPORTS(nsGIOProtocolHandler, nsIProtocolHandler, nsIObserver) michael@0: michael@0: nsresult michael@0: nsGIOProtocolHandler::Init() michael@0: { michael@0: #ifdef PR_LOGGING michael@0: sGIOLog = PR_NewLogModule("gio"); michael@0: #endif michael@0: michael@0: nsCOMPtr prefs = do_GetService(NS_PREFSERVICE_CONTRACTID); michael@0: if (prefs) michael@0: { michael@0: InitSupportedProtocolsPref(prefs); michael@0: prefs->AddObserver(MOZ_GIO_SUPPORTED_PROTOCOLS, this, false); michael@0: } michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: void michael@0: nsGIOProtocolHandler::InitSupportedProtocolsPref(nsIPrefBranch *prefs) michael@0: { michael@0: // Get user preferences to determine which protocol is supported. michael@0: // Gvfs/GIO has a set of supported protocols like obex, network, archive, michael@0: // computer, dav, cdda, gphoto2, trash, etc. Some of these seems to be michael@0: // irrelevant to process by browser. By default accept only smb and sftp michael@0: // protocols so far. michael@0: nsresult rv = prefs->GetCharPref(MOZ_GIO_SUPPORTED_PROTOCOLS, michael@0: getter_Copies(mSupportedProtocols)); michael@0: if (NS_SUCCEEDED(rv)) { michael@0: mSupportedProtocols.StripWhitespace(); michael@0: ToLowerCase(mSupportedProtocols); michael@0: } michael@0: else michael@0: mSupportedProtocols.Assign("smb:,sftp:"); // use defaults michael@0: michael@0: LOG(("gio: supported protocols \"%s\"\n", mSupportedProtocols.get())); michael@0: } michael@0: michael@0: bool michael@0: nsGIOProtocolHandler::IsSupportedProtocol(const nsCString &aSpec) michael@0: { michael@0: const char *specString = aSpec.get(); michael@0: const char *colon = strchr(specString, ':'); michael@0: if (!colon) michael@0: return false; michael@0: michael@0: uint32_t length = colon - specString + 1; michael@0: michael@0: // + ':' michael@0: nsCString scheme(specString, length); michael@0: michael@0: char *found = PL_strcasestr(mSupportedProtocols.get(), scheme.get()); michael@0: if (!found) michael@0: return false; michael@0: michael@0: if (found[length] != ',' && found[length] != '\0') michael@0: return false; michael@0: michael@0: return true; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsGIOProtocolHandler::GetScheme(nsACString &aScheme) michael@0: { michael@0: aScheme.Assign(MOZ_GIO_SCHEME); michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsGIOProtocolHandler::GetDefaultPort(int32_t *aDefaultPort) michael@0: { michael@0: *aDefaultPort = -1; michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsGIOProtocolHandler::GetProtocolFlags(uint32_t *aProtocolFlags) michael@0: { michael@0: // Is URI_STD true of all GnomeVFS URI types? michael@0: *aProtocolFlags = URI_STD | URI_DANGEROUS_TO_LOAD; michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsGIOProtocolHandler::NewURI(const nsACString &aSpec, michael@0: const char *aOriginCharset, michael@0: nsIURI *aBaseURI, michael@0: nsIURI **aResult) michael@0: { michael@0: const nsCString flatSpec(aSpec); michael@0: LOG(("gio: NewURI [spec=%s]\n", flatSpec.get())); michael@0: michael@0: if (!aBaseURI) michael@0: { michael@0: // XXX Is it good to support all GIO protocols? michael@0: if (!IsSupportedProtocol(flatSpec)) michael@0: return NS_ERROR_UNKNOWN_PROTOCOL; michael@0: michael@0: int32_t colon_location = flatSpec.FindChar(':'); michael@0: if (colon_location <= 0) michael@0: return NS_ERROR_UNKNOWN_PROTOCOL; michael@0: michael@0: // Verify that GIO supports this URI scheme. michael@0: bool uri_scheme_supported = false; michael@0: michael@0: GVfs *gvfs = g_vfs_get_default(); michael@0: michael@0: if (!gvfs) { michael@0: g_warning("Cannot get GVfs object."); michael@0: return NS_ERROR_UNKNOWN_PROTOCOL; michael@0: } michael@0: michael@0: const gchar* const * uri_schemes = g_vfs_get_supported_uri_schemes(gvfs); michael@0: michael@0: while (*uri_schemes != nullptr) { michael@0: // While flatSpec ends with ':' the uri_scheme does not. Therefore do not michael@0: // compare last character. michael@0: if (StringHead(flatSpec, colon_location).Equals(*uri_schemes)) { michael@0: uri_scheme_supported = true; michael@0: break; michael@0: } michael@0: uri_schemes++; michael@0: } michael@0: michael@0: if (!uri_scheme_supported) { michael@0: return NS_ERROR_UNKNOWN_PROTOCOL; michael@0: } michael@0: } michael@0: michael@0: nsresult rv; michael@0: nsCOMPtr url = michael@0: do_CreateInstance(NS_STANDARDURL_CONTRACTID, &rv); michael@0: if (NS_FAILED(rv)) michael@0: return rv; michael@0: michael@0: rv = url->Init(nsIStandardURL::URLTYPE_STANDARD, -1, flatSpec, michael@0: aOriginCharset, aBaseURI); michael@0: if (NS_SUCCEEDED(rv)) michael@0: rv = CallQueryInterface(url, aResult); michael@0: return rv; michael@0: michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsGIOProtocolHandler::NewChannel(nsIURI *aURI, nsIChannel **aResult) michael@0: { michael@0: NS_ENSURE_ARG_POINTER(aURI); michael@0: nsresult rv; michael@0: michael@0: nsAutoCString spec; michael@0: rv = aURI->GetSpec(spec); michael@0: if (NS_FAILED(rv)) michael@0: return rv; michael@0: michael@0: nsRefPtr stream = new nsGIOInputStream(spec); michael@0: if (!stream) michael@0: { michael@0: rv = NS_ERROR_OUT_OF_MEMORY; michael@0: } michael@0: else michael@0: { michael@0: // start out assuming an unknown content-type. we'll set the content-type michael@0: // to something better once we open the URI. michael@0: rv = NS_NewInputStreamChannel(aResult, michael@0: aURI, michael@0: stream, michael@0: NS_LITERAL_CSTRING(UNKNOWN_CONTENT_TYPE)); michael@0: if (NS_SUCCEEDED(rv)) michael@0: stream->SetChannel(*aResult); michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsGIOProtocolHandler::AllowPort(int32_t aPort, michael@0: const char *aScheme, michael@0: bool *aResult) michael@0: { michael@0: // Don't override anything. michael@0: *aResult = false; michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsGIOProtocolHandler::Observe(nsISupports *aSubject, michael@0: const char *aTopic, michael@0: const char16_t *aData) michael@0: { michael@0: if (strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID) == 0) { michael@0: nsCOMPtr prefs = do_QueryInterface(aSubject); michael@0: InitSupportedProtocolsPref(prefs); michael@0: } michael@0: return NS_OK; michael@0: } michael@0: michael@0: //----------------------------------------------------------------------------- michael@0: michael@0: #define NS_GIOPROTOCOLHANDLER_CID \ michael@0: { /* ee706783-3af8-4d19-9e84-e2ebfe213480 */ \ michael@0: 0xee706783, \ michael@0: 0x3af8, \ michael@0: 0x4d19, \ michael@0: {0x9e, 0x84, 0xe2, 0xeb, 0xfe, 0x21, 0x34, 0x80} \ michael@0: } michael@0: michael@0: NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsGIOProtocolHandler, Init) michael@0: NS_DEFINE_NAMED_CID(NS_GIOPROTOCOLHANDLER_CID); michael@0: michael@0: static const mozilla::Module::CIDEntry kVFSCIDs[] = { michael@0: { &kNS_GIOPROTOCOLHANDLER_CID, false, nullptr, nsGIOProtocolHandlerConstructor }, michael@0: { nullptr } michael@0: }; michael@0: michael@0: static const mozilla::Module::ContractIDEntry kVFSContracts[] = { michael@0: { NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX MOZ_GIO_SCHEME, &kNS_GIOPROTOCOLHANDLER_CID }, michael@0: { nullptr } michael@0: }; michael@0: michael@0: static const mozilla::Module kVFSModule = { michael@0: mozilla::Module::kVersion, michael@0: kVFSCIDs, michael@0: kVFSContracts michael@0: }; michael@0: michael@0: NSMODULE_DEFN(nsGIOModule) = &kVFSModule;