]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_httpd.cpp
m_spanningtree Remove duplicate code for sending channel messages from RouteCommand()
[user/henk/code/inspircd.git] / src / modules / m_httpd.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
6  *   Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
7  *   Copyright (C) 2006-2008 Craig Edwards <craigedwards@brainbox.cc>
8  *   Copyright (C) 2007 John Brooks <john.brooks@dereferenced.net>
9  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
10  *
11  * This file is part of InspIRCd.  InspIRCd is free software: you can
12  * redistribute it and/or modify it under the terms of the GNU General Public
13  * License as published by the Free Software Foundation, version 2.
14  *
15  * This program is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  */
23
24
25 #include "inspircd.h"
26 #include "iohook.h"
27 #include "modules/httpd.h"
28
29 class ModuleHttpServer;
30
31 static ModuleHttpServer* HttpModule;
32 static bool claimed;
33
34 /** HTTP socket states
35  */
36 enum HttpState
37 {
38         HTTP_SERVE_WAIT_REQUEST = 0, /* Waiting for a full request */
39         HTTP_SERVE_RECV_POSTDATA = 1, /* Waiting to finish recieving POST data */
40         HTTP_SERVE_SEND_DATA = 2 /* Sending response */
41 };
42
43 /** A socket used for HTTP transport
44  */
45 class HttpServerSocket : public BufferedSocket
46 {
47         HttpState InternalState;
48         std::string ip;
49
50         HTTPHeaders headers;
51         std::string reqbuffer;
52         std::string postdata;
53         unsigned int postsize;
54         std::string request_type;
55         std::string uri;
56         std::string http_version;
57
58  public:
59         HttpServerSocket(int newfd, const std::string& IP, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
60                 : BufferedSocket(newfd), ip(IP), postsize(0)
61         {
62                 InternalState = HTTP_SERVE_WAIT_REQUEST;
63
64                 FOREACH_MOD(OnHookIO, (this, via));
65                 if (GetIOHook())
66                         GetIOHook()->OnStreamSocketAccept(this, client, server);
67         }
68
69         void OnError(BufferedSocketError) CXX11_OVERRIDE
70         {
71                 ServerInstance->GlobalCulls.AddItem(this);
72         }
73
74         std::string Response(int response)
75         {
76                 switch (response)
77                 {
78                         case 100:
79                                 return "CONTINUE";
80                         case 101:
81                                 return "SWITCHING PROTOCOLS";
82                         case 200:
83                                 return "OK";
84                         case 201:
85                                 return "CREATED";
86                         case 202:
87                                 return "ACCEPTED";
88                         case 203:
89                                 return "NON-AUTHORITATIVE INFORMATION";
90                         case 204:
91                                 return "NO CONTENT";
92                         case 205:
93                                 return "RESET CONTENT";
94                         case 206:
95                                 return "PARTIAL CONTENT";
96                         case 300:
97                                 return "MULTIPLE CHOICES";
98                         case 301:
99                                 return "MOVED PERMENANTLY";
100                         case 302:
101                                 return "FOUND";
102                         case 303:
103                                 return "SEE OTHER";
104                         case 304:
105                                 return "NOT MODIFIED";
106                         case 305:
107                                 return "USE PROXY";
108                         case 307:
109                                 return "TEMPORARY REDIRECT";
110                         case 400:
111                                 return "BAD REQUEST";
112                         case 401:
113                                 return "UNAUTHORIZED";
114                         case 402:
115                                 return "PAYMENT REQUIRED";
116                         case 403:
117                                 return "FORBIDDEN";
118                         case 404:
119                                 return "NOT FOUND";
120                         case 405:
121                                 return "METHOD NOT ALLOWED";
122                         case 406:
123                                 return "NOT ACCEPTABLE";
124                         case 407:
125                                 return "PROXY AUTHENTICATION REQUIRED";
126                         case 408:
127                                 return "REQUEST TIMEOUT";
128                         case 409:
129                                 return "CONFLICT";
130                         case 410:
131                                 return "GONE";
132                         case 411:
133                                 return "LENGTH REQUIRED";
134                         case 412:
135                                 return "PRECONDITION FAILED";
136                         case 413:
137                                 return "REQUEST ENTITY TOO LARGE";
138                         case 414:
139                                 return "REQUEST-URI TOO LONG";
140                         case 415:
141                                 return "UNSUPPORTED MEDIA TYPE";
142                         case 416:
143                                 return "REQUESTED RANGE NOT SATISFIABLE";
144                         case 417:
145                                 return "EXPECTATION FAILED";
146                         case 500:
147                                 return "INTERNAL SERVER ERROR";
148                         case 501:
149                                 return "NOT IMPLEMENTED";
150                         case 502:
151                                 return "BAD GATEWAY";
152                         case 503:
153                                 return "SERVICE UNAVAILABLE";
154                         case 504:
155                                 return "GATEWAY TIMEOUT";
156                         case 505:
157                                 return "HTTP VERSION NOT SUPPORTED";
158                         default:
159                                 return "WTF";
160                         break;
161
162                 }
163         }
164
165         void SendHTTPError(int response)
166         {
167                 HTTPHeaders empty;
168                 std::string data = "<html><head></head><body>Server error "+ConvToStr(response)+": "+Response(response)+"<br>"+
169                                    "<small>Powered by <a href='http://www.inspircd.org'>InspIRCd</a></small></body></html>";
170
171                 SendHeaders(data.length(), response, empty);
172                 WriteData(data);
173         }
174
175         void SendHeaders(unsigned long size, int response, HTTPHeaders &rheaders)
176         {
177
178                 WriteData(http_version + " "+ConvToStr(response)+" "+Response(response)+"\r\n");
179
180                 time_t local = ServerInstance->Time();
181                 struct tm *timeinfo = gmtime(&local);
182                 char *date = asctime(timeinfo);
183                 date[strlen(date) - 1] = '\0';
184                 rheaders.CreateHeader("Date", date);
185
186                 rheaders.CreateHeader("Server", BRANCH);
187                 rheaders.SetHeader("Content-Length", ConvToStr(size));
188
189                 if (size)
190                         rheaders.CreateHeader("Content-Type", "text/html");
191                 else
192                         rheaders.RemoveHeader("Content-Type");
193
194                 /* Supporting Connection: keep-alive causes a whole world of hurt syncronizing timeouts,
195                  * so remove it, its not essential for what we need.
196                  */
197                 rheaders.SetHeader("Connection", "Close");
198
199                 WriteData(rheaders.GetFormattedHeaders());
200                 WriteData("\r\n");
201         }
202
203         void OnDataReady()
204         {
205                 if (InternalState == HTTP_SERVE_RECV_POSTDATA)
206                 {
207                         postdata.append(recvq);
208                         if (postdata.length() >= postsize)
209                                 ServeData();
210                 }
211                 else
212                 {
213                         reqbuffer.append(recvq);
214
215                         if (reqbuffer.length() >= 8192)
216                         {
217                                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "m_httpd dropped connection due to an oversized request buffer");
218                                 reqbuffer.clear();
219                                 SetError("Buffer");
220                         }
221
222                         if (InternalState == HTTP_SERVE_WAIT_REQUEST)
223                                 CheckRequestBuffer();
224                 }
225         }
226
227         void CheckRequestBuffer()
228         {
229                 std::string::size_type reqend = reqbuffer.find("\r\n\r\n");
230                 if (reqend == std::string::npos)
231                         return;
232
233                 // We have the headers; parse them all
234                 std::string::size_type hbegin = 0, hend;
235                 while ((hend = reqbuffer.find("\r\n", hbegin)) != std::string::npos)
236                 {
237                         if (hbegin == hend)
238                                 break;
239
240                         if (request_type.empty())
241                         {
242                                 std::istringstream cheader(std::string(reqbuffer, hbegin, hend - hbegin));
243                                 cheader >> request_type;
244                                 cheader >> uri;
245                                 cheader >> http_version;
246
247                                 if (request_type.empty() || uri.empty() || http_version.empty())
248                                 {
249                                         SendHTTPError(400);
250                                         return;
251                                 }
252
253                                 hbegin = hend + 2;
254                                 continue;
255                         }
256
257                         std::string cheader = reqbuffer.substr(hbegin, hend - hbegin);
258
259                         std::string::size_type fieldsep = cheader.find(':');
260                         if ((fieldsep == std::string::npos) || (fieldsep == 0) || (fieldsep == cheader.length() - 1))
261                         {
262                                 SendHTTPError(400);
263                                 return;
264                         }
265
266                         headers.SetHeader(cheader.substr(0, fieldsep), cheader.substr(fieldsep + 2));
267
268                         hbegin = hend + 2;
269                 }
270
271                 reqbuffer.erase(0, reqend + 4);
272
273                 std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
274                 std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
275
276                 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.0"))
277                 {
278                         SendHTTPError(505);
279                         return;
280                 }
281
282                 if (headers.IsSet("Content-Length") && (postsize = ConvToInt(headers.GetHeader("Content-Length"))) > 0)
283                 {
284                         InternalState = HTTP_SERVE_RECV_POSTDATA;
285
286                         if (reqbuffer.length() >= postsize)
287                         {
288                                 postdata = reqbuffer.substr(0, postsize);
289                                 reqbuffer.erase(0, postsize);
290                         }
291                         else if (!reqbuffer.empty())
292                         {
293                                 postdata = reqbuffer;
294                                 reqbuffer.clear();
295                         }
296
297                         if (postdata.length() >= postsize)
298                                 ServeData();
299
300                         return;
301                 }
302
303                 ServeData();
304         }
305
306         void ServeData()
307         {
308                 InternalState = HTTP_SERVE_SEND_DATA;
309
310                 claimed = false;
311                 HTTPRequest acl((Module*)HttpModule, "httpd_acl", request_type, uri, &headers, this, ip, postdata);
312                 acl.Send();
313                 if (!claimed)
314                 {
315                         HTTPRequest url((Module*)HttpModule, "httpd_url", request_type, uri, &headers, this, ip, postdata);
316                         url.Send();
317                         if (!claimed)
318                         {
319                                 SendHTTPError(404);
320                         }
321                 }
322         }
323
324         void Page(std::stringstream* n, int response, HTTPHeaders *hheaders)
325         {
326                 SendHeaders(n->str().length(), response, *hheaders);
327                 WriteData(n->str());
328         }
329 };
330
331 class HTTPdAPIImpl : public HTTPdAPIBase
332 {
333  public:
334         HTTPdAPIImpl(Module* parent)
335                 : HTTPdAPIBase(parent)
336         {
337         }
338
339         void SendResponse(HTTPDocumentResponse& resp) CXX11_OVERRIDE
340         {
341                 claimed = true;
342                 resp.src.sock->Page(resp.document, resp.responsecode, &resp.headers);
343         }
344 };
345
346 class ModuleHttpServer : public Module
347 {
348         std::vector<HttpServerSocket *> httpsocks;
349         HTTPdAPIImpl APIImpl;
350
351  public:
352         ModuleHttpServer()
353                 : APIImpl(this)
354         {
355         }
356
357         void init() CXX11_OVERRIDE
358         {
359                 HttpModule = this;
360                 ServerInstance->Modules->AddService(APIImpl);
361         }
362
363         ModResult OnAcceptConnection(int nfd, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
364         {
365                 if (from->bind_tag->getString("type") != "httpd")
366                         return MOD_RES_PASSTHRU;
367                 int port;
368                 std::string incomingip;
369                 irc::sockets::satoap(*client, incomingip, port);
370                 new HttpServerSocket(nfd, incomingip, from, client, server);
371                 return MOD_RES_ALLOW;
372         }
373
374         ~ModuleHttpServer()
375         {
376                 for (size_t i = 0; i < httpsocks.size(); i++)
377                 {
378                         httpsocks[i]->cull();
379                         delete httpsocks[i];
380                 }
381         }
382
383         Version GetVersion() CXX11_OVERRIDE
384         {
385                 return Version("Provides HTTP serving facilities to modules", VF_VENDOR);
386         }
387 };
388
389 MODULE_INIT(ModuleHttpServer)