]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_httpd.cpp
Remove some debug (im on a crusade to make debug mode useful, but at the same time...
[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 <algorithm>
15 #include "modules.h"
16 #include "inspircd.h"
17 #include "httpd.h"
18
19 /* $ModDesc: Provides HTTP serving facilities to modules */
20
21 class ModuleHttpServer;
22
23 static ModuleHttpServer* HttpModule;
24 static bool claimed;
25
26 /** HTTP socket states
27  */
28 enum HttpState
29 {
30         HTTP_LISTEN = 0,
31         HTTP_SERVE_WAIT_REQUEST = 1,
32         HTTP_SERVE_RECV_POSTDATA = 2,
33         HTTP_SERVE_SEND_DATA = 3
34 };
35
36 class HttpServerSocket;
37
38 /** This class is used to handle HTTP socket timeouts
39  */
40 class HttpServerTimeout : public InspTimer
41 {
42  private:
43         /** HttpServerSocket we are attached to
44          */
45         HttpServerSocket* s;
46         /** Socketengine the file descriptor is in
47          */
48         SocketEngine* SE;
49  public:
50         /** Attach timeout to HttpServerSocket
51          */
52         HttpServerTimeout(HttpServerSocket* sock, SocketEngine* engine);
53         /** Handle timer tick
54          */
55         void Tick(time_t TIME);
56 };
57
58 /** A socket used for HTTP transport
59  */
60 class HttpServerSocket : public InspSocket
61 {
62         FileReader* index;
63         HttpState InternalState;
64         std::stringstream headers;
65         std::string postdata;
66         std::string request_type;
67         std::string uri;
68         std::string http_version;
69         unsigned int postsize;
70         HttpServerTimeout* Timeout;
71
72  public:
73
74         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)
75         {
76                 SI->Log(DEBUG,"HttpServerSocket constructor");
77                 InternalState = HTTP_LISTEN;
78                 Timeout = NULL;
79         }
80
81         HttpServerSocket(InspIRCd* SI, int newfd, char* ip, FileReader* ind) : InspSocket(SI, newfd, ip), index(ind), postsize(0)
82         {
83                 InternalState = HTTP_SERVE_WAIT_REQUEST;
84                 Timeout = new HttpServerTimeout(this, Instance->SE);
85                 Instance->Timers->AddTimer(Timeout);
86         }
87
88         FileReader* GetIndex()
89         {
90                 return index;
91         }
92
93         ~HttpServerSocket()
94         {
95                 if (Timeout)
96                 {
97                         if (Instance->Time() < Timeout->GetTimer())
98                                 Instance->Timers->DelTimer(Timeout);
99                         Timeout = NULL;
100                 }
101         }
102
103         virtual int OnIncomingConnection(int newsock, char* ip)
104         {
105                 if (InternalState == HTTP_LISTEN)
106                 {
107                         HttpServerSocket* s = new HttpServerSocket(this->Instance, newsock, ip, index);
108                         s = s; /* Stop GCC whining */
109                 }
110                 return true;
111         }
112
113         virtual void OnClose()
114         {
115         }
116
117         std::string Response(int response)
118         {
119                 switch (response)
120                 {
121                         case 100:
122                                 return "CONTINUE";
123                         case 101:
124                                 return "SWITCHING PROTOCOLS";
125                         case 200:
126                                 return "OK";
127                         case 201:
128                                 return "CREATED";
129                         case 202:
130                                 return "ACCEPTED";
131                         case 203:
132                                 return "NON-AUTHORITATIVE INFORMATION";
133                         case 204:
134                                 return "NO CONTENT";
135                         case 205:
136                                 return "RESET CONTENT";
137                         case 206:
138                                 return "PARTIAL CONTENT";
139                         case 300:
140                                 return "MULTIPLE CHOICES";
141                         case 301:
142                                 return "MOVED PERMENANTLY";
143                         case 302:
144                                 return "FOUND";
145                         case 303:
146                                 return "SEE OTHER";
147                         case 304:
148                                 return "NOT MODIFIED";
149                         case 305:
150                                 return "USE PROXY";
151                         case 307:
152                                 return "TEMPORARY REDIRECT";
153                         case 400:
154                                 return "BAD REQUEST";
155                         case 401:
156                                 return "UNAUTHORIZED";
157                         case 402:
158                                 return "PAYMENT REQUIRED";
159                         case 403:
160                                 return "FORBIDDEN";
161                         case 404:
162                                 return "NOT FOUND";
163                         case 405:
164                                 return "METHOD NOT ALLOWED";
165                         case 406:
166                                 return "NOT ACCEPTABLE";
167                         case 407:
168                                 return "PROXY AUTHENTICATION REQUIRED";
169                         case 408:
170                                 return "REQUEST TIMEOUT";
171                         case 409:
172                                 return "CONFLICT";
173                         case 410:
174                                 return "GONE";
175                         case 411:
176                                 return "LENGTH REQUIRED";
177                         case 412:
178                                 return "PRECONDITION FAILED";
179                         case 413:
180                                 return "REQUEST ENTITY TOO LARGE";
181                         case 414:
182                                 return "REQUEST-URI TOO LONG";
183                         case 415:
184                                 return "UNSUPPORTED MEDIA TYPE";
185                         case 416:
186                                 return "REQUESTED RANGE NOT SATISFIABLE";
187                         case 417:
188                                 return "EXPECTATION FAILED";
189                         case 500:
190                                 return "INTERNAL SERVER ERROR";
191                         case 501:
192                                 return "NOT IMPLEMENTED";
193                         case 502:
194                                 return "BAD GATEWAY";
195                         case 503:
196                                 return "SERVICE UNAVAILABLE";
197                         case 504:
198                                 return "GATEWAY TIMEOUT";
199                         case 505:
200                                 return "HTTP VERSION NOT SUPPORTED";
201                         default:
202                                 return "WTF";
203                         break;
204                                 
205                 }
206         }
207
208         void SendHeaders(unsigned long size, int response, const std::string &extraheaders)
209         {
210                 time_t local = this->Instance->Time();
211                 struct tm *timeinfo = gmtime(&local);
212                 this->Write("HTTP/1.1 "+ConvToStr(response)+" "+Response(response)+"\r\nDate: ");
213                 this->Write(asctime(timeinfo));
214                 if (extraheaders.empty())
215                 {
216                         this->Write("Content-Type: text/html\r\n");
217                 }
218                 else
219                 {
220                         this->Write(extraheaders);
221                 }
222                 this->Write("Server: InspIRCd/m_httpd.so/1.1\r\nContent-Length: "+ConvToStr(size)+
223                                 "\r\nConnection: close\r\n\r\n");
224         }
225
226         virtual bool OnDataReady()
227         {
228                 char* data = this->Read();
229
230                 /* Check that the data read is a valid pointer and it has some content */
231                 if (data && *data)
232                 {
233                         headers << data;
234
235                         if (headers.str().find("\r\n\r\n") != std::string::npos)
236                         {
237                                 if (request_type == "")
238                                 {
239                                         headers >> request_type;
240                                         headers >> uri;
241                                         headers >> http_version;
242
243                                         std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
244                                         std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
245                                 }
246
247                                 if ((InternalState == HTTP_SERVE_WAIT_REQUEST) && (request_type == "POST"))
248                                 {
249                                         /* Do we need to fetch postdata? */
250                                         postdata = "";
251                                         InternalState = HTTP_SERVE_RECV_POSTDATA;
252                                         std::string header_item;
253                                         while (headers >> header_item)
254                                         {
255                                                 if (header_item == "Content-Length:")
256                                                 {
257                                                         headers >> header_item;
258                                                         postsize = atoi(header_item.c_str());
259                                                 }
260                                         }
261                                         if (!postsize)
262                                         {
263                                                 InternalState = HTTP_SERVE_SEND_DATA;
264                                                 SendHeaders(0, 400, "");
265                                                 Timeout = new HttpServerTimeout(this, Instance->SE);
266                                                 Instance->Timers->AddTimer(Timeout);
267                                         }
268                                         else
269                                         {
270                                                 Instance->Log(DEBUG,"%d bytes to read for POST",postsize);
271                                                 std::string::size_type x = headers.str().find("\r\n\r\n");
272                                                 postdata = headers.str().substr(x+4, headers.str().length());
273                                                 /* Get content length and store */
274                                                 Instance->Log(DEBUG,"Initial postdata: '%s'", postdata.c_str());
275                                                 if (postdata.length() >= postsize)
276                                                         ServeData();
277                                         }
278                                 }
279                                 else if (InternalState == HTTP_SERVE_RECV_POSTDATA)
280                                 {
281                                         /* Add postdata, once we have it all, send the event */
282                                         postdata.append(data);
283                                         if (postdata.length() >= postsize)
284                                                 ServeData();
285                                 }
286                                 else
287                                 {
288                                         ServeData();
289                                 }
290                                 return true;
291                         }
292                         return true;
293                 }
294                 else
295                 {
296                         return false;
297                 }
298         }
299
300         void ServeData()
301         {
302                 /* Headers are complete */
303                 InternalState = HTTP_SERVE_SEND_DATA;
304
305                 Instance->Timers->DelTimer(Timeout);
306                 Timeout = NULL;
307         
308                 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.0"))
309                 {
310                         SendHeaders(0, 505, "");
311                 }
312                 else
313                 {
314                         if ((request_type == "GET") && (uri == "/"))
315                         {
316                                 SendHeaders(index->ContentSize(), 200, "");
317                                 this->Write(index->Contents());
318                         }
319                         else
320                         {
321                                 claimed = false;
322                                 HTTPRequest httpr(request_type,uri,&headers,this,this->GetIP(),postdata);
323                                 Event e((char*)&httpr, (Module*)HttpModule, "httpd_url");
324                                 e.Send(this->Instance);
325                                 if (!claimed)
326                                 {
327                                         SendHeaders(0, 404, "");
328                                         Instance->Log(DEBUG,"Page not claimed, 404");
329                                 }
330                         }
331                 }
332                 Timeout = new HttpServerTimeout(this, Instance->SE);
333                 Instance->Timers->AddTimer(Timeout);
334         }
335
336         void Page(std::stringstream* n, int response, std::string& extraheaders)
337         {
338                 Instance->Log(DEBUG,"Sending page");
339                 SendHeaders(n->str().length(), response, extraheaders);
340                 this->Write(n->str());
341         }
342 };
343
344 HttpServerTimeout::HttpServerTimeout(HttpServerSocket* sock, SocketEngine* engine) : InspTimer(60, time(NULL)), s(sock), SE(engine)
345 {
346 }
347
348 void HttpServerTimeout::Tick(time_t TIME)
349 {
350         SE->DelFd(s);
351         s->Close();
352         delete s;
353 }
354
355 class ModuleHttpServer : public Module
356 {
357         std::vector<HttpServerSocket*> httpsocks;
358  public:
359
360         void ReadConfig()
361         {
362                 int port;
363                 std::string host;
364                 std::string bindip;
365                 std::string indexfile;
366                 FileReader* index;
367                 HttpServerSocket* http;
368                 ConfigReader c(ServerInstance);
369
370                 httpsocks.clear();
371
372                 for (int i = 0; i < c.Enumerate("http"); i++)
373                 {
374                         host = c.ReadValue("http", "host", i);
375                         bindip = c.ReadValue("http", "ip", i);
376                         port = c.ReadInteger("http", "port", i, true);
377                         indexfile = c.ReadValue("http", "index", i);
378                         index = new FileReader(ServerInstance, indexfile);
379                         http = new HttpServerSocket(ServerInstance, bindip, port, true, 0, index);
380                         httpsocks.push_back(http);
381                 }
382         }
383
384         ModuleHttpServer(InspIRCd* Me) : Module::Module(Me)
385         {
386                 ReadConfig();
387         }
388
389         void OnEvent(Event* event)
390         {
391         }
392
393         char* OnRequest(Request* request)
394         {
395                 ServerInstance->Log(DEBUG,"Got HTTPDocument object");
396                 claimed = true;
397                 HTTPDocument* doc = (HTTPDocument*)request->GetData();
398                 HttpServerSocket* sock = (HttpServerSocket*)doc->sock;
399                 sock->Page(doc->GetDocument(), doc->GetResponseCode(), doc->GetExtraHeaders());
400                 return NULL;
401         }
402
403         void Implements(char* List)
404         {
405                 List[I_OnEvent] = List[I_OnRequest] = 1;
406         }
407
408         virtual ~ModuleHttpServer()
409         {
410                 for (size_t i = 0; i < httpsocks.size(); i++)
411                 {
412                         ServerInstance->SE->DelFd(httpsocks[i]);
413                         delete httpsocks[i]->GetIndex();
414                         delete httpsocks[i];
415                 }
416         }
417
418         virtual Version GetVersion()
419         {
420                 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
421         }
422 };
423
424
425 class ModuleHttpServerFactory : public ModuleFactory
426 {
427  public:
428         ModuleHttpServerFactory()
429         {
430         }
431         
432         ~ModuleHttpServerFactory()
433         {
434         }
435         
436         virtual Module * CreateModule(InspIRCd* Me)
437         {
438                 HttpModule = new ModuleHttpServer(Me);
439                 return HttpModule;
440         }
441 };
442
443
444 extern "C" void * init_module( void )
445 {
446         return new ModuleHttpServerFactory;
447 }