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