]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_http_client.cpp
9004b202b0c56b9d69f03af3c0547b1c206cd189
[user/henk/code/inspircd.git] / src / modules / m_http_client.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 /* Written by Special (john@yarbbles.com) */
18
19 #include "inspircd.h"
20 #include "httpclient.h"
21
22 /* $ModDesc: HTTP client service provider */
23
24 class URL
25 {
26  public:
27         std::string url;
28         std::string protocol, username, password, domain, request;
29         int port;
30 };
31
32 class HTTPSocket : public InspSocket
33 {
34  private:
35         InspIRCd *Server;
36         class ModuleHTTPClient *Mod;
37         HTTPClientRequest *req;
38         HTTPClientResponse *response;
39         URL url;
40         enum { HTTP_CLOSED, HTTP_REQSENT, HTTP_HEADERS, HTTP_DATA } status;
41         std::string data;
42
43  public:
44         HTTPSocket(InspIRCd *Instance, class ModuleHTTPClient *Mod);
45         virtual ~HTTPSocket();
46         virtual bool DoRequest(HTTPClientRequest *req);
47         virtual bool ParseURL(const std::string &url);
48         virtual void Connect(const std::string &ip);
49         virtual bool OnConnected();
50         virtual bool OnDataReady();
51         virtual void OnClose();
52 };
53
54 class HTTPResolver : public Resolver
55 {
56  private:
57         HTTPSocket *socket;
58  public:
59         HTTPResolver(HTTPSocket *socket, InspIRCd *Instance, const string &hostname) : Resolver(Instance, hostname, DNS_QUERY_FORWARD), socket(socket)
60         {
61         }
62         
63         void OnLookupComplete(const string &result)
64         {
65                 socket->Connect(result);
66         }
67         
68         void OnError(ResolverError e, const string &errmsg)
69         {
70                 delete socket;
71         }
72 };
73
74 typedef vector<HTTPSocket*> HTTPList;
75
76 class ModuleHTTPClient : public Module
77 {
78  public:
79         HTTPList sockets;
80
81         ModuleHTTPClient(InspIRCd *Me)
82                 : Module::Module(Me)
83         {
84         }
85         
86         virtual ~ModuleHTTPClient()
87         {
88                 for (HTTPList::iterator i = sockets.begin(); i != sockets.end(); i++)
89                         delete *i;
90         }
91         
92         virtual Version GetVersion()
93         {
94                 return Version(1, 0, 0, 0, VF_SERVICEPROVIDER | VF_VENDOR, API_VERSION);
95         }
96
97         void Implements(char* List)
98         {
99                 List[I_OnRequest] = 1;
100         }
101
102         char* OnRequest(Request *req)
103         {
104                 HTTPClientRequest *httpreq = (HTTPClientRequest *)req;
105                 if (!strcmp(httpreq->GetId(), HTTP_CLIENT_REQUEST))
106                 {
107                         HTTPSocket *sock = new HTTPSocket(ServerInstance, this);
108                         sock->DoRequest(httpreq);
109                         // No return value
110                 }
111                 return NULL;
112         }
113 };
114
115 HTTPSocket::HTTPSocket(InspIRCd *Instance, ModuleHTTPClient *Mod)
116                 : InspSocket(Instance), Server(Instance), Mod(Mod), status(HTTP_CLOSED)
117 {
118         this->ClosePending = false;
119         this->port = 80;
120 }
121
122 HTTPSocket::~HTTPSocket()
123 {
124         Close();
125         for (HTTPList::iterator i = Mod->sockets.begin(); i != Mod->sockets.end(); i++)
126         {
127                 if (*i == this)
128                 {
129                         Mod->sockets.erase(i);
130                         break;
131                 }
132         }
133 }
134
135 bool HTTPSocket::DoRequest(HTTPClientRequest *req)
136 {
137         this->req = req;
138         
139         if (!ParseURL(req->GetURL()))
140                 return false;
141         
142         this->port = url.port;
143         strlcpy(this->host, url.domain.c_str(), MAXBUF);
144
145         if (!inet_aton(this->host, &this->addy))
146         {
147                 new HTTPResolver(this, Server, url.domain);
148                 return true;
149         }
150         else
151         {
152                 this->Connect(url.domain);
153         }
154         
155         return true;
156 }
157
158 bool HTTPSocket::ParseURL(const std::string &iurl)
159 {
160         url.url = iurl;
161         url.port = 80;
162         
163         // Tokenize by slashes (protocol:, blank, domain, request..)
164         int pos = 0, pstart = 0, pend = 0;
165         
166         for (; ; pend = url.url.find('/', pstart))
167         {
168                 string part = url.url.substr(pstart, pend);
169
170                 switch (pos)
171                 {
172                         case 0:
173                                 // Protocol
174                                 if (part[part.length()-1] != ':')
175                                         return false;
176                                 url.protocol = part.substr(0, part.length() - 1);
177                                 break;
178                         case 1:
179                                 // Empty, skip
180                                 break;
181                         case 2:
182                                 // User and password (user:pass@)
183                                 string::size_type aend = part.find('@', 0);
184                                 if (aend != string::npos)
185                                 {
186                                         // Technically, it is valid to not have a password (username@domain)
187                                         string::size_type usrend = part.find(':', 0);
188                                         
189                                         if ((usrend != string::npos) && (usrend < aend))
190                                                 url.password = part.substr(usrend + 1, aend);
191                                         else
192                                                 usrend = aend;
193                                         
194                                         url.username = part.substr(0, usrend);
195                                 }
196                                 else
197                                         aend = 0;
198                                 
199                                 // Port (:port)
200                                 string::size_type dend = part.find(':', aend);
201                                 if (dend != string::npos)
202                                         url.port = atoi(part.substr(dend + 1).c_str());
203
204                                 // Domain
205                                 url.domain = part.substr(aend + 1, dend);
206                                 
207                                 // The rest of the string is the request
208                                 url.request = url.url.substr(pend);
209                                 break;
210                 }
211                 
212                 if (pos++ == 2)
213                         break;
214
215                 pstart = pend + 1;
216         }
217         
218         return true;
219 }
220
221 void HTTPSocket::Connect(const string &ip)
222 {
223         strlcpy(this->IP, ip.c_str(), MAXBUF);
224         
225         if (!this->DoConnect())
226         {
227                 Server->Log(DEBUG, "Unable to connect HTTPSocket to %s", this->host);
228                 delete this;
229         }
230 }
231
232 bool HTTPSocket::OnConnected()
233 {
234         std::string request = "GET " + url.request + " HTTP/1.1\r\n";
235
236         // Dump headers into the request
237         HeaderMap headers = req->GetHeaders();
238         
239         for (HeaderMap::iterator i = headers.begin(); i != headers.end(); i++)
240                 request += i->first + ": " + i->second + "\r\n";
241
242         // The Host header is required for HTTP 1.1 and isn't known when the request is created; if they didn't overload it
243         // manually, add it here
244         if (headers.find("Host") == headers.end())
245                 request += "Host: " + url.domain + "\r\n"; 
246         
247         request += "\r\n";
248         
249         this->status = HTTP_REQSENT;
250         
251         return this->Write(request);
252 }
253
254 bool HTTPSocket::OnDataReady()
255 {
256         char *data = this->Read();
257
258         if (!data)
259         {
260                 this->Close();
261                 return false;
262         }
263         
264         // Needs buffering for incomplete reads..
265         char *lend;
266         
267         if (this->status < HTTP_DATA)
268         {
269                 while ((lend = strstr(data, "\r\n")) != NULL)
270                 {
271                         if (strncmp(data, "\r\n", 2) == 0)
272                         {
273                                 this->status = HTTP_DATA;
274                                 break;
275                         }
276                         
277                         *lend = '\0';
278                         
279                         if (this->status == HTTP_REQSENT)
280                         {
281                                 // HTTP reply (HTTP/1.1 200 msg)
282                                 data += 9;
283                                 response = new HTTPClientResponse((Module*)Mod, req->GetSource() , url.url, atoi(data), data + 4);
284                                 this->status = HTTP_HEADERS;
285                                 continue;
286                         }
287                         
288                         char *hdata = strchr(data, ':');
289                         
290                         if (!hdata)
291                                 continue;
292                         
293                         *hdata = '\0';
294                         
295                         response->AddHeader(data, hdata + 2);
296                         
297                         data = lend + 2;
298                 }
299         }
300         
301         this->data += data;
302         return true;
303 }
304
305 void HTTPSocket::OnClose()
306 {
307         if (!data.length())
308         {
309                 Server->Log(DEBUG, "HTTP socket closed unexpectedly (no content recieved)");
310                 return;
311         }
312         Server->Log(DEBUG, "Got file from HTTP successfully");
313         response->data = data;
314         response->Send();
315         delete response;
316 }
317
318 class ModuleHTTPClientFactory : public ModuleFactory
319 {
320  public:
321         ModuleHTTPClientFactory()
322         {
323         }
324         
325         ~ModuleHTTPClientFactory()
326         {
327         }
328         
329         Module *CreateModule(InspIRCd* Me)
330         {
331                 return new ModuleHTTPClient(Me);
332         }
333 };
334
335 extern "C" void *init_module(void)
336 {
337         return new ModuleHTTPClientFactory;
338 }
339
340