summaryrefslogtreecommitdiffstats
path: root/xbmc/utils/HttpRangeUtils.cpp
blob: 18ad32ba00ad85e3abb8134c3370a9e38b37a3d0 (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
/*
 *  Copyright (C) 2015-2018 Team Kodi
 *  This file is part of Kodi - https://kodi.tv
 *
 *  SPDX-License-Identifier: GPL-2.0-or-later
 *  See LICENSES/README.md for more information.
 */

#include <algorithm>

#include "HttpRangeUtils.h"
#include "Util.h"
#ifdef HAS_WEB_SERVER
#include "network/httprequesthandler/IHTTPRequestHandler.h"
#endif // HAS_WEB_SERVER
#include "utils/StringUtils.h"
#include "utils/Variant.h"

#include <inttypes.h>

#define HEADER_NEWLINE        "\r\n"
#define HEADER_SEPARATOR      HEADER_NEWLINE HEADER_NEWLINE
#define HEADER_BOUNDARY       "--"

#define HEADER_CONTENT_RANGE_VALUE "{}"
#define HEADER_CONTENT_RANGE_VALUE_UNKNOWN  "*"
#define HEADER_CONTENT_RANGE_FORMAT_BYTES   "bytes " HEADER_CONTENT_RANGE_VALUE "-" HEADER_CONTENT_RANGE_VALUE "/"
#define CONTENT_RANGE_FORMAT_TOTAL          HEADER_CONTENT_RANGE_FORMAT_BYTES HEADER_CONTENT_RANGE_VALUE
#define CONTENT_RANGE_FORMAT_TOTAL_UNKNOWN  HEADER_CONTENT_RANGE_FORMAT_BYTES HEADER_CONTENT_RANGE_VALUE_UNKNOWN

CHttpRange::CHttpRange(uint64_t firstPosition, uint64_t lastPosition)
  : m_first(firstPosition),
    m_last(lastPosition)
{ }

bool CHttpRange::operator<(const CHttpRange &other) const
{
  return (m_first < other.m_first) ||
         (m_first == other.m_first && m_last < other.m_last);
}

bool CHttpRange::operator==(const CHttpRange &other) const
{
  return m_first == other.m_first && m_last == other.m_last;
}

bool CHttpRange::operator!=(const CHttpRange &other) const
{
  return !(*this == other);
}

uint64_t CHttpRange::GetLength() const
{
  if (!IsValid())
    return 0;

  return m_last - m_first + 1;
}

void CHttpRange::SetLength(uint64_t length)
{
  m_last = m_first + length - 1;
}

bool CHttpRange::IsValid() const
{
  return m_last >= m_first;
}

CHttpResponseRange::CHttpResponseRange()
  : CHttpRange(),
    m_data(NULL)
{ }

CHttpResponseRange::CHttpResponseRange(uint64_t firstPosition, uint64_t lastPosition)
  : CHttpRange(firstPosition, lastPosition),
    m_data(NULL)
{ }

CHttpResponseRange::CHttpResponseRange(const void* data, uint64_t firstPosition, uint64_t lastPosition)
  : CHttpRange(firstPosition, lastPosition),
    m_data(data)
{ }

CHttpResponseRange::CHttpResponseRange(const void* data, uint64_t length)
  : CHttpRange(0, length - 1),
    m_data(data)
{ }

bool CHttpResponseRange::operator==(const CHttpResponseRange &other) const
{
  if (!CHttpRange::operator==(other))
    return false;

  return m_data == other.m_data;
}

bool CHttpResponseRange::operator!=(const CHttpResponseRange &other) const
{
  return !(*this == other);
}

void CHttpResponseRange::SetData(const void* data, uint64_t length)
{
  if (length == 0)
    return;

  m_first = 0;

  SetData(data);
  SetLength(length);
}

void CHttpResponseRange::SetData(const void* data, uint64_t firstPosition, uint64_t lastPosition)
{
  SetData(data);
  SetFirstPosition(firstPosition);
  SetLastPosition(lastPosition);
}

bool CHttpResponseRange::IsValid() const
{
  if (!CHttpRange::IsValid())
    return false;

  return m_data != NULL;
}

CHttpRanges::CHttpRanges()
: m_ranges()
{ }

CHttpRanges::CHttpRanges(const HttpRanges& httpRanges)
: m_ranges(httpRanges)
{
  SortAndCleanup();
}

bool CHttpRanges::Get(size_t index, CHttpRange& range) const
{
  if (index >= Size())
    return false;

  range = m_ranges.at(index);
  return true;
}

bool CHttpRanges::GetFirst(CHttpRange& range) const
{
  if (m_ranges.empty())
    return false;

  range = m_ranges.front();
  return true;
}

bool CHttpRanges::GetLast(CHttpRange& range) const
{
  if (m_ranges.empty())
    return false;

  range = m_ranges.back();
  return true;
}

bool CHttpRanges::GetFirstPosition(uint64_t& position) const
{
  if (m_ranges.empty())
    return false;

  position = m_ranges.front().GetFirstPosition();
  return true;
}

bool CHttpRanges::GetLastPosition(uint64_t& position) const
{
  if (m_ranges.empty())
    return false;

  position = m_ranges.back().GetLastPosition();
  return true;
}

uint64_t CHttpRanges::GetLength() const
{
  uint64_t length = 0;
  for (HttpRanges::const_iterator range = m_ranges.begin(); range != m_ranges.end(); ++range)
    length += range->GetLength();

  return length;
}

bool CHttpRanges::GetTotalRange(CHttpRange& range) const
{
  if (m_ranges.empty())
    return false;

  uint64_t firstPosition, lastPosition;
  if (!GetFirstPosition(firstPosition) || !GetLastPosition(lastPosition))
    return false;

  range.SetFirstPosition(firstPosition);
  range.SetLastPosition(lastPosition);

  return range.IsValid();
}

void CHttpRanges::Add(const CHttpRange& range)
{
  if (!range.IsValid())
    return;

  m_ranges.push_back(range);

  SortAndCleanup();
}

void CHttpRanges::Remove(size_t index)
{
  if (index >= Size())
    return;

  m_ranges.erase(m_ranges.begin() + index);
}

void CHttpRanges::Clear()
{
  m_ranges.clear();
}

bool CHttpRanges::Parse(const std::string& header)
{
  return Parse(header, std::numeric_limits<uint64_t>::max());
}

bool CHttpRanges::Parse(const std::string& header, uint64_t totalLength)
{
  m_ranges.clear();

  if (header.empty() || totalLength == 0 || !StringUtils::StartsWithNoCase(header, "bytes="))
    return false;

  uint64_t lastPossiblePosition = totalLength - 1;

  // remove "bytes=" from the beginning
  std::string rangesValue = header.substr(6);

  // split the value of the "Range" header by ","
  std::vector<std::string> rangeValues = StringUtils::Split(rangesValue, ",");

  for (std::vector<std::string>::const_iterator range = rangeValues.begin(); range != rangeValues.end(); ++range)
  {
    // there must be a "-" in the range definition
    if (range->find("-") == std::string::npos)
      return false;

    std::vector<std::string> positions = StringUtils::Split(*range, "-");
    if (positions.size() != 2)
      return false;

    bool hasStart = false;
    uint64_t start = 0;
    bool hasEnd = false;
    uint64_t end = 0;

    // parse the start and end positions
    if (!positions.front().empty())
    {
      if (!StringUtils::IsNaturalNumber(positions.front()))
        return false;

      start = str2uint64(positions.front(), 0);
      hasStart = true;
    }
    if (!positions.back().empty())
    {
      if (!StringUtils::IsNaturalNumber(positions.back()))
        return false;

      end = str2uint64(positions.back(), 0);
      hasEnd = true;
    }

    // nothing defined at all
    if (!hasStart && !hasEnd)
      return false;

    // make sure that the end position makes sense
    if (hasEnd)
      end = std::min(end, lastPossiblePosition);

    if (!hasStart && hasEnd)
    {
      // the range is defined as the number of bytes from the end
      start = totalLength - end;
      end = lastPossiblePosition;
    }
    else if (hasStart && !hasEnd)
      end = lastPossiblePosition;

    // make sure the start position makes sense
    if (start > lastPossiblePosition)
      return false;

    // make sure that the start position is smaller or equal to the end position
    if (end < start)
      return false;

    m_ranges.push_back(CHttpRange(start, end));
  }

  if (m_ranges.empty())
    return false;

  SortAndCleanup();
  return !m_ranges.empty();
}

void CHttpRanges::SortAndCleanup()
{
  // sort the ranges by their first position
  std::sort(m_ranges.begin(), m_ranges.end());

  // check for overlapping ranges
  for (HttpRanges::iterator range = m_ranges.begin() + 1; range != m_ranges.end();)
  {
    HttpRanges::iterator previous = range - 1;

    // check if the current and the previous range overlap
    if (previous->GetLastPosition() + 1 >= range->GetFirstPosition())
    {
      // combine the previous and the current ranges by setting the last position of the previous range
      // to the last position of the current range
      previous->SetLastPosition(range->GetLastPosition());

      // then remove the current range which is not needed anymore
      range = m_ranges.erase(range);
    }
    else
      ++range;
  }
}

std::string HttpRangeUtils::GenerateContentRangeHeaderValue(const CHttpRange* range)
{
  if (range == NULL)
    return "";

  return StringUtils::Format(CONTENT_RANGE_FORMAT_TOTAL, range->GetFirstPosition(), range->GetLastPosition(), range->GetLength());
}

std::string HttpRangeUtils::GenerateContentRangeHeaderValue(uint64_t start, uint64_t end, uint64_t total)
{
  if (total > 0)
    return StringUtils::Format(CONTENT_RANGE_FORMAT_TOTAL, start, end, total);

  return StringUtils::Format(CONTENT_RANGE_FORMAT_TOTAL_UNKNOWN, start, end);
}

#ifdef HAS_WEB_SERVER

std::string HttpRangeUtils::GenerateMultipartBoundary()
{
  static char chars[] = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

  // create a string of length 30 to 40 and pre-fill it with "-"
  size_t count = static_cast<size_t>(CUtil::GetRandomNumber()) % 11 + 30;
  std::string boundary(count, '-');

  for (size_t i = static_cast<size_t>(CUtil::GetRandomNumber()) % 5 + 8; i < count; i++)
    boundary.replace(i, 1, 1, chars[static_cast<size_t>(CUtil::GetRandomNumber()) % 64]);

  return boundary;
}

std::string HttpRangeUtils::GenerateMultipartBoundaryContentType(const std::string& multipartBoundary)
{
  if (multipartBoundary.empty())
    return "";

  return "multipart/byteranges; boundary=" + multipartBoundary;
}

std::string HttpRangeUtils::GenerateMultipartBoundaryWithHeader(const std::string& multipartBoundary, const std::string& contentType)
{
  if (multipartBoundary.empty())
    return "";

  std::string boundaryWithHeader = HEADER_BOUNDARY + multipartBoundary + HEADER_NEWLINE;
  if (!contentType.empty())
    boundaryWithHeader += MHD_HTTP_HEADER_CONTENT_TYPE ": " + contentType + HEADER_NEWLINE;

  return boundaryWithHeader;
}

std::string HttpRangeUtils::GenerateMultipartBoundaryWithHeader(const std::string& multipartBoundary, const std::string& contentType, const CHttpRange* range)
{
  if (multipartBoundary.empty() || range == NULL)
    return "";

  return GenerateMultipartBoundaryWithHeader(GenerateMultipartBoundaryWithHeader(multipartBoundary, contentType), range);
}

std::string HttpRangeUtils::GenerateMultipartBoundaryWithHeader(const std::string& multipartBoundaryWithContentType, const CHttpRange* range)
{
  if (multipartBoundaryWithContentType.empty() || range == NULL)
    return "";

  std::string boundaryWithHeader = multipartBoundaryWithContentType;
  boundaryWithHeader += MHD_HTTP_HEADER_CONTENT_RANGE ": " + GenerateContentRangeHeaderValue(range);
  boundaryWithHeader += HEADER_SEPARATOR;

  return boundaryWithHeader;
}

std::string HttpRangeUtils::GenerateMultipartBoundaryEnd(const std::string& multipartBoundary)
{
  if (multipartBoundary.empty())
    return "";

  return HEADER_NEWLINE HEADER_BOUNDARY + multipartBoundary + HEADER_BOUNDARY;
}

#endif // HAS_WEB_SERVER