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
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, int resultnum = 0)
62 socket->Connect(result);
65 void OnError(ResolverError e, const string &errmsg)
67 if (ServerInstance->SocketCull.find(socket) == ServerInstance->SocketCull.end())
68 ServerInstance->SocketCull[socket] = socket;
72 typedef vector<HTTPSocket*> HTTPList;
74 class ModuleHTTPClient : public Module
79 ModuleHTTPClient(InspIRCd *Me)
82 Implementation eventlist[] = { I_OnRequest };
83 ServerInstance->Modules->Attach(eventlist, this, 1);
86 virtual ~ModuleHTTPClient()
88 for (HTTPList::iterator i = sockets.begin(); i != sockets.end(); i++)
92 virtual Version GetVersion()
94 return Version(1, 0, 0, 0, VF_SERVICEPROVIDER | VF_VENDOR, API_VERSION);
97 void Implements(char* List)
99 List[I_OnRequest] = 1;
102 char* OnRequest(Request *req)
104 HTTPClientRequest *httpreq = (HTTPClientRequest *)req;
105 if (!strcmp(httpreq->GetId(), HTTP_CLIENT_REQUEST))
107 HTTPSocket *sock = new HTTPSocket(ServerInstance, this);
108 sock->DoRequest(httpreq);
115 HTTPSocket::HTTPSocket(InspIRCd *Instance, ModuleHTTPClient *Mod)
116 : BufferedSocket(Instance), Server(Instance), Mod(Mod), status(HTTP_CLOSED)
118 this->ClosePending = false;
122 HTTPSocket::~HTTPSocket()
125 for (HTTPList::iterator i = Mod->sockets.begin(); i != Mod->sockets.end(); i++)
129 Mod->sockets.erase(i);
135 bool HTTPSocket::DoRequest(HTTPClientRequest *req)
137 /* Tweak by brain - we take a copy of this,
138 * so that the caller doesnt need to leave
139 * pointers knocking around, less chance of
144 if (!ParseURL(this->req.GetURL()))
147 this->port = url.port;
148 strlcpy(this->host, url.domain.c_str(), MAXBUF);
153 if ((inet_aton(this->host, &addy1) > 0) || (inet_pton(AF_INET6, this->host, &addy2) > 0))
155 if (inet_aton(this->host, &addy1) > 0)
159 HTTPResolver* r = new HTTPResolver(this, Server, url.domain, cached, (Module*)Mod);
160 Instance->AddResolver(r, cached);
165 this->Connect(url.domain);
171 bool HTTPSocket::ParseURL(const std::string &iurl)
175 url.protocol = "http";
177 irc::sepstream tokenizer(iurl, '/');
179 for (int p = 0;; p++)
182 if (!tokenizer.GetToken(part))
185 if ((p == 0) && (part[part.length() - 1] == ':'))
187 // Protocol ('http:')
188 url.protocol = part.substr(0, part.length() - 1);
190 else if ((p == 1) && (part.empty()))
194 else if (url.domain.empty())
196 // Domain part: [user[:pass]@]domain[:port]
197 std::string::size_type usrpos = part.find('@');
198 if (usrpos != std::string::npos)
200 // Have a user (and possibly password) part
201 std::string::size_type ppos = part.find(':');
202 if ((ppos != std::string::npos) && (ppos < usrpos))
205 url.password = part.substr(ppos + 1, usrpos - ppos - 1);
206 url.username = part.substr(0, ppos);
210 url.username = part.substr(0, usrpos);
213 part = part.substr(usrpos + 1);
216 std::string::size_type popos = part.rfind(':');
217 if (popos != std::string::npos)
219 url.port = atoi(part.substr(popos + 1).c_str());
220 url.domain = part.substr(0, popos);
229 // Request (part of it)..
230 url.request.append("/");
231 url.request.append(part);
235 if (url.request.empty())
238 if ((url.domain.empty()) || (!url.port) || (url.protocol.empty()))
240 Instance->Log(DEFAULT, "Invalid URL (%s): Missing required value", iurl.c_str());
244 if (url.protocol != "http")
246 Instance->Log(DEFAULT, "Invalid URL (%s): Unsupported protocol '%s'", iurl.c_str(), url.protocol.c_str());
253 void HTTPSocket::Connect(const string &ip)
255 strlcpy(this->IP, ip.c_str(), MAXBUF);
257 if (!this->DoConnect())
263 bool HTTPSocket::OnConnected()
265 std::string request = "GET " + url.request + " HTTP/1.1\r\n";
267 // Dump headers into the request
268 HeaderMap headers = req.GetHeaders();
270 for (HeaderMap::iterator i = headers.begin(); i != headers.end(); i++)
271 request += i->first + ": " + i->second + "\r\n";
273 // The Host header is required for HTTP 1.1 and isn't known when the request is created; if they didn't overload it
274 // manually, add it here
275 if (headers.find("Host") == headers.end())
276 request += "Host: " + url.domain + "\r\n";
280 this->status = HTTP_REQSENT;
282 return this->Write(request);
285 bool HTTPSocket::OnDataReady()
287 char *data = this->Read();
295 if (this->status < HTTP_DATA)
298 std::string::size_type pos;
300 this->buffer += data;
301 while ((pos = buffer.find("\r\n")) != std::string::npos)
303 line = buffer.substr(0, pos);
304 buffer = buffer.substr(pos + 2);
307 this->status = HTTP_DATA;
308 this->data += this->buffer;
309 this->buffer.clear();
313 if (this->status == HTTP_REQSENT)
315 // HTTP reply (HTTP/1.1 200 msg)
316 char const* data = line.c_str();
318 response = new HTTPClientResponse((Module*)Mod, req.GetSource() , url.url, atoi(data), data + 4);
319 this->status = HTTP_HEADERS;
323 if ((pos = line.find(':')) != std::string::npos)
325 response->AddHeader(line.substr(0, pos), line.substr(pos + 1));
340 void HTTPSocket::OnClose()
343 return; // notification that request failed?
345 response->data = data;
350 MODULE_INIT(ModuleHTTPClient)