1 /**
2  * Start a HTTP server on a port and serve the files in the current directory.
3  *
4  * License:
5  *   This Source Code Form is subject to the terms of
6  *   the Mozilla Public License, v. 2.0. If a copy of
7  *   the MPL was not distributed with this file, You
8  *   can obtain one at http://mozilla.org/MPL/2.0/.
9  *
10  * Authors:
11  *   Vladimir Panteleev <vladimir@thecybershadow.net>
12  */
13 
14 module ae.demo.http.httpserve;
15 
16 import std.base64;
17 import std.conv;
18 import std.datetime;
19 import std.exception;
20 import std.stdio;
21 import std..string;
22 
23 import ae.net.asockets;
24 import ae.net.http.common;
25 import ae.net.http.responseex;
26 import ae.net.http.server;
27 import ae.net.ietf.headers;
28 import ae.net.ssl.openssl;
29 import ae.sys.log;
30 import ae.sys.shutdown;
31 import ae.utils.funopt;
32 import ae.utils.main;
33 
34 mixin SSLUseLib;
35 
36 void httpserve(
37 	ushort port = 0, string host = null,
38 	string sslCert = null, string sslKey = null,
39 	string userName = null, string password = null,
40 )
41 {
42 	HttpServer server;
43 
44 	if (sslCert || sslKey)
45 	{
46 		auto https = new HttpsServer();
47 		https.ctx.setCertificate(sslCert);
48 		https.ctx.setPrivateKey(sslKey);
49 		server = https;
50 	}
51 	else
52 		server = new HttpServer();
53 
54 	server.log = consoleLogger("Web");
55 	server.handleRequest =
56 		(HttpRequest request, HttpServerConnection conn)
57 		{
58 			auto response = new HttpResponseEx();
59 
60 			if ((userName || password) &&
61 				!response.authorize(request, (reqUser, reqPass) => reqUser == userName && reqPass == password))
62 				return conn.sendResponse(response);
63 
64 			response.status = HttpStatusCode.OK;
65 
66 			try
67 				response.serveFile(
68 					decodeUrlParameter(request.resource[1..$]),
69 					"",
70 					true,
71 					formatAddress("http", conn.localAddress, request.host, request.port) ~ "/");
72 			catch (Exception e)
73 				response.writeError(HttpStatusCode.InternalServerError, e.msg);
74 			conn.sendResponse(response);
75 		};
76 	server.listen(port, host);
77 	addShutdownHandler({ server.close(); });
78 
79 	socketManager.loop();
80 }
81 
82 mixin main!(funopt!httpserve);