HttpServerAgent.IsHandledResult IHttpServerAgent.IsHandled(HttpMessageReader httpReader) { if (httpReader.RequestUri.StartsWith(xcapUri) == false) { return(HttpServerAgent.IsHandledResult.NotHandle()); } if (httpReader.Method == Methods.Options) { return(HttpServerAgent.IsHandledResult.Handle()); } if (ParsePath(httpReader.RequestUri) == false) { return(HttpServerAgent.IsHandledResult.Handle()); } if (pathParser.Domain.IsInvalid || pathParser.Username.IsInvalid) { return(HttpServerAgent.IsHandledResult.Handle()); } if (pathParser.Auid.Equals(pidfManipulation) && httpReader.Method == Methods.Get) { return(HttpServerAgent.IsHandledResult.Handle()); } return(HttpServerAgent.IsHandledResult.HandleWithAuthorization(pathParser.Domain)); }
private void ExecuteInternal(BaseConnection c, HttpMessageReader httpReader, ArraySegment <byte> content) { var method = GetRestMethod(GetHttpMethod(httpReader.Method)); if (method.Method == RestMethods.None) { SendResponse(c, StatusCodes.NotImplemented); } else { var domainName = (parser.DomainName.IsValid) ? parser.DomainName : parser.Authname; var account = accounts.GetAccount(domainName); if (IsAuthorized(httpReader.RequestUri, method.Auth, account) == false) { SendResponse(c, StatusCodes.Forbidden); } else { try { var result = CallMethod(content, method, account, (method.UsersIndex < 0) ? null : userz[method.UsersIndex]); SendResponse(c, StatusCodes.OK, result.Result); } catch (Exception ex) { SendResponse(c, StatusCodes.NotAcceptable, "{ \"message\": \"" + ex.Message.ToString().Replace("\"", "\\\"") + "\" }"); } } } }
private static int GetSessionId(HttpMessageReader httpReader) { var prefix = @"id="; var requestUri = httpReader.RequestUri.ToString(); int s = requestUri.IndexOf(prefix); if (s >= 0) { s += prefix.Length; int result = 0; for (int i = s; i < requestUri.Length; i++) { if (requestUri[i] >= '0' && requestUri[i] <= '9') { result *= 10; result += requestUri[i] - '0'; } else { break; } } return((result == 0) ? Session.InvalidId : result); } return(Session.InvalidId); }
static void Wain(string[] args) { var arg = args.Length > 0 ? args[0] : throw new Exception("Missing file specification."); if (IsZipFile(arg)) { foreach (var e in Saz.ReadCorrelated(arg, (reqn, req, rspn, rsp) => new { Request = new { FullName = reqn, Message = (HttpMessage)req }, Response = new { FullName = rspn, Message = (HttpMessage)rsp }, })) { foreach (var r in new[] { e.Request, e.Response }) { Console.WriteLine($":{r.FullName}"); Console.WriteLine(); Dump(r.Message, Console.Out); Console.WriteLine(); } } } else { using var input = File.OpenRead(arg); using var message = HttpMessageReader.Read(input); Dump(message, Console.Error, Console.OpenStandardOutput()); } }
public static int CompileParseMethod() { int start = Environment.TickCount; var reader = new HttpMessageReader(); reader.SetDefaultValue(); reader.Parse(new byte[] { 0 }, 0, 1); return(Environment.TickCount - start); }
private int GenerateSessionId(HttpMessageReader httpReader) { int newSessionCount, oldSessionCount; do { oldSessionCount = sessionCount; newSessionCount = (oldSessionCount < int.MaxValue) ? oldSessionCount + 1 : 1; }while (Interlocked.CompareExchange(ref sessionCount, newSessionCount, oldSessionCount) != oldSessionCount); return(newSessionCount); }
private void InitializeHttpReader(bool forceDefaultValue) { if (httpReader == null) { httpReader = new HttpMessageReader(); httpReader.SetDefaultValue(); } else if (forceDefaultValue) { httpReader.SetDefaultValue(); } }
public static HttpMessageReader GetEmpty() { connectionId = -1; if (Value == null) { Value = new HttpMessageReader(); } Value.SetDefaultValue(); return(Value); }
public static void InitializeAsync(string path, Action <int> callback) { System.Threading.ThreadPool.QueueUserWorkItem((stateInfo) => { HttpMessageReader.LoadTables(); int time = HttpMessageReader.CompileParseMethod(); if (callback != null) { callback(time); } }); }
public static void Update(int currentConnectionId, ArraySegment <byte> header) { connectionId = currentConnectionId; if (Value == null) { Value = new HttpMessageReader(); } Value.SetDefaultValue(); Value.Parse(header.Array, header.Offset, header.Count); Value.SetArray(header.Array); }
void IHttpServerAgent.HandleRequest(BaseConnection c, HttpMessageReader httpReader, ArraySegment <byte> httpContent) { if (httpReader.Method != Methods.Get) { var writer = new HttpMessageWriter(); writer.WriteResponse(StatusCodes.NotAcceptable); httpServer.SendResponse(c, writer); } else { if (httpReader.RequestUri.Equals(uri1)) { var writer = new HttpMessageWriter(); writer.WriteStatusLine(StatusCodes.MovedPermanently); writer.WriteContentLength(0); writer.WriteLocation(c.LocalEndPoint.Protocol == ServerProtocol.Tcp, httpReader.Host.Host, httpReader.Host.Port, uri2); writer.WriteCRLF(); httpServer.SendResponse(c, writer); } else { var rawFile = GetFile(httpReader); if (rawFile.HasValue == false) { var writer = new HttpMessageWriter(); writer.WriteResponse(StatusCodes.NotFound); httpServer.SendResponse(c, writer); } else { var file = rawFile.Value; var writer = new HttpMessageWriter(); writer.WriteStatusLine(StatusCodes.OK); writer.WriteContentType(file.ContentType); writer.WriteContentLength(file.Content.Length); writer.WriteCRLF(); httpServer.SendResponse(c, writer); httpServer.SendResponse(c, new ArraySegment <byte>(file.Content)); } } } }
public void SetUp() { { var dfa = new SipMessageReader(); dfa.LoadTables(@"..\..\..\Server\dll\Sip.Message.dfa"); dfa.SetDefaultValue(); dfa.Parse(new byte[] { 0 }, 0, 1); } { HttpMessageReader.LoadTables(@"..\..\..\Server\dll\"); var dfa = new HttpMessageReader(); dfa.SetDefaultValue(); dfa.Parse(new byte[] { 0 }, 0, 1); } }
public void ChunkedTransferEncoding() { const string crlf = "\r\n"; const string response = "HTTP/1.1 200 OK" + crlf + "Content-Type: text/plain" + crlf + "Transfer-Encoding: chunked" + crlf + crlf + "7" + crlf + "Mozilla" + crlf + "9" + crlf + "Developer" + crlf + "7" + crlf + "Network" + crlf + "0" + crlf + crlf; var ascii = Encoding.ASCII; using var input = new MemoryStream(ascii.GetBytes(response)); using var hs = HttpMessageReader.ReadResponse(input); Assert.That(hs.Kind, Is.EqualTo(HttpMessageKind.Response)); Assert.That(hs.ProtocolVersion, Is.EqualTo(new Version(1, 1))); Assert.That(hs.StatusCode, Is.EqualTo(HttpStatusCode.OK)); Assert.That(hs.ReasonPhrase, Is.EqualTo("OK")); Assert.That(hs.Headers.Count, Is.EqualTo(2)); using var h = hs.Headers.GetEnumerator(); Assert.That(h.MoveNext(), Is.True); Assert.That(h.Current.Key, Is.EqualTo("Content-Type")); Assert.That(h.Current.Value, Is.EqualTo("text/plain")); Assert.That(h.MoveNext(), Is.True); Assert.That(h.Current.Key, Is.EqualTo("Transfer-Encoding")); Assert.That(h.Current.Value, Is.EqualTo("chunked")); Assert.That(h.MoveNext(), Is.False); using var output = new MemoryStream(); hs.ContentStream.CopyTo(output); var content = ascii.GetString(output.ToArray()); Assert.That(content, Is.EqualTo("MozillaDeveloperNetwork")); }
public static bool IsAjax(HttpMessageReader rawReader, byte[] array) { if (rawReader.RequestUri.Length < ajaxUri.Length) { return(false); } for (int i = 0; i < ajaxUri.Length; i++) { if (ajaxUri[i] != array[rawReader.RequestUri.Begin + i]) { return(false); } } return(true); }
void IHttpServerAgent.HandleRequest(BaseConnection c, HttpMessageReader httpReader, ArraySegment <byte> httpContent) { InitializeThreadStaticVariables(); parser.SetDefaultValue(); parser.ParseAll(httpReader.RequestUri.ToArraySegment()); if (parser.IsFinal) { parser.SetArray(httpReader.RequestUri.Bytes); ExecuteInternal(c, httpReader, httpContent); } else { SendResponse(c, StatusCodes.BadRequest); } }
private static void TestSpeed(HttpMessageReader dfa, byte[] message) { Console.WriteLine("Testing speed"); int repeat = 1000000; int start2 = Environment.TickCount; for (int i = 0; i < repeat; i++) { dfa.SetDefaultValue(); dfa.Parse(message, 0, message.Length); dfa.SetArray(message); } int spent = Environment.TickCount - start2; Console.WriteLine("Parsed {0} times, {1} ms", repeat, spent); }
private void ParseHtppMessage(string message) { var bytes = Encoding.UTF8.GetBytes(message); httpExpected = new HttpMessageReader(); httpExpected.SetDefaultValue(); int parsed = httpExpected.Parse(bytes, 0, bytes.Length); httpExpected.SetArray(bytes); if (httpExpected.ContentLength < 0) { httpExpected.ContentLength = 0; } httpHeader = message.Substring(0, parsed); httpContent = message.Substring(parsed); }
public void HeaderFolding() { const string crlf = "\r\n"; var ua = new[] { "Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0)", " \t \t Gecko/20100101 ", "\t \t Firefox/42.0", }; var request = "GET / HTTP/1.1" + crlf + "User-Agent: " + string.Join(crlf, ua) + crlf + "Host: www.example.com" + crlf + crlf; var ascii = Encoding.ASCII; using var input = new MemoryStream(ascii.GetBytes(request)); using var hs = HttpMessageReader.ReadRequest(input); Assert.That(hs.ProtocolVersion, Is.EqualTo(new Version(1, 1))); Assert.That(hs.Url.OriginalString, Is.EqualTo("/")); Assert.That(hs.Method, Is.EqualTo("GET")); Assert.That(hs.Headers.Count, Is.EqualTo(2)); using var h = hs.Headers.GetEnumerator(); Assert.That(h.MoveNext(), Is.True); Assert.That(h.Current.Key, Is.EqualTo("User-Agent")); Assert.That(h.Current.Value, Is.EqualTo(string.Join(string.Empty, ua))); Assert.That(h.MoveNext(), Is.True); Assert.That(h.Current.Key, Is.EqualTo("Host")); Assert.That(h.Current.Value, Is.EqualTo("www.example.com")); Assert.That(h.MoveNext(), Is.False); }
private HttpFile?GetFile(HttpMessageReader reader) { var uri = reader.RequestUri.ToString(uri1.Length); if (uri == null) { return(null); } int parameters = uri.IndexOf('?'); if (parameters != -1) { uri = uri.Substring(0, parameters); } lock (files) { HttpFile file; if (uri.EndsWith("/") == false) { if (files.TryGetValue(uri, out file)) { return(file); } } else { foreach (var defaultName in defaultFiles) { if (files.TryGetValue(uri + defaultName, out file)) { return(file); } } } } return(null); }
public void HeaderValuesAreOptional() { const string crlf = "\r\n"; const string response = "HTTP/1.1 200 OK" + crlf + "Content-Type: text/plain" + crlf + "Content-Length:" + crlf + "Content-Length: 0" + crlf + crlf; var ascii = Encoding.ASCII; using var input = new MemoryStream(ascii.GetBytes(response)); using var hs = HttpMessageReader.ReadResponse(input); Assert.That(hs.Kind, Is.EqualTo(HttpMessageKind.Response)); Assert.That(hs.ProtocolVersion, Is.EqualTo(new Version(1, 1))); Assert.That(hs.StatusCode, Is.EqualTo(HttpStatusCode.OK)); Assert.That(hs.ReasonPhrase, Is.EqualTo("OK")); Assert.That(hs.Headers.Count, Is.EqualTo(3)); using var h = hs.Headers.GetEnumerator(); Assert.That(h.MoveNext(), Is.True); Assert.That(h.Current.Key, Is.EqualTo("Content-Type")); Assert.That(h.Current.Value, Is.EqualTo("text/plain")); Assert.That(h.MoveNext(), Is.True); Assert.That(h.Current.Key, Is.EqualTo("Content-Length")); Assert.That(h.Current.Value, Is.EqualTo(string.Empty)); Assert.That(h.MoveNext(), Is.True); Assert.That(h.Current.Key, Is.EqualTo("Content-Length")); Assert.That(h.Current.Value, Is.EqualTo("0")); Assert.That(h.MoveNext(), Is.False); Assert.That(hs.ContentLength, Is.EqualTo((HttpFieldStatus.Defined, 0))); }
public static void InitializeAsync(Action <int> callback) { HttpMessageReader.InitializeAsync(null, callback); }
static void Main(string[] args) { Console.Write("Loading..."); int start = Environment.TickCount; int loadTablesDelay = Environment.TickCount - start; HttpMessageReader.LoadTables(@"..\..\..\Http.Message\bin\Release"); start = Environment.TickCount; var dfa = new HttpMessageReader(); dfa.SetDefaultValue(); dfa.Parse(new byte[] { 0 }, 0, 1); Console.WriteLine("Done (LoadTables {0} ms + JIT {1} ms)", loadTablesDelay, Environment.TickCount - start); var utf = new UTF8Encoding(); var message0 = utf.GetBytes( "POST /enlighten/calais.asmx/Enlighten HTTP/1.1\r\n" + "Test: test\r\n" + "Host: api.opencalais.com:9000\r\n" + "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n" + //"Content-Type: application/x-www-form-urlencoded\r\n" + "Content-Length: 123\r\n" + "Upgrade: first, websocket, websocketex, websocket/v15, second/567, third\r\n" + "Referer: http://localhost/#ffff\r\n" + //"Referer: referer.com\r\n" + "Origin: http://example.com\r\n" + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n" + "Sec-WebSocket-Protocol: chat , superchat\r\n" + "Cookie: session-id1=1; session-id2=2\r\n" + "Cookie: session-id3=3; session-id4=4\r\n" + "Sec-WebSocket-Version: 13\r\n" + "If-Match: \"01234567\"\r\n" + "\r\n"); dfa.SetDefaultValue(); int proccessed = dfa.Parse(message0, 0, message0.Length); dfa.SetArray(message0); Console.WriteLine("Total: {0}", message0.Length); Console.WriteLine("Proccessed: {0}", proccessed); Console.WriteLine("Final: {0}", dfa.IsFinal); Console.WriteLine("Error: {0}", dfa.IsError); Console.WriteLine("Method: {0}", dfa.Method); Console.WriteLine("Request-URI: |{0}|", dfa.RequestUri.ToString()); Console.WriteLine("Host: |{0}| : {1}", dfa.Host.Host.ToString(), dfa.Host.Port); Console.WriteLine("Content-Type: |{0}|", dfa.ContentType.Value.ToString()); Console.WriteLine("Content-Length: {0}", dfa.ContentLength); Console.WriteLine("Referer: |{0}|", dfa.Referer.ToString()); Console.WriteLine("Cookie"); for (int i = 0; i < dfa.Count.Cookie; i++) { Console.WriteLine(" #{0} |{1}| : |{2}|", i, dfa.Cookie[i].Name.ToString(), dfa.Cookie[i].Value.ToString()); } //Console.WriteLine("Upgrade"); //for (int i = 0; i < dfa.Count.UpgradeCount; i++) // Console.WriteLine(" #{0} |{1}| + |{2}| = |{3}| ({4})", i, dfa.Upgrades[i].Name.ToString(), dfa.Upgrades[i].Version.ToString(), dfa.Upgrades[i].Value.ToString(), dfa.Upgrades[i].Upgrate); Console.Write("Upgrade: "); for (int i = 0; i < dfa.Count.Upgrade; i++) { Console.Write("{0}, ", dfa.Upgrade[i]); } Console.WriteLine(); Console.Write("If-Match: "); for (int i = 0; i < dfa.Count.IfMatches; i++) { Console.Write("{0}, ", dfa.IfMatches[i].ToString()); } Console.WriteLine(); Console.WriteLine("Sec-WebSocket-Key: |{0}|", dfa.SecWebSocketKey.ToString()); Console.Write("Sec-WebSocket-Protocol: "); for (int i = 0; i < dfa.Count.SecWebSocketProtocol; i++) { Console.Write("|{0}|, ", dfa.SecWebSocketProtocol[i].ToString()); } Console.WriteLine(); Console.WriteLine("Sec-WebSocket-Version: {0}", dfa.SecWebSocketVersion); var message1 = utf.GetBytes( "GET /api/role?time=1343516363983&sig=4c25f6162d70ede434b37571cbe23201 HTTP/1.1\r\n" + "Accept: */*\r\n" + "Content-Type: application/json\r\n" + "X-Requested-With: XMLHttpRequest\r\n" + "Referer: http://localhost/#\r\n" + "Accept-Language: ru\r\n" + "Accept-Encoding: gzip, deflate\r\n" + "User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0)\r\n" + "Host: localhost\r\n" + "Connection: Keep-Alive\r\n" + "\r\n"); //TestSpeed(dfa, message0); }
bool IHttpServerAgent.IsAuthorized(HttpMessageReader reader, ByteArrayPart username) { return(true); }
public HttpMessageWriter ProcessPutItem(ByteArrayPart username, ByteArrayPart domain, HttpMessageReader reader, ArraySegment <byte> content) { return(CreateErrorResponse(XcapErrors.CannotInsert, "Not Implemented")); }
string ReadLine() => HttpMessageReader.ReadLine(_input, LineBuilder);
static void Main(string[] args) { var exePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); ///////////////////////////////////////////////////////////////////////// serversManager = new ServersManager <HttpConnection>(new ServersManagerConfig()); serversManager.Bind(new ProtocolPort() { Protocol = ServerProtocol.Tcp, Port = 8080, }); serversManager.ServerAdded += ServersManager_ServerAdded; serversManager.ServerRemoved += ServersManager_ServerRemoved; serversManager.ServerInfo += ServersManager_ServerInfo; serversManager.NewConnection += ServersManager_NewConnection; serversManager.EndConnection += ServersManager_EndConnection; serversManager.Received += ServersManager_Received; serversManager.Sent += ServersManager_Sent; serversManager.Logger.Enable(exePath + @"\Log.pcap"); ///////////////////////////////////////////////////////////////////////// HttpMessage.BufferManager = new BufferManagerProxy(); ///////////////////////////////////////////////////////////////////////// Console.WriteLine(@"Loading DFA table..."); HttpMessageReader.LoadTables(exePath + @"\Http.Message.dfa"); XcapUriParser.LoadTables(exePath); ///////////////////////////////////////////////////////////////////////// xcapServer = new XcapServer(); xcapServer.AddHandler(new ResourceListsHandlerExample()); //xcapServer.AddHandler(new RlsServicesHandler()); ///////////////////////////////////////////////////////////////////////// httpServer = new HttpServer(); httpServer.SendAsync = serversManager.SendAsync; (httpServer as IHttpServerAgentRegistrar).Register(xcapServer, 0, true); ///////////////////////////////////////////////////////////////////////// Console.WriteLine(@"Starting..."); try { serversManager.Start(); Console.WriteLine(@"Started!"); } catch (Exception ex) { Console.WriteLine(@"Failed to start"); Console.WriteLine(@"Error: {0}", ex.Message); } ///////////////////////////////////////////////////////////////////////// Console.WriteLine(@"Press any key to stop server..."); Console.ReadKey(true); Console.WriteLine(); }
public override HttpMessageWriter ProcessPutItem(ByteArrayPart username, ByteArrayPart domain, HttpMessageReader reader, ArraySegment <byte> content) { var statusCode = StatusCodes.OK; int sipIfMatch = simpleModule.InvalidEtag; if (reader.Count.IfMatches > 0) { if (HexEncoding.TryParseHex8(reader.IfMatches[0].Bytes, reader.IfMatches[0].Begin, out sipIfMatch) == false) { statusCode = StatusCodes.PreconditionFailed; } } if (statusCode == StatusCodes.OK) { if (simpleModule.Publish(username.ToString() + "@" + domain.ToString(), ref sipIfMatch, 60, content) == false) { statusCode = StatusCodes.BadRequest; } } HttpMessageWriter response; if (statusCode != StatusCodes.OK) { response = CreateResponse(statusCode); } else { response = CreateNotFinishedResponse(statusCode, ContentType.None); response.WriteEtag(sipIfMatch); response.WriteCRLF(); } return(response); }
bool IHttpServerAgent.IsAuthorized(HttpMessageReader httpReader, ByteArrayPart username) { return(ParsePath(httpReader.RequestUri) && pathParser.Username.IsValid && pathParser.Username.Equals(username)); }
void IHttpServerAgent.HandleRequest(BaseConnection c, HttpMessageReader httpReader, ArraySegment <byte> httpContent) { Console.WriteLine("{0} :: {1}", httpReader.Method.ToString(), httpReader.RequestUri.ToString()); HttpMessageWriter response = null; InitializeXcapPathParser(); int parsed; if (pathParser.ParseAll(httpReader.RequestUri.ToArraySegment(), out parsed) == false) { Console.WriteLine("Failed to parse requesr uri."); Console.WriteLine(" " + httpReader.RequestUri.ToString()); Console.WriteLine(" " + "^".PadLeft(parsed + 1, '-')); } else { pathParser.SetArray(httpReader.RequestUri.Bytes); if (httpReader.Method == Methods.Options) { response = GetWriter(); response.WriteOptionsResponse(); } else { if (pathParser.Username.IsValid && pathParser.Domain.IsValid) { var handler = usersHandlers.Get(pathParser.Auid.ToString()); switch (httpReader.Method) { case Methods.Get: response = handler.ProcessGetItem(pathParser.Username, pathParser.Domain); break; case Methods.Put: response = handler.ProcessPutItem(pathParser.Username, pathParser.Domain, httpReader, httpContent); break; case Methods.Delete: response = handler.ProcessDeleteItem(pathParser.Username, pathParser.Domain); break; default: response = null; break; } } else { var handler = genericHandlers.Get(pathParser.Auid.ToString()); if (handler == xcapCapsHander && xcapCapsHander.IsValid == false) { xcapCapsHander.Update(Handlers); } if (handler != null) { if (pathParser.IsGlobal) { response = handler.ProcessGlobal(); } else { switch (httpReader.Method) { case Methods.Get: response = handler.ProcessGetItem(pathParser.Item); break; case Methods.Put: response = handler.ProcessPutItem(pathParser.Item, httpContent); break; case Methods.Delete: response = handler.ProcessDeleteItem(pathParser.Item); break; default: response = null; break; } } } } } } if (response == null) { response = GetWriter(); response.WriteEmptyResponse(StatusCodes.NotFound); } httpServer.SendResponse(c, response); }
protected bool IsAuthorizedByAgent(HttpMessageReader reader, ByteArrayPart username, int agentIndex) { return(agents[agentIndex].Value.IsAuthorized(reader, username)); }
public static int CompileParseMethod() { int start = Environment.TickCount; var reader = new HttpMessageReader(); reader.SetDefaultValue(); reader.Parse(new byte[] { 0 }, 0, 1); return Environment.TickCount - start; }