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