Mercurial > hg > ucis.core
annotate Net/HTTP.cs @ 6:5ce7a138fdba
Improvements in HTTP server
author | Ivo Smits <Ivo@UCIS.nl> |
---|---|
date | Tue, 08 Jan 2013 16:38:37 +0100 |
parents | 9e2e6433f57a |
children | 4b78cc5f116b |
rev | line source |
---|---|
0 | 1 ???using System; |
2 using System.Collections.Generic; | |
3 using System.IO; | |
3 | 4 using System.Net; |
5 using System.Net.Sockets; | |
0 | 6 using System.Text; |
6 | 7 using UCIS.Net; |
3 | 8 using UCIS.Util; |
9 using HTTPHeader = System.Collections.Generic.KeyValuePair<string, string>; | |
0 | 10 |
11 namespace UCIS.Net.HTTP { | |
3 | 12 public class HTTPServer : TCPServer.IModule, IDisposable { |
13 public IHTTPContentProvider ContentProvider { get; set; } | |
14 public Boolean ServeFlashPolicyFile { get; set; } | |
15 private Socket Listener = null; | |
0 | 16 |
3 | 17 public HTTPServer() { } |
0 | 18 |
3 | 19 public void Listen(int port) { |
20 Listen(new IPEndPoint(IPAddress.Any, port)); | |
0 | 21 } |
22 | |
3 | 23 public void Listen(EndPoint localep) { |
24 if (Listener != null) throw new InvalidOperationException("A listener exists"); | |
25 Listener = new Socket(localep.AddressFamily, SocketType.Stream, ProtocolType.Tcp); | |
26 Listener.Bind(localep); | |
27 Listener.Listen(5); | |
28 Listener.BeginAccept(AcceptCallback, null); | |
0 | 29 } |
30 | |
3 | 31 private void AcceptCallback(IAsyncResult ar) { |
32 try { | |
33 Socket socket = Listener.EndAccept(ar); | |
34 new HTTPContext(this, socket); | |
35 } catch (Exception) { } | |
36 try { | |
37 Listener.BeginAccept(AcceptCallback, null); | |
38 } catch (Exception) { } | |
0 | 39 } |
40 | |
3 | 41 public void Dispose() { |
42 if (Listener != null) Listener.Close(); | |
0 | 43 } |
44 | |
3 | 45 bool TCPServer.IModule.Accept(TCPStream stream) { |
46 new HTTPContext(this, stream); | |
47 return false; | |
0 | 48 } |
49 } | |
50 | |
51 public class HTTPContext { | |
3 | 52 public HTTPServer Server { get; private set; } |
53 public EndPoint LocalEndPoint { get; private set; } | |
54 public EndPoint RemoteEndPoint { get; private set; } | |
55 | |
56 public String RequestMethod { get; private set; } | |
57 public String RequestPath { get; private set; } | |
58 public String RequestQuery { get; private set; } | |
59 public int HTTPVersion { get; set; } | |
60 | |
61 public Socket Socket { get; private set; } | |
62 public Boolean SuppressStandardHeaders { get; set; } | |
6 | 63 public TCPStream TCPStream { get; private set; } |
3 | 64 |
65 private StreamWriter Writer; | |
6 | 66 private PrebufferingStream Reader; |
3 | 67 private List<HTTPHeader> RequestHeaders; |
68 private HTTPConnectionState State = HTTPConnectionState.Starting; | |
69 | |
70 private enum HTTPConnectionState { | |
71 Starting = 0, | |
72 ReceivingRequest = 1, | |
73 ProcessingRequest = 2, | |
74 SendingHeaders = 3, | |
75 SendingContent = 4, | |
76 Closed = 5, | |
77 } | |
78 | |
79 public HTTPContext(HTTPServer server, TCPStream stream) { | |
80 this.Server = server; | |
6 | 81 this.TCPStream = stream; |
3 | 82 this.Socket = stream.Socket; |
83 this.LocalEndPoint = Socket.LocalEndPoint; | |
84 this.RemoteEndPoint = Socket.RemoteEndPoint; | |
6 | 85 Init(stream); |
3 | 86 } |
87 | |
88 public HTTPContext(HTTPServer server, Socket socket) { | |
89 this.Server = server; | |
6 | 90 this.TCPStream = null; |
3 | 91 this.Socket = socket; |
92 this.LocalEndPoint = socket.LocalEndPoint; | |
93 this.RemoteEndPoint = socket.RemoteEndPoint; | |
6 | 94 Init(new NetworkStream(socket, true)); |
3 | 95 } |
96 | |
6 | 97 private void Init(Stream Stream) { |
3 | 98 Writer = new StreamWriter(Stream, Encoding.ASCII); |
99 Writer.NewLine = "\r\n"; | |
100 Writer.AutoFlush = true; | |
6 | 101 Reader = new PrebufferingStream(Stream); |
102 Reader.BeginPrebuffering(PrebufferCallback, null); | |
3 | 103 } |
104 | |
105 private String ReadLine() { | |
106 StringBuilder s = new StringBuilder(); | |
107 while (true) { | |
6 | 108 int b = Reader.ReadByte(); |
3 | 109 if (b == -1) { |
4
9e2e6433f57a
Small fix for HTTP Server - Flash Cross Domain Policy File support
Ivo Smits <Ivo@UCIS.nl>
parents:
3
diff
changeset
|
110 if (s.Length == 0) return null; |
3 | 111 break; |
112 } else if (b == 13) { | |
4
9e2e6433f57a
Small fix for HTTP Server - Flash Cross Domain Policy File support
Ivo Smits <Ivo@UCIS.nl>
parents:
3
diff
changeset
|
113 } else if (b == 10 || b == 0) { |
3 | 114 break; |
115 } else { | |
116 s.Append((Char)b); | |
117 } | |
118 } | |
119 return s.ToString(); | |
120 } | |
121 | |
6 | 122 private void PrebufferCallback(IAsyncResult ar) { |
3 | 123 State = HTTPConnectionState.ReceivingRequest; |
124 try { | |
6 | 125 Reader.EndPrebuffering(ar); |
3 | 126 String line = ReadLine(); |
127 if (line == null) { | |
128 Close(); | |
129 return; | |
130 } | |
131 if (Server.ServeFlashPolicyFile && line[0] == '<') { //<policy-file-request/> | |
132 Writer.WriteLine("<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"*\" /></cross-domain-policy>"); | |
6 | 133 Reader.WriteByte(0); |
3 | 134 Close(); |
135 return; | |
136 } | |
137 String[] request = line.Split(' '); | |
138 if (request.Length != 3) goto SendError400AndClose; | |
139 RequestMethod = request[0]; | |
140 String RequestAddress = request[1]; | |
141 switch (request[2]) { | |
142 case "HTTP/1.0": HTTPVersion = 10; break; | |
143 case "HTTP/1.1": HTTPVersion = 11; break; | |
144 default: goto SendError400AndClose; | |
145 } | |
146 request = RequestAddress.Split(new Char[] { '?' }); | |
147 RequestPath = Uri.UnescapeDataString(request[0]); | |
148 RequestQuery = request.Length > 1 ? request[1] : null; | |
149 RequestHeaders = new List<HTTPHeader>(); | |
150 while (true) { | |
151 line = ReadLine(); | |
152 if (line == null) goto SendError400AndClose; | |
153 if (line.Length == 0) break; | |
154 request = line.Split(new String[] { ": " }, 2, StringSplitOptions.None); | |
155 if (request.Length != 2) goto SendError400AndClose; | |
156 RequestHeaders.Add(new HTTPHeader(request[0], request[1])); | |
157 } | |
158 IHTTPContentProvider content = Server.ContentProvider; | |
159 if (content == null) goto SendError500AndClose; | |
160 State = HTTPConnectionState.ProcessingRequest; | |
161 content.ServeRequest(this); | |
162 } catch (Exception ex) { | |
163 Console.Error.WriteLine(ex); | |
164 switch (State) { | |
165 case HTTPConnectionState.ProcessingRequest: goto SendError500AndClose; | |
166 default: | |
167 Close(); | |
168 break; | |
169 } | |
170 } | |
171 return; | |
172 | |
173 SendError400AndClose: | |
174 SendErrorAndClose(400); | |
175 return; | |
176 SendError500AndClose: | |
177 SendErrorAndClose(500); | |
178 return; | |
179 } | |
180 | |
181 public String GetRequestHeader(String name) { | |
182 if (State != HTTPConnectionState.ProcessingRequest && State != HTTPConnectionState.SendingHeaders && State != HTTPConnectionState.SendingContent) throw new InvalidOperationException(); | |
183 foreach (HTTPHeader h in RequestHeaders) { | |
184 if (name.Equals(h.Key, StringComparison.OrdinalIgnoreCase)) return h.Value; | |
185 } | |
186 return null; | |
187 } | |
188 public String[] GetRequestHeaders(String name) { | |
189 if (State != HTTPConnectionState.ProcessingRequest && State != HTTPConnectionState.SendingHeaders && State != HTTPConnectionState.SendingContent) throw new InvalidOperationException(); | |
190 String[] items = new String[0]; | |
191 foreach (HTTPHeader h in RequestHeaders) { | |
192 if (name.Equals(h.Key, StringComparison.OrdinalIgnoreCase)) ArrayUtil.Add(ref items, h.Value); | |
193 } | |
194 return items; | |
195 } | |
196 | |
197 public void SendErrorAndClose(int state) { | |
198 try { | |
199 SendStatus(state); | |
200 GetResponseStream(); | |
201 } catch (Exception ex) { | |
202 Console.Error.WriteLine(ex); | |
203 } | |
204 Close(); | |
205 } | |
206 | |
207 public void SendStatus(int code) { | |
208 String message; | |
209 switch (code) { | |
210 case 101: message = "Switching Protocols"; break; | |
211 case 200: message = "OK"; break; | |
212 case 400: message = "Bad Request"; break; | |
213 case 404: message = "Not Found"; break; | |
214 case 500: message = "Internal Server Error"; break; | |
215 default: message = "Unknown Status"; break; | |
216 } | |
217 SendStatus(code, message); | |
218 } | |
219 public void SendStatus(int code, String message) { | |
220 if (State != HTTPConnectionState.ProcessingRequest) throw new InvalidOperationException(); | |
221 StringBuilder sb = new StringBuilder(); | |
222 sb.Append("HTTP/"); | |
223 switch (HTTPVersion) { | |
224 case 10: sb.Append("1.0"); break; | |
225 case 11: sb.Append("1.1"); break; | |
226 default: throw new ArgumentException("The HTTP version is not supported", "HTTPVersion"); | |
227 } | |
228 sb.Append(" "); | |
229 sb.Append(code); | |
230 sb.Append(" "); | |
231 sb.Append(message); | |
232 Writer.WriteLine(sb.ToString()); | |
233 State = HTTPConnectionState.SendingHeaders; | |
234 if (!SuppressStandardHeaders) { | |
235 SendHeader("Expires", "Expires: Sun, 1 Jan 2000 00:00:00 GMT"); | |
236 SendHeader("Cache-Control", "no-store, no-cache, must-revalidate"); | |
237 SendHeader("Cache-Control", "post-check=0, pre-check=0"); | |
238 SendHeader("Pragma", "no-cache"); | |
239 SendHeader("Server", "UCIS Webserver"); | |
240 SendHeader("Connection", "Close"); | |
241 } | |
242 } | |
243 public void SendHeader(String name, String value) { | |
244 if (State == HTTPConnectionState.ProcessingRequest) SendStatus(200); | |
245 if (State != HTTPConnectionState.SendingHeaders) throw new InvalidOperationException(); | |
246 Writer.WriteLine(name + ": " + value); | |
247 } | |
248 public Stream GetResponseStream() { | |
249 if (State == HTTPConnectionState.ProcessingRequest) SendStatus(200); | |
250 if (State == HTTPConnectionState.SendingHeaders) { | |
251 Writer.WriteLine(); | |
252 State = HTTPConnectionState.SendingContent; | |
253 } | |
254 if (State != HTTPConnectionState.SendingContent) throw new InvalidOperationException(); | |
6 | 255 return Reader; |
3 | 256 } |
257 | |
258 public void Close() { | |
259 if (State == HTTPConnectionState.Closed) return; | |
6 | 260 Reader.Close(); |
3 | 261 State = HTTPConnectionState.Closed; |
262 } | |
0 | 263 } |
264 | |
3 | 265 public interface IHTTPContentProvider { |
266 void ServeRequest(HTTPContext context); | |
267 } | |
268 public class HTTPPathSelector : IHTTPContentProvider { | |
269 private List<KeyValuePair<String, IHTTPContentProvider>> Prefixes; | |
270 private StringComparison PrefixComparison; | |
271 public HTTPPathSelector() : this(false) { } | |
272 public HTTPPathSelector(Boolean caseSensitive) { | |
273 Prefixes = new List<KeyValuePair<string, IHTTPContentProvider>>(); | |
274 PrefixComparison = caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; | |
275 } | |
276 public void AddPrefix(String prefix, IHTTPContentProvider contentProvider) { | |
277 Prefixes.Add(new KeyValuePair<string, IHTTPContentProvider>(prefix, contentProvider)); | |
278 } | |
279 public void DeletePrefix(String prefix) { | |
280 Prefixes.RemoveAll(delegate(KeyValuePair<string, IHTTPContentProvider> item) { return prefix.Equals(item.Key, PrefixComparison); }); | |
281 } | |
282 public void ServeRequest(HTTPContext context) { | |
283 KeyValuePair<string, IHTTPContentProvider> c = Prefixes.Find(delegate(KeyValuePair<string, IHTTPContentProvider> item) { return context.RequestPath.StartsWith(item.Key, PrefixComparison); }); | |
284 if (c.Value != null) { | |
285 c.Value.ServeRequest(context); | |
286 } else { | |
287 context.SendErrorAndClose(404); | |
288 } | |
289 } | |
290 } | |
291 public class HTTPFileProvider : IHTTPContentProvider { | |
292 public String FileName { get; private set; } | |
293 public String ContentType { get; private set; } | |
294 public HTTPFileProvider(String fileName) : this(fileName, "application/octet-stream") { } | |
295 public HTTPFileProvider(String fileName, String contentType) { | |
296 this.FileName = fileName; | |
297 this.ContentType = contentType; | |
298 } | |
299 public void ServeRequest(HTTPContext context) { | |
300 if (File.Exists(FileName)) { | |
301 using (FileStream fs = File.OpenRead(FileName)) { | |
302 context.SendStatus(200); | |
303 context.SendHeader("Content-Type", ContentType); | |
304 context.SendHeader("Content-Length", fs.Length.ToString()); | |
305 long left = fs.Length; | |
306 Stream response = context.GetResponseStream(); | |
307 byte[] buffer = new byte[1024 * 10]; | |
308 while (fs.CanRead) { | |
309 int len = fs.Read(buffer, 0, buffer.Length); | |
310 if (len <= 0) break; | |
311 left -= len; | |
312 response.Write(buffer, 0, len); | |
313 } | |
314 response.Close(); | |
315 } | |
316 } else { | |
317 context.SendErrorAndClose(404); | |
318 } | |
319 } | |
0 | 320 } |
3 | 321 public class HTTPUnTarchiveProvider : IHTTPContentProvider { |
322 public String TarFileName { get; private set; } | |
323 public HTTPUnTarchiveProvider(String tarFile) { | |
324 this.TarFileName = tarFile; | |
325 } | |
326 public void ServeRequest(HTTPContext context) { | |
327 if (!File.Exists(TarFileName)) { | |
328 context.SendErrorAndClose(404); | |
329 return; | |
330 } | |
331 String reqname1 = context.RequestPath; | |
332 if (reqname1.Length > 0 && reqname1[0] == '/') reqname1 = reqname1.Substring(1); | |
333 String reqname2 = reqname1; | |
334 if (reqname2.Length > 0 && !reqname2.EndsWith("/")) reqname2 += "/"; | |
335 reqname2 += "index.htm"; | |
336 using (FileStream fs = File.OpenRead(TarFileName)) { | |
337 while (true) { | |
338 Byte[] header = new Byte[512]; | |
339 if (fs.Read(header, 0, 512) != 512) break; | |
340 int flen = Array.IndexOf<Byte>(header, 0, 0, 100); | |
341 if (flen == 0) continue; | |
342 if (flen == -1) flen = 100; | |
343 String fname = Encoding.ASCII.GetString(header, 0, flen); | |
344 String fsize = Encoding.ASCII.GetString(header, 124, 11); | |
345 int fsizei = Convert.ToInt32(fsize, 8); | |
346 if (reqname1.Equals(fname, StringComparison.OrdinalIgnoreCase) || reqname2.Equals(fname)) { | |
347 context.SendStatus(200); | |
348 context.SendHeader("Content-Length", fsizei.ToString()); | |
349 String ctype = null; | |
350 switch (Path.GetExtension(fname).ToUpperInvariant()) { | |
351 case ".txt": ctype = "text/plain"; break; | |
352 case ".htm": | |
353 case ".html": ctype = "text/html"; break; | |
354 case ".css": ctype = "text/css"; break; | |
355 case ".js": ctype = "application/x-javascript"; break; | |
356 case ".png": ctype = "image/png"; break; | |
357 case ".jpg": | |
358 case ".jpeg": ctype = "image/jpeg"; break; | |
359 case ".gif": ctype = "image/gif"; break; | |
360 case ".ico": ctype = "image/x-icon"; break; | |
361 } | |
362 if (ctype != null) context.SendHeader("Content-Type", ctype); | |
363 Stream response = context.GetResponseStream(); | |
364 int left = fsizei; | |
365 while (left > 0) { | |
366 byte[] buffer = new byte[1024 * 10]; | |
367 int len = fs.Read(buffer, 0, buffer.Length); | |
368 if (len <= 0) break; | |
369 left -= len; | |
370 response.Write(buffer, 0, len); | |
371 } | |
372 response.Close(); | |
373 return; | |
374 } else { | |
375 fs.Seek(fsizei, SeekOrigin.Current); | |
376 } | |
377 int padding = fsizei % 512; | |
378 if (padding != 0) padding = 512 - padding; | |
379 fs.Seek(padding, SeekOrigin.Current); | |
380 } | |
381 } | |
382 context.SendErrorAndClose(404); | |
383 } | |
0 | 384 } |
385 } |