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");
73 /*if (ServerInstance->SocketCull.find(socket) == ServerInstance->SocketCull.end())
74 ServerInstance->SocketCull[socket] = socket;*/
78 typedef vector<HTTPSocket*> HTTPList;
80 class ModuleHTTPClient : public Module
85 ModuleHTTPClient(InspIRCd *Me)
88 Implementation eventlist[] = { I_OnRequest };
89 ServerInstance->Modules->Attach(eventlist, this, 1);
92 virtual ~ModuleHTTPClient()
94 for (HTTPList::iterator i = sockets.begin(); i != sockets.end(); i++)
98 virtual Version GetVersion()
100 return Version(1, 0, 0, 0, VF_SERVICEPROVIDER | VF_VENDOR, API_VERSION);
104 char* OnRequest(Request *req)
106 HTTPClientRequest *httpreq = (HTTPClientRequest *)req;
107 if (!strcmp(httpreq->GetId(), HTTP_CLIENT_REQUEST))
109 HTTPSocket *sock = new HTTPSocket(ServerInstance, this);
110 sock->DoRequest(httpreq);
117 HTTPSocket::HTTPSocket(InspIRCd *Instance, ModuleHTTPClient *Mod)
118 : BufferedSocket(Instance), Server(Instance), Mod(Mod), status(HTTP_CLOSED)
120 Instance->Log(DEBUG,"HTTPSocket::HTTPSocket");
124 HTTPSocket::~HTTPSocket()
127 for (HTTPList::iterator i = Mod->sockets.begin(); i != Mod->sockets.end(); i++)
131 Mod->sockets.erase(i);
137 bool HTTPSocket::DoRequest(HTTPClientRequest *req)
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
147 if (!ParseURL(this->req.GetURL()))
150 this->port = url.port;
151 strlcpy(this->host, url.domain.c_str(), MAXBUF);
154 HTTPResolver* r = new HTTPResolver(this, Server, url.domain, cached, (Module*)Mod);
155 Instance->AddResolver(r, cached);
161 bool HTTPSocket::ParseURL(const std::string &iurl)
163 Instance->Log(DEBUG,"HTTPSocket::ParseURL");
166 url.protocol = "http";
168 irc::sepstream tokenizer(iurl, '/');
170 for (int p = 0;; p++)
173 if (!tokenizer.GetToken(part))
176 if ((p == 0) && (part[part.length() - 1] == ':'))
178 // Protocol ('http:')
179 url.protocol = part.substr(0, part.length() - 1);
181 else if ((p == 1) && (part.empty()))
185 else if (url.domain.empty())
187 // Domain part: [user[:pass]@]domain[:port]
188 std::string::size_type usrpos = part.find('@');
189 if (usrpos != std::string::npos)
191 // Have a user (and possibly password) part
192 std::string::size_type ppos = part.find(':');
193 if ((ppos != std::string::npos) && (ppos < usrpos))
196 url.password = part.substr(ppos + 1, usrpos - ppos - 1);
197 url.username = part.substr(0, ppos);
201 url.username = part.substr(0, usrpos);
204 part = part.substr(usrpos + 1);
207 std::string::size_type popos = part.rfind(':');
208 if (popos != std::string::npos)
210 url.port = atoi(part.substr(popos + 1).c_str());
211 url.domain = part.substr(0, popos);
220 // Request (part of it)..
221 url.request.append("/");
222 url.request.append(part);
226 if (url.request.empty())
229 if ((url.domain.empty()) || (!url.port) || (url.protocol.empty()))
231 Instance->Log(DEFAULT, "Invalid URL (%s): Missing required value", iurl.c_str());
235 if (url.protocol != "http")
237 Instance->Log(DEFAULT, "Invalid URL (%s): Unsupported protocol '%s'", iurl.c_str(), url.protocol.c_str());
244 void HTTPSocket::Connect(const string &ip)
246 Instance->Log(DEBUG,"HTTPSocket::Connect");
247 strlcpy(this->IP, ip.c_str(), MAXBUF);
249 if (!this->DoConnect())
255 bool HTTPSocket::OnConnected()
257 std::string request = "GET " + url.request + " HTTP/1.1\r\n";
259 // Dump headers into the request
260 HeaderMap headers = req.GetHeaders();
262 for (HeaderMap::iterator i = headers.begin(); i != headers.end(); i++)
263 request += i->first + ": " + i->second + "\r\n";
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";
272 this->status = HTTP_REQSENT;
274 return this->Write(request);
277 bool HTTPSocket::OnDataReady()
279 Instance->Log(DEBUG,"HTTPSocket::OnDataReady()");
280 char *data = this->Read();
285 if (this->status < HTTP_DATA)
288 std::string::size_type pos;
290 this->buffer += data;
291 while ((pos = buffer.find("\r\n")) != std::string::npos)
293 line = buffer.substr(0, pos);
294 buffer = buffer.substr(pos + 2);
297 this->status = HTTP_DATA;
298 this->data += this->buffer;
299 this->buffer.clear();
303 if (this->status == HTTP_REQSENT)
305 // HTTP reply (HTTP/1.1 200 msg)
306 char const* data = line.c_str();
308 response = new HTTPClientResponse((Module*)Mod, req.GetSource() , url.url, atoi(data), data + 4);
309 this->status = HTTP_HEADERS;
313 if ((pos = line.find(':')) != std::string::npos)
315 response->AddHeader(line.substr(0, pos), line.substr(pos + 1));
330 void HTTPSocket::OnClose()
332 Instance->Log(DEBUG,"HTTPSocket::OnClose");
334 return; // notification that request failed?
336 response->data = data;
341 MODULE_INIT(ModuleHTTPClient)