]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_httpd.cpp
Add 'you are banned' numeric to banredirect output, from avenger's patch
[user/henk/code/inspircd.git] / src / modules / m_httpd.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include <algorithm>
16 #include "modules.h"
17 #include "httpd.h"
18
19 /* $ModDesc: Provides HTTP serving facilities to modules */
20 /* $ModDep: httpd.h */
21
22 class ModuleHttpServer;
23
24 static ModuleHttpServer* HttpModule;
25 static bool claimed;
26
27 /** HTTP socket states
28  */
29 enum HttpState
30 {
31         HTTP_LISTEN = 0,
32         HTTP_SERVE_WAIT_REQUEST = 1, /* Waiting for a full request */
33         HTTP_SERVE_RECV_POSTDATA = 2, /* Waiting to finish recieving POST data */
34         HTTP_SERVE_SEND_DATA = 3 /* Sending response */
35 };
36
37 class HttpServerSocket;
38
39 /** This class is used to handle HTTP socket timeouts
40  */
41 class HttpServerTimeout : public InspTimer
42 {
43  private:
44         /** HttpServerSocket we are attached to
45          */
46         HttpServerSocket* s;
47         /** Socketengine the file descriptor is in
48          */
49         SocketEngine* SE;
50  public:
51         /** Attach timeout to HttpServerSocket
52          */
53         HttpServerTimeout(HttpServerSocket* sock, SocketEngine* engine);
54         /** Handle timer tick
55          */
56         void Tick(time_t TIME);
57 };
58
59 /** A socket used for HTTP transport
60  */
61 class HttpServerSocket : public InspSocket
62 {
63         FileReader* index;
64         HttpState InternalState;
65         
66         HTTPHeaders headers;
67         std::string reqbuffer;
68         std::string postdata;
69         unsigned int postsize;
70         std::string request_type;
71         std::string uri;
72         std::string http_version;
73         bool keepalive;
74         
75         HttpServerTimeout* Timeout;
76         bool DataSinceLastTick;
77         friend class HttpServerTimeout;
78         
79  public:
80
81         HttpServerSocket(InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, FileReader* index_page) : InspSocket(SI, host, port, listening, maxtime), index(index_page), postsize(0)
82         {
83                 InternalState = HTTP_LISTEN;
84                 Timeout = NULL;
85         }
86
87         HttpServerSocket(InspIRCd* SI, int newfd, char* ip, FileReader* ind) : InspSocket(SI, newfd, ip), index(ind), postsize(0), keepalive(false), DataSinceLastTick(false)
88         {
89                 InternalState = HTTP_SERVE_WAIT_REQUEST;
90                 Timeout = new HttpServerTimeout(this, Instance->SE);
91                 Instance->Timers->AddTimer(Timeout);
92         }
93
94         FileReader* GetIndex()
95         {
96                 return index;
97         }
98
99         ~HttpServerSocket()
100         {
101                 if (Timeout)
102                 {
103                         if (Instance->Time() < Timeout->GetTimer())
104                                 Instance->Timers->DelTimer(Timeout);
105                         Timeout = NULL;
106                 }
107         }
108         
109         void ResetRequest()
110         {
111                 headers.Clear();
112                 postdata.clear();
113                 postsize = 0;
114                 request_type.clear();
115                 uri.clear();
116                 http_version.clear();
117                 InternalState = HTTP_SERVE_WAIT_REQUEST;
118                 
119                 if (reqbuffer.size())
120                         CheckRequestBuffer();
121         }
122         
123         virtual int OnIncomingConnection(int newsock, char* ip)
124         {
125                 if (InternalState == HTTP_LISTEN)
126                 {
127                         new HttpServerSocket(this->Instance, newsock, ip, index);
128                 }
129                 return true;
130         }
131
132         virtual void OnClose()
133         {
134         }
135
136         std::string Response(int response)
137         {
138                 switch (response)
139                 {
140                         case 100:
141                                 return "CONTINUE";
142                         case 101:
143                                 return "SWITCHING PROTOCOLS";
144                         case 200:
145                                 return "OK";
146                         case 201:
147                                 return "CREATED";
148                         case 202:
149                                 return "ACCEPTED";
150                         case 203:
151                                 return "NON-AUTHORITATIVE INFORMATION";
152                         case 204:
153                                 return "NO CONTENT";
154                         case 205:
155                                 return "RESET CONTENT";
156                         case 206:
157                                 return "PARTIAL CONTENT";
158                         case 300:
159                                 return "MULTIPLE CHOICES";
160                         case 301:
161                                 return "MOVED PERMENANTLY";
162                         case 302:
163                                 return "FOUND";
164                         case 303:
165                                 return "SEE OTHER";
166                         case 304:
167                                 return "NOT MODIFIED";
168                         case 305:
169                                 return "USE PROXY";
170                         case 307:
171                                 return "TEMPORARY REDIRECT";
172                         case 400:
173                                 return "BAD REQUEST";
174                         case 401:
175                                 return "UNAUTHORIZED";
176                         case 402:
177                                 return "PAYMENT REQUIRED";
178                         case 403:
179                                 return "FORBIDDEN";
180                         case 404:
181                                 return "NOT FOUND";
182                         case 405:
183                                 return "METHOD NOT ALLOWED";
184                         case 406:
185                                 return "NOT ACCEPTABLE";
186                         case 407:
187                                 return "PROXY AUTHENTICATION REQUIRED";
188                         case 408:
189                                 return "REQUEST TIMEOUT";
190                         case 409:
191                                 return "CONFLICT";
192                         case 410:
193                                 return "GONE";
194                         case 411:
195                                 return "LENGTH REQUIRED";
196                         case 412:
197                                 return "PRECONDITION FAILED";
198                         case 413:
199                                 return "REQUEST ENTITY TOO LARGE";
200                         case 414:
201                                 return "REQUEST-URI TOO LONG";
202                         case 415:
203                                 return "UNSUPPORTED MEDIA TYPE";
204                         case 416:
205                                 return "REQUESTED RANGE NOT SATISFIABLE";
206                         case 417:
207                                 return "EXPECTATION FAILED";
208                         case 500:
209                                 return "INTERNAL SERVER ERROR";
210                         case 501:
211                                 return "NOT IMPLEMENTED";
212                         case 502:
213                                 return "BAD GATEWAY";
214                         case 503:
215                                 return "SERVICE UNAVAILABLE";
216                         case 504:
217                                 return "GATEWAY TIMEOUT";
218                         case 505:
219                                 return "HTTP VERSION NOT SUPPORTED";
220                         default:
221                                 return "WTF";
222                         break;
223                                 
224                 }
225         }
226         
227         void SendHTTPError(int response)
228         {
229                 HTTPHeaders empty;
230                 std::string data = "<html><head></head><body>Server error "+ConvToStr(response)+": "+Response(response)+"<br>"+
231                                    "<small>Powered by <a href='http://www.inspircd.org'>InspIRCd</a></small></body></html>";
232                 
233                 SendHeaders(data.length(), response, empty);
234                 this->Write(data);
235                 
236                 if (keepalive)
237                         ResetRequest();
238         }
239         
240         void SendHeaders(unsigned long size, int response, HTTPHeaders &rheaders)
241         {
242
243                 this->Write(http_version + " "+ConvToStr(response)+" "+Response(response)+"\r\n");
244
245                 time_t local = this->Instance->Time();
246                 struct tm *timeinfo = gmtime(&local);
247                 char *date = asctime(timeinfo);
248                 date[strlen(date) - 1] = '\0';
249                 rheaders.CreateHeader("Date", date);
250                 
251                 rheaders.CreateHeader("Server", "InspIRCd/m_httpd.so/1.1");
252                 rheaders.SetHeader("Content-Length", ConvToStr(size));
253                 
254                 if (size)
255                         rheaders.CreateHeader("Content-Type", "text/html");
256                 else
257                         rheaders.RemoveHeader("Content-Type");
258                 
259                 if (rheaders.GetHeader("Connection") == "Close")
260                         keepalive = false;
261                 else if (rheaders.GetHeader("Connection") == "Keep-Alive" && !headers.IsSet("Connection"))
262                         keepalive = true;
263                 else if (!rheaders.IsSet("Connection") && !keepalive)
264                         rheaders.SetHeader("Connection", "Close");
265                 
266                 this->Write(rheaders.GetFormattedHeaders());
267                 this->Write("\r\n");
268                 
269                 if (!size && keepalive)
270                         ResetRequest();
271         }
272
273         virtual bool OnDataReady()
274         {
275                 char* data = this->Read();
276
277                 /* Check that the data read is a valid pointer and it has some content */
278                 if (!data || !*data)
279                         return false;
280                 
281                 DataSinceLastTick = true;
282                 
283                 if (InternalState == HTTP_SERVE_RECV_POSTDATA)
284                 {
285                         postdata.append(data);
286                         if (postdata.length() >= postsize)
287                                 ServeData();
288                 }
289                 else
290                 {
291                         reqbuffer.append(data);
292                         
293                         if (reqbuffer.length() >= 8192)
294                         {
295                                 Instance->Log(DEBUG, "m_httpd dropped connection due to an oversized request buffer");
296                                 reqbuffer.clear();
297                                 return false;
298                         }
299                         
300                         if (InternalState == HTTP_SERVE_WAIT_REQUEST)
301                                 CheckRequestBuffer();
302                 }
303                 
304                 return true;
305         }
306         
307         void CheckRequestBuffer()
308         {
309                 std::string::size_type reqend = reqbuffer.find("\r\n\r\n");
310                 if (reqend == std::string::npos)
311                         return;
312                 
313                 // We have the headers; parse them all
314                 std::string::size_type hbegin = 0, hend;
315                 while ((hend = reqbuffer.find("\r\n", hbegin)) != std::string::npos)
316                 {
317                         if (hbegin == hend)
318                                 break;
319                         
320                         if (request_type.empty())
321                         {
322                                 std::istringstream cheader(std::string(reqbuffer, hbegin, hend - hbegin));
323                                 cheader >> request_type;
324                                 cheader >> uri;
325                                 cheader >> http_version;
326                                 
327                                 if (request_type.empty() || uri.empty() || http_version.empty())
328                                 {
329                                         SendHTTPError(400);
330                                         return;
331                                 }
332                                 
333                                 hbegin = hend + 2;
334                                 continue;
335                         }
336                         
337                         std::string cheader = reqbuffer.substr(hbegin, hend - hbegin);
338                         
339                         std::string::size_type fieldsep = cheader.find(':');
340                         if ((fieldsep == std::string::npos) || (fieldsep == 0) || (fieldsep == cheader.length() - 1))
341                         {
342                                 SendHTTPError(400);
343                                 return;
344                         }
345                         
346                         headers.SetHeader(cheader.substr(0, fieldsep), cheader.substr(fieldsep + 2));
347                         
348                         hbegin = hend + 2;
349                 }
350                 
351                 reqbuffer.erase(0, reqend + 4);
352                 
353                 std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
354                 std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
355                 
356                 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.0"))
357                 {
358                         SendHTTPError(505);
359                         return;
360                 }
361                 
362                 if (strcasecmp(headers.GetHeader("Connection").c_str(), "keep-alive") == 0)
363                         keepalive = true;
364                 
365                 if (headers.IsSet("Content-Length") && (postsize = atoi(headers.GetHeader("Content-Length").c_str())) != 0)
366                 {
367                         InternalState = HTTP_SERVE_RECV_POSTDATA;
368                         
369                         if (reqbuffer.length() >= postsize)
370                         {
371                                 postdata = reqbuffer.substr(0, postsize);
372                                 reqbuffer.erase(0, postsize);
373                         }
374                         else if (!reqbuffer.empty())
375                         {
376                                 postdata = reqbuffer;
377                                 reqbuffer.clear();
378                         }
379                         
380                         if (postdata.length() >= postsize)
381                                 ServeData();
382                         
383                         return;
384                 }
385                 
386                 ServeData();
387         }
388
389         void ServeData()
390         {
391                 InternalState = HTTP_SERVE_SEND_DATA;
392
393                 if ((request_type == "GET") && (uri == "/"))
394                 {
395                         HTTPHeaders empty;
396                         SendHeaders(index->ContentSize(), 200, empty);
397                         this->Write(index->Contents());
398                 }
399                 else
400                 {
401                         claimed = false;
402                         HTTPRequest httpr(request_type,uri,&headers,this,this->GetIP(),postdata);
403                         Event e((char*)&httpr, (Module*)HttpModule, "httpd_url");
404                         e.Send(this->Instance);
405                         if (!claimed)
406                         {
407                                 SendHTTPError(404);
408                         }
409                 }
410         }
411
412         void Page(std::stringstream* n, int response, HTTPHeaders *headers)
413         {
414                 SendHeaders(n->str().length(), response, *headers);
415                 this->Write(n->str());
416                 
417                 if (!keepalive)
418                 {
419                         Instance->SE->DelFd(this);
420                         this->Close();
421                 }
422                 else
423                         this->ResetRequest();
424         }
425 };
426
427 HttpServerTimeout::HttpServerTimeout(HttpServerSocket* sock, SocketEngine* engine) : InspTimer(15, time(NULL), true), s(sock), SE(engine)
428 {
429 }
430
431 void HttpServerTimeout::Tick(time_t TIME)
432 {
433         if (!s->DataSinceLastTick)
434         {
435                 SE->DelFd(s);
436                 s->Close();
437                 s->Timeout = NULL;
438                 this->CancelRepeat();
439         }
440         else
441                 s->DataSinceLastTick = false;
442 }
443
444 class ModuleHttpServer : public Module
445 {
446         std::vector<HttpServerSocket*> httpsocks;
447  public:
448
449         void ReadConfig()
450         {
451                 int port;
452                 std::string host;
453                 std::string bindip;
454                 std::string indexfile;
455                 FileReader* index;
456                 HttpServerSocket* http;
457                 ConfigReader c(ServerInstance);
458
459                 httpsocks.clear();
460
461                 for (int i = 0; i < c.Enumerate("http"); i++)
462                 {
463                         host = c.ReadValue("http", "host", i);
464                         bindip = c.ReadValue("http", "ip", i);
465                         port = c.ReadInteger("http", "port", i, true);
466                         indexfile = c.ReadValue("http", "index", i);
467                         index = new FileReader(ServerInstance, indexfile);
468                         if (!index->Exists())
469                                 throw ModuleException("Can't read index file: "+indexfile);
470                         http = new HttpServerSocket(ServerInstance, bindip, port, true, 0, index);
471                         httpsocks.push_back(http);
472                 }
473         }
474
475         ModuleHttpServer(InspIRCd* Me) : Module(Me)
476         {
477                 ReadConfig();
478                 HttpModule = this;
479         }
480
481         char* OnRequest(Request* request)
482         {
483                 claimed = true;
484                 HTTPDocument* doc = (HTTPDocument*)request->GetData();
485                 HttpServerSocket* sock = (HttpServerSocket*)doc->sock;
486                 sock->Page(doc->GetDocument(), doc->GetResponseCode(), &doc->headers);
487                 return NULL;
488         }
489
490         void Implements(char* List)
491         {
492                 List[I_OnRequest] = 1;
493         }
494
495         virtual ~ModuleHttpServer()
496         {
497                 for (size_t i = 0; i < httpsocks.size(); i++)
498                 {
499                         ServerInstance->SE->DelFd(httpsocks[i]);
500                         httpsocks[i]->Close();
501                         delete httpsocks[i]->GetIndex();
502                 }
503                 ServerInstance->InspSocketCull();
504         }
505
506         virtual Version GetVersion()
507         {
508                 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
509         }
510 };
511
512 MODULE_INIT(ModuleHttpServer)