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