-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwebserver.cpp
458 lines (416 loc) · 11.3 KB
/
webserver.cpp
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
/**
* webserver.cpp
* This file is part of the YATE Project http://YATE.null.ro
*
* Filesystem access for HTTP server module
*
* Yet Another Telephony Engine - a fully featured software PBX and IVR
* Copyright (C) 2004-2014 Null Team
* Author: Marian Podgoreanu
*
* This software is distributed under multiple licenses;
* see the COPYING file in the main directory for licensing
* information for this specific distribution.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <yatephone.h>
#include <sys/stat.h>
#include <unistd.h>
using namespace TelEngine;
namespace { // anonymous
class WebServer: public GenObject
{
public:
WebServer(const String& name);
~WebServer();
bool received(Message &msg, bool reqdata);
static String guessContentType(const String& path);
private:
String m_name;
};
/**
* YWebServerModule
*/
class YWebServerModule : public Module
{
enum {
HttpRequest = Private,
HttpReqData = (Private << 1),
};
protected:
virtual bool received(Message &msg, int id);
public:
YWebServerModule();
virtual ~YWebServerModule();
virtual void initialize();
private:
WebServer* m_server;
};
class Servant : public RefObject
{
public:
Servant(const String& path, NamedList* cfg);
~Servant();
bool received(Message& msg);
public: // GenObject
void* getObject(const String& name) const;
private:
String m_path;
File m_fh;
NamedList* m_cfg;
};
class DirectoryHandler : public RefObject, public Stream
{
public:
DirectoryHandler(const String& path, NamedList* cfg);
~DirectoryHandler();
bool received(Message& msg);
public: // GenObject
void* getObject(const String& name) const;
public: // Stream
virtual bool terminate();
virtual bool valid() const;
virtual int writeData(const void* buffer, int length);
virtual int readData(void* buffer, int length);
private:
String m_path;
MemoryStream m_file;
NamedList* m_cfg;
};
/**
* Local data
*/
static YWebServerModule plugin;
static Configuration s_cfg;
/**
* WebServer
*/
WebServer::WebServer(const String& name)
: m_name(name)
{
Debug(&plugin, DebugAll, "WebServer '%s' created", m_name.c_str());
}
WebServer::~WebServer()
{
Debug(&plugin, DebugAll, "WebServer '%s' destroyed.", m_name.c_str());
}
String WebServer::guessContentType(const String& path)
{
if(path.endsWith(".png"))
return "image/png";
if(path.endsWith(".jpg") || path.endsWith(".jpeg"))
return "image/jpeg";
if(path.endsWith(".htm") || path.endsWith(".html"))
return "text/html";
if(path.endsWith(".js"))
return "application/x-javascript";
if(path.endsWith(".css"))
return "text/css";
if(path.endsWith(".txt") || path.endsWith(".asc"))
return "text/plain";
return "application/octet-stream";
}
static TelEngine::String guessHandler(const TelEngine::String path)
{
if (path.endsWith("/"))
return "directory";
#ifdef _WINDOWS
struct _stat st;
if (0 != _stat(path.c_str(), &st)) {
#else
struct stat st;
if (0 != stat(path.c_str(), &st)) {
#endif
switch (errno) {
case EACCES: return "error 403";
case ENOENT: return "error 404";
default: return "error 500";
}
}
if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))
return "file";
if (S_ISDIR(st.st_mode))
return "directory";
return "error 500";
}
static void cleanupUri(String& uri)
{
int idx;
while ((idx = uri.find("/../")) >= 0)
uri = uri.substr(0, idx) + uri.substr(idx + 3);
while ((idx = uri.find("/./")) >= 0)
uri = uri.substr(0, idx) + uri.substr(idx + 2);
while ((idx = uri.find("//")) >= 0)
uri = uri.substr(0, idx) + uri.substr(idx + 1);
}
bool WebServer::received(Message &msg, bool reqdata)
{
if (reqdata && ! msg.getBoolValue("reqbody"))
return false;
if (reqdata) // no handlers below accept request data
return false;
/* prepare configuration parameters list */
NamedList* cfg = new NamedList("params");
NamedList* nl;
if ((nl = s_cfg.getSection(YSTRING("default"))))
cfg->copyParams(*nl);
String server = msg.getValue("server");
if ((nl = s_cfg.getSection(server)))
cfg->copyParams(*nl);
if ((nl = s_cfg.getSection(msg.getValue("conf"))))
cfg->copyParams(*nl);
cfg->copyParams(msg);
String handler = msg.getValue("handler", "auto");
String path = msg.getValue("path");
if (! path.length()) {
String uri = msg.getParam("uri");
cleanupUri(uri);
path = cfg->getValue(YSTRING("root"), "/var/www") + uri;
}
if (handler == YSTRING("auto"))
handler = guessHandler(path);
String dumpcfg;
cfg->dump(dumpcfg, ", ");
Debug(&plugin, DebugAll, "WebServer '%s' is serving resource '%s', handler is '%s', cfg: %s", m_name.c_str(), path.c_str(), handler.c_str(), dumpcfg.c_str());
if (handler == YSTRING("file")) {
Servant* s = reinterpret_cast<Servant*>(msg.userObject("Servant"));
if(! s)
s = new Servant(path, cfg);
else
TelEngine::destruct(cfg);
return s->received(msg);
}
if (handler == YSTRING("directory")) {
DirectoryHandler* s = reinterpret_cast<DirectoryHandler*>(msg.userObject("DirectoryHandler"));
if(! s)
s = new DirectoryHandler(path, cfg);
else
TelEngine::destruct(cfg); // noone need it
return s->received(msg);
}
TelEngine::destruct(cfg); // noone need it
if (handler.startSkip("error")) {
msg.setParam("status", handler);
return true;
}
if (handler.startSkip("redirect")) {
const char* status = msg.getValue("status");
if (!status || *status != '3')
msg.setParam("status", "302");
if (handler.find("://") < 0)
handler = YSTRING("http://") + msg.getParam("hdr_Host") + handler;
msg.setParam("ohdr_Location", handler);
return true;
}
if (handler == YSTRING("bulkfile")) {
if(YSTRING("GET") != msg.getValue("method")) {
msg.setParam("status", "405");
return true;
}
if(! File::exists(path)) {
msg.setParam("status", "404");
return true;
}
File f;
if(! f.openPath(path)) {
msg.setParam("status", "403");
return true;
}
int64_t l = f.length();
char buf[l + 1];
f.readData(buf, l);
f.terminate();
buf[l] = '\0';
msg.setParam("status", "200");
msg.setParam("ohdr_Content-Type", guessContentType(path));
msg.retValue() = buf;
return true;
}
return false;
}
/**
* YWebServerModule
*/
YWebServerModule::YWebServerModule()
: Module("webserver","misc")
, m_server(NULL)
{
Output("Loaded module WebServer");
}
YWebServerModule::~YWebServerModule()
{
Output("Unloading module WebServer");
TelEngine::destruct(m_server);
}
void YWebServerModule::initialize()
{
static bool notFirst = false;
Output("Initializing module WebServer");
// Load configuration
s_cfg = Engine::configFile("webserver");
s_cfg.load();
TelEngine::destruct(m_server);
m_server = new WebServer("WebServer");
if (notFirst)
return;
notFirst = true;
installRelay(HttpRequest, "http.serve", 150);
installRelay(HttpReqData, "http.preserve", 150);
setup();
}
bool YWebServerModule::received(Message &msg, int id)
{
if(! m_server)
return false;
switch(id) {
case HttpRequest:
return m_server->received(msg, false);
case HttpReqData:
return m_server->received(msg, true);
}
return Module::received(msg, id);
}
/**
* Servant
*/
Servant::Servant(const String& path, NamedList* cfg)
: m_path(path)
, m_cfg(cfg)
{
XDebug(&plugin, DebugAll, "Servant %p created, path: '%s'", this, m_path.c_str());
}
Servant::~Servant()
{
XDebug(&plugin, DebugAll, "Servant %p destroyed, path: '%s'", this, m_path.c_str());
TelEngine::destruct(m_cfg);
}
void* Servant::getObject(const String& name) const
{
if (name == YATOM("Stream"))
return const_cast<File*>(&m_fh);
if (name == YATOM("Servant"))
return const_cast<Servant*>(this);
return RefObject::getObject(name);
}
bool Servant::received(Message& msg)
{
XDebug(&plugin, DebugAll, "Servant %p got message '%s'", this, msg.c_str());
if(! File::exists(m_path)) {
Debug(&plugin, DebugInfo, "File '%s' does not exist", m_path.c_str());
msg.setParam("status", "404");
return true;
}
if(YSTRING("GET") != msg.getValue("method")) {
msg.setParam("status", "405");
return true;
}
if(! m_fh.openPath(m_path)) {
TelEngine::String error;
Thread::errorString(error,m_fh.error());
Debug(&plugin, DebugWarn, "Can not open File '%s': %s", m_path.c_str(), error.c_str());
switch(m_fh.error()) {
#ifdef _WINDOWS
case ERROR_FILE_NOT_FOUND:
case ERROR_PATH_NOT_FOUND: msg.setParam("status", "404"); break;
case ERROR_ACCESS_DENIED: msg.setParam("status", "403"); break;
#else
case EACCES: msg.setParam("status", "403"); break;
case ENOENT: msg.setParam("status", "404"); break;
#endif
default: msg.setParam("status", "500"); break;
}
return true;
}
int64_t l = m_fh.length();
msg.setParam("status", "200");
msg.userData(this);
msg.setParam("ohdr_Content-Type", WebServer::guessContentType(m_path));
msg.setParam("ohdr_Content-Length", String(l));
msg.retValue() = String::empty();
deref();
return true;
}
/*
* DirectoryHandler
*/
DirectoryHandler::DirectoryHandler(const String& path, NamedList* cfg)
: m_path(path)
, m_cfg(cfg)
{
}
DirectoryHandler::~DirectoryHandler()
{
TelEngine::destruct(m_cfg);
}
bool DirectoryHandler::received(Message& msg)
{
if (! m_cfg->getBoolValue("dirlist", false)) {
msg.setParam("status", "403");
msg.retValue() = "Directory listing denied";
return true;
}
ObjList dirs, files;
int error;
if (! File::listDirectory(m_path, &dirs, &files, &error)) {
TelEngine::String s;
Thread::errorString(s,error);
Debug(&plugin,DebugNote,"Failed to list directory '%s': %d %s",
m_path.c_str(),error,s.c_str());
msg.setParam("status", "400");
return true;
}
TelEngine::String s;
for (ObjList* o = dirs.skipNull(); o; o = o->skipNext()) {
String* n = static_cast<String*>(o->get());
if (!*n)
continue;
s << " * " << *n << "/\r\n";
}
for (ObjList* o = files.skipNull(); o; o = o->skipNext()) {
String* n = static_cast<String*>(o->get());
if (!*n)
continue;
s << " * " << *n << "\r\n";
}
m_file.writeData(s.c_str(), s.length());
m_file.seek(Stream::SeekBegin, 0);
msg.setParam("status", "200");
msg.userData(this);
msg.setParam("ohdr_Content-Type", "text/plain");
msg.setParam("ohdr_Content-Length", TelEngine::String(m_file.length()));
msg.retValue() = String::empty();
deref();
return true;
}
void* DirectoryHandler::getObject(const String& name) const
{
if (name == YATOM("Stream"))
return static_cast<Stream*>(const_cast<DirectoryHandler*>(this));
if (name == YATOM("Servant"))
return const_cast<DirectoryHandler*>(this);
return RefObject::getObject(name);
}
bool DirectoryHandler::terminate()
{
return m_file.terminate();
}
bool DirectoryHandler::valid() const
{
return m_file.valid();
}
int DirectoryHandler::writeData(const void* buffer, int length)
{
return 0;
}
int DirectoryHandler::readData(void* buffer, int length)
{
return m_file.readData(buffer, length);
}
}; // anonymous namespace
/* vi: set ts=8 sw=4 sts=4 noet: */