]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_http_client.cpp
d96b8e59f964568f620f057752a5455dc529675e
[user/henk/code/inspircd.git] / src / modules / m_http_client.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 "httpclient.h"
16
17 /* $ModDesc: HTTP client service provider */
18
19 class URL
20 {
21  public:
22         std::string url;
23         std::string protocol, username, password, domain, request;
24         int port;
25 };
26
27 class HTTPSocket : public BufferedSocket
28 {
29  private:
30         InspIRCd *Server;
31         class ModuleHTTPClient *Mod;
32         HTTPClientRequest req;
33         HTTPClientResponse *response;
34         URL url;
35         enum { HTTP_CLOSED, HTTP_REQSENT, HTTP_HEADERS, HTTP_DATA } status;
36         std::string data;
37         std::string buffer;
38
39  public:
40         HTTPSocket(InspIRCd *Instance, class ModuleHTTPClient *Mod);
41         virtual ~HTTPSocket();
42         virtual bool DoRequest(HTTPClientRequest *req);
43         virtual bool ParseURL(const std::string &url);
44         virtual void Connect(const std::string &ip);
45         virtual bool OnConnected();
46         virtual bool OnDataReady();
47         virtual void OnClose();
48 };
49
50 class HTTPResolver : public Resolver
51 {
52  private:
53         HTTPSocket *socket;
54         std::string orig;
55  public:
56         HTTPResolver(HTTPSocket *socket, InspIRCd *Instance, const string &hostname, bool &cached, Module* me) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, cached, me), socket(socket)
57         {
58                 ServerInstance->Log(DEBUG,"HTTPResolver::HTTPResolver");
59                 orig = hostname;
60         }
61         
62         void OnLookupComplete(const string &result, unsigned int ttl, bool cached, int resultnum = 0)
63         {
64                 ServerInstance->Log(DEBUG,"HTTPResolver::OnLookupComplete");
65                 if (!resultnum)
66                         socket->Connect(result);
67                 else
68                         socket->OnClose();
69         }
70         
71         void OnError(ResolverError e, const string &errmsg)
72         {
73                 ServerInstance->Log(DEBUG,"HTTPResolver::OnError");
74                 socket->OnClose();
75         }
76 };
77
78 typedef vector<HTTPSocket*> HTTPList;
79
80 class ModuleHTTPClient : public Module
81 {
82  public:
83         HTTPList sockets;
84
85         ModuleHTTPClient(InspIRCd *Me)
86                 : Module(Me)
87         {
88                 Implementation eventlist[] = { I_OnRequest };
89                 ServerInstance->Modules->Attach(eventlist, this, 1);
90         }
91         
92         virtual ~ModuleHTTPClient()
93         {
94                 for (HTTPList::iterator i = sockets.begin(); i != sockets.end(); i++)
95                         delete *i;
96         }
97         
98         virtual Version GetVersion()
99         {
100                 return Version(1, 0, 0, 0, VF_SERVICEPROVIDER | VF_VENDOR, API_VERSION);
101         }
102
103
104         char* OnRequest(Request *req)
105         {
106                 HTTPClientRequest *httpreq = (HTTPClientRequest *)req;
107                 if (!strcmp(httpreq->GetId(), HTTP_CLIENT_REQUEST))
108                 {
109                         HTTPSocket *sock = new HTTPSocket(ServerInstance, this);
110                         sock->DoRequest(httpreq);
111                         // No return value
112                 }
113                 return NULL;
114         }
115 };
116
117 HTTPSocket::HTTPSocket(InspIRCd *Instance, ModuleHTTPClient *Mod)
118                 : BufferedSocket(Instance), Server(Instance), Mod(Mod), status(HTTP_CLOSED)
119 {
120         Instance->Log(DEBUG,"HTTPSocket::HTTPSocket");
121         this->port = 80;
122 }
123
124 HTTPSocket::~HTTPSocket()
125 {
126         Close();
127         for (HTTPList::iterator i = Mod->sockets.begin(); i != Mod->sockets.end(); i++)
128         {
129                 if (*i == this)
130                 {
131                         Mod->sockets.erase(i);
132                         break;
133                 }
134         }
135 }
136
137 bool HTTPSocket::DoRequest(HTTPClientRequest *req)
138 {
139         Instance->Log(DEBUG,"HTTPSocket::DoRequest");
140         /* Tweak by brain - we take a copy of this,
141          * so that the caller doesnt need to leave
142          * pointers knocking around, less chance of
143          * a memory leak.
144          */
145         this->req = *req;
146
147         if (!ParseURL(this->req.GetURL()))
148                 return false;
149         
150         this->port = url.port;
151         strlcpy(this->host, url.domain.c_str(), MAXBUF);
152
153         in6_addr s6;
154         in_addr s4;
155         /* Doesnt look like an ipv4 or an ipv6 address */
156         if ((inet_pton(AF_INET6, url.domain.c_str(), &s6) < 1) && (inet_pton(AF_INET, url.domain.c_str(), &s4) < 1))
157         {
158                 bool cached;
159                 HTTPResolver* r = new HTTPResolver(this, Server, url.domain, cached, (Module*)Mod);
160                 Instance->AddResolver(r, cached);
161         }
162         else
163                 Connect(url.domain);
164         
165         return true;
166 }
167
168 bool HTTPSocket::ParseURL(const std::string &iurl)
169 {
170         Instance->Log(DEBUG,"HTTPSocket::ParseURL");
171         url.url = iurl;
172         url.port = 80;
173         url.protocol = "http";
174
175         irc::sepstream tokenizer(iurl, '/');
176         
177         for (int p = 0;; p++)
178         {
179                 std::string part;
180                 if (!tokenizer.GetToken(part))
181                         break;
182
183                 if ((p == 0) && (part[part.length() - 1] == ':'))
184                 {
185                         // Protocol ('http:')
186                         url.protocol = part.substr(0, part.length() - 1);
187                 }
188                 else if ((p == 1) && (part.empty()))
189                 {
190                         continue;
191                 }
192                 else if (url.domain.empty())
193                 {
194                         // Domain part: [user[:pass]@]domain[:port]
195                         std::string::size_type usrpos = part.find('@');
196                         if (usrpos != std::string::npos)
197                         {
198                                 // Have a user (and possibly password) part
199                                 std::string::size_type ppos = part.find(':');
200                                 if ((ppos != std::string::npos) && (ppos < usrpos))
201                                 {
202                                         // Have password too
203                                         url.password = part.substr(ppos + 1, usrpos - ppos - 1);
204                                         url.username = part.substr(0, ppos);
205                                 }
206                                 else
207                                 {
208                                         url.username = part.substr(0, usrpos);
209                                 }
210                                 
211                                 part = part.substr(usrpos + 1);
212                         }
213                         
214                         std::string::size_type popos = part.rfind(':');
215                         if (popos != std::string::npos)
216                         {
217                                 url.port = atoi(part.substr(popos + 1).c_str());
218                                 url.domain = part.substr(0, popos);
219                         }
220                         else
221                         {
222                                 url.domain = part;
223                         }
224                 }
225                 else
226                 {
227                         // Request (part of it)..
228                         url.request.append("/");
229                         url.request.append(part);
230                 }
231         }
232         
233         if (url.request.empty())
234                 url.request = "/";
235
236         if ((url.domain.empty()) || (!url.port) || (url.protocol.empty()))
237         {
238                 Instance->Log(DEFAULT, "Invalid URL (%s): Missing required value", iurl.c_str());
239                 return false;
240         }
241         
242         if (url.protocol != "http")
243         {
244                 Instance->Log(DEFAULT, "Invalid URL (%s): Unsupported protocol '%s'", iurl.c_str(), url.protocol.c_str());
245                 return false;
246         }
247         
248         return true;
249 }
250
251 void HTTPSocket::Connect(const string &ip)
252 {
253         Instance->Log(DEBUG,"HTTPSocket::Connect(%s)", ip.c_str());
254         strlcpy(this->IP, ip.c_str(), MAXBUF);
255         strlcpy(this->host, ip.c_str(), MAXBUF);
256
257         if (!this->DoConnect())
258                 this->Close();
259 }
260
261 bool HTTPSocket::OnConnected()
262 {
263         std::string request = "GET " + url.request + " HTTP/1.1\r\n";
264
265         // Dump headers into the request
266         HeaderMap headers = req.GetHeaders();
267         
268         for (HeaderMap::iterator i = headers.begin(); i != headers.end(); i++)
269                 request += i->first + ": " + i->second + "\r\n";
270
271         // The Host header is required for HTTP 1.1 and isn't known when the request is created; if they didn't overload it
272         // manually, add it here
273         if (headers.find("Host") == headers.end())
274                 request += "Host: " + url.domain + "\r\n"; 
275         
276         request += "\r\n";
277         
278         this->status = HTTP_REQSENT;
279         
280         return this->Write(request);
281 }
282
283 bool HTTPSocket::OnDataReady()
284 {
285         Instance->Log(DEBUG,"HTTPSocket::OnDataReady()");
286         char *data = this->Read();
287
288         if (!data || !*data)
289                 return false;
290
291         if (this->status < HTTP_DATA)
292         {
293                 std::string line;
294                 std::string::size_type pos;
295
296                 this->buffer += data;
297                 while ((pos = buffer.find("\r\n")) != std::string::npos)
298                 {
299                         line = buffer.substr(0, pos);
300                         buffer = buffer.substr(pos + 2);
301                         if (line.empty())
302                         {
303                                 this->status = HTTP_DATA;
304                                 this->data += this->buffer;
305                                 this->buffer.clear();
306                                 break;
307                         }
308
309                         if (this->status == HTTP_REQSENT)
310                         {
311                                 // HTTP reply (HTTP/1.1 200 msg)
312                                 char const* data = line.c_str();
313                                 data += 9;
314                                 response = new HTTPClientResponse((Module*)Mod, req.GetSource() , url.url, atoi(data), data + 4);
315                                 this->status = HTTP_HEADERS;
316                                 continue;
317                         }
318                         
319                         if ((pos = line.find(':')) != std::string::npos)
320                         {
321                                 response->AddHeader(line.substr(0, pos), line.substr(pos + 1));
322                         }
323                         else
324                         {
325                                 continue;
326                         }
327                 }
328         }
329         else
330         {
331                 this->data += data;
332         }
333         return true;
334 }
335
336 void HTTPSocket::OnClose()
337 {
338         Instance->Log(DEBUG,"HTTPSocket::OnClose");
339         if (data.empty())
340         {
341                 HTTPClientError* err = new HTTPClientError((Module*)Mod, req.GetSource(), req.GetURL(), 0);
342                 err->Send();
343                 delete err;
344                 return;
345         }
346
347         Instance->Log(DEBUG,"Set data and send");
348         response->data = data;
349         response->Send();
350         delete response;
351 }
352
353 MODULE_INIT(ModuleHTTPClient)
354