/// <summary> /// Get the parent collection from the requested /// <see cref="Uri" />. /// <see cref="WebDavException" /> 409 Conflict possible. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</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( WebDavServer server, IWebDavStore store, Uri childUri) { Uri parentCollectionUri = childUri.GetParentUri(); IWebDavStoreCollection collection; try { collection = parentCollectionUri.GetItem(server, store) as IWebDavStoreCollection; } catch (UnauthorizedAccessException) { throw new WebDavUnauthorizedException(); } catch (WebDavNotFoundException wex) { throw new WebDavConflictException(innerException : wex); } if (collection == null) throw new WebDavConflictException(String.Format("Get parent collection return null. Uri: {0}", childUri)); //if (WebDavServer.Log.IsDebugEnabled) //{ // WebDavServer.Log.DebugFormat("GETPARENTCOLLECTION: uri {0} parenturi {1} return collection {2}", // childUri, parentCollectionUri, GetFullItemPath(collection)); //} return collection; }
/// <summary> /// Moves the /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> /// <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 static void MoveItem(WebDavServer server, IHttpListenerContext context, IWebDavStore store, IWebDavStoreItem sourceWebDavStoreItem) { Uri destinationUri = GetDestinationHeader(context.Request); IWebDavStoreCollection destinationParentCollection = GetParentCollection(server, store, destinationUri); bool isNew = true; string destinationName = destinationUri.GetLastSegment(); 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.SendSimpleResponse(isNew ? (int)HttpStatusCode.Created : (int)HttpStatusCode.NoContent); }
/// <summary> /// Copies the item. /// </summary> /// <param name="server">The server.</param> /// <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(WebDavServer server, IHttpListenerContext context, IWebDavStore store, IWebDavStoreItem source) { Uri destinationUri = GetDestinationHeader(context.Request); IWebDavStoreCollection destinationParentCollection = GetParentCollection(server, store, destinationUri); bool copyContent = (GetDepthHeader(context.Request) != 0); bool isNew = true; string destinationName = destinationUri.GetLastSegment(); 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); context.SendSimpleResponse(isNew ? (int)HttpStatusCode.Created : (int)HttpStatusCode.NoContent); }
/// <summary> /// Copies the item. /// </summary> /// <param name="server">The server.</param> /// <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(WebDavServer server, IHttpListenerContext context, IWebDavStore store, IWebDavStoreItem source) { var destinationUri = GetDestinationHeader(context.Request); var destinationParentCollection = GetParentCollection(server, store, destinationUri); var copyContent = (GetDepthHeader(context.Request) != 0); var isNew = true; var destinationName = Uri.UnescapeDataString(destinationUri.Segments.Last().TrimEnd('/', '\\')); var 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); context.SendSimpleResponse(isNew ? HttpStatusCode.Created : HttpStatusCode.NoContent); }
/// <summary> /// Copies the item. /// </summary> /// <param name="server">The server.</param> /// <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(WebDavServer server, IHttpListenerContext context, IWebDavStore store, IWebDavStoreItem source) { Uri destinationUri = GetDestinationHeader(context.Request); IWebDavStoreCollection destinationParentCollection = GetParentCollection(server, store, 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); context.SendSimpleResponse(isNew ? HttpStatusCode.Created : HttpStatusCode.NoContent); }
/// <summary> /// Moves the /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> /// <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(WebDavServer server, IHttpListenerContext context, IWebDavStore store, IWebDavStoreItem sourceWebDavStoreItem) { Uri destinationUri = GetDestinationHeader(context.Request); IWebDavStoreCollection destinationParentCollection = GetParentCollection(server, store, 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.SendSimpleResponse(isNew ? HttpStatusCode.Created : HttpStatusCode.NoContent); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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.WebDavUnsupportedMediaTypeException"></exception> /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavMethodNotAllowedException"></exception> /// <param name="response"></param> /// <param name="request"></param> protected override void OnProcessRequest( WebDavServer server, IHttpListenerContext context, IWebDavStore store, XmlDocument request, XmlDocument response) { if (context.Request.ContentLength64 > 0) throw new WebDavUnsupportedMediaTypeException(); IWebDavStoreCollection collection = GetParentCollection(server, store, context.Request.Url); string collectionName = context.Request.Url.GetLastSegment(); IWebDavStoreItem item; if ((item = collection.GetItemByName(collectionName)) != null) { WebDavServer.Log.WarnFormat("MKCOL Failed: item {0} already exists as child of {1}. ", collectionName, collection.ItemPath); throw new WebDavMethodNotAllowedException(); } collection.CreateCollection(collectionName); context.SendSimpleResponse((int)HttpStatusCode.Created); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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.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(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { IWebDavStoreCollection collection = GetParentCollection(server, store, 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()) { context.Response.StatusCode = (int)HttpStatusCode.OK; 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.Close(); }
/// <summary> /// Get the parent collection from the requested /// <see cref="Uri" />. /// <see cref="WebDavException" /> 409 Conflict possible. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</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( WebDavServer server, IWebDavStore store, Uri childUri) { Uri parentCollectionUri = childUri.GetParentUri(); IWebDavStoreCollection collection; try { collection = parentCollectionUri.GetItem(server, store) as IWebDavStoreCollection; } catch (UnauthorizedAccessException) { throw new WebDavUnauthorizedException(); } catch (WebDavNotFoundException wex) { throw new WebDavConflictException(innerException: wex); } if (collection == null) { throw new WebDavConflictException(String.Format("Get parent collection return null. Uri: {0}", childUri)); } //if (WebDavServer.Log.IsDebugEnabled) //{ // WebDavServer.Log.DebugFormat("GETPARENTCOLLECTION: uri {0} parenturi {1} return collection {2}", // childUri, parentCollectionUri, GetFullItemPath(collection)); //} return(collection); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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.WebDavUnsupportedMediaTypeException"></exception> /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavMethodNotAllowedException"></exception> /// <param name="response"></param> /// <param name="request"></param> protected override void OnProcessRequest( WebDavServer server, IHttpListenerContext context, IWebDavStore store, XmlDocument request, XmlDocument response) { if (context.Request.ContentLength64 > 0) { throw new WebDavUnsupportedMediaTypeException(); } IWebDavStoreCollection collection = GetParentCollection(server, store, context.Request.Url); string collectionName = context.Request.Url.GetLastSegment(); IWebDavStoreItem item; if ((item = collection.GetItemByName(collectionName)) != null) { WebDavServer.Log.Warning("MKCOL Failed: item {0} already exists as child of {1}. ", collectionName, collection.ItemPath); throw new WebDavMethodNotAllowedException(); } collection.CreateCollection(collectionName); context.SendSimpleResponse((int)HttpStatusCode.Created); }
/// <summary> /// Starts the server. /// Authentication used: Negotiate /// </summary> private static void StartServer() { IWebDavStoreItemLock lockSystem = new WebDavStoreItemLock(); IWebDavStore store = new WebDavDiskStore(Localpath, lockSystem); WebDavServer server = new WebDavServer(ref store); server.Start(Url); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { IWebDavStoreItem source = context.Request.Url.GetItem(server, store); if (source is IWebDavStoreDocument || source is IWebDavStoreCollection) CopyItem(server, context, store, source); else throw new WebDavMethodNotAllowedException(); }
/// <summary> /// </summary> /// <param name="name"></param> /// <param name="listener"></param> /// <param name="handlers"></param> /// <param name="store"></param> /// <param name="server"></param> public HttpReciever(string name, ref IHttpListener listener, ref Dictionary<string, IWebDavMethodHandler> handlers, ref IWebDavStore store, WebDavServer server) { _listener = listener; _methodHandlers = handlers; _store = store; _server = server; _name = name; }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavLengthRequiredException">If the ContentLength header was not found</exception> /// <param name="response"></param> /// <param name="request"></param> protected override void OnProcessRequest( WebDavServer server, IHttpListenerContext context, IWebDavStore store, XmlDocument request, XmlDocument response) { // Get the parent collection IWebDavStoreCollection parentCollection = GetParentCollection(server, store, context.Request.Url); // Gets the item name from the url string itemName = context.Request.Url.GetLastSegment(); 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); } Int64 contentLength = context.Request.ContentLength64; if (context.Request.ContentLength64 < 0) { var XLength = context.Request.Headers["x-expected-entity-length"]; if (!Int64.TryParse(XLength, out contentLength)) { throw new WebDavLengthRequiredException(); } } using (Stream stream = doc.OpenWriteStream(false)) { long left = contentLength; 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; } } doc.FinishWriteOperation(); context.SendSimpleResponse((int)HttpStatusCode.Created); }
public ActionResult Delete(int id) { DBEntities e = COREobject.i.Context; WebDavServer row = e.WebDavServers.Single(m => m.Id == id); e.WebDavServers.Remove(row); e.SaveChanges(); return(RedirectToRoute("Nexus", new { @action = "Index" })); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> /// <param name="response"></param> /// <param name="request"></param> protected override void OnProcessRequest( WebDavServer server, IHttpListenerContext context, IWebDavStore store, XmlDocument request, XmlDocument response) { IWebDavStoreItem source = context.Request.Url.GetItem(server, store); MoveItem(server, context, store, source); }
public void ProcessRequest( WebDavServer server, IHttpListenerContext context, IWebDavStore store, out XmlDocument request, out XmlDocument response) { request = new XmlDocument(); response = new XmlDocument(); OnProcessRequest(server, context, store, request, response); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> public override void ProcessRequest(WebDavServer server, IHttpListenerContext 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.SendSimpleResponse(); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> public void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { // Get the parent collection of the item var collection = GetParentCollection(server, store, context.Request.Url); // Get the item from the collection var item = GetItemFromCollection(collection, context.Request.Url); // Deletes the item collection.Delete(item); context.SendSimpleResponse(); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> public void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { // Get the parent collection of the item IWebDavStoreCollection collection = GetParentCollection(server, store, context.Request.Url); // Get the item from the collection IWebDavStoreItem item = GetItemFromCollection(collection, context.Request.Url); // Deletes the item collection.Delete(item); context.SendSimpleResponse(); }
/// <summary> /// Starts the server. /// Authentication used: Negotiate /// </summary> private void StartServer() { //IWebDavStoreItemLock lockSystem = new WebDavStoreItemLock(); //IWebDavStore store = new WebDavDiskStore(Localpath, lockSystem); //WebDavServer server = new WebDavServer(ref store); //server.Start(Url); WebDavServer server = new WebDavServer(new WebDavDiskStore(Root)); //server.Listener.Prefixes.Add("http://your_url_here/"); server.Start(Url); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { var source = context.Request.Url.GetItem(server, store); if (source is IWebDavStoreDocument || source is IWebDavStoreCollection) { CopyItem(server, context, store, source); } else { throw new WebDavMethodNotAllowedException(); } }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> public override void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { /*************************************************************************************************** * Send the response ***************************************************************************************************/ IWebDavStoreCollection collection = GetParentCollection(server, store, context.Request.Url); // Get the item from the collection IWebDavStoreItem storeItem = GetItemFromCollection(collection, context.Request.Url); if (storeItem == null) throw new WebDavNotFoundException(context.Request.Url.ToString()); var userIdentity = (WindowsIdentity) Thread.GetData(Thread.GetNamedDataSlot(WebDavServer.HttpUser)); context.SendSimpleResponse(store.LockSystem.UnLock(storeItem, context.Request.GetLockTokenHeader(), userIdentity.Name)); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavLengthRequiredException">If the ContentLength header was not found</exception> /// <param name="response"></param> /// <param name="request"></param> protected override void OnProcessRequest( WebDavServer server, IHttpListenerContext context, IWebDavStore store, XmlDocument request, XmlDocument response) { // Get the parent collection IWebDavStoreCollection parentCollection = GetParentCollection(server, store, context.Request.Url); // Gets the item name from the url string itemName = context.Request.Url.GetLastSegment(); 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); } Int64 contentLength = context.Request.ContentLength64; if (context.Request.ContentLength64 < 0) { var XLength = context.Request.Headers["x-expected-entity-length"]; if (!Int64.TryParse(XLength, out contentLength)) throw new WebDavLengthRequiredException(); } using (Stream stream = doc.OpenWriteStream(false)) { long left = contentLength; 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; } } doc.FinishWriteOperation(); context.SendSimpleResponse((int)HttpStatusCode.Created); }
/// <summary> /// This method is called when the service gets a request to start. /// </summary> /// <param name="args">Any command line arguments</param> public void OnStart(string[] args) { #if DEBUG NameValueCollection properties = new NameValueCollection { ["showDateTime"] = "true" }; LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter(properties); #endif IWebDavStoreItemLock lockSystem = new WebDavSqlStoreItemLock(); IWebDavStore store = new WebDavSqlStore("\\Data", new Guid("00000000-0000-0000-0000-000000000000"), lockSystem); WebDavServer server = new WebDavServer(ref store, AuthType.Negotiate); server.Start(Url); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> public void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { // Get the parent collection of the item IWebDavStoreCollection collection = GetParentCollection(server, store, context.Request.Url); // Get the item from the collection IWebDavStoreItem item = GetItemFromCollection(collection, context.Request.Url); /*************************************************************************************************** * Send the response ***************************************************************************************************/ context.SendSimpleResponse(HttpStatusCode.NoContent); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> public void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { // Get the parent collection of the item var collection = GetParentCollection(server, store, context.Request.Url); // Get the item from the collection var item = GetItemFromCollection(collection, context.Request.Url); /*************************************************************************************************** * Send the response ***************************************************************************************************/ context.SendSimpleResponse(HttpStatusCode.NoContent); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> public void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { List<string> verbsAllowed = new List<string> { "OPTIONS", "TRACE", "GET", "HEAD", "POST", "COPY", "PROPFIND", "LOCK", "UNLOCK" }; List<string> verbsPublic = new List<string> { "OPTIONS", "GET", "HEAD", "PROPFIND", "PROPPATCH", "MKCOL", "PUT", "DELETE", "COPY", "MOVE", "LOCK", "UNLOCK" }; foreach (string verb in verbsAllowed) context.Response.AppendHeader("Allow", verb); foreach (string verb in verbsPublic) context.Response.AppendHeader("Public", verb); // Sends 200 OK context.SendSimpleResponse(); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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.WebDavUnsupportedMediaTypeException"></exception> /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavMethodNotAllowedException"></exception> public override void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { if (context.Request.ContentLength64 > 0) throw new WebDavUnsupportedMediaTypeException(); IWebDavStoreCollection collection = GetParentCollection(server, store, 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.SendSimpleResponse((int) HttpStatusCode.Created); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavLengthRequiredException">If the ContentLength header was not found</exception> public void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { // Get the parent collection IWebDavStoreCollection parentCollection = GetParentCollection(server, store, 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.SendSimpleResponse(HttpStatusCode.Created); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <param name="context">The /// <see cref="IHttpListenerContext" /> object containing both the request and response /// objects to use.</param> /// <param name="request"></param> /// <param name="response"></param> /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param> /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavMethodNotAllowedException"></exception> protected override void OnProcessRequest( WebDavServer server, IHttpListenerContext context, IWebDavStore store, XmlDocument request, XmlDocument response) { IWebDavStoreItem source = context.Request.Url.GetItem(server, store); if (source is IWebDavStoreDocument || source is IWebDavStoreCollection) { CopyItem(server, context, store, source); } else { throw new WebDavMethodNotAllowedException(); } }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavLengthRequiredException">If the ContentLength header was not found</exception> public override void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { // Get the parent collection IWebDavStoreCollection parentCollection = GetParentCollection(server, store, 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[6000]; 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.SendSimpleResponse((int) HttpStatusCode.Created); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <param name="context">The /// <see cref="IHttpListenerContext" /> object containing both the request and response /// objects to use.</param> /// <param name="response"></param> /// <param name="request"></param> /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param> protected override void OnProcessRequest( WebDavServer server, IHttpListenerContext context, IWebDavStore store, XmlDocument request, XmlDocument response) { // Get the parent collection of the item IWebDavStoreCollection collection = GetParentCollection(server, store, context.Request.Url); // Get the item from the collection IWebDavStoreItem item = GetItemFromCollection(collection, context.Request.Url); // Deletes the item collection.Delete(item); //do not forget to clear all locks, if the object gets deleted there is no need to keep locks around. WebDavStoreItemLock.ClearLocks(context.Request.Url); context.SendSimpleResponse(); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> /// <param name="response"></param> /// <param name="request"></param> protected override void OnProcessRequest( WebDavServer server, IHttpListenerContext context, IWebDavStore store, XmlDocument request, XmlDocument response) { if (!WebDavStoreItemLock.LockEnabled) { throw new WebDavNotImplementedException("Lock support disabled"); } /*************************************************************************************************** * Send the response ***************************************************************************************************/ WindowsIdentity Identity = (WindowsIdentity)Thread.GetData(Thread.GetNamedDataSlot(WebDavServer.HttpUser)); var unlockResult = WebDavStoreItemLock.UnLock(context.Request.Url, GetLockTokenHeader(context.Request), Identity.Name); IWebDavStoreCollection collection = GetParentCollection(server, store, context.Request.Url); try { var item = GetItemFromCollection(collection, context.Request.Url); if (item != null) { //we already have an item var resourceCanBeUnLocked = item.UnLock(Identity.Name); if (!resourceCanBeUnLocked) { //TODO: decide what to do if the resource cannot be locked. } } } catch (Exception ex) { WebDavServer.Log.Warn( String.Format("Request unlock on a resource that does not exists: {0}", context.Request.Url), ex); } context.SendSimpleResponse(unlockResult); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> /// <param name="response"></param> /// <param name="request"></param> protected override void OnProcessRequest( WebDavServer server, IHttpListenerContext context, IWebDavStore store, XmlDocument request, XmlDocument response) { var baseVerbs = verbsAllowed.Aggregate((s1, s2) => s1 + ", " + s2); if (WebDavStoreItemLock.LockEnabled) { baseVerbs += ", LOCK, UNLOCK"; } context.Response.AppendHeader("Content-Type", "text /html; charset=UTF-8"); context.Response.AppendHeader("Allow", baseVerbs); context.Response.AppendHeader("Public", baseVerbs); context.Response.AppendHeader("Cache-Control", "no-cache"); context.Response.AppendHeader("Pragma", "no-cache"); context.Response.AppendHeader("Expires", "-1"); context.Response.AppendHeader("Accept-Ranges", "bytes"); context.Response.AppendHeader("Access-Control-Allow-Origin", "*"); context.Response.AppendHeader("Access-Control-Allow-Credentials", "true"); context.Response.AppendHeader("Access-Control-Allow-Methods", "ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL"); context.Response.AppendHeader("Access-Control-Allow-Headers", "Overwrite, Destination, Content-Type, Depth, User-Agent, Translate, Range, Content-Range, Timeout, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, Location, Lock-Token, If"); context.Response.AppendHeader("X-Engine", ".NETWebDav"); context.Response.AppendHeader("MS-Author-Via", "DAV"); context.Response.AppendHeader("Access-Control-Max-Age", "2147483647"); context.Response.AppendHeader("Public", ""); //foreach (string verb in verbsAllowed) // context.Response.AppendHeader("Allow", verb); //foreach (string verb in verbsPublic) // context.Response.AppendHeader("Public", verb); // Sends 200 OK context.SendSimpleResponse(); }
/// <summary> /// Get the parent collection from the requested /// <see cref="Uri" />. /// <see cref="WebDavException" /> 409 Conflict possible. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</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(WebDavServer server, IWebDavStore store, Uri childUri) { Uri parentCollectionUri = childUri.GetParentUri(); IWebDavStoreCollection collection; try { collection = parentCollectionUri.GetItem(server, store) 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="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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.WebDavUnsupportedMediaTypeException"></exception> /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavMethodNotAllowedException"></exception> public void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { if (context.Request.ContentLength64 > 0) { throw new WebDavUnsupportedMediaTypeException(); } IWebDavStoreCollection collection = GetParentCollection(server, store, 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.SendSimpleResponse(HttpStatusCode.Created); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> public void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { var verbsAllowed = new List <string> { "OPTIONS", "TRACE", "GET", "HEAD", "POST", "COPY", "PROPFIND", "LOCK", "UNLOCK" }; var verbsPublic = new List <string> { "OPTIONS", "GET", "HEAD", "PROPFIND", "PROPPATCH", "MKCOL", "PUT", "DELETE", "COPY", "MOVE", "LOCK", "UNLOCK" }; foreach (var verb in verbsAllowed) { context.Response.AppendHeader("Allow", verb); } foreach (var verb in verbsPublic) { context.Response.AppendHeader("Public", verb); } // Sends 200 OK context.SendSimpleResponse(); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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="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(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { // Get the parent collection of the item IWebDavStoreCollection collection = GetParentCollection(server, store, 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.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.StatusDescription = HttpWorkerRequest.GetStatusDescription((int)HttpStatusCode.OK); // 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")); context.Response.Close(); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> /// <param name="response"></param> /// <param name="request"></param> protected override void OnProcessRequest( WebDavServer server, IHttpListenerContext context, IWebDavStore store, XmlDocument request, XmlDocument response) { if (!WebDavStoreItemLock.LockEnabled) throw new WebDavNotImplementedException("Lock support disabled"); /*************************************************************************************************** * Send the response ***************************************************************************************************/ WindowsIdentity Identity = (WindowsIdentity)Thread.GetData(Thread.GetNamedDataSlot(WebDavServer.HttpUser)); var unlockResult = WebDavStoreItemLock.UnLock(context.Request.Url, GetLockTokenHeader(context.Request), Identity.Name); IWebDavStoreCollection collection = GetParentCollection(server, store, context.Request.Url); try { var item = GetItemFromCollection(collection, context.Request.Url); if (item != null) { //we already have an item var resourceCanBeUnLocked = item.UnLock(Identity.Name); if (!resourceCanBeUnLocked) { //TODO: decide what to do if the resource cannot be locked. } } } catch (Exception ex) { WebDavServer.Log.Warn( String.Format("Request unlock on a resource that does not exists: {0}", context.Request.Url), ex); } context.SendSimpleResponse(unlockResult); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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.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(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { IWebDavStoreCollection collection = GetParentCollection(server, store, 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()) { context.Response.StatusCode = (int)HttpStatusCode.OK; 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.Close(); }
/// <summary> /// Get the parent collection from the requested /// <see cref="Uri" />. /// <see cref="WebDavException" /> 409 Conflict possible. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</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(WebDavServer server, IWebDavStore store, Uri childUri) { Uri parentCollectionUri = childUri.GetParentUri(); IWebDavStoreCollection collection; try { collection = parentCollectionUri.GetItem(server, store) as IWebDavStoreCollection; } catch (UnauthorizedAccessException) { throw new WebDavUnauthorizedException(); } catch (WebDavNotFoundException) { throw new WebDavConflictException(); } if (collection == null) { throw new WebDavConflictException(); } return(collection); }
public ActionResult Save(WebDavServer model) { DBEntities e = COREobject.i.Context; if (!model.Id.Equals(null) && model.Id > 0) { WebDavServer row = e.WebDavServers.Single(m => m.Id == model.Id); row.Name = model.Name; row.UriBasePath = model.UriBasePath; row.AnonymousMode = model.AnonymousMode; row.AuthUsername = model.AuthUsername; if (model.AuthPassword.Length > 0) { row.AuthPassword = model.AuthPassword; } e.SaveChanges(); } else { e.WebDavServers.Add(model); e.SaveChanges(); } return(RedirectToRoute("Nexus", new { @action = "Index" })); }
/// <summary> /// Get the parent collection from the requested /// <see cref="Uri" />. /// <see cref="WebDavException" /> 409 Conflict possible. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</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(WebDavServer server, IWebDavStore store, Uri childUri) { Uri parentCollectionUri = childUri.GetParentUri(); return parentCollectionUri.GetItem(server, store) as IWebDavStoreCollection; }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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.WebDavPreconditionFailedException"></exception> /// <param name="response"></param> /// <param name="request"></param> protected override void OnProcessRequest( WebDavServer server, IHttpListenerContext context, IWebDavStore store, XmlDocument request, XmlDocument response) { if (!WebDavStoreItemLock.LockEnabled) throw new WebDavNotImplementedException("Lock support disabled"); /*************************************************************************************************** * 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 = 0; // Initiate the XmlNamespaceManager and the XmlNodes XmlNamespaceManager manager; XmlNode lockscopeNode, locktypeNode, ownerNode; 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) { request.LoadXml(requestBody); if (request.DocumentElement != null && request.DocumentElement.LocalName != "prop" && request.DocumentElement.LocalName != "lockinfo") { WebDavServer.Log.Debug("LOCK method without prop or lockinfo element in xml document"); } manager = new XmlNamespaceManager(request.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 = request.DocumentElement.SelectSingleNode("D:lockscope", manager); locktypeNode = request.DocumentElement.SelectSingleNode("D:locktype", manager); ownerNode = request.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(server, store, 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 userAgent = context.Request.Headers["User-Agent"]; WindowsIdentity Identity = (WindowsIdentity)Thread.GetData(Thread.GetNamedDataSlot(WebDavServer.HttpUser)); // Get the item from the collection try { var item = GetItemFromCollection(collection, context.Request.Url); String lockLogicalKey = context.Request.Url.AbsoluteUri; if (item != null) { lockLogicalKey = item.LockLogicalKey; } if (item != null && !item.Lock()) { lockResult = 423; //Resource cannot be locked } else { //try acquiring a standard lock, lockResult = WebDavStoreItemLock.Lock( context.Request.Url, lockLogicalKey, lockscope, locktype, Identity.Name, userAgent, ref timeout, out locktoken, request, depth); } } catch (Exception ex) { WebDavServer._log.Error(String.Format("Error occourred while acquiring lock {0}", context.Request.Url), ex); lockResult = 423; //Resource cannot be locked some exception occurred } #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 request); if (request == null) { context.SendSimpleResponse(409); return; } try { if (request.DocumentElement != null && request.DocumentElement.LocalName != "prop" && request.DocumentElement.LocalName != "lockinfo") { WebDavServer.Log.Debug("LOCK method without prop or lockinfo element in xml document"); } manager = new XmlNamespaceManager(request.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 = request.DocumentElement.SelectSingleNode("D:lockscope", manager); locktypeNode = request.DocumentElement.SelectSingleNode("D:locktype", manager); ownerNode = request.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 const string responseXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><D:prop xmlns:D=\"DAV:\"><D:lockdiscovery><D:activelock/></D:lockdiscovery></D:prop>"; response.LoadXml(responseXml); // Select the activelock XmlNode XmlNode activelock = response.DocumentElement.SelectSingleNode("D:lockdiscovery/D:activelock", manager); // Import the given nodes activelock.AppendChild(response.ImportNode(lockscopeNode, true)); activelock.AppendChild(response.ImportNode(locktypeNode, true)); activelock.AppendChild(response.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(response)); // The depth element WebDavProperty depthProperty = new WebDavProperty("depth", (depth == 0 ? "0" : "Infinity")); activelock.AppendChild(depthProperty.ToXmlElement(response)); // The locktoken element WebDavProperty locktokenProperty = new WebDavProperty("locktoken", string.Empty); XmlElement locktokenElement = locktokenProperty.ToXmlElement(response); WebDavProperty hrefProperty = new WebDavProperty("href", locktoken);//"opaquelocktoken:e71d4fae-5dec-22df-fea5-00a0c93bd5eb1"); locktokenElement.AppendChild(hrefProperty.ToXmlElement(response)); activelock.AppendChild(locktokenElement); // The lockroot element WebDavProperty lockRootProperty = new WebDavProperty("lockroot", string.Empty); XmlElement lockRootElement = lockRootProperty.ToXmlElement(response); WebDavProperty hrefRootProperty = new WebDavProperty("href", context.Request.Url.AbsoluteUri);//"lockroot lockRootElement.AppendChild(hrefRootProperty.ToXmlElement(response)); activelock.AppendChild(lockRootElement); /*************************************************************************************************** * Send the response ***************************************************************************************************/ // convert the StringBuilder string resp = response.InnerXml; if (WebDavServer.Log.IsDebugEnabled) { WebDavServer.Log.DebugFormat( @"Request {0}:{1}:{2} Request {3} Response: {4}", context.Request.HttpMethod, context.Request.RemoteEndPoint, context.Request.Url, request.Beautify(), response.Beautify()); } byte[] responseBytes = Encoding.UTF8.GetBytes(resp); context.Response.StatusCode = lockResult; context.Response.StatusDescription = HttpWorkerRequest.GetStatusDescription(lockResult); // set the headers of the response context.Response.ContentLength64 = responseBytes.Length; context.Response.AdaptedInstance.ContentType = "text/xml"; // the body context.Response.OutputStream.Write(responseBytes, 0, responseBytes.Length); context.Response.Close(); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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 override void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { /*************************************************************************************************** * Retreive all the information from the request ***************************************************************************************************/ // Read the headers, ... bool isPropname = false; int depth = GetDepthHeader(context.Request); Uri requestUri = GetRequestUri(context.Request.Url.ToString()); IWebDavStoreItem item = context.Request.Url.GetItem(server, store); List<IWebDavStoreItem> webDavStoreItems = GetWebDavStoreItems(item, depth); // Get the XmlDocument from the request XmlDocument requestDoc = GetXmlDocument(context.Request); // See what is requested List<WebDavProperty> requestedProperties = new List<WebDavProperty>(); if (requestDoc.DocumentElement != null) { if (requestDoc.DocumentElement.LocalName != "propfind") { #if DEBUG WebDavServer.Log.Debug("PROPFIND method without propfind in xml document"); #endif } else { XmlNode n = requestDoc.DocumentElement.FirstChild; if (n == null) { #if DEBUG WebDavServer.Log.Debug("propfind element without children"); #endif } else { switch (n.LocalName) { case "allprop": requestedProperties = GetAllProperties(); break; case "propname": isPropname = true; requestedProperties = GetAllProperties(); break; case "prop": requestedProperties.AddRange(from XmlNode child in n.ChildNodes select 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 * Send the response ***************************************************************************************************/ string sdoc = ResponseDocument(context, isPropname, requestUri, requestedProperties, webDavStoreItems, store.LockSystem, store); SendResponse(context, sdoc); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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.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> /// <param name="response"></param> /// <param name="request"></param> protected override void OnProcessRequest( WebDavServer server, IHttpListenerContext context, IWebDavStore store, XmlDocument request, XmlDocument response) { IWebDavStoreCollection collection = GetParentCollection(server, store, context.Request.Url); IWebDavStoreItem item = GetItemFromCollection(collection, context.Request.Url); IWebDavStoreDocument doc = item as IWebDavStoreDocument; if (doc == null) { throw new WebDavNotFoundException(string.Format("Cannot find document item {0}", context.Request.Url)); } context.Response.SetEtag(doc.Etag); context.Response.SetLastModified(doc.ModificationDate); var extension = doc.ItemPath.GetFileExtensionSafe(); context.Response.AppendHeader("Content-Type", MimeMapping.GetMimeMapping(extension)); context.Response.AppendHeader("Cache-Control", "no-cache"); context.Response.AppendHeader("Pragma", "no-cache"); context.Response.AppendHeader("Expires", "-1"); context.Response.AppendHeader("Accept-Ranges", "bytes"); context.Response.AppendHeader("Access-Control-Allow-Origin", "*"); context.Response.AppendHeader("Access-Control-Allow-Credentials", "true"); context.Response.AppendHeader("Access-Control-Allow-Methods", "ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL"); context.Response.AppendHeader("Access-Control-Allow-Headers", "Overwrite, Destination, Content-Type, Depth, User-Agent, Translate, Range, Content-Range, Timeout, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, Location, Lock-Token, If"); context.Response.AppendHeader("X-Engine", ".NETWebDav"); context.Response.AppendHeader("MS-Author-Via", "DAV"); context.Response.AppendHeader("Access-Control-Max-Age", "2147483647"); context.Response.AppendHeader("Public", ""); var ifModifiedSince = context.Request.Headers["If-Modified-Since"]; var ifNoneMatch = context.Request.Headers["If-None-Match"]; if (ifNoneMatch != null) { if (ifNoneMatch == doc.Etag) { context.Response.StatusCode = 304; context.Response.Close(); return; } } 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; 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(); } } context.Response.Close(); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> /// <param name="response"></param> /// <param name="request"></param> protected override void OnProcessRequest( WebDavServer server, IHttpListenerContext context, IWebDavStore store, XmlDocument request, XmlDocument response) { /*************************************************************************************************** * 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; XDocument requestXDocument = null; // try to read the body try { StreamReader reader = new StreamReader(context.Request.InputStream, Encoding.UTF8); string requestBody = reader.ReadToEnd(); if (!String.IsNullOrEmpty(requestBody)) { request.LoadXml(requestBody); if (request.DocumentElement != null) { if (request.DocumentElement.LocalName != "propertyupdate") { WebDavServer.Log.Debug("PROPPATCH method without propertyupdate element in xml document"); } manager = new XmlNamespaceManager(request.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 = request.DocumentElement.SelectSingleNode("D:set/D:prop", manager); } requestXDocument = XDocument.Parse(requestBody); } } catch (Exception ex) { WebDavServer.Log.Warn(ex.Message); } /*************************************************************************************************** * Take action ***************************************************************************************************/ // Get the parent collection of the item IWebDavStoreCollection collection = GetParentCollection(server, store, context.Request.Url); // Get the item from the collection IWebDavStoreItem item = GetItemFromCollection(collection, context.Request.Url); //we need to get properties to set List<WebDavProperty> propertiesToSet = new List<WebDavProperty>(); if (requestXDocument != null) { foreach (XElement propertySet in requestXDocument.Descendants() .Where(n => n.Name.LocalName == "set")) { //this is a property to set var allPropertiesToSet = propertySet.Elements().First().Elements(); foreach (var propSetNode in allPropertiesToSet) { propertiesToSet.Add(new WebDavProperty() { Name = propSetNode.Name.LocalName, Namespace = propSetNode.Name.NamespaceName, Value = propSetNode.Value }); } } } item.SetProperties(propertiesToSet); /*************************************************************************************************** * Create the body for the response ***************************************************************************************************/ // Create the basic response 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>"; response.LoadXml(responseXml); // Select the response node XmlNode responseNode = response.DocumentElement.SelectSingleNode("D:response", manager); // Add the elements // The href element WebDavProperty hrefProperty = new WebDavProperty("href", requestUri.ToString()); responseNode.AppendChild(hrefProperty.ToXmlElement(response)); // The propstat element WebDavProperty propstatProperty = new WebDavProperty("propstat", string.Empty); XmlElement propstatElement = propstatProperty.ToXmlElement(response); // The propstat/status element WebDavProperty statusProperty = new WebDavProperty("status", "HTTP/1.1 " + context.Response.StatusCode + " " + HttpWorkerRequest.GetStatusDescription(context.Response.StatusCode)); propstatElement.AppendChild(statusProperty.ToXmlElement(response)); // 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(response)); responseNode.AppendChild(propstatElement); /*************************************************************************************************** * Send the response ***************************************************************************************************/ // convert the StringBuilder string resp = response.InnerXml; byte[] responseBytes = Encoding.UTF8.GetBytes(resp); // HttpStatusCode doesn't contain WebDav status codes, but HttpWorkerRequest can handle these WebDav status codes context.Response.StatusCode = (int)WebDavStatusCode.MultiStatus; context.Response.StatusDescription = HttpWorkerRequest.GetStatusDescription((int)WebDavStatusCode.MultiStatus); // set the headers of the response context.Response.ContentLength64 = responseBytes.Length; context.Response.AdaptedInstance.ContentType = "text/xml"; // the body context.Response.OutputStream.Write(responseBytes, 0, responseBytes.Length); context.Response.Close(); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> /// <param name="response"></param> /// <param name="request"></param> protected override void OnProcessRequest( WebDavServer server, IHttpListenerContext context, IWebDavStore store, XmlDocument request, XmlDocument response) { /*************************************************************************************************** * 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; XDocument requestXDocument = null; // try to read the body try { StreamReader reader = new StreamReader(context.Request.InputStream, Encoding.UTF8); string requestBody = reader.ReadToEnd(); if (!String.IsNullOrEmpty(requestBody)) { request.LoadXml(requestBody); if (request.DocumentElement != null) { if (request.DocumentElement.LocalName != "propertyupdate") { WebDavServer.Log.Debug("PROPPATCH method without propertyupdate element in xml document"); } manager = new XmlNamespaceManager(request.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 = request.DocumentElement.SelectSingleNode("D:set/D:prop", manager); } requestXDocument = XDocument.Parse(requestBody); } } catch (Exception ex) { WebDavServer.Log.Warning(ex.Message); } /*************************************************************************************************** * Take action ***************************************************************************************************/ // Get the parent collection of the item IWebDavStoreCollection collection = GetParentCollection(server, store, context.Request.Url); // Get the item from the collection IWebDavStoreItem item = GetItemFromCollection(collection, context.Request.Url); //we need to get properties to set List <WebDavProperty> propertiesToSet = new List <WebDavProperty>(); if (requestXDocument != null) { foreach (XElement propertySet in requestXDocument.Descendants() .Where(n => n.Name.LocalName == "set")) { //this is a property to set var allPropertiesToSet = propertySet.Elements().First().Elements(); foreach (var propSetNode in allPropertiesToSet) { propertiesToSet.Add(new WebDavProperty() { Name = propSetNode.Name.LocalName, Namespace = propSetNode.Name.NamespaceName, Value = propSetNode.Value }); } } } item.SetProperties(propertiesToSet); /*************************************************************************************************** * Create the body for the response ***************************************************************************************************/ // Create the basic response 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>"; response.LoadXml(responseXml); // Select the response node XmlNode responseNode = response.DocumentElement.SelectSingleNode("D:response", manager); // Add the elements // The href element WebDavProperty hrefProperty = new WebDavProperty("href", requestUri.ToString()); responseNode.AppendChild(hrefProperty.ToXmlElement(response)); // The propstat element WebDavProperty propstatProperty = new WebDavProperty("propstat", string.Empty); XmlElement propstatElement = propstatProperty.ToXmlElement(response); // The propstat/status element WebDavProperty statusProperty = new WebDavProperty("status", "HTTP/1.1 " + context.Response.StatusCode + " " + HttpWorkerRequest.GetStatusDescription(context.Response.StatusCode)); propstatElement.AppendChild(statusProperty.ToXmlElement(response)); // 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(response)); } responseNode.AppendChild(propstatElement); /*************************************************************************************************** * Send the response ***************************************************************************************************/ // convert the StringBuilder string resp = response.InnerXml; byte[] responseBytes = Encoding.UTF8.GetBytes(resp); // HttpStatusCode doesn't contain WebDav status codes, but HttpWorkerRequest can handle these WebDav status codes context.Response.StatusCode = (int)WebDavStatusCode.MultiStatus; context.Response.StatusDescription = HttpWorkerRequest.GetStatusDescription((int)WebDavStatusCode.MultiStatus); // set the headers of the response context.Response.ContentLength64 = responseBytes.Length; context.Response.AdaptedInstance.ContentType = "text/xml"; // the body context.Response.OutputStream.Write(responseBytes, 0, responseBytes.Length); context.Response.Close(); }
protected abstract void OnProcessRequest( WebDavServer server, IHttpListenerContext context, IWebDavStore store, XmlDocument request, XmlDocument response);
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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> public void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { var source = context.Request.Url.GetItem(server, store); MoveItem(server, context, store, source); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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="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> /// <param name="response"></param> /// <param name="request"></param> protected override void OnProcessRequest( WebDavServer server, IHttpListenerContext context, IWebDavStore store, XmlDocument request, XmlDocument response) { // Get the parent collection of the item IWebDavStoreCollection collection; IWebDavStoreItem item = null; //PATCH: Cyberduck and some windows ask HEAD of the root, and it was not supported. var uri = context.Request.Url; if (uri.Segments.Length == 1) { collection = store.Root; item = store.Root; } else { collection = GetParentCollection(server, store, uri); // Get the item from the collection item = GetItemFromCollection(collection, context.Request.Url); } if (item is IWebDavStoreDocument) { var doc = (IWebDavStoreDocument)item; context.Response.SetEtag(doc.Etag); context.Response.SetLastModified(doc.ModificationDate); var extension = Path.GetExtension(doc.ItemPath); context.Response.AppendHeader("Content-Type", MimeMapping.GetMimeMapping(extension)); } else { context.Response.AppendHeader("Content-Type", "text/html"); } /*************************************************************************************************** * Send the response ***************************************************************************************************/ // HttpStatusCode doesn't contain WebDav status codes, but HttpWorkerRequest can handle these WebDav status codes context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.StatusDescription = HttpWorkerRequest.GetStatusDescription((int)HttpStatusCode.OK); // set the headers of the response context.Response.ContentLength64 = 0; context.Response.AppendHeader("Cache-Control", "no-cache"); context.Response.AppendHeader("Pragma", "no-cache"); context.Response.AppendHeader("Expires", "-1"); context.Response.AppendHeader("Accept-Ranges", "bytes"); context.Response.AppendHeader("Access-Control-Allow-Origin", "*"); context.Response.AppendHeader("Access-Control-Allow-Credentials", "true"); context.Response.AppendHeader("Access-Control-Allow-Methods", "ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL"); context.Response.AppendHeader("Access-Control-Allow-Headers", "Overwrite, Destination, Content-Type, Depth, User-Agent, Translate, Range, Content-Range, Timeout, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, Location, Lock-Token, If"); context.Response.AppendHeader("X-Engine", ".NETWebDav"); context.Response.AppendHeader("MS-Author-Via", "DAV"); context.Response.AppendHeader("Access-Control-Max-Age", "2147483647"); context.Response.AppendHeader("Public", ""); context.Response.Close(); }
/// <summary> /// </summary> /// <param name="server"></param> /// <param name="context"></param> /// <param name="store"></param> public abstract void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store);
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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.WebDavPreconditionFailedException"></exception> public void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { ILog log = LogManager.GetCurrentClassLogger(); /*************************************************************************************************** * Retreive al the information from the request ***************************************************************************************************/ // read the headers int depth = GetDepthHeader(context.Request); string timeout = GetTimeoutHeader(context.Request); // Initiate the XmlNamespaceManager and the XmlNodes XmlNamespaceManager manager = null; XmlNode lockscopeNode = null, locktypeNode = null, ownerNode = null; // 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) { XmlDocument requestDocument = new XmlDocument(); requestDocument.LoadXml(requestBody); if (requestDocument.DocumentElement != null && requestDocument.DocumentElement.LocalName != "prop" && requestDocument.DocumentElement.LocalName != "lockinfo") { 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) { log.Warn(ex.Message); throw; } /*************************************************************************************************** * Lock the file or folder ***************************************************************************************************/ bool isNew = false; // Get the parent collection of the item IWebDavStoreCollection collection = GetParentCollection(server, store, context.Request.Url); try { // Get the item from the collection IWebDavStoreItem item = GetItemFromCollection(collection, context.Request.Url); } catch (Exception) { collection.CreateDocument(context.Request.Url.Segments.Last().TrimEnd('/', '\\')); isNew = true; } /*************************************************************************************************** * Create the body for the response ***************************************************************************************************/ // Create the basic response XmlDocument XmlDocument responseDoc = new XmlDocument(); 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); 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", ""); XmlElement locktokenElement = locktokenProperty.ToXmlElement(responseDoc); WebDavProperty hrefProperty = new WebDavProperty("href", "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); if (isNew) { // HttpStatusCode doesn't contain WebDav status codes, but HttpWorkerRequest can handle these WebDav status codes context.Response.StatusCode = (int)HttpStatusCode.Created; context.Response.StatusDescription = HttpWorkerRequest.GetStatusDescription((int)HttpStatusCode.Created); } else { // HttpStatusCode doesn't contain WebDav status codes, but HttpWorkerRequest can handle these WebDav status codes context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.StatusDescription = HttpWorkerRequest.GetStatusDescription((int)HttpStatusCode.OK); } // set the headers of the response context.Response.ContentLength64 = responseBytes.Length; context.Response.AdaptedInstance.ContentType = "text/xml"; // the body context.Response.OutputStream.Write(responseBytes, 0, responseBytes.Length); context.Response.Close(); }
/// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <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.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> /// <param name="response"></param> /// <param name="request"></param> protected override void OnProcessRequest( WebDavServer server, IHttpListenerContext context, IWebDavStore store, XmlDocument request, XmlDocument response) { IWebDavStoreCollection collection = GetParentCollection(server, store, context.Request.Url); IWebDavStoreItem item = GetItemFromCollection(collection, context.Request.Url); IWebDavStoreDocument doc = item as IWebDavStoreDocument; if (doc == null) throw new WebDavNotFoundException(string.Format("Cannot find document item {0}", context.Request.Url)); context.Response.SetEtag(doc.Etag); context.Response.SetLastModified(doc.ModificationDate); var extension = Path.GetExtension(doc.ItemPath); context.Response.AppendHeader("Content-Type", MimeMapping.GetMimeMapping(extension)); context.Response.AppendHeader("Cache-Control", "no-cache"); context.Response.AppendHeader("Pragma", "no-cache"); context.Response.AppendHeader("Expires", "-1"); context.Response.AppendHeader("Accept-Ranges", "bytes"); context.Response.AppendHeader("Access-Control-Allow-Origin", "*"); context.Response.AppendHeader("Access-Control-Allow-Credentials", "true"); context.Response.AppendHeader("Access-Control-Allow-Methods", "ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL"); context.Response.AppendHeader("Access-Control-Allow-Headers", "Overwrite, Destination, Content-Type, Depth, User-Agent, Translate, Range, Content-Range, Timeout, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, Location, Lock-Token, If"); context.Response.AppendHeader("X-Engine", ".NETWebDav"); context.Response.AppendHeader("MS-Author-Via", "DAV"); context.Response.AppendHeader("Access-Control-Max-Age", "2147483647"); context.Response.AppendHeader("Public", ""); var ifModifiedSince = context.Request.Headers["If-Modified-Since"]; var ifNoneMatch = context.Request.Headers["If-None-Match"]; if (ifNoneMatch != null) { if (ifNoneMatch == doc.Etag) { context.Response.StatusCode = 304; context.Response.Close(); return; } } 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; 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(); } } context.Response.Close(); }