]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_http_client.cpp
Hmm
[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                 if (!resultnum)
65                         socket->Connect(result);
66                 else
67                         socket->Connect(orig);
68         }
69         
70         void OnError(ResolverError e, const string &errmsg)
71         {
72                 ServerInstance->Log(DEBUG,"HTTPResolver::OnError");
73                 /*if (ServerInstance->SocketCull.find(socket) == ServerInstance->SocketCull.end())
74                         ServerInstance->SocketCull[socket] = socket;*/
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         bool cached;
154         HTTPResolver* r = new HTTPResolver(this, Server, url.domain, cached, (Module*)Mod);
155         Instance->AddResolver(r, cached);
156         return true;
157         
158         return true;
159 }
160
161 bool HTTPSocket::ParseURL(const std::string &iurl)
162 {
163         Instance->Log(DEBUG,"HTTPSocket::ParseURL");
164         url.url = iurl;
165         url.port = 80;
166         url.protocol = "http";
167
168         irc::sepstream tokenizer(iurl, '/');
169         
170         for (int p = 0;; p++)
171         {
172                 std::string part;
173                 if (!tokenizer.GetToken(part))
174                         break;
175
176                 if ((p == 0) && (part[part.length() - 1] == ':'))
177                 {
178                         // Protocol ('http:')
179                         url.protocol = part.substr(0, part.length() - 1);
180                 }
181                 else if ((p == 1) && (part.empty()))
182                 {
183                         continue;
184                 }
185                 else if (url.domain.empty())
186                 {
187                         // Domain part: [user[:pass]@]domain[:port]
188                         std::string::size_type usrpos = part.find('@');
189                         if (usrpos != std::string::npos)
190                         {
191                                 // Have a user (and possibly password) part
192                                 std::string::size_type ppos = part.find(':');
193                                 if ((ppos != std::string::npos) && (ppos < usrpos))
194                                 {
195                                         // Have password too
196                                         url.password = part.substr(ppos + 1, usrpos - ppos - 1);
197                                         url.username = part.substr(0, ppos);
198                                 }
199                                 else
200                                 {
201                                         url.username = part.substr(0, usrpos);
202                                 }
203                                 
204                                 part = part.substr(usrpos + 1);
205                         }
206                         
207                         std::string::size_type popos = part.rfind(':');
208                         if (popos != std::string::npos)
209                         {
210                                 url.port = atoi(part.substr(popos + 1).c_str());
211                                 url.domain = part.substr(0, popos);
212                         }
213                         else
214                         {
215                                 url.domain = part;
216                         }
217                 }
218                 else
219                 {
220                         // Request (part of it)..
221                         url.request.append("/");
222                         url.request.append(part);
223                 }
224         }
225         
226         if (url.request.empty())
227                 url.request = "/";
228
229         if ((url.domain.empty()) || (!url.port) || (url.protocol.empty()))
230         {
231                 Instance->Log(DEFAULT, "Invalid URL (%s): Missing required value", iurl.c_str());
232                 return false;
233         }
234         
235         if (url.protocol != "http")
236         {
237                 Instance->Log(DEFAULT, "Invalid URL (%s): Unsupported protocol '%s'", iurl.c_str(), url.protocol.c_str());
238                 return false;
239         }
240         
241         return true;
242 }
243
244 void HTTPSocket::Connect(const string &ip)
245 {
246         Instance->Log(DEBUG,"HTTPSocket::Connect");
247         strlcpy(this->IP, ip.c_str(), MAXBUF);
248         
249         if (!this->DoConnect())
250         {
251                 delete this;
252         }
253 }
254
255 bool HTTPSocket::OnConnected()
256 {
257         std::string request = "GET " + url.request + " HTTP/1.1\r\n";
258
259         // Dump headers into the request
260         HeaderMap headers = req.GetHeaders();
261         
262         for (HeaderMap::iterator i = headers.begin(); i != headers.end(); i++)
263                 request += i->first + ": " + i->second + "\r\n";
264
265         // The Host header is required for HTTP 1.1 and isn't known when the request is created; if they didn't overload it
266         // manually, add it here
267         if (headers.find("Host") == headers.end())
268                 request += "Host: " + url.domain + "\r\n"; 
269         
270         request += "\r\n";
271         
272         this->status = HTTP_REQSENT;
273         
274         return this->Write(request);
275 }
276
277 bool HTTPSocket::OnDataReady()
278 {
279         Instance->Log(DEBUG,"HTTPSocket::OnDataReady()");
280         char *data = this->Read();
281
282         if (!data || !*data)
283                 return false;
284
285         if (this->status < HTTP_DATA)
286         {
287                 std::string line;
288                 std::string::size_type pos;
289
290                 this->buffer += data;
291                 while ((pos = buffer.find("\r\n")) != std::string::npos)
292                 {
293                         line = buffer.substr(0, pos);
294                         buffer = buffer.substr(pos + 2);
295                         if (line.empty())
296                         {
297                                 this->status = HTTP_DATA;
298                                 this->data += this->buffer;
299                                 this->buffer.clear();
300                                 break;
301                         }
302
303                         if (this->status == HTTP_REQSENT)
304                         {
305                                 // HTTP reply (HTTP/1.1 200 msg)
306                                 char const* data = line.c_str();
307                                 data += 9;
308                                 response = new HTTPClientResponse((Module*)Mod, req.GetSource() , url.url, atoi(data), data + 4);
309                                 this->status = HTTP_HEADERS;
310                                 continue;
311                         }
312                         
313                         if ((pos = line.find(':')) != std::string::npos)
314                         {
315                                 response->AddHeader(line.substr(0, pos), line.substr(pos + 1));
316                         }
317                         else
318                         {
319                                 continue;
320                         }
321                 }
322         }
323         else
324         {
325                 this->data += data;
326         }
327         return true;
328 }
329
330 void HTTPSocket::OnClose()
331 {
332         Instance->Log(DEBUG,"HTTPSocket::OnClose");
333         if (data.empty())
334                 return; // notification that request failed?
335
336         response->data = data;
337         response->Send();
338         delete response;
339 }
340
341 MODULE_INIT(ModuleHTTPClient)
342