summaryrefslogtreecommitdiffstats
path: root/lib/libUPnP/Neptune/Source/Apps/ZipHttpServer/ZipHttpServer.cpp
blob: 65343a16c75ca8177bd47725e4ecedb588d0970b (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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
/*****************************************************************
|
|      Virtual ZIP file HTTP Server
|
|      (c) 2001-2014 Gilles Boccon-Gibod
|      Author: Gilles Boccon-Gibod (bok@bok.net)
|
 ****************************************************************/

/*----------------------------------------------------------------------
|       includes
+---------------------------------------------------------------------*/
#include "Neptune.h"

/*----------------------------------------------------------------------
|   logging
+---------------------------------------------------------------------*/
NPT_SET_LOCAL_LOGGER("neptune.ziphttpserver")

/*----------------------------------------------------------------------
|   GetContentType
+---------------------------------------------------------------------*/
struct FileTypeMapEntry {
    const char* extension;
    const char* mime_type;
};
static const FileTypeMapEntry
DefaultFileTypeMap[] = {
    {"xml",  "text/xml"  },
    {"htm",  "text/html" },
    {"html", "text/html" },
    {"c",    "text/plain"},
    {"h",    "text/plain"},
    {"txt",  "text/plain"},
    {"css",  "text/css"  },
    {"gif",  "image/gif" },
    {"thm",  "image/jpeg"},
    {"png",  "image/png"},
    {"tif",  "image/tiff"},
    {"tiff", "image/tiff"},
    {"jpg",  "image/jpeg"},
    {"jpeg", "image/jpeg"},
    {"jpe",  "image/jpeg"},
    {"jp2",  "image/jp2" },
    {"png",  "image/png" },
    {"bmp",  "image/bmp" },
    {"aif",  "audio/x-aiff"},
    {"aifc", "audio/x-aiff"},
    {"aiff", "audio/x-aiff"},
    {"mpa",  "audio/mpeg"},
    {"mp2",  "audio/mpeg"},
    {"mp3",  "audio/mpeg"},
    {"m4a",  "audio/mp4"},
    {"wma",  "audio/x-ms-wma"},
    {"wav",  "audio/x-wav"},
    {"mpeg", "video/mpeg"},
    {"mpg",  "video/mpeg"},
    {"mp4",  "video/mp4"},
    {"m4v",  "video/mp4"},
    {"m4f",  "video/mp4"},
    {"m4s",  "video/mp4"},
    {"ts",   "video/MP2T"}, // RFC 3555
    {"mov",  "video/quicktime"},
    {"wmv",  "video/x-ms-wmv"},
    {"asf",  "video/x-ms-asf"},
    {"avi",  "video/x-msvideo"},
    {"divx", "video/x-msvideo"},
    {"xvid", "video/x-msvideo"},
    {"doc",  "application/msword"},
    {"js",   "application/javascript"},
    {"m3u8", "application/x-mpegURL"},
    {"pdf",  "application/pdf"},
    {"ps",   "application/postscript"},
    {"eps",  "application/postscript"},
    {"zip",  "application/zip"},
    {"mpd",  "application/dash+xml"}
};

NPT_Map<NPT_String, NPT_String> FileTypeMap;

static const char*
GetContentType(const NPT_String& filename)
{
    int last_dot = filename.ReverseFind('.');
    if (last_dot > 0) {
        NPT_String extension = filename.GetChars()+last_dot+1;
        extension.MakeLowercase();
        
        NPT_String* mime_type;
        if (NPT_SUCCEEDED(FileTypeMap.Get(extension, mime_type))) {
            return mime_type->GetChars();
        }
    }

    return "application/octet-stream";
}

/*----------------------------------------------------------------------
|   ZipRequestHandler
+---------------------------------------------------------------------*/
class ZipRequestHandler : public NPT_HttpRequestHandler
{
public:
    // constructors
    ZipRequestHandler(const char* url_root,
                      const char* file_root) :
        m_UrlRoot(url_root),
        m_FileRoot(file_root) {}

    // NPT_HttpRequestHandler methods
    virtual NPT_Result SetupResponse(NPT_HttpRequest&              request, 
                                     const NPT_HttpRequestContext& context,
                                     NPT_HttpResponse&             response);

private:
    NPT_String m_UrlRoot;
    NPT_String m_FileRoot;
};

/*----------------------------------------------------------------------
|   ZipRequestHandler::SetupResponse
+---------------------------------------------------------------------*/
NPT_Result
ZipRequestHandler::SetupResponse(NPT_HttpRequest&              request, 
                                 const NPT_HttpRequestContext& /*context*/,
                                 NPT_HttpResponse&             response)
{
    NPT_HttpEntity* entity = response.GetEntity();
    if (entity == NULL) return NPT_ERROR_INVALID_STATE;

    // check the method
    if (request.GetMethod() != NPT_HTTP_METHOD_GET &&
        request.GetMethod() != NPT_HTTP_METHOD_HEAD) {
        response.SetStatus(405, "Method Not Allowed");
        return NPT_SUCCESS;
    }

    // set some default headers
    response.GetHeaders().SetHeader(NPT_HTTP_HEADER_ACCEPT_RANGES, "bytes");

    // declare HTTP/1.1 if the client asked for it
    if (request.GetProtocol() == NPT_HTTP_PROTOCOL_1_1) {
        response.SetProtocol(NPT_HTTP_PROTOCOL_1_1);
    }
    
    // default status
    response.SetStatus(404, "Not Found");

    // check that the request's path is an entry under the url root
    if (!request.GetUrl().GetPath().StartsWith(m_UrlRoot)) {
        return NPT_ERROR_INVALID_PARAMETERS;
    }

    // compute the path relative to the URL root
    NPT_String relative_path = NPT_Url::PercentDecode(request.GetUrl().GetPath().GetChars()+m_UrlRoot.GetLength());
    
    // check that there is no '..' in the path, for security reasons
    if (relative_path.Find("..") >= 0) {
        NPT_LOG_INFO(".. in path is not supported");
        return NPT_SUCCESS;
    }
    // check that the path does not end with a /
    if (relative_path.EndsWith("/")) {
        NPT_LOG_INFO("skipping paths that end in /");
        return NPT_SUCCESS;
    }
    NPT_List<NPT_String> path_parts = relative_path.Split("/");
    
    // walk down the path until we find a file
    NPT_String path = m_FileRoot;
    NPT_String subpath;
    NPT_List<NPT_String>::Iterator fragment = path_parts.GetFirstItem();
    bool anchor_found = false;
    bool is_zip = false;
    for (; fragment; ++fragment) {
        if (!anchor_found) {
            path += '/';
            path += *fragment;

            // get info about the file
            NPT_FileInfo info;
            NPT_File::GetInfo(path, &info);
            if (info.m_Type == NPT_FileInfo::FILE_TYPE_DIRECTORY) {
                continue;
            } else if (info.m_Type == NPT_FileInfo::FILE_TYPE_REGULAR) {
                anchor_found = true;
                if (path.EndsWith(".zip", true)) {
                    // this is a zip file
                    is_zip = true;
                }
            } else {
                return NPT_SUCCESS;
            }
        } else {
            if (!subpath.IsEmpty()) {
                subpath += '/';
            }
            subpath += *fragment;
        }
    }
    NPT_LOG_FINE_3("is_zip=%d, path=%s, subpath=%s", (int)is_zip, path.GetChars(), subpath.GetChars());
    
    // return now if no anchor was found
    if (!anchor_found) {
        return NPT_SUCCESS;
    }
    
    // deal with regular files
    if (!is_zip) {
        if (subpath.IsEmpty()) {
            // open the file
            NPT_File file(path);
            NPT_Result result = file.Open(NPT_FILE_OPEN_MODE_READ);
            if (NPT_FAILED(result)) {
                NPT_LOG_FINE("file not found");
                return NPT_SUCCESS;
            }
            NPT_InputStreamReference file_stream;
            file.GetInputStream(file_stream);
            entity->SetInputStream(file_stream, true);
            entity->SetContentType(GetContentType(path));
            response.SetStatus(200, "OK");
        }
        return NPT_SUCCESS;
    }
    
    // load the zip file
    NPT_File file(path);
    NPT_Result result = file.Open(NPT_FILE_OPEN_MODE_READ);
    if (NPT_FAILED(result)) {
        NPT_LOG_WARNING_1("failed to open file (%d)", result);
        return result;
    }
    NPT_InputStreamReference zip_stream;
    file.GetInputStream(zip_stream);
    NPT_ZipFile* zip_file = NULL;
    result = NPT_ZipFile::Parse(*zip_stream, zip_file);
    if (NPT_FAILED(result)) {
        NPT_LOG_WARNING_1("failed to parse zip file (%d)", result);
        return result;
    }
    
    // look for the entry in the zip file
    for (unsigned int i=0; i<zip_file->GetEntries().GetItemCount(); i++) {
        NPT_ZipFile::Entry& entry = zip_file->GetEntries()[i];
        if (subpath == entry.m_Name) {
            // send the file
            NPT_InputStream* file_stream = NULL;
            result = NPT_ZipFile::GetInputStream(entry, zip_stream, file_stream);
            if (NPT_FAILED(result)) {
                NPT_LOG_WARNING_1("failed to get the file stream (%d)", result);
                delete zip_file;
                return result;
            }
            NPT_InputStreamReference file_stream_ref(file_stream);
            entity->SetInputStream(file_stream_ref, true);
            entity->SetContentType(GetContentType(subpath));
            response.SetStatus(200, "OK");
            break;
        }
    }
    
    delete zip_file;
    return NPT_SUCCESS;
}

/*----------------------------------------------------------------------
|   ZipHttpWorker
+---------------------------------------------------------------------*/
class ZipHttpServer;
class ZipHttpWorker : public NPT_Thread {
public:
    // types
    enum {
        IDLE,
        RUNNING,
        DEAD
    } State;
    
    // constructor
    ZipHttpWorker(unsigned int id, ZipHttpServer* server) :
        m_Id(id),
        m_Server(server),
        m_State(IDLE),
        m_Verbose(false) {}
    
    // NPT_Runnable methods
    virtual void Run();
    NPT_Result Respond();
    
    // members
    unsigned int              m_Id;
    ZipHttpServer*            m_Server;
    NPT_SharedVariable        m_State;
    NPT_InputStreamReference  m_InputStream;
    NPT_OutputStreamReference m_OutputStream;
    NPT_HttpRequestContext    m_Context;
    bool                      m_Verbose;
};

/*----------------------------------------------------------------------
|   ZipHttpServer
+---------------------------------------------------------------------*/
class ZipHttpServer : public NPT_HttpServer {
public:
    ZipHttpServer(const char*  file_root,
                  const char*  url_root,
                  unsigned int port,
                  unsigned int threads);
    
    void Loop();
    void OnWorkerDone(ZipHttpWorker* worker);
    
private:
    NPT_Mutex                m_Lock;
    unsigned int             m_Threads;
    ZipRequestHandler*       m_Handler;
    NPT_List<ZipHttpWorker*> m_Workers;
    NPT_List<ZipHttpWorker*> m_ReadyWorkers;
    NPT_SharedVariable       m_AllWorkersBusy;
};

/*----------------------------------------------------------------------
|   ZipHttpServer::ZipHttpServer
+---------------------------------------------------------------------*/
ZipHttpServer::ZipHttpServer(const char*  file_root,
                             const char*  url_root,
                             unsigned int port,
                             unsigned int threads) :
        NPT_HttpServer(port),
        m_Threads(threads),
        m_AllWorkersBusy(0)
{
    m_Handler = new ZipRequestHandler(url_root, file_root);
    AddRequestHandler(m_Handler, url_root, true);
    
    for (unsigned int i=0; i<threads; i++) {
        ZipHttpWorker* worker = new ZipHttpWorker(i, this);
        m_Workers.Add(worker);
        m_ReadyWorkers.Add(worker);
        
        // start threads unless we're single threaded
        if (threads > 1) {
            worker->Start();
        }
    }
}

/*----------------------------------------------------------------------
|   ZipHttpServer::Loop
+---------------------------------------------------------------------*/
void
ZipHttpServer::Loop()
{
    for (;;) {
        // wait until at least one worker is ready
        if (m_AllWorkersBusy.GetValue() == 1) {
            NPT_LOG_FINEST("all workers busy");
        }
        NPT_LOG_FINEST("waiting for a worker");
        m_AllWorkersBusy.WaitUntilEquals(0);
        NPT_LOG_FINEST("got a worker");
        
        // pick a worker
        m_Lock.Lock();
        ZipHttpWorker* worker = NULL;
        m_ReadyWorkers.PopHead(worker);
        if (m_ReadyWorkers.GetItemCount() == 0) {
            m_AllWorkersBusy.SetValue(1);
        }
        m_Lock.Unlock();
        
        NPT_Result result = WaitForNewClient(worker->m_InputStream, worker->m_OutputStream, &worker->m_Context);
        if (NPT_FAILED(result)) {
            NPT_LOG_WARNING_1("WaitForNewClient returned %d", result);
            
            // wait a bit before continuing
            NPT_System::Sleep(NPT_TimeInterval(1.0));
        }

        if (m_Threads == 1) {
            // single threaded
            worker->Respond();
            OnWorkerDone(worker);
        } else {
            worker->m_State.SetValue(ZipHttpWorker::RUNNING);
        }
        worker = NULL;
    }

}

/*----------------------------------------------------------------------
|   ZipHttpWorker::OnWorkerDone
+---------------------------------------------------------------------*/
void
ZipHttpServer::OnWorkerDone(ZipHttpWorker* worker)
{
    NPT_LOG_FINEST_1("worker %d done", worker->m_Id);
    m_Lock.Lock();
    m_ReadyWorkers.Add(worker);
    m_AllWorkersBusy.SetValue(0);
    m_Lock.Unlock();
}

/*----------------------------------------------------------------------
|   ZipHttpWorker::Run
+---------------------------------------------------------------------*/
void
ZipHttpWorker::Run(void)
{
    NPT_LOG_FINE_1("worker %d started", m_Id);
    for (;;) {
        // wait while we're idle
        NPT_LOG_FINER_1("worker %d waiting for work", m_Id);
        m_State.WaitWhileEquals(IDLE);
        
        NPT_LOG_FINER_1("worker %d woke up", m_Id);

        if (m_State.GetValue() == DEAD) {
            NPT_LOG_FINE_1("worker %d exiting", m_Id);
            return;
        }
        
        // respond to the client
        Respond();
        
        // update our state
        m_State.SetValue(IDLE);
        
        // notify the server
        m_Server->OnWorkerDone(this);
    }
}

/*----------------------------------------------------------------------
|   ZipHttpWorker::Respond
+---------------------------------------------------------------------*/
NPT_Result
ZipHttpWorker::Respond()
{
    NPT_LOG_FINER_1("worker %d responding to request", m_Id);

    NPT_Result result = m_Server->RespondToClient(m_InputStream, m_OutputStream, m_Context);

    NPT_LOG_FINER_2("worker %d responded to request (%d)", m_Id, result);
    
    m_InputStream  = NULL;
    m_OutputStream = NULL;

    return result;
}

/*----------------------------------------------------------------------
|       main
+---------------------------------------------------------------------*/
int
main(int /*argc*/, char** argv)
{
    NPT_String   file_root;
    NPT_String   url_root = "/";
    unsigned int port    = 8000;
    unsigned int threads = 5;
    bool         verbose = false;
    
    while (const char* arg = *++argv) {
        if (NPT_StringsEqual(arg, "--help") ||
            NPT_StringsEqual(arg, "-h")) {
            NPT_Console::Output("usage: ziphttpserver [--file-root <dir>] [--url-root <path>] [--port <port>] [--threads <n>] [--verbose]\n");
            return 0;
        } else if (NPT_StringsEqual(arg, "--file-root")) {
            arg = *++argv;
            if (arg == NULL) {
                NPT_Console::Output("ERROR: missing argument for --file-root option\n");
                return 1;
            }
            file_root = arg;
        } else if (NPT_StringsEqual(arg, "--url-root")) {
            arg = *++argv;
            if (arg == NULL) {
                NPT_Console::Output("ERROR: missing argument for --url-root option\n");
                return 1;
            }
            url_root = arg;
        } else if (NPT_StringsEqual(arg, "--port")) {
            arg = *++argv;
            if (arg == NULL) {
                NPT_Console::Output("ERROR: missing argument for --port option\n");
                return 1;
            }
            NPT_ParseInteger(arg, port, true);
        } else if (NPT_StringsEqual(arg, "--threads")) {
            arg = *++argv;
            if (arg == NULL) {
                NPT_Console::Output("ERROR: missing argument for --threads option\n");
                return 1;
            }
            NPT_ParseInteger(arg, threads, true);
        } else if (NPT_StringsEqual(arg, "--verbose")) {
            verbose = true;
        }
    }

    // sanity check on some parameters
    if (threads == 0 || threads > 20) {
        fprintf(stderr, "ERROR: --threads must be between 1 and 20");
        return 1;
    }
    
    // ensure the URL root start with a /
    if (!url_root.StartsWith("/")) {
        url_root = "/"+url_root;
    }
    
    // initialize the file type map
    for (unsigned int i=0; i<NPT_ARRAY_SIZE(DefaultFileTypeMap); i++) {
        FileTypeMap[DefaultFileTypeMap[i].extension] =DefaultFileTypeMap[i].mime_type;
    }
    
    if (file_root.GetLength() == 0) {
        NPT_File::GetWorkingDir(file_root);
    }
    
    if (verbose) {
        NPT_Console::OutputF("Starting server on port %d, file-root=%s, url-root=%s, threads=%d\n",
                             port, file_root.GetChars(), url_root.GetChars(), threads);
    }
    
    ZipHttpServer* server = new ZipHttpServer(file_root, url_root, port, threads);
    server->Loop();
    delete server;
    
    return 0;
}