summaryrefslogtreecommitdiff
path: root/src/modules/m_http_client.cpp
blob: 0ca302ef6ac792f0605ce2c0673c1ca9c7573129 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/*       +------------------------------------+
 *       | Inspire Internet Relay Chat Daemon |
 *       +------------------------------------+
 *
 *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
 *                       E-mail:
 *                <brain@chatspike.net>
 *           	  <Craig@chatspike.net>
 *     
 * Written by Craig Edwards, Craig McLure, and others.
 * This program is free but copyrighted software; see
 *            the file COPYING for details.
 *
 * ---------------------------------------------------
 */

/* Written by Special (john@yarbbles.com) */

#include "inspircd.h"
#include "httpclient.h"

/* $ModDesc: HTTP client service provider */

class URL
{
 public:
	std::string url;
	std::string protocol, username, password, domain, request;
	int port;
};

class HTTPSocket : public InspSocket
{
 private:
	InspIRCd *Server;
	class ModuleHTTPClient *Mod;
	HTTPClientRequest req;
	HTTPClientResponse *response;
	URL url;
	enum { HTTP_CLOSED, HTTP_REQSENT, HTTP_HEADERS, HTTP_DATA } status;
	std::string data;

 public:
	HTTPSocket(InspIRCd *Instance, class ModuleHTTPClient *Mod);
	virtual ~HTTPSocket();
	virtual bool DoRequest(HTTPClientRequest *req);
	virtual bool ParseURL(const std::string &url);
	virtual void Connect(const std::string &ip);
	virtual bool OnConnected();
	virtual bool OnDataReady();
	virtual void OnClose();
};

class HTTPResolver : public Resolver
{
 private:
	HTTPSocket *socket;
 public:
	HTTPResolver(HTTPSocket *socket, InspIRCd *Instance, const string &hostname) : Resolver(Instance, hostname, DNS_QUERY_FORWARD), socket(socket)
	{
	}
	
	void OnLookupComplete(const string &result, unsigned int ttl)
	{
		socket->Connect(result);
	}
	
	void OnError(ResolverError e, const string &errmsg)
	{
		delete socket;
	}
};

typedef vector<HTTPSocket*> HTTPList;

class ModuleHTTPClient : public Module
{
 public:
	HTTPList sockets;

	ModuleHTTPClient(InspIRCd *Me)
		: Module::Module(Me)
	{
	}
	
	virtual ~ModuleHTTPClient()
	{
		for (HTTPList::iterator i = sockets.begin(); i != sockets.end(); i++)
			delete *i;
	}
	
	virtual Version GetVersion()
	{
		return Version(1, 0, 0, 0, VF_SERVICEPROVIDER | VF_VENDOR, API_VERSION);
	}

	void Implements(char* List)
	{
		List[I_OnRequest] = 1;
	}

	char* OnRequest(Request *req)
	{
		HTTPClientRequest *httpreq = (HTTPClientRequest *)req;
		if (!strcmp(httpreq->GetId(), HTTP_CLIENT_REQUEST))
		{
			HTTPSocket *sock = new HTTPSocket(ServerInstance, this);
			sock->DoRequest(httpreq);
			// No return value
		}
		return NULL;
	}
};

HTTPSocket::HTTPSocket(InspIRCd *Instance, ModuleHTTPClient *Mod)
		: InspSocket(Instance), Server(Instance), Mod(Mod), status(HTTP_CLOSED)
{
	this->ClosePending = false;
	this->port = 80;
}

HTTPSocket::~HTTPSocket()
{
	Close();
	for (HTTPList::iterator i = Mod->sockets.begin(); i != Mod->sockets.end(); i++)
	{
		if (*i == this)
		{
			Mod->sockets.erase(i);
			break;
		}
	}
}

bool HTTPSocket::DoRequest(HTTPClientRequest *req)
{
	/* Tweak by brain - we take a copy of this,
	 * so that the caller doesnt need to leave
	 * pointers knocking around, less chance of
	 * a memory leak.
	 */
	this->req = *req;

	if (!ParseURL(this->req.GetURL()))
		return false;
	
	this->port = url.port;
	strlcpy(this->host, url.domain.c_str(), MAXBUF);

	if (!inet_aton(this->host, &this->addy))
	{
		new HTTPResolver(this, Server, url.domain);
		return true;
	}
	else
	{
		this->Connect(url.domain);
	}
	
	return true;
}

bool HTTPSocket::ParseURL(const std::string &iurl)
{
	url.url = iurl;
	url.port = 80;
	
	// Tokenize by slashes (protocol:, blank, domain, request..)
	int pos = 0, pstart = 0, pend = 0;
	
	for (; ; pend = url.url.find('/', pstart))
	{
		string part = url.url.substr(pstart, pend);

		switch (pos)
		{
			case 0:
				// Protocol
				if (part[part.length()-1] != ':')
					return false;
				url.protocol = part.substr(0, part.length() - 1);
				break;
			case 1:
				// Empty, skip
				break;
			case 2:
				// User and password (user:pass@)
				string::size_type aend = part.find('@', 0);
				if (aend != string::npos)
				{
					// Technically, it is valid to not have a password (username@domain)
					string::size_type usrend = part.find(':', 0);
					
					if ((usrend != string::npos) && (usrend < aend))
						url.password = part.substr(usrend + 1, aend);
					else
						usrend = aend;
					
					url.username = part.substr(0, usrend);
				}
				else
					aend = 0;
				
				// Port (:port)
				string::size_type dend = part.find(':', aend);
				if (dend != string::npos)
					url.port = atoi(part.substr(dend + 1).c_str());

				// Domain
				url.domain = part.substr(aend + 1, dend);
				
				// The rest of the string is the request
				url.request = url.url.substr(pend);
				break;
		}
		
		if (pos++ == 2)
			break;

		pstart = pend + 1;
	}
	
	return true;
}

void HTTPSocket::Connect(const string &ip)
{
	strlcpy(this->IP, ip.c_str(), MAXBUF);
	
	if (!this->DoConnect())
	{
		Server->Log(DEBUG, "Unable to connect HTTPSocket to %s", this->host);
		delete this;
	}
}

bool HTTPSocket::OnConnected()
{
	std::string request = "GET " + url.request + " HTTP/1.1\r\n";

	// Dump headers into the request
	HeaderMap headers = req.GetHeaders();
	
	for (HeaderMap::iterator i = headers.begin(); i != headers.end(); i++)
		request += i->first + ": " + i->second + "\r\n";

	// The Host header is required for HTTP 1.1 and isn't known when the request is created; if they didn't overload it
	// manually, add it here
	if (headers.find("Host") == headers.end())
		request += "Host: " + url.domain + "\r\n"; 
	
	request += "\r\n";
	
	this->status = HTTP_REQSENT;
	
	return this->Write(request);
}

bool HTTPSocket::OnDataReady()
{
	char *data = this->Read();

	if (!data)
	{
		this->Close();
		return false;
	}
	
	// Needs buffering for incomplete reads..
	char *lend;
	
	if (this->status < HTTP_DATA)
	{
		while ((lend = strstr(data, "\r\n")) != NULL)
		{
			if (strncmp(data, "\r\n", 2) == 0)
			{
				this->status = HTTP_DATA;
				break;
			}
			
			*lend = '\0';
			
			if (this->status == HTTP_REQSENT)
			{
				// HTTP reply (HTTP/1.1 200 msg)
				data += 9;
				response = new HTTPClientResponse((Module*)Mod, req.GetSource() , url.url, atoi(data), data + 4);
				this->status = HTTP_HEADERS;
				continue;
			}
			
			char *hdata = strchr(data, ':');
			
			if (!hdata)
				continue;
			
			*hdata = '\0';
			
			response->AddHeader(data, hdata + 2);
			
			data = lend + 2;
		}
	}
	
	this->data += data;
	return true;
}

void HTTPSocket::OnClose()
{
	if (!data.length())
	{
		Server->Log(DEBUG, "HTTP socket closed unexpectedly (no content recieved)");
		return;
	}
	Server->Log(DEBUG, "Got file from HTTP successfully");
	response->data = data;
	response->Send();
	delete response;
}

class ModuleHTTPClientFactory : public ModuleFactory
{
 public:
	ModuleHTTPClientFactory()
	{
	}
	
	~ModuleHTTPClientFactory()
	{
	}
	
	Module *CreateModule(InspIRCd* Me)
	{
		return new ModuleHTTPClient(Me);
	}
};

extern "C" void *init_module(void)
{
	return new ModuleHTTPClientFactory;
}