summaryrefslogtreecommitdiff
path: root/modules/m_httpd.cpp
blob: 7d8055a3662f07a0582c4ce477d8b6cb6eb8d801 (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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/*
 *
 * (C) 2003-2017 Anope Team
 * Contact us at team@anope.org
 *
 * Please read COPYING and README for further details.
 */

#include "module.h"
#include "modules/httpd.h"
#include "modules/ssl.h"

static Anope::string BuildDate()
{
	char timebuf[64];
	struct tm *tm = localtime(&Anope::CurTime);
	strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S %Z", tm);
	return timebuf;
}

static Anope::string GetStatusFromCode(HTTPError err)
{
	switch (err)
	{
		case HTTP_ERROR_OK:
			return "200 OK";
		case HTTP_FOUND:
			return "302 Found";
		case HTTP_BAD_REQUEST:
			return "400 Bad Request";
		case HTTP_PAGE_NOT_FOUND:
			return "404 Not Found";
		case HTTP_NOT_SUPPORTED:
			return "505 HTTP Version Not Supported";
	}

	return "501 Not Implemented";
}

class MyHTTPClient : public HTTPClient
{
	HTTPProvider *provider;
	HTTPMessage message;
	bool header_done, served;
	Anope::string page_name;
	Reference<HTTPPage> page;
	Anope::string ip;

	unsigned content_length;

	enum
	{
		ACTION_NONE,
		ACTION_GET,
		ACTION_POST
	} action;

	void Serve()
	{
		if (this->served)
			return;
		this->served = true;

		if (!this->page)
		{
			this->SendError(HTTP_PAGE_NOT_FOUND, "Page not found");
			return;
		}

		if (this->ip == this->provider->ext_ip)
		{
			for (unsigned i = 0; i < this->provider->ext_headers.size(); ++i)
			{
				const Anope::string &token = this->provider->ext_headers[i];

				if (this->message.headers.count(token))
				{
					this->ip = this->message.headers[token];
					Log(LOG_DEBUG, "httpd") << "m_httpd: IP for connection " << this->GetFD() << " changed to " << this->ip;
					break;
				}
			}
		}

		Log(LOG_DEBUG, "httpd") << "m_httpd: Serving page " << this->page_name << " to " << this->ip;

		HTTPReply reply;
		reply.content_type = this->page->GetContentType();

		if (this->page->OnRequest(this->provider, this->page_name, this, this->message, reply))
			this->SendReply(&reply);
	}

 public:
	time_t created;

	MyHTTPClient(HTTPProvider *l, int f, const sockaddrs &a) : Socket(f, l->IsIPv6()), HTTPClient(l, f, a), provider(l), header_done(false), served(false), ip(a.addr()), content_length(0), action(ACTION_NONE), created(Anope::CurTime)
	{
		Log(LOG_DEBUG, "httpd") << "Accepted connection " << f << " from " << a.addr();
	}

	~MyHTTPClient()
	{
		Log(LOG_DEBUG, "httpd") << "Closing connection " << this->GetFD() << " from " << this->ip;
	}

	/* Close connection once all data is written */
	bool ProcessWrite() anope_override
	{
		return !BinarySocket::ProcessWrite() || this->write_buffer.empty() ? false : true;
	}

	const Anope::string GetIP() anope_override
	{
		return this->ip;
	}

	bool Read(const char *buffer, size_t l) anope_override
	{
		message.content.append(buffer, l);

		for (size_t nl; !this->header_done && (nl = message.content.find('\n')) != Anope::string::npos;)
		{
			Anope::string token = message.content.substr(0, nl).trim();
			message.content = message.content.substr(nl + 1);

			if (token.empty())
				this->header_done = true;
			else
				this->Read(token);
		}

		if (!this->header_done)
			return true;

		if (this->message.content.length() >= this->content_length)
		{
			sepstream sep(this->message.content, '&');
			Anope::string token;

			while (sep.GetToken(token))
			{
				size_t sz = token.find('=');
				if (sz == Anope::string::npos || !sz || sz + 1 >= token.length())
					continue;
				this->message.post_data[token.substr(0, sz)] = HTTPUtils::URLDecode(token.substr(sz + 1));
				Log(LOG_DEBUG_2) << "HTTP POST from " << this->clientaddr.addr() << ": " << token.substr(0, sz) << ": " << this->message.post_data[token.substr(0, sz)];
			}

			this->Serve();
		}
		
		return true;
	}

	bool Read(const Anope::string &buf)
	{
		Log(LOG_DEBUG_2) << "HTTP from " << this->clientaddr.addr() << ": " << buf;

		if (this->action == ACTION_NONE)
		{
			std::vector<Anope::string> params;
			spacesepstream(buf).GetTokens(params);

			if (params.empty() || (params[0] != "GET" && params[0] != "POST"))
			{
				this->SendError(HTTP_BAD_REQUEST, "Unknown operation");
				return true;
			}

			if (params.size() != 3)
			{
				this->SendError(HTTP_BAD_REQUEST, "Invalid parameters");
				return true;
			}

			if (params[0] == "GET")
				this->action = ACTION_GET;
			else if (params[0] == "POST")
				this->action = ACTION_POST;

			Anope::string targ = params[1];
			size_t q = targ.find('?');
			if (q != Anope::string::npos)
			{
				sepstream sep(targ.substr(q + 1), '&');
				targ = targ.substr(0, q);

				Anope::string token;
				while (sep.GetToken(token))
				{
					size_t sz = token.find('=');
					if (sz == Anope::string::npos || !sz || sz + 1 >= token.length())
						continue;
					this->message.get_data[token.substr(0, sz)] = HTTPUtils::URLDecode(token.substr(sz + 1));
				}
			}

			this->page = this->provider->FindPage(targ);
			this->page_name = targ;
		}
		else if (buf.find("Cookie: ") == 0)
		{
			spacesepstream sep(buf.substr(8));
			Anope::string token;

			while (sep.GetToken(token))
			{
				size_t sz = token.find('=');
				if (sz == Anope::string::npos || !sz || sz + 1 >= token.length())
					continue;
				size_t end = token.length() - (sz + 1);
				if (!sep.StreamEnd())
					--end; // Remove trailing ;
				this->message.cookies[token.substr(0, sz)] = token.substr(sz + 1, end);
			}
		}
		else if (buf.find("Content-Length: ") == 0)
		{
			try
			{
				this->content_length = convertTo<unsigned>(buf.substr(16));
			}
			catch (const ConvertException &ex) { }
		}
		else if (buf.find(':') != Anope::string::npos)
		{
			size_t sz = buf.find(':');
			if (sz + 2 < buf.length())
				this->message.headers[buf.substr(0, sz)] = buf.substr(sz + 2);
		}

		return true;
	}

	void SendError(HTTPError err, const Anope::string &msg) anope_override
	{
		HTTPReply h;

		h.error = err;

		h.Write(msg);

		this->SendReply(&h);
	}

	void SendReply(HTTPReply *msg) anope_override
	{
		this->WriteClient("HTTP/1.1 " + GetStatusFromCode(msg->error));
		this->WriteClient("Date: " + BuildDate());
		this->WriteClient("Server: Anope-" + Anope::VersionShort());
		if (msg->content_type.empty())
			this->WriteClient("Content-Type: text/html");
		else
			this->WriteClient("Content-Type: " + msg->content_type);
		this->WriteClient("Content-Length: " + stringify(msg->length));

		for (unsigned i = 0; i < msg->cookies.size(); ++i)
		{
			Anope::string buf = "Set-Cookie:";

			for (HTTPReply::cookie::iterator it = msg->cookies[i].begin(), it_end = msg->cookies[i].end(); it != it_end; ++it)
				buf += " " + it->first + "=" + it->second + ";";

			buf.erase(buf.length() - 1);

			this->WriteClient(buf);
		}

		typedef std::map<Anope::string, Anope::string> map;
		for (map::iterator it = msg->headers.begin(), it_end = msg->headers.end(); it != it_end; ++it)
			this->WriteClient(it->first + ": " + it->second);

		this->WriteClient("Connection: Close");
		this->WriteClient("");

		for (unsigned i = 0; i < msg->out.size(); ++i)
		{
			HTTPReply::Data* d = msg->out[i];

			this->Write(d->buf, d->len);

			delete d;
		}

		msg->out.clear();
	}
};

class MyHTTPProvider : public HTTPProvider, public Timer
{
	int timeout;
	std::map<Anope::string, HTTPPage *> pages;
	std::list<Reference<MyHTTPClient> > clients;

 public:
	MyHTTPProvider(Module *c, const Anope::string &n, const Anope::string &i, const unsigned short p, const int t, bool s) : Socket(-1, i.find(':') != Anope::string::npos), HTTPProvider(c, n, i, p, s), Timer(c, 10, Anope::CurTime, true), timeout(t) { }

	void Tick(time_t) anope_override
	{
		while (!this->clients.empty())
		{
			Reference<MyHTTPClient>& c = this->clients.front();
			if (c && c->created + this->timeout >= Anope::CurTime)
				break;

			delete c;
			this->clients.pop_front();
		}
	}

	ClientSocket* OnAccept(int fd, const sockaddrs &addr) anope_override
	{
		MyHTTPClient *c = new MyHTTPClient(this, fd, addr);
		this->clients.push_back(c);
		return c;
	}

	bool RegisterPage(HTTPPage *page) anope_override
	{
		return this->pages.insert(std::make_pair(page->GetURL(), page)).second;
	}

	void UnregisterPage(HTTPPage *page) anope_override
	{
		this->pages.erase(page->GetURL());
	}

	HTTPPage* FindPage(const Anope::string &pname)
	{
		if (this->pages.count(pname) == 0)
			return NULL;
		return this->pages[pname];
	}
};

class HTTPD : public Module
{
	ServiceReference<SSLService> sslref;
	std::map<Anope::string, MyHTTPProvider *> providers;
 public:
	HTTPD(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, EXTRA | VENDOR), sslref("SSLService", "ssl")
	{

	}

	~HTTPD()
	{
		for (std::map<int, Socket *>::const_iterator it = SocketEngine::Sockets.begin(), it_end = SocketEngine::Sockets.end(); it != it_end;)
		{
			Socket *s = it->second;
			++it;

			if (dynamic_cast<MyHTTPProvider *>(s) || dynamic_cast<MyHTTPClient *>(s))
				delete s;
		}

		this->providers.clear();
	}

	void OnReload(Configuration::Conf *config) anope_override
	{
		Configuration::Block *conf = config->GetModule(this);
		std::set<Anope::string> existing;

		for (int i = 0; i < conf->CountBlock("httpd"); ++i)
		{
			Configuration::Block *block = conf->GetBlock("httpd", i);


			const Anope::string &hname = block->Get<const Anope::string>("name", "httpd/main");
			existing.insert(hname);

			Anope::string ip = block->Get<const Anope::string>("ip");
			int port = block->Get<int>("port", "8080");
			int timeout = block->Get<int>("timeout", "30");
			bool ssl = block->Get<bool>("ssl", "no");
			Anope::string ext_ip = block->Get<const Anope::string>("extforward_ip");
			Anope::string ext_header = block->Get<const Anope::string>("extforward_header");

			if (ip.empty())
			{
				Log(this) << "You must configure a bind IP for HTTP server " << hname;
				continue;
			}
			else if (port <= 0 || port > 65535)
			{
				Log(this) << "You must configure a (valid) listen port for HTTP server " << hname;
				continue;
			}

			MyHTTPProvider *p;
			if (this->providers.count(hname) == 0)
			{
				try
				{
					p = new MyHTTPProvider(this, hname, ip, port, timeout, ssl);
					if (ssl && sslref)
						sslref->Init(p);
				}
				catch (const SocketException &ex)
				{
					Log(this) << "Unable to create HTTP server " << hname << ": " << ex.GetReason();
					continue;
				}
				this->providers[hname] = p;

				Log(this) << "Created HTTP server " << hname;
			}
			else
			{
				p = this->providers[hname];

				if (p->GetIP() != ip || p->GetPort() != port)
				{
					delete p;
					this->providers.erase(hname);

					Log(this) << "Changing HTTP server " << hname << " to " << ip << ":" << port;

					try
					{
						p = new MyHTTPProvider(this, hname, ip, port, timeout, ssl);
						if (ssl && sslref)
							sslref->Init(p);
					}
					catch (const SocketException &ex)
					{
						Log(this) << "Unable to create HTTP server " << hname << ": " << ex.GetReason();
						continue;
					}

					this->providers[hname] = p;
				}
			}


			p->ext_ip = ext_ip;
			spacesepstream(ext_header).GetTokens(p->ext_headers);
		}

		for (std::map<Anope::string, MyHTTPProvider *>::iterator it = this->providers.begin(), it_end = this->providers.end(); it != it_end;)
		{
			HTTPProvider *p = it->second;
			++it;

			if (existing.count(p->name) == 0)
			{
				Log(this) << "Removing HTTP server " << p->name;
				this->providers.erase(p->name);
				delete p;
			}
		}
	}

	void OnModuleLoad(User *u, Module *m) anope_override
	{
		for (std::map<Anope::string, MyHTTPProvider *>::iterator it = this->providers.begin(), it_end = this->providers.end(); it != it_end; ++it)
		{
			MyHTTPProvider *p = it->second;

			if (p->IsSSL() && sslref)
				try
				{
					sslref->Init(p);
				}
				catch (const CoreException &) { } // Throws on reinitialization
		}
	}
};

MODULE_INIT(HTTPD)