summaryrefslogtreecommitdiff
path: root/server/server.cpp
blob: af2295a6fabe90065b120ef7844794a8df22c68b (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
/*
 * server.cpp
 *
 *  Created on: 31.07.2012
 *      Author: savop
 */

#include <vdr/tools.h>
#include <string>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <unistd.h>
#include "../include/server.h"
#include "../include/service.h"
#include "../include/webserver.h"
#include "../include/tools.h"
#include "../include/media/mediaManager.h"
#include "../upnp.h"

using namespace upnp;
using namespace std;

cMediaServer* cMediaServer::GetInstance(){
	static cMediaServer server;
	return &server;
}

cMediaServer::cMediaServer()
: mServerDescription("VDR UPnP/DLNA MS", "Denis Loh", "http://upnp.vdr-developer.org",
                     tr(DESCRIPTION), "VDR UPnP-DLNA MS", VERSION,
                     "http://projects.vdr-developer.org/projects/plg-upnp/files", VERSION,
                     "deviceDescription.xml")
, mDeviceHandle(0)
, mAnnounceMaxAge(1800)
, mMaxContentLength(KB(20))
, mWebserver(NULL)
, mMediaManager(NULL)
{
  char tmp[255];

  if (gethostname(tmp, sizeof(tmp)) == 0) {
    string name = tmp;
    boost::to_upper(name);
    mServerDescription.friendlyName = name + " - " + mServerDescription.friendlyName;
  }

  mServerIcons.push_back(ServerIcon(image::DLNA_ICON_PNG_SM_24A, "images/upnpIconSm.png"));
  mServerIcons.push_back(ServerIcon(image::DLNA_ICON_PNG_LRG_24A, "images/upnpIconLrg.png"));
  mServerIcons.push_back(ServerIcon(image::DLNA_ICON_JPEG_SM_24, "images/upnpIconSm.jpeg"));
  mServerIcons.push_back(ServerIcon(image::DLNA_ICON_JPEG_LRG_24, "images/upnpIconLrg.jpeg"));
}

cMediaServer::~cMediaServer(){
  delete mWebserver;
  delete mMediaManager;
}

bool cMediaServer::Start(){

  isyslog("UPnP\tStarting UPnP media server");

  int ret;

  // Disable internal webserver, we don't need it.
  UpnpEnableWebserver(false);

  if(!mWebserver->Start()){
    esyslog("UPnP\tFailed to start the web server");
    return false;
  }

  isyslog("UPnP\tRegistering UPnP media server");

  string description = GetDeviceDescriptionUrl();

  ret = UpnpRegisterRootDevice2(UPNPREG_URL_DESC,
                                description.c_str(),
                                description.size(),
                                0,
                                &cMediaServer::ActionCallback,
                                this,
                                &mDeviceHandle);

  if(ret != UPNP_E_SUCCESS){
    esyslog("UPnP\tFailed to register the device. Error code: %d", ret);
    return false;
  }

  ret = UpnpUnRegisterRootDevice(mDeviceHandle);
  if (ret != UPNP_E_SUCCESS) {
    esyslog("UPnP\tUnregistering old devices failed");
    return false;
  }

  ret = UpnpRegisterRootDevice2(UPNPREG_URL_DESC,
                                description.c_str(),
                                description.size(),
                                0,
                                &cMediaServer::ActionCallback,
                                this,
                                &mDeviceHandle);

  if(ret != UPNP_E_SUCCESS){
    esyslog("UPnP\tFailed to register the device. Error code: %d", ret);
    return false;
  }

  isyslog("UPnP\tInitialising services...");
  serviceMap&  services = cMediaServer::GetServices();
  for(serviceMap::iterator it = services.begin(); it != services.end(); ++it){
    isyslog("UPnP\t...%s", (*it).second->GetServiceDescription().serviceType.c_str());
    (*it).second->Init(this, mDeviceHandle);
  }

  //send first advertisments
  isyslog("UPnP\tSend first advertisements to publish start in network");
  ret = UpnpSendAdvertisement(mDeviceHandle, GetAnnounceMaxAge());
  if (ret != UPNP_E_SUCCESS) {
    esyslog("UPnP\tError while sending first advertisments - Errorcode: %d", ret);
    return false;
  }

  return true;
}

bool cMediaServer::Stop(){

  int ret = 0;

  isyslog("UPnP\tStopping services...");
  serviceMap&  services = cMediaServer::GetServices();
  for(serviceMap::iterator it = services.begin(); it != services.end(); ++it){
    isyslog("UPnP\t...%s", (*it).second->GetServiceDescription().serviceType.c_str());
    (*it).second->Stop();
  }

  isyslog("UPnP\tStopping UPnP media server");
  UpnpUnRegisterRootDevice(mDeviceHandle);
  if (ret != UPNP_E_SUCCESS) {
    esyslog("UPnP\tError while sending first advertisments - Errorcode: %d", ret);
    return false;
  }

  UpnpFinish();

  isyslog("UPnP\tStopping web server...");
  if(mWebserver){
    mWebserver->Stop();

    delete mWebserver;
    mWebserver = NULL;
  }

  if(mMediaManager){
    delete mMediaManager;
    mMediaManager = NULL;
  }

  return true;
}

void cMediaServer::Housekeeping(){
  if(mMediaManager){
    mMediaManager->Housekeeping();
  }
}

bool cMediaServer::Initialize(){
  string address;
  uint16_t port = 0;

  mConfigDirectory = cPlugin::ConfigDirectory(PLUGIN_NAME_I18N);

  if(mCurrentConfiguration.expertSettings){
    address = mCurrentConfiguration.bindToAddress
              ? mCurrentConfiguration.address
              : tools::GetAddressByInterface(mCurrentConfiguration.interface);

    if(address.empty() || !address.compare("0.0.0.0")){
      address = tools::GetAddressByInterface(tools::GetNetworkInterfaceByIndex(0, true));
    }

    port = mCurrentConfiguration.port;
  } else {
    address = tools::GetAddressByInterface(tools::GetNetworkInterfaceByIndex(0, true));
    port = 0;
  }

  int ret = 0;

  isyslog("UPnP\tInitializing UPnP media server on %s:%d", address.c_str(), port);

  ret = UpnpInit(address.c_str(), mCurrentConfiguration.port);

  if(ret != UPNP_E_SUCCESS && ret != UPNP_E_INIT){
    esyslog("UPnP\tFailed to initialise UPnP media server. Error code: %d", ret);
    return false;
  }

  mWebserver = new cWebserver(GetServerIPAddress());
  mMediaManager = new cMediaManager();

  if(mCurrentConfiguration.expertSettings){

    if(mCurrentConfiguration.maxContentLength)
      SetMaxContentLength(mCurrentConfiguration.maxContentLength);

    if(mCurrentConfiguration.announceMaxAge)
      SetAnnounceMaxAge(mCurrentConfiguration.announceMaxAge);

    if(!mCurrentConfiguration.webServerRoot.empty())
      mWebserver->SetWebserverRootDir(mCurrentConfiguration.webServerRoot);

    if(!mCurrentConfiguration.useLive){
      if(!mCurrentConfiguration.presentationURL.empty())
        mWebserver->SetPresentationUrl(mCurrentConfiguration.presentationURL);
    } else {
      stringstream ss;

      uint16_t port = mCurrentConfiguration.livePort ? mCurrentConfiguration.livePort : 8008;

      ss << "http://" << GetServerIPAddress() << ":" << port << "/";

      mWebserver->SetPresentationUrl(ss.str());
    }

    if(mCurrentConfiguration.webServerPort)
      mWebserver->SetListenerPort(mCurrentConfiguration.webServerPort);

    if(mCurrentConfiguration.maxRequestTime)
      mWebserver->SetMaxRequestTime(mCurrentConfiguration.maxRequestTime);

    if(!mCurrentConfiguration.databaseDir.empty())
      mMediaManager->SetDatabaseDir(mCurrentConfiguration.databaseDir);
  }

  ret = UpnpSetMaxContentLength(GetMaxContentLength());

  if(ret != UPNP_E_SUCCESS){
    esyslog("UPnP\tFailed to set max. content length of SOAP messages. Error code: %d", ret);
    return false;
  }

  isyslog("UPnP\tInitialising webserver");
  if(!mWebserver->Initialise()){
    esyslog("UPnP\tFailed to initialise the web server.");
    return false;
  }

  isyslog("UPnP\tInitialising media manager");
  if(!mMediaManager->Initialise()){
    esyslog("UPnP\tFailed to initialise the media manager.");
    return false;
  }

  return true;
}

void cMediaServer::SetAnnounceMaxAge(int announceMaxAge){
  mAnnounceMaxAge = (announceMaxAge != 0) ? announceMaxAge : 1800;
}

void cMediaServer::SetMaxContentLength(size_t maxContentLength){
  mMaxContentLength = (maxContentLength != 0) ? maxContentLength : KB(20);
}

void cMediaServer::SetConfiguration(upnp::cConfig newConfig){
  mCurrentConfiguration = newConfig;
}

upnp::cConfig cMediaServer::GetConfiguration() const {
  return mCurrentConfiguration;
}

const char* cMediaServer::GetServerIPAddress() const {
  return UpnpGetServerIpAddress();
}

uint16_t cMediaServer::GetServerPort() const {
  return UpnpGetServerPort();
}

string cMediaServer::GetDeviceDescriptionUrl() const {
  return mWebserver->GetServiceUrl() + mServerDescription.descriptionFile;
}

cMediaServer::serviceMap& cMediaServer::GetServices(){
  static serviceMap services;
  return services;
}

void cMediaServer::RegisterService(cUPnPService* service){
  if(service != NULL){
    dsyslog("UPnP\tRegistered service: %s", service->GetServiceDescription().serviceType.c_str());
    GetServices()[service->GetServiceDescription().serviceID] = service;
  }
}

int cMediaServer::ActionCallback(Upnp_EventType eventtype, void *event, void *cookie){
  Upnp_Subscription_Request* eventRequest = NULL;
  Upnp_Action_Request*       actionRequest = NULL;

  cMediaServer* mediaServer = (cMediaServer*)cookie;

  //check committed event variable
  if (event == NULL) {
      esyslog("UPnP\tUPnP Callback - NULL request");
      return UPNP_E_BAD_REQUEST;
  }

  cUPnPService* service;

  switch(eventtype){
  case UPNP_CONTROL_ACTION_REQUEST:
    actionRequest = (Upnp_Action_Request*) event;

    dsyslog("UPnP\tAction request: %s", actionRequest->ActionName);

    if(!mediaServer->CheckDeviceUUID(actionRequest->DevUDN)){
      esyslog("UPnP\tUPnP Callback - action request not for this device");
      return UPNP_E_BAD_REQUEST;
    }

    service = cMediaServer::GetServices()[actionRequest->ServiceID];

    if(service == NULL){
      esyslog("UPnP\tCallback - unsupported service called for control");
      return UPNP_E_BAD_REQUEST;
    }

    return service->Execute(actionRequest);

  case UPNP_EVENT_SUBSCRIPTION_REQUEST:
    eventRequest = (Upnp_Subscription_Request*) event;

    dsyslog("UPnP\tSubscription request from: %s", eventRequest->ServiceId);

    if(!mediaServer->CheckDeviceUUID(eventRequest->UDN)){
      esyslog("UPnP\tUPnP Callback - event request not for this device");
      return UPNP_E_BAD_REQUEST;
    }

    service = cMediaServer::GetServices()[eventRequest->ServiceId];

    if(service == NULL){
      esyslog("UPnP\tCallback - unsupported service called for eventing");
      return UPNP_E_BAD_REQUEST;
    }

    return service->Subscribe(eventRequest);

  default:
    esyslog("UPnP\tUPnP Action Callback - Unsupported Event");
    return UPNP_E_BAD_REQUEST;
  }

}

bool cMediaServer::CheckDeviceUUID(string deviceUUID) const {
  return deviceUUID.find(mCurrentConfiguration.deviceUUID) != string::npos;
}

cMediaServer::Description::Description(
    string fn, string m, string murl,
    string mod, string mon, string mono,
    string mourl, string sno, string desc)
: friendlyName(fn)
, manufacturer(m)
, manufacturerURL(murl)
, modelDescription(mod)
, modelName(mon)
, modelNumber(mono)
, modelURL(mourl)
, serialNumber(sno)
, descriptionFile(desc)
{
}

cMediaServer::ServerIcon::ServerIcon(image::cIcon profile, string filename)
: profile(profile)
, filename(filename)
{
}