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