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