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