Ejemplo n.º 1
0
        /// <summary>
        /// Copies the item.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="store">The store.</param>
        /// <param name="source">The source.</param>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavForbiddenException"></exception>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavPreconditionFailedException"></exception>
        private static void CopyItem(IWebDavContext context, IWebDavStore store, IWebDavStoreItem source)
        {
            Uri destinationUri = GetDestinationHeader(context.Request);
            IWebDavStoreCollection destinationParentCollection = GetParentCollection(store, context, destinationUri);

            bool copyContent = (GetDepthHeader(context.Request) != 0);
            bool isNew       = true;

            string           destinationName = Uri.UnescapeDataString(destinationUri.Segments.Last().TrimEnd('/', '\\'));
            IWebDavStoreItem destination     = destinationParentCollection.GetItemByName(destinationName);

            if (destination != null)
            {
                if (source.ItemPath == destination.ItemPath)
                {
                    throw new WebDavForbiddenException();
                }
                if (!GetOverwriteHeader(context.Request))
                {
                    throw new WebDavPreconditionFailedException();
                }
                if (destination is IWebDavStoreCollection)
                {
                    destinationParentCollection.Delete(destination);
                }
                isNew = false;
            }

            destinationParentCollection.CopyItemHere(source, destinationName, copyContent);

            var statusCode = isNew ? HttpStatusCode.Created : HttpStatusCode.NoContent;

            context.SetStatusCode(statusCode);
        }
        /// <summary>
        /// Moves the
        /// </summary>
        /// <param name="context">The
        /// <see cref="IWebDavContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        /// <param name="sourceWebDavStoreItem">The <see cref="IWebDavStoreItem" /> that will be moved</param>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavForbiddenException">If the source path is the same as the destination path</exception>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavPreconditionFailedException">If one of the preconditions failed</exception>
        private void MoveItem(IWebDavContext context, IWebDavStore store, IWebDavStoreItem sourceWebDavStoreItem)
        {
            Uri destinationUri = GetDestinationHeader(context.Request);
            IWebDavStoreCollection destinationParentCollection = GetParentCollection(store, context, destinationUri);

            bool isNew = true;

            string           destinationName = Uri.UnescapeDataString(destinationUri.Segments.Last().TrimEnd('/', '\\'));
            IWebDavStoreItem destination     = destinationParentCollection.GetItemByName(destinationName);

            if (destination != null)
            {
                if (sourceWebDavStoreItem.ItemPath == destination.ItemPath)
                {
                    throw new WebDavForbiddenException();
                }
                // if the overwrite header is F, statuscode = precondition failed
                if (!GetOverwriteHeader(context.Request))
                {
                    throw new WebDavPreconditionFailedException();
                }
                // else delete destination and set isNew to false
                destinationParentCollection.Delete(destination);
                isNew = false;
            }

            destinationParentCollection.MoveItemHere(sourceWebDavStoreItem, destinationName);

            // send correct response
            context.SetStatusCode(isNew ? HttpStatusCode.Created : HttpStatusCode.NoContent);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="TextFilePropertyStoreFactory"/> class.
 /// </summary>
 /// <param name="options">The options for the text file property store</param>
 /// <param name="deadPropertyFactory">The factory for the dead properties</param>
 /// <param name="webDavContext">The WebDAV request context</param>
 /// <param name="logger">The logger for the property store factory</param>
 public TextFilePropertyStoreFactory(IOptions <TextFilePropertyStoreOptions> options, IDeadPropertyFactory deadPropertyFactory, IWebDavContext webDavContext, ILogger <TextFilePropertyStore> logger)
 {
     _options             = options?.Value ?? new TextFilePropertyStoreOptions();
     _logger              = logger;
     _deadPropertyFactory = deadPropertyFactory;
     _webDavContext       = webDavContext;
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SQLitePropertyStoreFactory"/> class.
 /// </summary>
 /// <param name="webDavContext">The WebDAV request context</param>
 /// <param name="logger">The logger for the property store factory</param>
 /// <param name="deadPropertyFactory">The factory for dead properties</param>
 /// <param name="options">The options for this property store</param>
 public SQLitePropertyStoreFactory(IWebDavContext webDavContext, ILogger <SQLitePropertyStore> logger, IDeadPropertyFactory deadPropertyFactory, IOptions <SQLitePropertyStoreOptions> options = null)
 {
     _webDavContext       = webDavContext;
     _logger              = logger;
     _deadPropertyFactory = deadPropertyFactory;
     _options             = options;
 }
Ejemplo n.º 5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PutHandler"/> class.
 /// </summary>
 /// <param name="fileSystem">The root file system</param>
 /// <param name="context">The WebDAV request context</param>
 /// <param name="entryPropertyInitializer">The property initializer</param>
 /// <param name="logger">The logger</param>
 public PutHandler(IFileSystem fileSystem, IWebDavContext context, IEntryPropertyInitializer entryPropertyInitializer, ILogger <PutHandler> logger)
 {
     _fileSystem = fileSystem;
     _context    = context;
     _entryPropertyInitializer = entryPropertyInitializer;
     _logger = logger;
 }
        /// <summary>
        /// Copies the item.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="store">The store.</param>
        /// <param name="source">The source.</param>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavForbiddenException"></exception>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavPreconditionFailedException"></exception>
        private static void CopyItem(IWebDavContext context, IWebDavStore store, IWebDavStoreItem source)
        {
            Uri destinationUri = GetDestinationHeader(context.Request);
            IWebDavStoreCollection destinationParentCollection = GetParentCollection(store, context, destinationUri);

            bool copyContent = (GetDepthHeader(context.Request) != 0);
            bool isNew = true;

            string destinationName = Uri.UnescapeDataString(destinationUri.Segments.Last().TrimEnd('/', '\\'));
            IWebDavStoreItem destination = destinationParentCollection.GetItemByName(destinationName);
            
            if (destination != null)
            {
                if (source.ItemPath == destination.ItemPath)
                    throw new WebDavForbiddenException();
                if (!GetOverwriteHeader(context.Request))
                    throw new WebDavPreconditionFailedException();
                if (destination is IWebDavStoreCollection)
                    destinationParentCollection.Delete(destination);
                isNew = false;
            }

            destinationParentCollection.CopyItemHere(source, destinationName, copyContent);

            var statusCode = isNew ? HttpStatusCode.Created : HttpStatusCode.NoContent;
            context.SetStatusCode(statusCode);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SQLitePropertyStoreFactory"/> class.
 /// </summary>
 /// <param name="webDavContext">The WebDAV request context</param>
 /// <param name="logger">The logger for the property store factory</param>
 /// <param name="deadPropertyFactory">The factory for dead properties</param>
 /// <param name="options">The options for this property store</param>
 public SQLitePropertyStoreFactory([NotNull] IWebDavContext webDavContext, [NotNull] ILogger <SQLitePropertyStore> logger, [NotNull] IDeadPropertyFactory deadPropertyFactory, [CanBeNull] IOptions <SQLitePropertyStoreOptions> options = null)
 {
     _webDavContext       = webDavContext;
     _logger              = logger;
     _deadPropertyFactory = deadPropertyFactory;
     _options             = options;
 }
 /// <summary>
 /// Processes the request.
 /// </summary>
 /// <param name="context">The 
 /// <see cref="IHttpListenerContext" /> object containing both the request and response
 /// objects to use.</param>
 /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
 /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavMethodNotAllowedException"></exception>
 public void ProcessRequest(IWebDavContext context, IWebDavStore store)
 {            
     IWebDavStoreItem source = context.Request.Url.GetItem(store, context);
     if (source is IWebDavStoreDocument || source is IWebDavStoreCollection)
         CopyItem(context, store, source);
     else
         throw new WebDavMethodNotAllowedException();
 }
 /// <summary>
 /// Create generic property
 /// </summary>
 /// <param name="entry">The entry to create the properties for</param>
 /// <param name="propertyStore">The property store</param>
 /// <param name="context">The PUT/MKCOL request context</param>
 /// <param name="cancellationToken">The cancellation token</param>
 /// <returns>The task</returns>
 protected virtual Task CreateGenericPropertiesAsync(
     IEntry entry,
     IPropertyStore propertyStore,
     IWebDavContext context,
     CancellationToken cancellationToken)
 {
     return(Task.CompletedTask);
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LockHandler"/> class.
 /// </summary>
 /// <param name="context">The WebDAV request context</param>
 /// <param name="rootFileSystem">The root file system</param>
 /// <param name="lockManager">The lock manager</param>
 /// <param name="timeoutPolicy">The timeout policy for the selection of the <see cref="TimeoutHeader"/> value</param>
 public LockHandler(IWebDavContext context, IFileSystem rootFileSystem, ILockManager lockManager = null, ITimeoutPolicy timeoutPolicy = null)
 {
     _context        = context;
     _rootFileSystem = rootFileSystem;
     _lockManager    = lockManager;
     _timeoutPolicy  = timeoutPolicy;
     HttpMethods     = _lockManager == null ? new string[0] : new[] { "LOCK" };
 }
 /// <summary>
 /// Processes the request.
 /// </summary>
 /// <param name="context">The 
 /// <see cref="IWebDavContext" /> object containing both the request and response
 /// objects to use.</param>
 /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
 public void ProcessRequest(IWebDavContext context, IWebDavStore store)
 {
     /***************************************************************************************************
     * Send the response
     ***************************************************************************************************/
     WindowsIdentity Identity = (WindowsIdentity)Thread.GetData(Thread.GetNamedDataSlot(Constants.HttpUser));
     var statusCode = WebDavStoreItemLock.UnLock(context.Request.Url, GetLockTokenHeader(context.Request), Identity.Name);
     context.SetStatusCode(statusCode);
 }
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="context">The
        /// <see cref="IWebDavContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        public void ProcessRequest(IWebDavContext context, IWebDavStore store)
        {
            /***************************************************************************************************
            * Send the response
            ***************************************************************************************************/
            WindowsIdentity Identity   = (WindowsIdentity)Thread.GetData(Thread.GetNamedDataSlot(Constants.HttpUser));
            var             statusCode = WebDavStoreItemLock.UnLock(context.Request.Url, GetLockTokenHeader(context.Request), Identity.Name);

            context.SetStatusCode(statusCode);
        }
        /// <summary>
        /// Sets status code and description.
        /// </summary>
        /// <param name="context">The <see cref="IHttpListenerContext" /> to send the response through.</param>
        /// <param name="statusCode">The HTTP status code for the response.</param>
        /// <exception cref="System.ArgumentNullException">context</exception>
        /// <exception cref="ArgumentNullException"><paramref name="context" /> is <c>null</c>.</exception>
        public static void SetStatusCode(this IWebDavContext context, int statusCode)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            context.Response.StatusCode        = statusCode;
            context.Response.StatusDescription = HttpWorkerRequest.GetStatusDescription(statusCode);
        }
        ///// <summary>
        ///// Gets the prefix <see cref="Uri" /> that matches the specified <see cref="Uri" />.
        ///// </summary>
        ///// <param name="uri">The <see cref="Uri" /> to find the most specific prefix <see cref="Uri" /> for.</param>
        ///// <param name="context">Context</param>
        ///// <returns>
        ///// The most specific <see cref="Uri" /> for the given <paramref name="uri" />.
        ///// </returns>
        ///// <exception cref="WebDAVSharp.Server.Exceptions.WebDavInternalServerException">Unable to find correct server root</exception>
        ///// <exception cref="WebDavInternalServerException"><paramref name="uri" /> specifies a <see cref="Uri" /> that is not known to the <paramref name="server" />.</exception>
        //public static Uri GetPrefixUri(this Uri uri, IWebDavContext context)
        //{
        //    string.Format("{0}://{1}", context.Request.Url.Scheme, context.Request.Url.Authority);

        //    string url = uri.ToString();
        //    foreach (
        //        string prefix in
        //            server.Listener.Prefixes.Where(
        //                prefix => url.StartsWith(uri.ToString(), StringComparison.OrdinalIgnoreCase)))
        //        return new Uri(prefix);
        //    throw new WebDavInternalServerException("Unable to find correct server root");
        //}

        /// <summary>
        /// Retrieves a store item through the specified
        /// <see cref="Uri" /> from the
        /// specified
        /// <see cref="WebDavServer" /> and
        /// <see cref="IWebDavStore" />.
        /// </summary>
        /// <param name="uri">The <see cref="Uri" /> to retrieve the store item for.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> from which to retrieve the store item.</param>
        /// <param name="context">Context</param>
        /// <returns>
        /// The retrieved store item.
        /// </returns>
        /// <exception cref="System.ArgumentNullException"><para>
        ///   <paramref name="uri" /> is <c>null</c>.</para>
        /// <para>
        ///   <paramref name="context" /> is <c>null</c>.</para>
        /// <para>
        ///   <paramref name="store" /> is <c>null</c>.</para></exception>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavNotFoundException">If the item was not found.</exception>
        /// <exception cref="WebDavConflictException"><paramref name="uri" /> refers to a document in a collection, where the collection does not exist.</exception>
        /// <exception cref="WebDavNotFoundException"><paramref name="uri" /> refers to a document that does not exist.</exception>
        public static IWebDavStoreItem GetItem(this Uri uri, IWebDavStore store, IWebDavContext context)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (store == null)
            {
                throw new ArgumentNullException("store");
            }

            IWebDavStoreCollection collection = store.Root;

            IWebDavStoreItem item = null;

            if (context.Request.Url.Segments.Length - 1 == uri.Segments.Length)
            {
                return(collection);
            }

            //todo пути с глубиной больше рута глючат. надо дописать логику далее.

            for (int index = uri.Segments.Length; index < context.Request.Url.Segments.Length; index++)
            {
                string           segmentName = Uri.UnescapeDataString(context.Request.Url.Segments[index]);
                IWebDavStoreItem nextItem    = collection.GetItemByName(segmentName.TrimEnd('/', '\\'));
                if (nextItem == null)
                {
                    throw new WebDavNotFoundException(); //throw new WebDavConflictException();
                }
                if (index == context.Request.Url.Segments.Length - 1)
                {
                    item = nextItem;
                }
                else
                {
                    collection = nextItem as IWebDavStoreCollection;
                    if (collection == null)
                    {
                        throw new WebDavNotFoundException();
                    }
                }
            }

            if (item == null)
            {
                throw new WebDavNotFoundException();
            }

            return(item);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Parses the text into a <see cref="IfHeader"/>
        /// </summary>
        /// <param name="s">The text to parse</param>
        /// <param name="etagComparer">The comparer to use for entity tag comparison</param>
        /// <param name="context">The WebDAV request context</param>
        /// <returns>The new <see cref="IfHeader"/></returns>
        public static IfHeader Parse(string s, EntityTagComparer etagComparer, IWebDavContext context)
        {
            var source = new StringSource(s);
            var lists  = IfHeaderList.Parse(source, etagComparer, context).ToList();

            if (!source.Empty)
            {
                throw new ArgumentException("Not an accepted list of conditions", nameof(s));
            }
            return(new IfHeader(lists));
        }
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="context">The
        /// <see cref="IWebDavContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        public void ProcessRequest(IWebDavContext context, IWebDavStore store)
        {
            // Get the parent collection of the item
            IWebDavStoreCollection collection = GetParentCollection(store, context, context.Request.Url);

            // Get the item from the collection
            IWebDavStoreItem item = GetItemFromCollection(collection, context.Request.Url);

            // Deletes the item
            collection.Delete(item);
        }
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="context">The
        /// <see cref="IWebDavContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        public void ProcessRequest(IWebDavContext context, IWebDavStore store)
        {
            // Get the parent collection of the item
            IWebDavStoreCollection collection = GetParentCollection(store, context, context.Request.Url);

            // Get the item from the collection
            IWebDavStoreItem item = GetItemFromCollection(collection, context.Request.Url);

            // Deletes the item
            collection.Delete(item);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Sends the response
        /// </summary>
        /// <param name="context">The <see cref="IWebDavContext" /> containing the response</param>
        /// <param name="responseDocument">The <see cref="XmlDocument" /> containing the response body</param>
        private static void MakeResponse(IWebDavContext context, XmlDocument responseDocument)
        {
            // convert the XmlDocument
            byte[] responseBytes = Encoding.UTF8.GetBytes(responseDocument.InnerXml);

            // HttpStatusCode doesn't contain WebDav status codes, but HttpWorkerRequest can handle these WebDav status codes
            context.SetStatusCode((int)WebDavStatusCode.MultiStatus);

            context.Response.ContentLength64 = responseBytes.Length;
            context.Response.AppendHeader("Content-Type", "text/xml");
            context.Response.OutputStream.Write(responseBytes, 0, responseBytes.Length);
        }
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="context">The 
        /// <see cref="IWebDavContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        public void ProcessRequest(IWebDavContext context, IWebDavStore store)
        {

            foreach (string verb in verbsAllowed)
                context.Response.AppendHeader("Allow", verb);

            foreach (string verb in verbsPublic)
                context.Response.AppendHeader("Public", verb);

            // Sends 200 OK
            context.SetStatusCode();
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="context">The
        /// <see cref="IHttpListenerContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavMethodNotAllowedException"></exception>
        public void ProcessRequest(IWebDavContext context, IWebDavStore store)
        {
            IWebDavStoreItem source = context.Request.Url.GetItem(store, context);

            if (source is IWebDavStoreDocument || source is IWebDavStoreCollection)
            {
                CopyItem(context, store, source);
            }
            else
            {
                throw new WebDavMethodNotAllowedException();
            }
        }
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="context">The
        /// <see cref="IWebDavContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        public void ProcessRequest(IWebDavContext context, IWebDavStore store)
        {
            foreach (string verb in verbsAllowed)
            {
                context.Response.AppendHeader("Allow", verb);
            }

            foreach (string verb in verbsPublic)
            {
                context.Response.AppendHeader("Public", verb);
            }

            // Sends 200 OK
            context.SetStatusCode();
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="context">The
        /// <see cref="IWebDavContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavNotFoundException"></exception>
        /// <exception cref="WebDavNotFoundException"><para>
        ///   <paramref name="context" /> specifies a request for a store item that does not exist.</para>
        /// <para>- or -</para>
        /// <para>
        ///   <paramref name="context" /> specifies a request for a store item that is not a document.</para></exception>
        /// <exception cref="WebDavConflictException"><paramref name="context" /> specifies a request for a store item using a collection path that does not exist.</exception>
        public void ProcessRequest(IWebDavContext context, IWebDavStore store)
        {
            IWebDavStoreCollection collection = GetParentCollection(store, context, context.Request.Url);
            IWebDavStoreItem       item       = GetItemFromCollection(collection, context.Request.Url);
            IWebDavStoreDocument   doc        = item as IWebDavStoreDocument;

            if (doc == null)
            {
                throw new WebDavNotFoundException();
            }

            long docSize = doc.Size;

            if (docSize == 0)
            {
                context.Response.StatusCode      = (int)HttpStatusCode.OK;
                context.Response.ContentLength64 = 0;
            }

            using (Stream stream = doc.OpenReadStream())
            {
                if (stream == null)
                {
                    context.Response.StatusCode      = (int)HttpStatusCode.OK;
                    context.Response.ContentLength64 = 0;
                }
                else
                {
                    context.Response.StatusCode = (int)HttpStatusCode.OK;

                    //todo Это статика. Надо определять MIME тип по расширению
                    context.Response.AppendHeader("Content-type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");

                    if (docSize > 0)
                    {
                        context.Response.ContentLength64 = docSize;
                    }

                    byte[] buffer = new byte[4096];
                    int    inBuffer;
                    while ((inBuffer = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        context.Response.OutputStream.Write(buffer, 0, inBuffer);
                    }
                    context.Response.OutputStream.Flush();
                }
            }
        }
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="context">The 
        /// <see cref="IWebDavContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavUnsupportedMediaTypeException"></exception>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavMethodNotAllowedException"></exception>
        public void ProcessRequest(IWebDavContext context, IWebDavStore store)
        {
            if (context.Request.ContentLength64 > 0)
                throw new WebDavUnsupportedMediaTypeException();

            IWebDavStoreCollection collection = GetParentCollection(store, context, context.Request.Url);
                
            string collectionName = Uri.UnescapeDataString(
                context.Request.Url.Segments.Last().TrimEnd('/', '\\')
                );
            if (collection.GetItemByName(collectionName) != null)
                throw new WebDavMethodNotAllowedException();

            collection.CreateCollection(collectionName);

            context.SetStatusCode(HttpStatusCode.Created);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="context">The
        /// <see cref="IWebDavContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavMethodNotAllowedException"></exception>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavLengthRequiredException">If the ContentLength header was not found</exception>
        public void ProcessRequest(IWebDavContext context, IWebDavStore store)
        {
            // Get the parent collection
            IWebDavStoreCollection parentCollection = GetParentCollection(store, context, context.Request.Url);

            // Gets the item name from the url
            string itemName = Uri.UnescapeDataString(context.Request.Url.Segments.Last().TrimEnd('/', '\\'));

            IWebDavStoreItem     item = parentCollection.GetItemByName(itemName);
            IWebDavStoreDocument doc;

            if (item != null)
            {
                doc = item as IWebDavStoreDocument;
                if (doc == null)
                {
                    throw new WebDavMethodNotAllowedException();
                }
            }
            else
            {
                doc = parentCollection.CreateDocument(itemName);
            }

            if (context.Request.ContentLength64 < 0)
            {
                throw new WebDavLengthRequiredException();
            }

            using (Stream stream = doc.OpenWriteStream(false))
            {
                long   left   = context.Request.ContentLength64;
                byte[] buffer = new byte[4096];
                while (left > 0)
                {
                    int toRead   = Convert.ToInt32(Math.Min(left, buffer.Length));
                    int inBuffer = context.Request.InputStream.Read(buffer, 0, toRead);
                    stream.Write(buffer, 0, inBuffer);

                    left -= inBuffer;
                }
            }

            context.SetStatusCode(HttpStatusCode.Created);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="WebDavDispatcherClass2"/> class.
        /// </summary>
        /// <param name="handlers">The WebDAV class 2 handlers</param>
        /// <param name="context">The WebDAV context</param>
        public WebDavDispatcherClass2([NotNull][ItemNotNull] IEnumerable <IClass2Handler> handlers, [NotNull] IWebDavContext context)
        {
            var httpMethods = new HashSet <string>();

            foreach (var handler in handlers)
            {
                var handlerFound = false;

                if (handler is ILockHandler lockHandler)
                {
                    _lockHandler = lockHandler;
                    handlerFound = true;
                }

                if (handler is IUnlockHandler unlockHandler)
                {
                    _unlockHandler = unlockHandler;
                    handlerFound   = true;
                }

                if (!handlerFound)
                {
                    throw new NotSupportedException();
                }

                foreach (var httpMethod in handler.HttpMethods)
                {
                    httpMethods.Add(httpMethod);
                }
            }

            HttpMethods   = httpMethods.ToList();
            WebDavContext = context;

            OptionsResponseHeaders = new Dictionary <string, IEnumerable <string> >()
            {
                ["Allow"] = HttpMethods,
            };

            DefaultResponseHeaders = new Dictionary <string, IEnumerable <string> >()
            {
                ["DAV"] = new[] { "2" },
            };
        }
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="context">The 
        /// <see cref="IWebDavContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        /// <exception cref="WebDavNotFoundException"><para>
        ///   <paramref name="context" /> specifies a request for a store item that does not exist.</para>
        /// <para>- or -</para>
        /// <para>
        ///   <paramref name="context" /> specifies a request for a store item that is not a document.</para></exception>
        /// <exception cref="WebDavConflictException"><paramref name="context" /> specifies a request for a store item using a collection path that does not exist.</exception>
        public void ProcessRequest(IWebDavContext context, IWebDavStore store)
        {
            // Get the parent collection of the item
            IWebDavStoreCollection collection = GetParentCollection(store, context, context.Request.Url);

            // Get the item from the collection
            IWebDavStoreItem item = GetItemFromCollection(collection, context.Request.Url);

            /***************************************************************************************************
            * Send the response
            ***************************************************************************************************/
            
            // HttpStatusCode doesn't contain WebDav status codes, but HttpWorkerRequest can handle these WebDav status codes
            context.SetStatusCode();

            // set the headers of the response
            context.Response.ContentLength64 = 0;
            context.Response.AppendHeader("Content-Type", "text/html");
            context.Response.AppendHeader("Last-Modified", item.ModificationDate.ToUniversalTime().ToString("R"));
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="context">The
        /// <see cref="IWebDavContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        /// <exception cref="WebDavNotFoundException"><para>
        ///   <paramref name="context" /> specifies a request for a store item that does not exist.</para>
        /// <para>- or -</para>
        /// <para>
        ///   <paramref name="context" /> specifies a request for a store item that is not a document.</para></exception>
        /// <exception cref="WebDavConflictException"><paramref name="context" /> specifies a request for a store item using a collection path that does not exist.</exception>
        public void ProcessRequest(IWebDavContext context, IWebDavStore store)
        {
            // Get the parent collection of the item
            IWebDavStoreCollection collection = GetParentCollection(store, context, context.Request.Url);

            // Get the item from the collection
            IWebDavStoreItem item = GetItemFromCollection(collection, context.Request.Url);

            /***************************************************************************************************
            * Send the response
            ***************************************************************************************************/

            // HttpStatusCode doesn't contain WebDav status codes, but HttpWorkerRequest can handle these WebDav status codes
            context.SetStatusCode();

            // set the headers of the response
            context.Response.ContentLength64 = 0;
            context.Response.AppendHeader("Content-Type", "text/html");
            context.Response.AppendHeader("Last-Modified", item.ModificationDate.ToUniversalTime().ToString("R"));
        }
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="context">The
        /// <see cref="IWebDavContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavNotFoundException"></exception>
        /// <exception cref="WebDavNotFoundException"><para>
        ///   <paramref name="context" /> specifies a request for a store item that does not exist.</para>
        /// <para>- or -</para>
        /// <para>
        ///   <paramref name="context" /> specifies a request for a store item that is not a document.</para></exception>
        /// <exception cref="WebDavConflictException"><paramref name="context" /> specifies a request for a store item using a collection path that does not exist.</exception>
        public void ProcessRequest(IWebDavContext context, IWebDavStore store)
        {
            IWebDavStoreCollection collection = GetParentCollection(store, context, context.Request.Url);
            IWebDavStoreItem item = GetItemFromCollection(collection, context.Request.Url);
            IWebDavStoreDocument doc = item as IWebDavStoreDocument;
            if (doc == null)
                throw new WebDavNotFoundException();

            long docSize = doc.Size;
            if (docSize == 0)
            {
                context.Response.StatusCode = (int)HttpStatusCode.OK;
                context.Response.ContentLength64 = 0;
            }

            using (Stream stream = doc.OpenReadStream())
            {
                if (stream == null)
                {
                    context.Response.StatusCode = (int)HttpStatusCode.OK;
                    context.Response.ContentLength64 = 0;
                }
                else
                {
                    context.Response.StatusCode = (int)HttpStatusCode.OK;

                    //todo Это статика. Надо определять MIME тип по расширению
                    context.Response.AppendHeader("Content-type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");

                    if (docSize > 0)
                        context.Response.ContentLength64 = docSize;

                    byte[] buffer = new byte[4096];
                    int inBuffer;
                    while ((inBuffer = stream.Read(buffer, 0, buffer.Length)) > 0)
                        context.Response.OutputStream.Write(buffer, 0, inBuffer);
                    context.Response.OutputStream.Flush();
                }
            }
            
        }
        /// <summary>
        /// Get the parent collection from the requested
        /// <see cref="Uri" />.
        /// <see cref="WebDavException" /> 409 Conflict possible.
        /// </summary>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        /// <param name="context">Context</param>
        /// <param name="childUri">The <see cref="Uri" /> object containing the specific location of the child</param>
        /// <returns>
        /// The parrent collection as an <see cref="IWebDavStoreCollection" />
        /// </returns>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavUnauthorizedException"></exception>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavConflictException">
        /// </exception>
        /// <exception cref="WebDavUnauthorizedException">When the user is unauthorized and doesn't have access</exception>
        /// <exception cref="WebDavConflictException">When the parent collection doesn't exist</exception>
        public static IWebDavStoreCollection GetParentCollection(IWebDavStore store, IWebDavContext context, Uri childUri)
        {
            Uri parentCollectionUri = childUri.GetParentUri();
            IWebDavStoreCollection collection;
            try
            {
                collection = parentCollectionUri.GetItem(store, context) as IWebDavStoreCollection;
            }
            catch (UnauthorizedAccessException)
            {
                throw new WebDavUnauthorizedException();
            }
            catch (WebDavNotFoundException)
            {
                throw new WebDavConflictException();
            }
            if (collection == null)
                throw new WebDavConflictException();

            return collection;
        }
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="context">The 
        /// <see cref="IWebDavContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavMethodNotAllowedException"></exception>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavLengthRequiredException">If the ContentLength header was not found</exception>
        public void ProcessRequest(IWebDavContext context, IWebDavStore store)
        {
            // Get the parent collection
            IWebDavStoreCollection parentCollection = GetParentCollection(store, context, context.Request.Url);

            // Gets the item name from the url
            string itemName = Uri.UnescapeDataString(context.Request.Url.Segments.Last().TrimEnd('/', '\\'));

            IWebDavStoreItem item = parentCollection.GetItemByName(itemName);
            IWebDavStoreDocument doc;
            if (item != null)
            {
                doc = item as IWebDavStoreDocument;
                if (doc == null)
                    throw new WebDavMethodNotAllowedException();
            }
            else
            {
                doc = parentCollection.CreateDocument(itemName);
            }

            if (context.Request.ContentLength64 < 0)
                throw new WebDavLengthRequiredException();

            using (Stream stream = doc.OpenWriteStream(false))
            {
                long left = context.Request.ContentLength64;
                byte[] buffer = new byte[4096];
                while (left > 0)
                {
                    int toRead = Convert.ToInt32(Math.Min(left, buffer.Length));
                    int inBuffer = context.Request.InputStream.Read(buffer, 0, toRead);
                    stream.Write(buffer, 0, inBuffer);

                    left -= inBuffer;
                }
            }

            context.SetStatusCode(HttpStatusCode.Created);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="context">The
        /// <see cref="IWebDavContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavUnsupportedMediaTypeException"></exception>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavMethodNotAllowedException"></exception>
        public void ProcessRequest(IWebDavContext context, IWebDavStore store)
        {
            if (context.Request.ContentLength64 > 0)
            {
                throw new WebDavUnsupportedMediaTypeException();
            }

            IWebDavStoreCollection collection = GetParentCollection(store, context, context.Request.Url);

            string collectionName = Uri.UnescapeDataString(
                context.Request.Url.Segments.Last().TrimEnd('/', '\\')
                );

            if (collection.GetItemByName(collectionName) != null)
            {
                throw new WebDavMethodNotAllowedException();
            }

            collection.CreateCollection(collectionName);

            context.SetStatusCode(HttpStatusCode.Created);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Get the parent collection from the requested
        /// <see cref="Uri" />.
        /// <see cref="WebDavException" /> 409 Conflict possible.
        /// </summary>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        /// <param name="context">Context</param>
        /// <param name="childUri">The <see cref="Uri" /> object containing the specific location of the child</param>
        /// <returns>
        /// The parrent collection as an <see cref="IWebDavStoreCollection" />
        /// </returns>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavUnauthorizedException"></exception>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavConflictException">
        /// </exception>
        /// <exception cref="WebDavUnauthorizedException">When the user is unauthorized and doesn't have access</exception>
        /// <exception cref="WebDavConflictException">When the parent collection doesn't exist</exception>
        public static IWebDavStoreCollection GetParentCollection(IWebDavStore store, IWebDavContext context, Uri childUri)
        {
            Uri parentCollectionUri = childUri.GetParentUri();
            IWebDavStoreCollection collection;

            try
            {
                collection = parentCollectionUri.GetItem(store, context) as IWebDavStoreCollection;
            }
            catch (UnauthorizedAccessException)
            {
                throw new WebDavUnauthorizedException();
            }
            catch (WebDavNotFoundException)
            {
                throw new WebDavConflictException();
            }
            if (collection == null)
            {
                throw new WebDavConflictException();
            }

            return(collection);
        }
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="context">The
        /// <see cref="IWebDavContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavPreconditionFailedException"></exception>
        public void ProcessRequest(IWebDavContext context, IWebDavStore store)
        {
            /***************************************************************************************************
             * Retreive al the information from the request
             ***************************************************************************************************/

            // read the headers
            int depth = GetDepthHeader(context.Request);
            string timeout = GetTimeoutHeader(context.Request);
            string locktoken = GetLockTokenIfHeader(context.Request);
            int lockResult;
            // Initiate the XmlNamespaceManager and the XmlNodes
            XmlNamespaceManager manager;
            XmlNode lockscopeNode, locktypeNode, ownerNode;
            XmlDocument requestDocument = new XmlDocument();

            if (string.IsNullOrEmpty(locktoken))
            {
                #region New Lock
                // try to read the body
                try
                {
                    StreamReader reader = new StreamReader(context.Request.InputStream, Encoding.UTF8);
                    string requestBody = reader.ReadToEnd();

                    if (!requestBody.Equals("") && requestBody.Length != 0)
                    {

                        requestDocument.LoadXml(requestBody);

                        if (requestDocument.DocumentElement != null &&
                            requestDocument.DocumentElement.LocalName != "prop" &&
                            requestDocument.DocumentElement.LocalName != "lockinfo")
                        {
                            WebDavServer.Log.Debug("LOCK method without prop or lockinfo element in xml document");
                        }

                        manager = new XmlNamespaceManager(requestDocument.NameTable);
                        manager.AddNamespace("D", "DAV:");
                        manager.AddNamespace("Office", "schemas-microsoft-com:office:office");
                        manager.AddNamespace("Repl", "http://schemas.microsoft.com/repl/");
                        manager.AddNamespace("Z", "urn:schemas-microsoft-com:");

                        // Get the lockscope, locktype and owner as XmlNodes from the XML document
                        lockscopeNode = requestDocument.DocumentElement.SelectSingleNode("D:lockscope", manager);
                        locktypeNode = requestDocument.DocumentElement.SelectSingleNode("D:locktype", manager);
                        ownerNode = requestDocument.DocumentElement.SelectSingleNode("D:owner", manager);
                    }
                    else
                    {
                        throw new WebDavPreconditionFailedException();
                    }
                }
                catch (Exception ex)
                {
                    WebDavServer.Log.Warn(ex.Message);
                    throw;
                }


                /***************************************************************************************************
                * Lock the file or folder
                ***************************************************************************************************/


                // Get the parent collection of the item
            IWebDavStoreCollection collection = GetParentCollection(store, context, context.Request.Url);

                WebDavLockScope lockscope = (lockscopeNode.InnerXml.StartsWith("<D:exclusive"))
                    ? WebDavLockScope.Exclusive
                    : WebDavLockScope.Shared;

                //Only lock available at this time is a Write Lock according to RFC
                WebDavLockType locktype = (locktypeNode.InnerXml.StartsWith("<D:write")) ? WebDavLockType.Write : WebDavLockType.Write;

                string lockuser = ownerNode.InnerText;

                WindowsIdentity Identity = (WindowsIdentity)Thread.GetData(Thread.GetNamedDataSlot(Constants.HttpUser));

                lockResult = WebDavStoreItemLock.Lock(context.Request.Url, lockscope, locktype, Identity.Name, ref timeout,
                    out locktoken, requestDocument, depth);

                // Get the item from the collection
                try
                {
                    GetItemFromCollection(collection, context.Request.Url);
                }
                catch (Exception)
                {
                    lockResult = (int)HttpStatusCode.Created;
                }
                #endregion
            }
            else
            {
                #region Refreshing a lock
                //Refresh lock will ref us back the original XML document which was used to request this lock, from
                //this we will grab the data we need to build the response to the lock refresh request.
                lockResult = WebDavStoreItemLock.RefreshLock(context.Request.Url, locktoken, ref timeout, out requestDocument);
                if (requestDocument == null)
                {
                    context.SetStatusCode(409);
                    return;
                }

                try
                {
                    if (requestDocument.DocumentElement != null &&
                        requestDocument.DocumentElement.LocalName != "prop" &&
                        requestDocument.DocumentElement.LocalName != "lockinfo")
                    {
                        WebDavServer.Log.Debug("LOCK method without prop or lockinfo element in xml document");
                    }

                    manager = new XmlNamespaceManager(requestDocument.NameTable);
                    manager.AddNamespace("D", "DAV:");
                    manager.AddNamespace("Office", "schemas-microsoft-com:office:office");
                    manager.AddNamespace("Repl", "http://schemas.microsoft.com/repl/");
                    manager.AddNamespace("Z", "urn:schemas-microsoft-com:");

                    // Get the lockscope, locktype and owner as XmlNodes from the XML document
                    lockscopeNode = requestDocument.DocumentElement.SelectSingleNode("D:lockscope", manager);
                    locktypeNode = requestDocument.DocumentElement.SelectSingleNode("D:locktype", manager);
                    ownerNode = requestDocument.DocumentElement.SelectSingleNode("D:owner", manager);
                }
                catch (Exception ex)
                {
                    WebDavServer.Log.Warn(ex.Message);
                    throw;
                }

                #endregion
            }

            /***************************************************************************************************
             * Create the body for the response
             ***************************************************************************************************/

            // Create the basic response XmlDocument
            XmlDocument responseDoc = new XmlDocument();
            const string responseXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><D:prop xmlns:D=\"DAV:\"><D:lockdiscovery><D:activelock/></D:lockdiscovery></D:prop>";
            responseDoc.LoadXml(responseXml);

            // Select the activelock XmlNode
            XmlNode activelock = responseDoc.DocumentElement.SelectSingleNode("D:lockdiscovery/D:activelock", manager);

            // Import the given nodes
            activelock.AppendChild(responseDoc.ImportNode(lockscopeNode, true));
            activelock.AppendChild(responseDoc.ImportNode(locktypeNode, true));
            activelock.AppendChild(responseDoc.ImportNode(ownerNode, true));

            // Add the additional elements, e.g. the header elements

            // The timeout element
            WebDavProperty timeoutProperty = new WebDavProperty("timeout", timeout);// timeout);
            activelock.AppendChild(timeoutProperty.ToXmlElement(responseDoc));

            // The depth element
            WebDavProperty depthProperty = new WebDavProperty("depth", (depth == 0 ? "0" : "Infinity"));
            activelock.AppendChild(depthProperty.ToXmlElement(responseDoc));

            // The locktoken element
            WebDavProperty locktokenProperty = new WebDavProperty("locktoken", string.Empty);
            XmlElement locktokenElement = locktokenProperty.ToXmlElement(responseDoc);
            WebDavProperty hrefProperty = new WebDavProperty("href", locktoken);//"opaquelocktoken:e71d4fae-5dec-22df-fea5-00a0c93bd5eb1");
            locktokenElement.AppendChild(hrefProperty.ToXmlElement(responseDoc));


            activelock.AppendChild(locktokenElement);

            /***************************************************************************************************
             * Send the response
             ***************************************************************************************************/

            // convert the StringBuilder
            string resp = responseDoc.InnerXml;
            byte[] responseBytes = Encoding.UTF8.GetBytes(resp);

            context.SetStatusCode(lockResult);
            context.Response.StatusDescription = HttpWorkerRequest.GetStatusDescription(lockResult);

            // set the headers of the response
            context.Response.ContentLength64 = responseBytes.Length;
            context.Response.AppendHeader("ContentType", "text/xml");

            // the body
            context.Response.OutputStream.Write(responseBytes, 0, responseBytes.Length);
        }
        /// <summary>
        /// Builds the <see cref="XmlDocument" /> containing the response body
        /// </summary>
        /// <param name="context">The <see cref="IHttpListenerContext" /></param>
        /// <param name="propname">The boolean defining the Propfind propname request</param>
        /// <returns>
        /// The <see cref="XmlDocument" /> containing the response body
        /// </returns>
        private XmlDocument ResponseDocument(IWebDavContext context, bool propname)
        {
            // Create the basic response XmlDocument
            XmlDocument responseDoc = new XmlDocument();
            const string responseXml = "<?xml version=\"1.0\"?><D:multistatus xmlns:D=\"DAV:\"></D:multistatus>";
            responseDoc.LoadXml(responseXml);

            // Generate the manager
            XmlNamespaceManager manager = new XmlNamespaceManager(responseDoc.NameTable);
            manager.AddNamespace("D", "DAV:");
            manager.AddNamespace("Office", "schemas-microsoft-com:office:office");
            manager.AddNamespace("Repl", "http://schemas.microsoft.com/repl/");
            manager.AddNamespace("Z", "urn:schemas-microsoft-com:");

            int count = 0;

            foreach (IWebDavStoreItem webDavStoreItem in _webDavStoreItems)
            {
                // Create the response element
                WebDavProperty responseProperty = new WebDavProperty("response", string.Empty);
                XmlElement responseElement = responseProperty.ToXmlElement(responseDoc);

                // The href element
                Uri result;
                if (count == 0)
                {
                    Uri.TryCreate(_requestUri, string.Empty, out result);
                }
                else
                {
                    Uri.TryCreate(_requestUri, webDavStoreItem.Name, out result);
                }
                WebDavProperty hrefProperty = new WebDavProperty("href", result.AbsoluteUri);
                responseElement.AppendChild(hrefProperty.ToXmlElement(responseDoc));
                count++;

                // The propstat element
                WebDavProperty propstatProperty = new WebDavProperty("propstat", string.Empty);
                XmlElement propstatElement = propstatProperty.ToXmlElement(responseDoc);

                // The prop element
                WebDavProperty propProperty = new WebDavProperty("prop", string.Empty);
                XmlElement propElement = propProperty.ToXmlElement(responseDoc);

                //All properties but lockdiscovery and supportedlock can be handled here.
                foreach (WebDavProperty davProperty in _requestedProperties.Where(d => d.Name != "lockdiscovery" && d.Name != "supportedlock"))
                    propElement.AppendChild(PropChildElement(davProperty, responseDoc, webDavStoreItem, propname));

                //Since lockdiscovery returns an xml tree, we need to process it seperately.
                if (_requestedProperties.FirstOrDefault(d => d.Name == "lockdiscovery") != null)
                    propElement.AppendChild(LockDiscovery(result, ref responseDoc));

                //Since supportedlock returns an xml tree, we need to process it seperately.
                if (_requestedProperties.FirstOrDefault(d => d.Name == "supportedlock") != null)
                    propElement.AppendChild(SupportedLocks(ref responseDoc));

                // Add the prop element to the propstat element
                propstatElement.AppendChild(propElement);

                // The status element
                WebDavProperty statusProperty = new WebDavProperty("status",
                    "HTTP/1.1 " + context.Response.StatusCode + " " +
                    HttpWorkerRequest.GetStatusDescription(context.Response.StatusCode));
                propstatElement.AppendChild(statusProperty.ToXmlElement(responseDoc));

                // Add the propstat element to the response element
                responseElement.AppendChild(propstatElement);

                // Add the response element to the multistatus element
                responseDoc.DocumentElement.AppendChild(responseElement);
            }

            return responseDoc;
        }
Ejemplo n.º 35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PropPatchHandler"/> class.
 /// </summary>
 /// <param name="fileSystem">The root file system</param>
 /// <param name="context">The WebDAV request context</param>
 public PropPatchHandler([NotNull] IFileSystem fileSystem, [NotNull] IWebDavContext context)
 {
     _fileSystem = fileSystem;
     _context    = context;
 }
Ejemplo n.º 36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PropFindHandler"/> class.
 /// </summary>
 /// <param name="fileSystem">The root file system</param>
 /// <param name="context">The WebDAV request context</param>
 /// <param name="options">The options for this handler</param>
 public PropFindHandler([NotNull] IFileSystem fileSystem, [NotNull] IWebDavContext context, [CanBeNull] IOptions <PropFindHandlerOptions> options)
 {
     _options   = options?.Value ?? new PropFindHandlerOptions();
     _context   = context;
     FileSystem = fileSystem;
 }
Ejemplo n.º 37
0
 public PropertyCollector([NotNull] PropFindHandler handler, [NotNull] IWebDavContext host, [NotNull][ItemNotNull] params IPropertyFilter[] filters)
 {
     _handler = handler;
     _host    = host;
     _filters = filters;
 }
        /// <summary>
        /// Sends the response
        /// </summary>
        /// <param name="context">The <see cref="IWebDavContext" /> containing the response</param>
        /// <param name="responseDocument">The <see cref="XmlDocument" /> containing the response body</param>
        private static void MakeResponse(IWebDavContext context, XmlDocument responseDocument)
        {
            // convert the XmlDocument
            byte[] responseBytes = Encoding.UTF8.GetBytes(responseDocument.InnerXml);

            // HttpStatusCode doesn't contain WebDav status codes, but HttpWorkerRequest can handle these WebDav status codes
            context.SetStatusCode((int)WebDavStatusCode.MultiStatus);

            context.Response.ContentLength64 = responseBytes.Length;
            context.Response.AppendHeader("Content-Type", "text/xml");
            context.Response.OutputStream.Write(responseBytes, 0, responseBytes.Length);
        }
 /// <inheritdoc />
 public virtual Task CreatePropertiesAsync(ICollection collection, IPropertyStore propertyStore, IWebDavContext context, CancellationToken cancellationToken)
 {
     return(CreateGenericPropertiesAsync(collection, propertyStore, context, cancellationToken));
 }
        /// <inheritdoc />
        public virtual async Task CreatePropertiesAsync(IDocument document, IPropertyStore propertyStore, IWebDavContext context, CancellationToken cancellationToken)
        {
            if (context.RequestHeaders.Headers.TryGetValue("Content-Type", out var contentTypeValues))
            {
                var contentType = contentTypeValues.FirstOrDefault();
                if (!string.IsNullOrEmpty(contentType))
                {
                    var contentTypeProperty = new GetContentTypeProperty(document, propertyStore);
                    await contentTypeProperty.SetValueAsync(contentType, cancellationToken);
                }
            }

            await CreateGenericPropertiesAsync(document, propertyStore, context, cancellationToken);
        }
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="context">The
        /// <see cref="IHttpListenerContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavUnauthorizedException"></exception>
        public void ProcessRequest(IWebDavContext context, IWebDavStore store)
        {
            Context = context;
            /***************************************************************************************************
             * Retreive all the information from the request
             ***************************************************************************************************/

            // Read the headers, ...
            bool isPropname = false;
            int depth = GetDepthHeader(context.Request);
            _requestUri = GetRequestUri(context.Request.Url.ToString());
            try
            {
                _webDavStoreItems = GetWebDavStoreItems(context.Request.Url.GetItem(store, context), depth);
            }
            catch (UnauthorizedAccessException)
            {
                throw new WebDavUnauthorizedException();
            }

            // Get the XmlDocument from the request
            XmlDocument requestDoc = GetXmlDocument(context.Request);

            // See what is requested
            _requestedProperties = new List<WebDavProperty>();
            if (requestDoc.DocumentElement != null)
            {
                if (requestDoc.DocumentElement.LocalName != "propfind")
                    WebDavServer.Log.Debug("PROPFIND method without propfind in xml document");
                else
                {
                    XmlNode n = requestDoc.DocumentElement.FirstChild;
                    if (n == null)
                        WebDavServer.Log.Debug("propfind element without children");
                    else
                    {
                        switch (n.LocalName)
                        {
                            case "allprop":
                                _requestedProperties = GetAllProperties();
                                break;
                            case "propname":
                                isPropname = true;
                                _requestedProperties = GetAllProperties();
                                break;
                            case "prop":
                                foreach (XmlNode child in n.ChildNodes)
                                    _requestedProperties.Add(new WebDavProperty(child.LocalName, "", child.NamespaceURI));
                                break;
                            default:
                                _requestedProperties.Add(new WebDavProperty(n.LocalName, "", n.NamespaceURI));
                                break;
                        }
                    }
                }
            }
            else
                _requestedProperties = GetAllProperties();

            /***************************************************************************************************
             * Create the body for the response
             ***************************************************************************************************/

            XmlDocument responseDoc = ResponseDocument(context, isPropname);

            /***************************************************************************************************
             * Send the response
             ***************************************************************************************************/

            MakeResponse(context, responseDoc);
        }
Ejemplo n.º 42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WebDavControllerBase"/> class.
 /// </summary>
 /// <param name="context">The WebDAV request context</param>
 /// <param name="dispatcher">The WebDAV HTTP method dispatcher</param>
 /// <param name="responseLogger">The logger for the <see cref="WebDavIndirectResult"/></param>
 public WebDavControllerBase(IWebDavContext context, IWebDavDispatcher dispatcher, ILogger <WebDavIndirectResult> responseLogger = null)
 {
     _context        = context;
     _dispatcher     = dispatcher;
     _responseLogger = responseLogger;
 }
Ejemplo n.º 43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MkColHandler"/> class.
 /// </summary>
 /// <param name="rootFileSystem">The root file system</param>
 /// <param name="context">The WebDAV request context</param>
 /// <param name="entryPropertyInitializer">The property initializer</param>
 public MkColHandler(IFileSystem rootFileSystem, IWebDavContext context, IEntryPropertyInitializer entryPropertyInitializer)
 {
     _rootFileSystem           = rootFileSystem;
     _context                  = context;
     _entryPropertyInitializer = entryPropertyInitializer;
 }
Ejemplo n.º 44
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MoveHandler"/> class.
 /// </summary>
 /// <param name="rootFileSystem">The root file system</param>
 /// <param name="host">The WebDAV server context</param>
 /// <param name="options">The options for the <c>MOVE</c> handler</param>
 /// <param name="logger">The logger for this handler</param>
 /// <param name="serviceProvider">The service provider used to lazily query the <see cref="IRemoteMoveTargetActionsFactory"/> implementation</param>
 public MoveHandler(IFileSystem rootFileSystem, IWebDavContext host, IOptions <MoveHandlerOptions> options, ILogger <MoveHandler> logger, IServiceProvider serviceProvider)
     : base(rootFileSystem, host, logger)
 {
     _serviceProvider = serviceProvider;
     _options         = options?.Value ?? new MoveHandlerOptions();
 }
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="context">The 
        /// <see cref="IWebDavContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        public void ProcessRequest(IWebDavContext context, IWebDavStore store)
        {
            /***************************************************************************************************
             * Retreive al the information from the request
             ***************************************************************************************************/

            // Get the URI to the location
            Uri requestUri = context.Request.Url;

            // Initiate the XmlNamespaceManager and the XmlNodes
            XmlNamespaceManager manager = null;
            XmlNode propNode = null;

            // try to read the body
            try
            {
                StreamReader reader = new StreamReader(context.Request.InputStream, Encoding.UTF8);
                string requestBody = reader.ReadToEnd();

                if (!String.IsNullOrEmpty(requestBody))
                {
                    XmlDocument requestDocument = new XmlDocument();
                    requestDocument.LoadXml(requestBody);

                    if (requestDocument.DocumentElement != null)
                    {
                        if (requestDocument.DocumentElement.LocalName != "propertyupdate")
                        {
                            WebDavServer.Log.Debug("PROPPATCH method without propertyupdate element in xml document");
                        }

                        manager = new XmlNamespaceManager(requestDocument.NameTable);
                        manager.AddNamespace("D", "DAV:");
                        manager.AddNamespace("Office", "schemas-microsoft-com:office:office");
                        manager.AddNamespace("Repl", "http://schemas.microsoft.com/repl/");
                        manager.AddNamespace("Z", "urn:schemas-microsoft-com:");

                        propNode = requestDocument.DocumentElement.SelectSingleNode("D:set/D:prop", manager);
                    }
                }
            }
            catch (Exception ex)
            {
                WebDavServer.Log.Warn(ex.Message);
            }

            /***************************************************************************************************
             * Take action
             ***************************************************************************************************/

            // Get the parent collection of the item
            IWebDavStoreCollection collection = GetParentCollection(store, context, context.Request.Url);

            // Get the item from the collection
            IWebDavStoreItem item = GetItemFromCollection(collection, context.Request.Url);

            FileInfo fileInfo = new FileInfo(item.ItemPath);

            if (propNode != null && fileInfo.Exists)
            {
                foreach (XmlNode node in propNode.ChildNodes)
                {
                    switch (node.LocalName)
                    {
                        case "Win32CreationTime":
                            fileInfo.CreationTime = Convert.ToDateTime(node.InnerText).ToUniversalTime();
                            break;
                        case "Win32LastAccessTime":
                            fileInfo.LastAccessTime = Convert.ToDateTime(node.InnerText).ToUniversalTime();
                            break;
                        case "Win32LastModifiedTime":
                            fileInfo.LastWriteTime = Convert.ToDateTime(node.InnerText).ToUniversalTime();
                            break;
                        case "Win32FileAttributes":
                            //todo Win32FileAttributes
                            //fileInfo.Attributes = 
                            //fileInfo.Attributes = Convert.ToDateTime(node.InnerText);
                            break;
                    }
                }
            }


            /***************************************************************************************************
             * Create the body for the response
             ***************************************************************************************************/

            // Create the basic response XmlDocument
            XmlDocument responseDoc = new XmlDocument();
            const string responseXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><D:multistatus " +
                                       "xmlns:Z=\"urn:schemas-microsoft-com:\" xmlns:D=\"DAV:\">" +
                                       "<D:response></D:response></D:multistatus>";
            responseDoc.LoadXml(responseXml);

            // Select the response node
            XmlNode responseNode = responseDoc.DocumentElement.SelectSingleNode("D:response", manager);

            // Add the elements

            // The href element
            WebDavProperty hrefProperty = new WebDavProperty("href", requestUri.ToString());
            responseNode.AppendChild(hrefProperty.ToXmlElement(responseDoc));

            // The propstat element
            WebDavProperty propstatProperty = new WebDavProperty("propstat", string.Empty);
            XmlElement propstatElement = propstatProperty.ToXmlElement(responseDoc);

            // The propstat/status element
            WebDavProperty statusProperty = new WebDavProperty("status", "HTTP/1.1 " + context.Response.StatusCode + " " +
                    HttpWorkerRequest.GetStatusDescription(context.Response.StatusCode));
            propstatElement.AppendChild(statusProperty.ToXmlElement(responseDoc));

            // The other propstat children
            foreach (WebDavProperty property in from XmlNode child in propNode.ChildNodes
                where child.Name.ToLower()
                    .Contains("creationtime") || child.Name.ToLower()
                        .Contains("fileattributes") || child.Name.ToLower()
                            .Contains("lastaccesstime") || child.Name.ToLower()
                                .Contains("lastmodifiedtime")
                let node = propNode.SelectSingleNode(child.Name, manager)

                select new WebDavProperty(child.LocalName, string.Empty, node != null ? node.NamespaceURI : string.Empty))

                propstatElement.AppendChild(property.ToXmlElement(responseDoc));

            responseNode.AppendChild(propstatElement);

            /***************************************************************************************************
            * Send the response
            ***************************************************************************************************/
            
            // convert the StringBuilder
            string resp = responseDoc.InnerXml;
            byte[] responseBytes = Encoding.UTF8.GetBytes(resp);


            // HttpStatusCode doesn't contain WebDav status codes, but HttpWorkerRequest can handle these WebDav status codes
            context.SetStatusCode((int)WebDavStatusCode.MultiStatus);

            // set the headers of the response
            context.Response.ContentLength64 = responseBytes.Length;
            context.Response.AppendHeader("Content-Type", "text/xml");

            // the body
            context.Response.OutputStream.Write(responseBytes, 0, responseBytes.Length);

            context.Response.Close();
        }