File: server.cc

package info (click to toggle)
gerbera 1.1.0+dfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 4,684 kB
  • sloc: cpp: 29,611; xml: 967; ansic: 463; perl: 328; sh: 316; sql: 135; python: 75; makefile: 11; fortran: 9
file content (414 lines) | stat: -rw-r--r-- 12,761 bytes parent folder | download
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
/*MT*
    
    MediaTomb - http://www.mediatomb.cc/
    
    server.cc - this file is part of MediaTomb.
    
    Copyright (C) 2005 Gena Batyan <bgeradz@mediatomb.cc>,
                       Sergey 'Jin' Bostandzhyan <jin@mediatomb.cc>
    
    Copyright (C) 2006-2010 Gena Batyan <bgeradz@mediatomb.cc>,
                            Sergey 'Jin' Bostandzhyan <jin@mediatomb.cc>,
                            Leonhard Wimmer <leo@mediatomb.cc>
    
    MediaTomb is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 2
    as published by the Free Software Foundation.
    
    MediaTomb 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.  See the
    GNU General Public License for more details.
    
    You should have received a copy of the GNU General Public License
    version 2 along with MediaTomb; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
    
    $Id$
*/

/// \file server.cc

#ifdef HAVE_CURL
#include <curl/curl.h>
#endif

#ifdef HAVE_LASTFMLIB
#include "lastfm_scrobbler.h"
#endif

#include "content_manager.h"
#include "server.h"
#include "update_manager.h"
#include "web_callbacks.h"

using namespace zmm;
using namespace mxml;

Ref<Storage> Server::storage = nullptr;

static int static_upnp_callback(Upnp_EventType eventtype, const void* event, void* cookie)
{
    return static_cast<Server *>(cookie)->upnp_callback(eventtype, event);
}

void Server::static_cleanup_callback()
{
    if (storage != nullptr) {
        try {
            storage->threadCleanup();
        } catch (const Exception& ex) {
        }
    }
}

Server::Server()
{
    server_shutdown_flag = false;
}

void Server::init()
{
    virtual_directory = _(SERVER_VIRTUAL_DIR);

    cds = ContentDirectoryService{};

    cmgr = ConnectionManagerService{};

    mrreg = MRRegistrarService{};

    Ref<ConfigManager> config = ConfigManager::getInstance();

    serverUDN = config->getOption(CFG_SERVER_UDN);
    alive_advertisement = config->getIntOption(CFG_SERVER_ALIVE_INTERVAL);

#ifdef HAVE_CURL
    curl_global_init(CURL_GLOBAL_ALL);
#endif

#ifdef HAVE_LASTFMLIB
    LastFm::getInstance();
#endif
}

void Server::upnp_init()
{
    int ret = 0; // general purpose error code
    log_debug("start\n");

    Ref<ConfigManager> config = ConfigManager::getInstance();

    String iface = config->getOption(CFG_SERVER_NETWORK_INTERFACE);
    String ip = config->getOption(CFG_SERVER_IP);

    if (string_ok(ip) && string_ok(iface))
        throw _Exception(_("You can not specify interface and IP at the same time!"));

    if (!string_ok(iface))
        iface = ipToInterface(ip);

    if (string_ok(ip) && !string_ok(iface))
        throw _Exception(_("Could not find ip: ") + ip);

    int port = config->getIntOption(CFG_SERVER_PORT);

    // this is important, so the storage lives a little longer when
    // shutdown is initiated
    // FIMXE: why?
    storage = Storage::getInstance();

    log_debug("Initialising libupnp with interface: %s, port: %d\n", iface.c_str(), port);
    ret = UpnpInit2(iface.c_str(), port);
    if (ret != UPNP_E_SUCCESS) {
        throw _UpnpException(ret, _("upnp_init: UpnpInit failed"));
    }

    port = UpnpGetServerPort();
    log_info("Initialized port: %d\n", port);

    if (!string_ok(ip)) {
        ip = UpnpGetServerIpAddress();
    }

    log_info("Server bound to: %s\n", ip.c_str());

    virtual_url = _("http://") + ip + ":" + port + "/" + virtual_directory;

    // next set webroot directory
    String web_root = config->getOption(CFG_SERVER_WEBROOT);

    if (!string_ok(web_root)) {
        throw _Exception(_("invalid web server root directory"));
    }

    ret = UpnpSetWebServerRootDir(web_root.c_str());
    if (ret != UPNP_E_SUCCESS) {
        throw _UpnpException(ret, _("upnp_init: UpnpSetWebServerRootDir failed"));
    }

    log_debug("webroot: %s\n", web_root.c_str());

    Ref<Array<StringBase> > arr = config->getStringArrayOption(CFG_SERVER_CUSTOM_HTTP_HEADERS);

    if (arr != nullptr) {
        String tmp;
        for (int i = 0; i < arr->size(); i++) {
            tmp = arr->get(i);
            if (string_ok(tmp)) {
                log_info("(NOT) Adding HTTP header \"%s\"\n", tmp.c_str());
                // FIXME upstream upnp
                //ret = UpnpAddCustomHTTPHeader(tmp.c_str());
                //if (ret != UPNP_E_SUCCESS)
                //{
                //    throw _UpnpException(ret, _("upnp_init: UpnpAddCustomHTTPHeader failed"));
                //}
            }
        }
    }

    log_debug("Setting virtual dir to: %s\n", virtual_directory.c_str());
    ret = UpnpAddVirtualDir(virtual_directory.c_str(), nullptr, nullptr);
    if (ret != UPNP_E_SUCCESS) {
        throw _UpnpException(ret, _("upnp_init: UpnpAddVirtualDir failed"));
    }

    ret = register_web_callbacks();
    if (ret != UPNP_E_SUCCESS) {
        throw _UpnpException(ret, _("upnp_init: UpnpSetVirtualDirCallbacks failed"));
    }

    String presentationURL = config->getOption(CFG_SERVER_PRESENTATION_URL);
    if (!string_ok(presentationURL)) {
        presentationURL = _("http://") + ip + ":" + port + "/";
    } else {
        String appendto = config->getOption(CFG_SERVER_APPEND_PRESENTATION_URL_TO);
        if (appendto == "ip") {
            presentationURL = _("http://") + ip + ":" + presentationURL;
        } else if (appendto == "port") {
            presentationURL = _("http://") + ip + ":" + port + "/" + presentationURL;
        } // else appendto is none and we take the URL as it entered by user
    }

    // register root device with the library
    String device_description = _("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") + UpnpXML_RenderDeviceDescription(presentationURL)->print();

    //log_debug("Device Description: \n%s\n", device_description.c_str());

    log_debug("Registering with UPnP...\n");
    ret = UpnpRegisterRootDevice2(UPNPREG_BUF_DESC,
        device_description.c_str(),
        device_description.length() + 1,
        true,
        static_upnp_callback,
        this,
        &device_handle);
    if (ret != UPNP_E_SUCCESS) {
        throw _UpnpException(ret, _("upnp_init: UpnpRegisterRootDevice failed"));
    }

    log_debug("Sending UPnP Alive advertisement\n");
    ret = UpnpSendAdvertisement(device_handle, alive_advertisement);
    if (ret != UPNP_E_SUCCESS) {
        throw _UpnpException(ret, _("upnp_init: UpnpSendAdvertisement failed"));
    }

    // initializing UpdateManager
    UpdateManager::getInstance();

    // initializing ContentManager
    ContentManager::getInstance();

    config->writeBookmark(ip, String::from(port));
    log_info("The Web UI can be reached by following this link: http://%s:%d/\n", ip.c_str(), port);

    log_debug("end\n");
}

bool Server::getShutdownStatus()
{
    return server_shutdown_flag;
}

void Server::shutdown()
{
    int ret = 0; // return code

    /*
    ContentManager::getInstance()->shutdown();
    UpdateManager::getInstance()->shutdown();
    Storage::getInstance()->shutdown();
    */

    server_shutdown_flag = true;

    log_debug("Server shutting down\n");

    ret = UpnpUnRegisterRootDevice(device_handle);
    if (ret != UPNP_E_SUCCESS) {
        throw _UpnpException(ret, _("upnp_cleanup: UpnpUnRegisterRootDevice failed"));
    }

#ifdef HAVE_CURL
    curl_global_cleanup();
#endif

    log_debug("now calling upnp finish\n");
    UpnpFinish();
    if (storage != nullptr && storage->threadCleanupRequired()) {
        static_cleanup_callback();
    }
    storage = nullptr;
}

String Server::getVirtualURL()
{
    return virtual_url;
}

int Server::upnp_callback(Upnp_EventType eventtype, const void* event)
{
    int ret = UPNP_E_SUCCESS; // general purpose return code

    log_debug("start\n");

    // check parameters
    if (event == nullptr) {
        log_debug("upnp_callback: NULL event structure\n");
        return UPNP_E_BAD_REQUEST;
    }

    //log_info("event is ok\n");
    // get device wide mutex (have to figure out what the hell that is)
    AutoLock lock(mutex);

    // dispatch event based on event type
    switch (eventtype) {

    case UPNP_CONTROL_ACTION_REQUEST:
        // a CP is invoking an action
        //log_info("UPNP_CONTROL_ACTION_REQUEST\n");
        try {
            // https://github.com/mrjimenez/pupnp/blob/master/upnp/sample/common/tv_device.c

            Ref<ActionRequest> request(new ActionRequest((UpnpActionRequest*)event));
            upnp_actions(request);
            request->update();
            // set in update() ((struct Upnp_Action_Request *)event)->ErrCode = ret;
        } catch (const UpnpException& upnp_e) {
            ret = upnp_e.getErrorCode();
            UpnpActionRequest_set_ErrCode((UpnpActionRequest*)event, ret);
        } catch (const Exception& e) {
            log_info("Exception: %s\n", e.getMessage().c_str());
        }

        break;

    case UPNP_EVENT_SUBSCRIPTION_REQUEST:
        // a cp wants a subscription
        //log_info("UPNP_EVENT_SUBSCRIPTION_REQUEST\n");
        try {
            Ref<SubscriptionRequest> request(new SubscriptionRequest((UpnpSubscriptionRequest*)event));
            upnp_subscriptions(request);
        } catch (const UpnpException& upnp_e) {
            log_warning("Subscription exception: %s\n", upnp_e.getMessage().c_str());
            ret = upnp_e.getErrorCode();
        }

        break;

    default:
        // unhandled event type
        log_warning("unsupported event type: %d\n", eventtype);
        ret = UPNP_E_BAD_REQUEST;
        break;
    }

    log_debug("returning %d\n", ret);
    return ret;
}

UpnpDevice_Handle Server::getDeviceHandle()
{
    return device_handle;
}

zmm::String Server::getIP()
{
    return UpnpGetServerIpAddress();
}

zmm::String Server::getPort()
{
    return String::from(UpnpGetServerPort());
}

void Server::upnp_actions(Ref<ActionRequest> request)
{
    log_debug("start\n");

    // make sure the request is for our device
    if (request->getUDN() != serverUDN) {
        // not for us
        throw _UpnpException(UPNP_E_BAD_REQUEST,
            _("upnp_actions: request not for this device"));
    }

    // we need to match the serviceID to one of our services
    if (request->getServiceID() == DESC_CM_SERVICE_ID) {
        // this call is for the lifetime stats service
        // log_debug("request for connection manager service\n");
        cmgr.process_action_request(request);
    } else if (request->getServiceID() == DESC_CDS_SERVICE_ID) {
        // this call is for the toaster control service
        //log_debug("upnp_actions: request for content directory service\n");
        cds.process_action_request(request);
    }
    else if (request->getServiceID() == DESC_MRREG_SERVICE_ID) {
        mrreg.process_action_request(request);
    }
    else {
        // cp is asking for a nonexistent service, or for a service
        // that does not support any actions
        throw _UpnpException(UPNP_E_BAD_REQUEST,
            _("Service does not exist or action not supported"));
    }
}

void Server::upnp_subscriptions(Ref<SubscriptionRequest> request)
{
    // make sure that the request is for our device
    if (request->getUDN() != serverUDN) {
        // not for us
        log_debug("upnp_subscriptions: request not for this device: %s vs %s\n",
            request->getUDN().c_str(), serverUDN.c_str());
        throw _UpnpException(UPNP_E_BAD_REQUEST,
            _("upnp_actions: request not for this device"));
    }

    // we need to match the serviceID to one of our services

    if (request->getServiceID() == DESC_CDS_SERVICE_ID) {
        // this call is for the content directory service
        //log_debug("upnp_subscriptions: request for content directory service\n");
        cds.process_subscription_request(request);
    } else if (request->getServiceID() == DESC_CM_SERVICE_ID) {
        // this call is for the connection manager service
        //log_debug("upnp_subscriptions: request for connection manager service\n");
        cmgr.process_subscription_request(request);
    }
    else if (request->getServiceID() == DESC_MRREG_SERVICE_ID) {
        mrreg.process_subscription_request(request);
    }
    else {
        // cp asks for a nonexistent service or for a service that
        // does not support subscriptions
        throw _UpnpException(UPNP_E_BAD_REQUEST,
            _("Service does not exist or subscriptions not supported"));
    }
}

// Temp
void Server::send_subscription_update(zmm::String updateString)
{
    cmgr.subscription_update(updateString);
}