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