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