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