/// <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.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(); }
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> /// 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); }
public async Task <string> Listen(string id, CancellationToken cancel) { if (httpListener.IsListening) { httpListener.Stop(); } httpListener.Start(); try { using (cancel.Register(httpListener.Stop)) { while (true) { lastContext = await httpListener.GetContextAsync().ConfigureAwait(false); var queryParts = HttpUtility.ParseQueryString(lastContext.Request.Url.Query); if (queryParts["state"] == id) { return(queryParts["code"]); } } } } catch (Exception) { httpListener.Stop(); throw; } }
/// <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 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> /// 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) { 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.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); }
private void SendResponseForException(IHttpListenerContext context, WebDavException ex) { try { context.Response.StatusCode = ex.StatusCode; context.Response.StatusDescription = ex.StatusDescription; var response = ex.GetResponse(context); if (!(context.Request.HttpMethod == "HEAD")) { if (response != context.Response.StatusDescription) { byte[] buffer = Encoding.UTF8.GetBytes(response); context.Response.ContentEncoding = Encoding.UTF8; context.Response.ContentLength64 = buffer.Length; context.Response.OutputStream.Write(buffer, 0, buffer.Length); context.Response.OutputStream.Flush(); } } context.Response.Close(); } catch (Exception innerEx) { _log.Error("Exception cannot be returned to caller: " + ex.Message, ex); _log.Error("Unable to send response for exception: " + innerEx.Message, innerEx); } }
/// <summary> /// The background thread method. /// </summary> private void BackgroundThreadMethod() { _log.Info("WebDAVServer background thread has started"); try { _listener.Start(); while (true) { if (_stopEvent.WaitOne(0)) { return; } IHttpListenerContext context = Listener.GetContext(_stopEvent); if (context == null) { _log.Debug("Exiting thread"); return; } ThreadPool.QueueUserWorkItem(ProcessRequest, context); } } finally { _listener.Stop(); _log.Info("WebDAVServer background thread has terminated"); } }
public IIdentity GetIdentity(IHttpListenerContext context) { try { HttpListenerBasicIdentity ident = (HttpListenerBasicIdentity)context.AdaptedInstance.User.Identity; var isDomainUser = ident.Name.Contains("\\"); var user = ident.Name; var pwd = ident.Password; if (isDomainUser) { return(AuthenticateOnSpecificDomain(user, pwd)); } else { try { using (PrincipalContext authContext = new PrincipalContext(ContextType.Domain)) { if (authContext.ValidateCredentials(user, pwd)) { return(new GenericIdentity(user)); } } } catch (PrincipalException) { } } return(null); } catch (Exception) { return(null); } }
/// <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); }
private void ProcessWorkflowRequest(IHttpListenerContext httpcontext) { var request = WorkflowHttpRequest.Create(httpcontext.Request); var response = _workflowHandler.HandleRequest(request); CopyResponse(response, httpcontext.Response); }
/// <summary> /// Called after everything was processed, it can be used for doing specific /// cleanup for the real implementation. /// It can also be used to log executed call with something different from the /// standard log4net logger used by the library; this is the reason why this method /// is accepting some information that can be directly used to log information /// as <paramref name="callInfo"/> /// </summary> /// <param name="context"></param> /// <param name="callInfo">String with call information for better logging</param> /// <param name="request">Xml document that contains the full request of the client</param> /// <param name="response">Xml document that contains the full response returned to the client </param> /// <param name="requestHeader">StringBuilder that contains the full request header</param> protected virtual void OnProcessRequestCompleted( IHttpListenerContext context, string callInfo, XmlDocument request, XmlDocument response, StringBuilder requestHeader) { }
public IIdentity GetIdentity(IHttpListenerContext context) { HttpListenerBasicIdentity ident = (HttpListenerBasicIdentity)context.AdaptedInstance.User.Identity; string domain = ident.Name.Split('\\')[0]; string username = ident.Name.Split('\\')[1]; var token = GetToken(domain, username, ident.Password); return new WindowsIdentity(token.DangerousGetHandle()); }
/// <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(); }
public async Task <IRocket> AcceptAsync(IHttpListenerContext context) { try { return(new Rocket(await context.AcceptWebSocketAsync())); } catch { SetErrorResponse(context); throw; } }
public void ProcessRequest(IHttpListenerContext httpcontext) { if (TryReturnFile(httpcontext.Response, httpcontext.Request.RawUrl)) { return; } ProcessWorkflowRequest(httpcontext); }
private static void SetErrorResponse(IHttpListenerContext context) { try { context.Response.ContentLength64 = _ErrorBytes.Length; context.Response.StatusCode = 500; context.Response.OutputStream.Write(_ErrorBytes, 0, _ErrorBytes.Length); context.Response.OutputStream.Close(); } catch { } }
public IIdentity GetIdentity(IHttpListenerContext context) { HttpListenerBasicIdentity ident = (HttpListenerBasicIdentity)context.AdaptedInstance.User.Identity; string domain = ident.Name.Split('\\')[0]; string username = ident.Name.Split('\\')[1]; var token = GetToken(domain, username, ident.Password); return(new WindowsIdentity(token.DangerousGetHandle())); }
/// <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> /// Sends a simple response with a specified HTTP status code but no content. /// </summary> /// <param name="context">The <see cref="IHttpListenerContext" /> to send the response through.</param> /// <param name="statusCode">The HTTP status code for the response.</param> /// <exception cref="System.ArgumentNullException">context</exception> /// <exception cref="ArgumentNullException"><paramref name="context" /> is <c>null</c>.</exception> public static void SendSimpleResponse(this IHttpListenerContext context, HttpStatusCode statusCode = HttpStatusCode.OK) { if (context == null) { throw new ArgumentNullException("context"); } context.Response.StatusCode = (int)statusCode; context.Response.StatusDescription = ((HttpStatusCode)statusCode).ToString();; 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) { 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> /// Sends a simple response with a specified HTTP status code but no content. /// </summary> /// <param name="context"> /// The <see cref="IHttpListenerContext"/> to send the response through. /// </param> /// <param name="statusCode"> /// The HTTP status code for the response. /// </param> /// <exception cref="ArgumentNullException"> /// <para><paramref name="context"/> is <c>null</c>.</para> /// </exception> public static void SendSimpleResponse(this IHttpListenerContext context, int statusCode = HttpStatusCodes.Successful.OK) { if (context == null) { throw new ArgumentNullException("context"); } context.Response.StatusCode = statusCode; context.Response.StatusDescription = HttpStatusCodes.GetName(statusCode); context.Response.Close(); }
/// <summary> /// Sends a simple response with a specified HTTP status code but no content. /// </summary> /// <param name="context">The <see cref="IHttpListenerContext" /> to send the response through.</param> /// <param name="statusCode">The HTTP status code for the response.</param> /// <exception cref="System.ArgumentNullException">context</exception> /// <exception cref="ArgumentNullException"><paramref name="context" /> is <c>null</c>.</exception> public static void SendSimpleResponse(this IHttpListenerContext context, int statusCode = (int)HttpStatusCode.OK) { if (context == null) { throw new ArgumentNullException("context"); } context.Response.StatusCode = statusCode; context.Response.StatusDescription = HttpWorkerRequest.GetStatusDescription(statusCode); context.Response.Close(); }
private static string CreateLogMessage(IHttpListenerContext context, string callInfo, XmlDocument request, XmlDocument response, StringBuilder requestHeader, String xLitmusTest) { var message = String.Format("{5}WEB-DAV-CALL-ENDED: {0}\r\nREQUEST HEADER\r\n{1}\r\nRESPONSE HEADER\r\n{2}\r\nrequest:{3}\r\nresponse{4}", callInfo, requestHeader, context.Response.DumpHeaders(), request.Beautify(), response.Beautify(), xLitmusTest); return(message); }
/// <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> /// <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> /// <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 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> /// <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 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> /// Sends the response /// </summary> /// <param name="context">The <see cref="IHttpListenerContext" /> containing the response</param> /// <param name="responseDocument">The <see cref="XmlDocument" /> containing the response body</param> private static void SendResponse(IHttpListenerContext context, XmlDocument responseDocument) { // convert the XmlDocument byte[] responseBytes = Encoding.UTF8.GetBytes(responseDocument.InnerXml); // HttpStatusCode doesn't contain WebDav status codes, but HttpWorkerRequest can handle these WebDav status codes context.Response.StatusCode = (int)WebDavStatusCode.MultiStatus; context.Response.StatusDescription = HttpWorkerRequest.GetStatusDescription((int)WebDavStatusCode.MultiStatus); context.Response.ContentLength64 = responseBytes.Length; context.Response.AdaptedInstance.ContentType = "text/xml"; 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> 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> /// https://www.ietf.org/proceedings/49/slides/WEBDAV-1/tsld008.htm /// </summary> /// <param name="context"></param> /// <returns></returns> public override string GetResponse(IHttpListenerContext context) { return String.Format( @"<response-detail xmlns:""DAV:""> <status-detail> <detail-code><child-was-locked /></detail-code> <user-text>{0}</user-text> </status-detail> <response> <href>{1}</href> <status>HTTP/1.1 423 Locked</status> <detail-code> <child-was-locked /> </detail-code> </response> </response-detail>", Message, context.Request.Url.AbsoluteUri); }
/// <summary> /// https://www.ietf.org/proceedings/49/slides/WEBDAV-1/tsld008.htm /// </summary> /// <param name="context"></param> /// <returns></returns> public override string GetResponse(IHttpListenerContext context) { return(String.Format( @"<response-detail xmlns:""DAV:""> <status-detail> <detail-code><child-was-locked /></detail-code> <user-text>{0}</user-text> </status-detail> <response> <href>{1}</href> <status>HTTP/1.1 423 Locked</status> <detail-code> <child-was-locked /> </detail-code> </response> </response-detail>", Message, context.Request.Url.AbsoluteUri)); }
/// <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) { 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="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.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> /// Builds the <see cref="XmlDocument" /> containing the response body /// </summary> /// <param name="context">The <see cref="IHttpListenerContext" /></param> /// <param name="propname">The boolean defining the Propfind propname request</param> /// <param name="requestUri"></param> /// <param name="requestedProperties"></param> /// <param name="webDavStoreItems"></param> /// <param name="lockSystem"></param> /// <param name="store"></param> /// <returns> /// The <see cref="XmlDocument" /> containing the response body /// </returns> private string ResponseDocument(IHttpListenerContext context, bool propname, Uri requestUri, List<WebDavProperty> requestedProperties, List<IWebDavStoreItem> webDavStoreItems, IWebDavStoreItemLock lockSystem, IWebDavStore store) { // Create the basic response XmlDocument XmlDocument responseDoc = new XmlDocument(); const string responseXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><D:multistatus xmlns:D=\"DAV:\" xmlns:Office=\"urn:schemas-microsoft-com:office:office\" xmlns:Repl=\"http://schemas.microsoft.com/repl/\" xmlns:Z=\"urn:schemas-microsoft-com:\"></D:multistatus>"; responseDoc.LoadXml(responseXml); // Generate the manager XmlNamespaceManager manager = new XmlNamespaceManager(responseDoc.NameTable); manager.AddNamespace("D", "DAV:"); manager.AddNamespace("Office", "schemas-microsoft-com:office:office"); manager.AddNamespace("Repl", "http://schemas.microsoft.com/repl/"); manager.AddNamespace("Z", "urn:schemas-microsoft-com:"); List<string> xmlFragments = new List<string>(); int count = 0; foreach (IWebDavStoreItem webDavStoreItem in webDavStoreItems) { string frag; if (count == 0) { frag = CreateFragment(true, responseDoc, webDavStoreItem, context, propname, requestUri, requestedProperties, lockSystem); } else { WindowsIdentity userIdentity = (WindowsIdentity) Thread.GetData(Thread.GetNamedDataSlot(WebDavServer.HttpUser)); string cacheValue = (string) store.GetCacheObject(this, userIdentity.Name, webDavStoreItem.ItemPath); if (cacheValue != null) { xmlFragments.Add(cacheValue); continue; } frag = CreateFragment(false, responseDoc, webDavStoreItem, context, propname, requestUri, requestedProperties, lockSystem); store.AddCacheObject(this, userIdentity.Name, webDavStoreItem.ItemPath, frag); } count++; xmlFragments.Add(frag); } StringBuilder sb = new StringBuilder(5000); sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?><D:multistatus xmlns:D=\"DAV:\" xmlns:Office=\"urn:schemas-microsoft-com:office:office\" xmlns:Repl=\"http://schemas.microsoft.com/repl/\" xmlns:Z=\"urn:schemas-microsoft-com:\">"); foreach (string xmlFragment in xmlFragments) sb.Append(xmlFragment); sb.Append("</D:multistatus>"); string t = sb.ToString(); return t; }
/// <summary> /// Sends the response /// </summary> /// <param name="context">The <see cref="IHttpListenerContext" /> containing the response</param> /// <param name="responseDocument">The <see cref="XmlDocument" /> containing the response body</param> private static void SendResponse(IHttpListenerContext context, string responseDocument) { // convert the XmlDocument byte[] responseBytes = Encoding.UTF8.GetBytes(responseDocument); // 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); context.Response.ContentLength64 = responseBytes.Length; context.Response.AdaptedInstance.ContentType = "text/xml"; 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); }
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> /// <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(); }
internal string CreateFragment(bool isRoot, XmlDocument responseDoc, IWebDavStoreItem webDavStoreItem, IHttpListenerContext context, bool propname, Uri requestUri, List<WebDavProperty> requestedProperties, IWebDavStoreItemLock lockSystem) { // Create the response element WebDavProperty responseProperty = new WebDavProperty("response", Empty); XmlElement responseElement = responseProperty.ToXmlElement(responseDoc); // The href element Uri result; if (isRoot) Uri.TryCreate(requestUri, Empty, out result); else Uri.TryCreate(requestUri, webDavStoreItem.Name, out result); WebDavProperty hrefProperty = new WebDavProperty("href", result.AbsoluteUri); responseElement.AppendChild(hrefProperty.ToXmlElement(responseDoc)); // The propstat element WebDavProperty propstatProperty = new WebDavProperty("propstat", Empty); XmlElement propstatElement = propstatProperty.ToXmlElement(responseDoc); // The prop element WebDavProperty propProperty = new WebDavProperty("prop", Empty); XmlElement propElement = propProperty.ToXmlElement(responseDoc); //All properties but lockdiscovery and supportedlock can be handled here. foreach (WebDavProperty davProperty in requestedProperties) { XmlNode toAdd; switch (davProperty.Name) { case "lockdiscovery": toAdd = LockDiscovery(webDavStoreItem, ref responseDoc, lockSystem); break; case "supportedlock": toAdd = SupportedLocks(ref responseDoc); break; default: toAdd = PropChildElement(davProperty, responseDoc, webDavStoreItem, propname); break; } if (toAdd != null) propElement.AppendChild(toAdd); } // Add the prop element to the propstat element propstatElement.AppendChild(propElement); // The status element WebDavProperty statusProperty = new WebDavProperty("status", "HTTP/1.1 " + context.Response.StatusCode + " " + HttpWorkerRequest.GetStatusDescription(context.Response.StatusCode)); propstatElement.AppendChild(statusProperty.ToXmlElement(responseDoc)); // Add the propstat element to the response element responseElement.AppendChild(propstatElement); if (responseDoc.DocumentElement == null) throw new Exception("Not Possible."); return responseElement.OuterXml.Replace("xmlns:D=\"DAV:\"", ""); }
/// <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(); }