private void MoveCollection(WebDAVServer server, IHttpListenerContext context, IWebDAVStore store, IWebDAVStoreCollection source) { var destinationUri = new Uri(context.Request.Headers["Destination"]); var destinationParentCollection = destinationUri.GetParentUri().GetItem(server, store) as IWebDAVStoreCollection; if (destinationParentCollection == null) { throw new HttpConflictException(); } string destinationName = destinationUri.Segments.Last().TrimEnd('/', '\\'); var destination = destinationParentCollection.GetItemByName(destinationName); if (destination != null) { if (context.Request.Headers["Overwrite"] == "F") { throw new HttpException(HttpStatusCodes.ClientErrors.PreconditionFailed); } destinationParentCollection.Delete(destination); } destinationParentCollection.MoveItemHere(source, destinationName); context.SendSimpleResponse(HttpStatusCodes.Successful.Created); }
/// <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> /// <param name="logger"> /// The <see cref="ILogger"/> to log to. /// </param> public void ProcessRequest(WebDAVServer server, IHttpListenerContext context, IWebDAVStore store, ILogger logger) { if (context.Request.ContentLength64 > 0) { throw new HttpException(HttpStatusCodes.ClientErrors.UnsupportedMediaType); } Uri uri = context.Request.Url.GetParentUri(); var collection = uri.GetItem(server, store) as IWebDAVStoreCollection; if (collection == null) { throw new HttpNotFoundException(); } string collectionName = context.Request.Url.Segments.Last().TrimEnd('/', '\\'); if (collection.GetItemByName(collectionName) != null) { throw new HttpException(HttpStatusCodes.ClientErrors.MethodNotAllowed); } collection.CreateCollection(collectionName); context.SendSimpleResponse(HttpStatusCodes.Successful.OK); }
/// <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> /// 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> /// 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> /// 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> /// 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.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> /// 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 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> /// 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 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> /// <param name="logger"> /// The <see cref="ILogger"/> to log to. /// </param> public void ProcessRequest(WebDAVServer server, IHttpListenerContext context, IWebDAVStore store, ILogger logger) { // var item = context.Request.Url.GetItem(server, store); var verbsAllowed = new List <string> { "OPTIONS" }; foreach (var verb in verbsAllowed) { context.Response.AppendHeader("Allow", verb); } context.SendSimpleResponse(HttpStatusCodes.Successful.OK); }
/// <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) { // 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) { 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> /// <param name="logger"> /// The <see cref="ILogger"/> to log to. /// </param> public void ProcessRequest(WebDAVServer server, IHttpListenerContext context, IWebDAVStore store, ILogger logger) { var parentCollection = context.Request.Url.GetParentUri().GetItem(server, store) as IWebDAVStoreCollection; if (parentCollection == null) { throw new HttpConflictException(); } string itemName = context.Request.Url.Segments.Last().TrimEnd('/', '\\'); var item = parentCollection.GetItemByName(itemName); IWebDAVStoreDocument doc; if (item != null) { doc = item as IWebDAVStoreDocument; if (doc == null) { throw new HttpMethodNotAllowedException(); } } else { doc = parentCollection.CreateDocument(itemName); } if (context.Request.ContentLength64 < 0) { throw new HttpException(HttpStatusCodes.ClientErrors.LengthRequired); } using (var 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(HttpStatusCodes.Successful.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="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="store"> /// The <see cref="IWebDAVStore"/> that the <see cref="WebDAVServer"/> is hosting. /// </param> /// <param name="logger"> /// The <see cref="ILogger"/> to log to. /// </param> public void ProcessRequest(WebDAVServer server, IHttpListenerContext context, IWebDAVStore store, ILogger logger) { Uri parentCollectionUri = context.Request.Url.GetParentUri(); var collection = parentCollectionUri.GetItem(server, store) as IWebDAVStoreCollection; if (collection == null) { throw new HttpConflictException(); } IWebDAVStoreItem item = collection.GetItemByName(context.Request.Url.Segments.Last().TrimEnd('/', '\\')); if (item == null) { throw new HttpNotFoundException(); } 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="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="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> /// 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> /// <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> /// 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.Warning(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.Warning(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.IsEnabled(Serilog.Events.LogEventLevel.Debug)) { WebDavServer.Log.Debug( @"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.WebDavPreconditionFailedException"></exception> public override void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { /*************************************************************************************************** * Retreive al the information from the request ***************************************************************************************************/ // Get the parent collection of the item 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()); // read the headers int depth = GetDepthHeader(context.Request); double? timeout = context.Request.GetTimeoutHeader(store); Guid? locktoken = context.Request.GetLockTokenIfHeader(); int lockResult; // Initiate the XmlNamespaceManager and the XmlNodes XmlNamespaceManager manager; XmlNode lockscopeNode, locktypeNode, ownerNode; XmlDocument requestDocument = new XmlDocument(); if (locktoken == null) { #region New Lock // try to read the body #if DEBUG try { #endif StreamReader reader = new StreamReader(context.Request.InputStream, Encoding.UTF8); string requestBody = reader.ReadToEnd(); if (!requestBody.Equals("") && requestBody.Length != 0) { requestDocument.LoadXml(requestBody); if (requestDocument.DocumentElement != null && requestDocument.DocumentElement.LocalName != "prop" && requestDocument.DocumentElement.LocalName != "lockinfo") { #if DEBUG WebDavServer.Log.Debug("LOCK method without prop or lockinfo element in xml document"); #endif } 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:"); if (requestDocument.DocumentElement == null) throw new NullReferenceException("requestDocument.DocumentElement"); // 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(); } #if DEBUG } catch (Exception ex) { WebDavServer.Log.Warn(ex.Message); throw; } #endif /*************************************************************************************************** * Lock the file or folder ***************************************************************************************************/ if (lockscopeNode == null) throw new NullReferenceException("lockscopeNode"); WebDavLockScope lockscope = (lockscopeNode.InnerXml.StartsWith("<D:exclusive")) ? WebDavLockScope.Exclusive : WebDavLockScope.Shared; if (locktypeNode == null) throw new NullReferenceException("locktypeNode"); //Only lock available at this time is a Write Lock according to RFC const WebDavLockType locktype = WebDavLockType.Write; //(locktypeNode.InnerXml.StartsWith("<D:write")) ? WebDavLockType.Write : WebDavLockType.Write; WindowsIdentity userIdentity = (WindowsIdentity) Thread.GetData(Thread.GetNamedDataSlot(WebDavServer.HttpUser)); lockResult = store.LockSystem.Lock(storeItem, lockscope, locktype, userIdentity.Name, timeout, out locktoken, requestDocument, depth); #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 = store.LockSystem.RefreshLock(storeItem, locktoken, timeout, out requestDocument); if (requestDocument == null) { context.SendSimpleResponse(409); return; } #if DEBUG try { if (requestDocument.DocumentElement != null && requestDocument.DocumentElement.LocalName != "prop" && requestDocument.DocumentElement.LocalName != "lockinfo") { WebDavServer.Log.Debug("LOCK method without prop or lockinfo element in xml document"); } #endif 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:"); if (requestDocument.DocumentElement == null) throw new NullReferenceException("requestDocument.DocumentElement"); // 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); #if DEBUG } catch (Exception ex) { WebDavServer.Log.Warn(ex.Message); throw; } #endif #endregion } if (lockResult == (int) HttpStatusCode.OK) { /*************************************************************************************************** * Create the body for the response ***************************************************************************************************/ // Create the basic response XmlDocument XmlDocument responseDoc = new XmlDocument(); const string responseXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><D:prop xmlns:D=\"DAV:\"><D:lockdiscovery><D:activelock/></D:lockdiscovery></D:prop>"; responseDoc.LoadXml(responseXml); // Select the activelock XmlNode if (responseDoc.DocumentElement == null) throw new NullReferenceException("responseDoc"); XmlNode activelock = responseDoc.DocumentElement.SelectSingleNode("D:lockdiscovery/D:activelock", manager); if (activelock == null) throw new NullReferenceException("activelock"); // Import the given nodes if (lockscopeNode == null || locktypeNode == null || ownerNode == null) throw new NullReferenceException("(lockscopeNode==null || locktypeNode==null || ownerNode==null)"); 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", "Second-" + timeout); activelock.AppendChild(timeoutProperty.ToXmlElement(responseDoc)); // The depth element WebDavProperty depthProperty = new WebDavProperty("depth", (depth == 0 ? "0" : "Infinity")); activelock.AppendChild(depthProperty.ToXmlElement(responseDoc)); // The locktoken element WebDavProperty locktokenProperty = new WebDavProperty("locktoken", string.Empty); XmlElement locktokenElement = locktokenProperty.ToXmlElement(responseDoc); WebDavProperty hrefProperty = new WebDavProperty("href", locktoken.ToLockToken()); locktokenElement.AppendChild(hrefProperty.ToXmlElement(responseDoc)); activelock.AppendChild(locktokenElement); /*************************************************************************************************** * Send the response ***************************************************************************************************/ // convert the StringBuilder string resp = responseDoc.InnerXml; byte[] responseBytes = Encoding.UTF8.GetBytes(resp); context.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(); } else { context.SendSimpleResponse(lockResult); } }
/// <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> /// 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(); }