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 BufferedSocket
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
56 HTTPResolver(HTTPSocket *socket, InspIRCd *Instance, const string &hostname, bool &cached, Module* me) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, cached, me), socket(socket)
58 ServerInstance->Log(DEBUG,"HTTPResolver::HTTPResolver");
62 void OnLookupComplete(const string &result, unsigned int ttl, bool cached, int resultnum = 0)
65 socket->Connect(result);
67 socket->Connect(orig);
70 void OnError(ResolverError e, const string &errmsg)
72 ServerInstance->Log(DEBUG,"HTTPResolver::OnError");
77 typedef vector<HTTPSocket*> HTTPList;
79 class ModuleHTTPClient : public Module
84 ModuleHTTPClient(InspIRCd *Me)
87 Implementation eventlist[] = { I_OnRequest };
88 ServerInstance->Modules->Attach(eventlist, this, 1);
91 virtual ~ModuleHTTPClient()
93 for (HTTPList::iterator i = sockets.begin(); i != sockets.end(); i++)
97 virtual Version GetVersion()
99 return Version(1, 0, 0, 0, VF_SERVICEPROVIDER | VF_VENDOR, API_VERSION);
103 char* OnRequest(Request *req)
105 HTTPClientRequest *httpreq = (HTTPClientRequest *)req;
106 if (!strcmp(httpreq->GetId(), HTTP_CLIENT_REQUEST))
108 HTTPSocket *sock = new HTTPSocket(ServerInstance, this);
109 sock->DoRequest(httpreq);
116 HTTPSocket::HTTPSocket(InspIRCd *Instance, ModuleHTTPClient *Mod)
117 : BufferedSocket(Instance), Server(Instance), Mod(Mod), status(HTTP_CLOSED)
119 Instance->Log(DEBUG,"HTTPSocket::HTTPSocket");
123 HTTPSocket::~HTTPSocket()
126 for (HTTPList::iterator i = Mod->sockets.begin(); i != Mod->sockets.end(); i++)
130 Mod->sockets.erase(i);
136 bool HTTPSocket::DoRequest(HTTPClientRequest *req)
138 Instance->Log(DEBUG,"HTTPSocket::DoRequest");
139 /* Tweak by brain - we take a copy of this,
140 * so that the caller doesnt need to leave
141 * pointers knocking around, less chance of
146 if (!ParseURL(this->req.GetURL()))
149 this->port = url.port;
150 strlcpy(this->host, url.domain.c_str(), MAXBUF);
154 /* Doesnt look like an ipv4 or an ipv6 address */
155 if ((inet_pton(AF_INET6, url.domain.c_str(), &s6) < 1) && (inet_pton(AF_INET, url.domain.c_str(), &s4) < 1))
158 HTTPResolver* r = new HTTPResolver(this, Server, url.domain, cached, (Module*)Mod);
159 Instance->AddResolver(r, cached);
167 bool HTTPSocket::ParseURL(const std::string &iurl)
169 Instance->Log(DEBUG,"HTTPSocket::ParseURL");
172 url.protocol = "http";
174 irc::sepstream tokenizer(iurl, '/');
176 for (int p = 0;; p++)
179 if (!tokenizer.GetToken(part))
182 if ((p == 0) && (part[part.length() - 1] == ':'))
184 // Protocol ('http:')
185 url.protocol = part.substr(0, part.length() - 1);
187 else if ((p == 1) && (part.empty()))
191 else if (url.domain.empty())
193 // Domain part: [user[:pass]@]domain[:port]
194 std::string::size_type usrpos = part.find('@');
195 if (usrpos != std::string::npos)
197 // Have a user (and possibly password) part
198 std::string::size_type ppos = part.find(':');
199 if ((ppos != std::string::npos) && (ppos < usrpos))
202 url.password = part.substr(ppos + 1, usrpos - ppos - 1);
203 url.username = part.substr(0, ppos);
207 url.username = part.substr(0, usrpos);
210 part = part.substr(usrpos + 1);
213 std::string::size_type popos = part.rfind(':');
214 if (popos != std::string::npos)
216 url.port = atoi(part.substr(popos + 1).c_str());
217 url.domain = part.substr(0, popos);
226 // Request (part of it)..
227 url.request.append("/");
228 url.request.append(part);
232 if (url.request.empty())
235 if ((url.domain.empty()) || (!url.port) || (url.protocol.empty()))
237 Instance->Log(DEFAULT, "Invalid URL (%s): Missing required value", iurl.c_str());
241 if (url.protocol != "http")
243 Instance->Log(DEFAULT, "Invalid URL (%s): Unsupported protocol '%s'", iurl.c_str(), url.protocol.c_str());
250 void HTTPSocket::Connect(const string &ip)
252 Instance->Log(DEBUG,"HTTPSocket::Connect");
253 strlcpy(this->IP, ip.c_str(), MAXBUF);
255 if (!this->DoConnect())
261 bool HTTPSocket::OnConnected()
263 std::string request = "GET " + url.request + " HTTP/1.1\r\n";
265 // Dump headers into the request
266 HeaderMap headers = req.GetHeaders();
268 for (HeaderMap::iterator i = headers.begin(); i != headers.end(); i++)
269 request += i->first + ": " + i->second + "\r\n";
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";
278 this->status = HTTP_REQSENT;
280 return this->Write(request);
283 bool HTTPSocket::OnDataReady()
285 Instance->Log(DEBUG,"HTTPSocket::OnDataReady()");
286 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;
305 this->buffer.clear();
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()
338 Instance->Log(DEBUG,"HTTPSocket::OnClose");
341 HTTPClientError* err = new HTTPClientError((Module*)Mod, req.GetSource(), req.GetURL(), 0);
347 Instance->Log(DEBUG,"Set data and send");
348 response->data = data;
353 MODULE_INIT(ModuleHTTPClient)