1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
15 #include "httpclient.h"
17 /* $ModDesc: HTTP client service provider */
23 std::string protocol, username, password, domain, request;
27 class HTTPSocket : public InspSocket
31 class ModuleHTTPClient *Mod;
32 HTTPClientRequest req;
33 HTTPClientResponse *response;
35 enum { HTTP_CLOSED, HTTP_REQSENT, HTTP_HEADERS, HTTP_DATA } status;
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();
50 class HTTPResolver : public Resolver
55 HTTPResolver(HTTPSocket *socket, InspIRCd *Instance, const string &hostname, bool &cached, Module* me) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, cached, me), socket(socket)
59 void OnLookupComplete(const string &result, unsigned int ttl, bool cached)
61 socket->Connect(result);
64 void OnError(ResolverError e, const string &errmsg)
70 typedef vector<HTTPSocket*> HTTPList;
72 class ModuleHTTPClient : public Module
77 ModuleHTTPClient(InspIRCd *Me)
82 virtual ~ModuleHTTPClient()
84 for (HTTPList::iterator i = sockets.begin(); i != sockets.end(); i++)
88 virtual Version GetVersion()
90 return Version(1, 0, 0, 0, VF_SERVICEPROVIDER | VF_VENDOR, API_VERSION);
93 void Implements(char* List)
95 List[I_OnRequest] = 1;
98 char* OnRequest(Request *req)
100 HTTPClientRequest *httpreq = (HTTPClientRequest *)req;
101 if (!strcmp(httpreq->GetId(), HTTP_CLIENT_REQUEST))
103 HTTPSocket *sock = new HTTPSocket(ServerInstance, this);
104 sock->DoRequest(httpreq);
111 HTTPSocket::HTTPSocket(InspIRCd *Instance, ModuleHTTPClient *Mod)
112 : InspSocket(Instance), Server(Instance), Mod(Mod), status(HTTP_CLOSED)
114 this->ClosePending = false;
118 HTTPSocket::~HTTPSocket()
121 for (HTTPList::iterator i = Mod->sockets.begin(); i != Mod->sockets.end(); i++)
125 Mod->sockets.erase(i);
131 bool HTTPSocket::DoRequest(HTTPClientRequest *req)
133 /* Tweak by brain - we take a copy of this,
134 * so that the caller doesnt need to leave
135 * pointers knocking around, less chance of
140 if (!ParseURL(this->req.GetURL()))
143 this->port = url.port;
144 strlcpy(this->host, url.domain.c_str(), MAXBUF);
149 if ((inet_aton(this->host, &addy1) > 0) || (inet_pton(AF_INET6, this->host, &addy2) > 0))
151 if (inet_aton(this->host, &addy1) > 0)
155 HTTPResolver* r = new HTTPResolver(this, Server, url.domain, cached, (Module*)Mod);
156 Instance->AddResolver(r, cached);
161 this->Connect(url.domain);
167 bool HTTPSocket::ParseURL(const std::string &iurl)
171 url.protocol = "http";
173 irc::sepstream tokenizer(iurl, '/');
175 for (int p = 0;; p++)
177 std::string part = tokenizer.GetToken();
178 if (part.empty() && tokenizer.StreamEnd())
181 if ((p == 0) && (part[part.length() - 1] == ':'))
183 // Protocol ('http:')
184 url.protocol = part.substr(0, part.length() - 1);
186 else if ((p == 1) && (part.empty()))
190 else if (url.domain.empty())
192 // Domain part: [user[:pass]@]domain[:port]
193 std::string::size_type usrpos = part.find('@');
194 if (usrpos != std::string::npos)
196 // Have a user (and possibly password) part
197 std::string::size_type ppos = part.find(':');
198 if ((ppos != std::string::npos) && (ppos < usrpos))
201 url.password = part.substr(ppos + 1, usrpos - ppos - 1);
202 url.username = part.substr(0, ppos);
206 url.username = part.substr(0, usrpos);
209 part = part.substr(usrpos + 1);
212 std::string::size_type popos = part.rfind(':');
213 if (popos != std::string::npos)
215 url.port = atoi(part.substr(popos + 1).c_str());
216 url.domain = part.substr(0, popos);
225 // Request (part of it)..
226 url.request.append("/");
227 url.request.append(part);
231 if (url.request.empty())
234 if ((url.domain.empty()) || (!url.port) || (url.protocol.empty()))
236 Instance->Log(DEFAULT, "Invalid URL (%s): Missing required value", iurl.c_str());
240 if (url.protocol != "http")
242 Instance->Log(DEFAULT, "Invalid URL (%s): Unsupported protocol '%s'", iurl.c_str(), url.protocol.c_str());
249 void HTTPSocket::Connect(const string &ip)
251 strlcpy(this->IP, ip.c_str(), MAXBUF);
253 if (!this->DoConnect())
259 bool HTTPSocket::OnConnected()
261 std::string request = "GET " + url.request + " HTTP/1.1\r\n";
263 // Dump headers into the request
264 HeaderMap headers = req.GetHeaders();
266 for (HeaderMap::iterator i = headers.begin(); i != headers.end(); i++)
267 request += i->first + ": " + i->second + "\r\n";
269 // The Host header is required for HTTP 1.1 and isn't known when the request is created; if they didn't overload it
270 // manually, add it here
271 if (headers.find("Host") == headers.end())
272 request += "Host: " + url.domain + "\r\n";
276 this->status = HTTP_REQSENT;
278 return this->Write(request);
281 bool HTTPSocket::OnDataReady()
283 char *data = this->Read();
291 if (this->status < HTTP_DATA)
294 std::string::size_type pos;
296 this->buffer += data;
297 while ((pos = buffer.find("\r\n")) != std::string::npos)
299 line = buffer.substr(0, pos);
300 buffer = buffer.substr(pos + 2);
303 this->status = HTTP_DATA;
304 this->data += this->buffer;
309 if (this->status == HTTP_REQSENT)
311 // HTTP reply (HTTP/1.1 200 msg)
312 char const* data = line.c_str();
314 response = new HTTPClientResponse((Module*)Mod, req.GetSource() , url.url, atoi(data), data + 4);
315 this->status = HTTP_HEADERS;
319 if ((pos = line.find(':')) != std::string::npos)
321 response->AddHeader(line.substr(0, pos), line.substr(pos + 1));
336 void HTTPSocket::OnClose()
339 return; // notification that request failed?
341 response->data = data;
346 class ModuleHTTPClientFactory : public ModuleFactory
349 ModuleHTTPClientFactory()
353 ~ModuleHTTPClientFactory()
357 Module *CreateModule(InspIRCd* Me)
359 return new ModuleHTTPClient(Me);
363 extern "C" void *init_module(void)
365 return new ModuleHTTPClientFactory;