summaryrefslogtreecommitdiff
path: root/libs/networking/src/ConnectionHandler.cc
blob: abed00f5730b29f71e3d0b24b873e6ffd0b9f630 (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
/**
 * ======================== legal notice ======================
 *
 * File:      ConnectionHandler.cc
 * Created:   4. Juli 2012, 07
 * Author:    <a href="mailto:geronimo013@gmx.de">Geronimo</a>
 * Project:   libnetworking: classes for tcp/ip sockets and http-protocol handling
 *
 * CMP - compound media player
 *
 * is a client/server mediaplayer intended to play any media from any workstation
 * without the need to export or mount shares. cmps is an easy to use backend
 * with a (ready to use) HTML-interface. Additionally the backend supports
 * authentication via HTTP-digest authorization.
 * cmpc is a client with vdr-like osd-menues.
 *
 * Copyright (c) 2012 Reinhard Mantey, some rights reserved!
 * published under Creative Commons by-sa
 * For details see http://creativecommons.org/licenses/by-sa/3.0/
 *
 * The cmp project's homepage is at http://projects.vdr-developer.org/projects/cmp
 *
 * --------------------------------------------------------------
 */
#include <ConnectionHandler.h>
#include <ServerSocket.h>
#include <HTTPRequest.h>
#include <HTTPFileResponse.h>
#include <HTTPAuthorizationRequest.h>
#include <HTTPRequestHandler.h>
#include <Authorization.h>
#include <Credentials.h>
#include <MD5Calculator.h>
#include <StringBuilder.h>
#include <TimeMs.h>
#include <Logging.h>
#include <util.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <iostream>
#include <tr1/unordered_map>

static unsigned long connectionCounter = 0;
class cHTTPRequestHandlers {
public:
  typedef std::tr1::unordered_map<std::string, cHTTPRequestHandler *>::iterator iterator;
  cHTTPRequestHandlers();
  ~cHTTPRequestHandlers();

  cHTTPRequestHandler *Handler(const char *UrlPrefix);
  void SetHandler(const char *UrlPrefix, cHTTPRequestHandler *Handler);
  cHTTPRequestHandler *DefaultHandler(void) { return defaultHandler; }
  void SetDefaultHandler(cHTTPRequestHandler *Handler) { defaultHandler = Handler; }

  cHTTPRequestHandlers::iterator begin() { return internalMap.begin(); }
  cHTTPRequestHandlers::iterator end() { return internalMap.end(); }

private:
  cHTTPRequestHandler *defaultHandler;
  std::tr1::unordered_map<std::string, cHTTPRequestHandler *> internalMap;
  };

cHTTPRequestHandlers::cHTTPRequestHandlers()
 : defaultHandler(NULL)
{
}

cHTTPRequestHandlers::~cHTTPRequestHandlers()
{
  cHTTPRequestHandlers::iterator it = internalMap.begin();

  while (it != internalMap.end()) {
        delete it->second;
        ++it;
        }
  if (defaultHandler) delete defaultHandler;
}

cHTTPRequestHandler *cHTTPRequestHandlers::Handler(const char* UrlPrefix)
{
  cHTTPRequestHandlers::iterator it = internalMap.find(UrlPrefix);

  if (it == internalMap.end()) return NULL;
  return it->second;
}

void cHTTPRequestHandlers::SetHandler(const char* UrlPrefix, cHTTPRequestHandler* Handler)
{
  Handler->SetID(UrlPrefix);
  internalMap[UrlPrefix] = Handler;
}
static cHTTPRequestHandlers registeredHandlers;

cConnectionHandler::cConnectionHandler(cConnectionPoint &Client, cServerConfig &Config, bool StayConnected)
 : config(Config)
 , client(Client)
 , connectionNumber(++connectionCounter)
 , bufSize(2048)
 , scratch(NULL)
 , nonce(NULL)
 , stayConnected(StayConnected)
{
}

cConnectionHandler::~cConnectionHandler()
{
  Cancel();
}

void cConnectionHandler::Action()
{
  if (!scratch) scratch = (char *)malloc(bufSize);
  if (!scratch) {
     esyslog("failed to allocate scratch buffer of size %ld", bufSize);
     return;
     }
  cHTTPRequest *request;
  cHTTPResponse *response = NULL;
  uint64_t start, end;
  size_t nTrans;

  isyslog("ConnectionHandler::Action() - start the loop");
  while (Running()) {
        memset(scratch, 0, bufSize);

        // process at least one request
        isyslog("read next request from Client");
        nTrans = read(client.Socket(), scratch, bufSize);
        if (nTrans < 1) {
           esyslog("failed to read client-Request! End of this connection handler ... #%d", errno);
           return;
           }
        start = cTimeMs::Now();
        if (nTrans == bufSize) {
           char *p = scratch + nTrans;

           bufSize += 2048;
           scratch = (char *) realloc(scratch, bufSize);
           nTrans += read(client.Socket(), p, 2048);

           //TODO: should we support multiple buffer resize?
           if (nTrans == bufSize) {
              esyslog("OUPS - buffer overflow? - Lets stop this connection handler ...");
              return;
              }
           }
        isyslog("#%lu - got client request |>%s<|", connectionNumber, scratch);

        request = new cHTTPRequest(scratch);
        if (!request) {
           esyslog("ERROR: failed to parse request from client!");
           response = new cHTTPResponse(HTTP_NotAcceptable);
           }
        else {
           isyslog("got request from client       (%ld bytes)       %s", nTrans, request->Url().Path());

           if (AuthorizationRequired()) {
              if (request->Authorization()) {
                 char *url = request->Url().ToString();

                 for (EVER) {
                     //TODO: 1, check uri from request against uri from auth
                     if (strcmp(request->Authorization()->Uri(), url)) {
                        esyslog("ATTENTION - security attack! URI mismatch between request and authorization header!");
                        response = new cHTTPResponse(HTTP_BadRequest);
                        break;
                        }

                     //TODO: 2. search user/principal
                     cAuthorization *auth = Authorizations().FindAuthorization(request->Authorization()->Opaque());

                     if (!auth) {
                        response = new cHTTPAuthorizationRequest(Authorizations().CreateAuthorization(*request, client, connectionNumber));
                        esyslog("Huh? - didn't find a matching authorization, but client sent authorization header. Something went wrong!");
                        break;
                        }

                     //TODO: 3. check auth->principal->hash against hash from found principal
                     if (IsAuthorizationValid(auth, *request))
                        response = ProcessRequest(*request);
                     if (!response) {
                        //TODO: 406 or should we create a new authorization request?
                        response = new cHTTPResponse(HTTP_NotAcceptable);
                        }
                     break;
                     }
                 free(url);
                 }
              else {
                 //TODO: create authorization request
                 response = new cHTTPAuthorizationRequest(Authorizations().CreateAuthorization(*request, client, connectionNumber));
                 }
              }
           else response = ProcessRequest(*request);
           }
        TransferResponse(response);
        delete response;
        delete request;
        response = NULL;
        request = NULL;
        end = cTimeMs::Now();
        isyslog("processing of request took %ld ms.", (end - start));

        isyslog("check IO status ...");
        if (!client.IOWait(500)) {
           if (!StayConnected()) {
              isyslog("         >>> connection timed out without any data <<<");
              break; // leave temporary connections after timeout
              }
           }
        }
  Cancel();
}

void cConnectionHandler::Cancel(int WaitSeconds)
{
  dsyslog("Ok, lets close the client socket ...");
  client.Close();
  FREE(scratch);
  FREE(nonce);
}

bool cConnectionHandler::IsAuthorizationValid(cAuthorization *ServerAuth, const cHTTPRequest &request)
{
  // Auth is the authorization based on opaque value from request->auth (session-ID)
  // check other values from auth/request too
  const cAuthorization *ClientAuth = request.Authorization();
  const cPrincipal *principal = ServerAuth->Principal();

  if (!principal || !strcmp(ServerAuth->UserID(), "unset"))
     principal = Credentials.FindPrincipal(ClientAuth->UserID(), ClientAuth->Realm());

  for (EVER) {
      if (!principal) {
         esyslog("username or realm is unknown");
         break;
         }
      if (strcmp(ClientAuth->UserID(), principal->Name()) || strcmp(ClientAuth->Realm(), principal->Realm())) {
         esyslog("username or realm did not match authenticated session");
         break;
         }
      if (strcmp(principal->Hash(), ClientAuth->UserCredential())) {
         esyslog("password given was invalid");
         break;
         }
      cAuthorization *authCheck = new cAuthorization(principal, request.Method(), *ClientAuth);
      const char *authHash = authCheck->CalculateResponse();

      if (strcmp(authHash, ClientAuth->Response())) {
         delete authCheck;
         break;
         }

      if (strcmp(ServerAuth->UserID(), principal->Name())) {
         // validation passed, so remember authorized user
         ServerAuth->SetPrincipal(principal);
         }
      delete authCheck;

      return true;
      }
  // validation of authorization failed, so remove any existing authorization from this session
  Authorizations().Del(ServerAuth);

  return false;
}

cHTTPResponse *cConnectionHandler::ProcessRequest(cHTTPRequest &Request)
{
  cHTTPResponse *res = NULL;

  isyslog("ConnectionHandler::ProcessRequest: %s", Request.Url().Path());
  if (!strcmp(Request.Url().Path(), "/stop")) {
      ServerSocket().SetActive(false);
      res = new cHTTPResponse(HTTP_Gone);
      }
  else if (!strcmp(Request.Url().Path(), "/favicon.ico")) {
      res = new cHTTPFileResponse(config.AppIconPath());
      }
  else if (!strcmp(Request.Url().Path(), "/help")) {
      cHTTPResponse *ir = new cHTTPResponse();

      isyslog("start assembling usage message ...");
      Usage(ir->StringBuilder());

      ir->StringBuilder().Append("<hr>").Append(ir->ServerID()).Append(" ").Append(config.DocumentRoot());
      isyslog("assembling of usage message done - let's send it to client ...");
      ir->SetContentType("text/html");
      ir->SetContentSize(ir->StringBuilder().Size());
      res = ir;
      }
  else {
     cHTTPRequestHandler *rh = registeredHandlers.Handler(Request.Url().Path());

     if (rh) res = rh->ProcessRequest(Request);
     if (!rh || !res) {
        rh = registeredHandlers.DefaultHandler();

        if (rh) res = rh->ProcessRequest(Request);
        }
     }
  if (!res) res = new cHTTPResponse(HTTP_NotFound);

  return res;
}

void cConnectionHandler::Usage(cStringBuilder& sb)
{
  cHTTPRequestHandlers::iterator it = registeredHandlers.begin();

  isyslog("start of cConnectionHandler::Usage() ...");
  sb.Append("<h2>Media server</h2><p>serves media files to remote/client media-players. Those ");
  sb.Append("media-player should support the http-protocol. Opposed to well known http-servers, this ");
  sb.Append("server handles multifile media transparently for the client.</p>");
  sb.Append("<h3>supported requests:</h3>");
  sb.Append("<dl>");

  while (it != registeredHandlers.end()) {
        sb.Append("<dt><br/><em>");
        sb.Append(it->first.c_str());
        sb.Append("</em></dt><dd>");
        it->second->Usage(sb);
        sb.Append("</dd>");
        ++it;
        }
  if (registeredHandlers.DefaultHandler()) {
     sb.Append("<dt><br/><em>");
     sb.Append("default");
     sb.Append("</em></dt><dd>");
     registeredHandlers.DefaultHandler()->Usage(sb);
     sb.Append("</dd>");
     sb.Append("</dl>");
     }
  isyslog("end of cConnectionHandler::Usage() ...");
}

void cConnectionHandler::TransferResponse(cHTTPResponse *Response)
{
  if (!Response) {
     esyslog("OUPS - should not happen!!! - Response was empty!");
     close(client.Socket());

     return;
     }
//#ifdef DEBUG
//  static int responseCounter = 0;
//  char filename[64] = {0};
//  sprintf(filename, "/tmp/rednose%03d", ++responseCounter);
//#endif

  memset(scratch, 0, bufSize);

//#ifdef DEBUG
//  int fdClient = open(filename, O_WRONLY | O_CREAT);
//#else
  int fdClient = client.Socket();
//#endif
  isyslog("gonna sent message to client (Socket #%d)", fdClient);

  int nRaw = Response->WritePrefix(scratch, bufSize);
  int nTrans = send(fdClient, scratch, nRaw, MSG_NOSIGNAL);
  size_t total = 0;

  if (nTrans != nRaw) esyslog("ERROR: failed to transmit response header! (%d <> %d)", nRaw, nTrans);
  while ((nRaw = Response->ReadContentChunk(scratch, bufSize)) > 0) {
        int nTrans = send(fdClient, scratch, nRaw, MSG_NOSIGNAL);

        if (nTrans < 1) {
           esyslog("failed to transmit chunk. Error #%d", errno);
           Response->HandleAbort();
           break;
           }
        total += nTrans;
        if (nTrans == nRaw) isyslog("successfully written message chunk of %d bytes", nTrans);
        else esyslog("failed to transmit response chunk (%d <> %d)", nRaw, nTrans);
        }
  if (total != Response->ContentSize())
     esyslog("failed to transfer response - should be %ld, was %ld", Response->ContentSize(), total);
//#ifdef DEBUG
//  close(fdClient);
//#endif
}

void cConnectionHandler::RegisterDefaultHandler(cHTTPRequestHandler *DefaultHandler)
{
  registeredHandlers.SetDefaultHandler(DefaultHandler);
}

void cConnectionHandler::RegisterRequestHandler(const char *UrlPrefix, cHTTPRequestHandler *RequestHandler)
{
  registeredHandlers.SetHandler(UrlPrefix, RequestHandler);
}