MythTV  master
httprequest.cpp
Go to the documentation of this file.
1 // Program Name: httprequest.cpp
3 // Created : Oct. 21, 2005
4 //
5 // Purpose : Http Request/Response
6 //
7 // Copyright (c) 2005 David Blain <dblain@mythtv.org>
8 //
9 // Licensed under the GPL v2 or later, see LICENSE for details
10 //
12 
13 #include "httprequest.h"
14 
15 #include <QFile>
16 #include <QFileInfo>
17 #include <QHostInfo>
18 #include <QStringList>
19 #include <QCryptographicHash>
20 #include <QDateTime>
21 #include <Qt>
22 
23 #include <cerrno>
24 #include <cstdlib>
25 #include <fcntl.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <unistd.h> // for gethostname
29 // FOR DEBUGGING
30 #include <iostream>
31 
32 #ifndef _WIN32
33 #include <netinet/tcp.h>
34 #endif
35 
36 #include "upnp.h"
37 
38 #include "libmythbase/compat.h"
41 #include "libmythbase/mythdate.h"
43 #include "libmythbase/mythtimer.h"
44 #include "libmythbase/mythversion.h"
45 #include "libmythbase/unziputil.h"
46 
51 
52 #ifndef O_LARGEFILE
53 #define O_LARGEFILE 0
54 #endif
55 
56 static std::array<const MIMETypes,66> g_MIMETypes
57 {{
58  // Image Mime Types
59  { "gif" , "image/gif" },
60  { "ico" , "image/x-icon" },
61  { "jpeg", "image/jpeg" },
62  { "jpg" , "image/jpeg" },
63  { "mng" , "image/x-mng" },
64  { "png" , "image/png" },
65  { "svg" , "image/svg+xml" },
66  { "svgz", "image/svg+xml" },
67  { "tif" , "image/tiff" },
68  { "tiff", "image/tiff" },
69  // Text Mime Types
70  { "htm" , "text/html" },
71  { "html", "text/html" },
72  { "qsp" , "text/html" },
73  { "txt" , "text/plain" },
74  { "xml" , "text/xml" },
75  { "qxml", "text/xml" },
76  { "xslt", "text/xml" },
77  { "css" , "text/css" },
78  // Application Mime Types
79  { "crt" , "application/x-x509-ca-cert" },
80  { "doc" , "application/vnd.ms-word" },
81  { "gz" , "application/x-tar" },
82  { "js" , "application/javascript" },
83  { "m3u" , "application/x-mpegurl" }, // HTTP Live Streaming
84  { "m3u8", "application/x-mpegurl" }, // HTTP Live Streaming
85  { "ogx" , "application/ogg" }, // http://wiki.xiph.org/index.php/MIME_Types_and_File_Extensions
86  { "pdf" , "application/pdf" },
87  { "pem" , "application/x-x509-ca-cert" },
88  { "qjs" , "application/javascript" },
89  { "rm" , "application/vnd.rn-realmedia" },
90  { "swf" , "application/x-shockwave-flash" },
91  { "xls" , "application/vnd.ms-excel" },
92  { "zip" , "application/x-tar" },
93  // Audio Mime Types:
94  { "aac" , "audio/mp4" },
95  { "ac3" , "audio/vnd.dolby.dd-raw" }, // DLNA?
96  { "flac", "audio/x-flac" }, // This may become audio/flac in the future
97  { "m4a" , "audio/x-m4a" },
98  { "mid" , "audio/midi" },
99  { "mka" , "audio/x-matroska" },
100  { "mp3" , "audio/mpeg" },
101  { "oga" , "audio/ogg" }, // Defined: http://wiki.xiph.org/index.php/MIME_Types_and_File_Extensions
102  { "ogg" , "audio/ogg" }, // Defined: http://wiki.xiph.org/index.php/MIME_Types_and_File_Extensions
103  { "wav" , "audio/wav" },
104  { "wma" , "audio/x-ms-wma" },
105  // Video Mime Types
106  { "3gp" , "video/3gpp" }, // Also audio/3gpp
107  { "3g2" , "video/3gpp2" }, // Also audio/3gpp2
108  { "asx" , "video/x-ms-asf" },
109  { "asf" , "video/x-ms-asf" },
110  { "avi" , "video/x-msvideo" }, // Also video/avi
111  { "m2p" , "video/mp2p" }, // RFC 3555
112  { "m4v" , "video/mp4" },
113  { "mpeg", "video/mp2p" }, // RFC 3555
114  { "mpeg2","video/mp2p" }, // RFC 3555
115  { "mpg" , "video/mp2p" }, // RFC 3555
116  { "mpg2", "video/mp2p" }, // RFC 3555
117  { "mov" , "video/quicktime" },
118  { "mp4" , "video/mp4" },
119  { "mkv" , "video/x-matroska" }, // See http://matroska.org/technical/specs/notes.html#MIME (See NOTE 1)
120  { "nuv" , "video/nupplevideo" },
121  { "ogv" , "video/ogg" }, // Defined: http://wiki.xiph.org/index.php/MIME_Types_and_File_Extensions
122  { "ps" , "video/mp2p" }, // RFC 3555
123  { "ts" , "video/mp2t" }, // RFC 3555
124  { "vob" , "video/mpeg" }, // Also video/dvd
125  { "wmv" , "video/x-ms-wmv" },
126  // Font Mime Types
127  { "ttf" , "font/ttf" },
128  { "woff" , "font/woff" },
129  { "woff2", "font/woff2" }
130 }};
131 
132 // NOTE 1
133 // This formerly was video/x-matroska, but got changed due to #8643
134 // This was reverted from video/x-mkv, due to #10980
135 // See http://matroska.org/technical/specs/notes.html#MIME
136 // If you can't please everyone, may as well be correct as you piss some off
137 
138 static QString StaticPage =
139  "<!DOCTYPE html>"
140  "<HTML>"
141  "<HEAD>"
142  "<TITLE>Error %1</TITLE>"
143  "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=ISO-8859-1\">"
144  "</HEAD>"
145  "<BODY><H1>%2.</H1></BODY>"
146  "</HTML>";
147 
148 const char *HTTPRequest::s_szServerHeaders = "Accept-Ranges: bytes\r\n";
149 
151 //
153 
154 QString HTTPRequest::GetLastHeader( const QString &sType ) const
155 {
156  QStringList values = m_mapHeaders.values( sType );
157  if (!values.isEmpty())
158  return values.last();
159  return {};
160 }
161 
163 //
165 
167 {
168  // HTTP
169  if (sType == "GET" ) return( m_eType = RequestTypeGet );
170  if (sType == "HEAD" ) return( m_eType = RequestTypeHead );
171  if (sType == "POST" ) return( m_eType = RequestTypePost );
172  if (sType == "OPTIONS" ) return( m_eType = RequestTypeOptions );
173 
174  // UPnP
175  if (sType == "M-SEARCH" ) return( m_eType = RequestTypeMSearch );
176  if (sType == "NOTIFY" ) return( m_eType = RequestTypeNotify );
177  if (sType == "SUBSCRIBE" ) return( m_eType = RequestTypeSubscribe );
178  if (sType == "UNSUBSCRIBE") return( m_eType = RequestTypeUnsubscribe );
179 
180  if (sType.startsWith( QString("HTTP/") )) return( m_eType = RequestTypeResponse );
181 
182  LOG(VB_HTTP, LOG_INFO,
183  QString("HTTPRequest::SentRequestType( %1 ) - returning Unknown.")
184  .arg(sType));
185 
186  return( m_eType = RequestTypeUnknown);
187 }
188 
190 //
192 
193 QString HTTPRequest::BuildResponseHeader( long long nSize )
194 {
195  QString sHeader;
196  QString sContentType = (m_eResponseType == ResponseTypeOther) ?
198  //-----------------------------------------------------------------------
199  // Headers describing the connection
200  //-----------------------------------------------------------------------
201 
202  // The protocol string
203  sHeader = QString( "%1 %2\r\n" ).arg(GetResponseProtocol(),
205 
208 
209  SetResponseHeader("Connection", m_bKeepAlive ? "Keep-Alive" : "Close" );
210  if (m_bKeepAlive)
211  {
212  if (m_nKeepAliveTimeout == 0s) // Value wasn't passed in by the server, so go with the configured value
213  m_nKeepAliveTimeout = gCoreContext->GetDurSetting<std::chrono::seconds>("HTTP/KeepAliveTimeoutSecs", 10s);
214  SetResponseHeader("Keep-Alive", QString("timeout=%1").arg(m_nKeepAliveTimeout.count()));
215  }
216 
217  //-----------------------------------------------------------------------
218  // Entity Headers - Describe the content and allowed methods
219  // RFC 2616 Section 7.1
220  //-----------------------------------------------------------------------
221  if (m_eResponseType != ResponseTypeHeader) // No entity headers
222  {
223  SetResponseHeader("Content-Language", gCoreContext->GetLanguageAndVariant().replace("_", "-"));
224  SetResponseHeader("Content-Type", sContentType);
225 
226  // Default to 'inline' but we should support 'attachment' when it would
227  // be appropriate i.e. not when streaming a file to a upnp player or browser
228  // that can support it natively
229  if (!m_sFileName.isEmpty())
230  {
231  // TODO: Add support for utf8 encoding - RFC 5987
232  QString filename = QFileInfo(m_sFileName).fileName(); // Strip any path
233  SetResponseHeader("Content-Disposition", QString("inline; filename=\"%2\"").arg(QString(filename.toLatin1())));
234  }
235 
236  SetResponseHeader("Content-Length", QString::number(nSize));
237 
238  // See DLNA 7.4.1.3.11.4.3 Tolerance to unavailable contentFeatures.dlna.org header
239  //
240  // It is better not to return this header, than to return it containing
241  // invalid or incomplete information. We are unable to currently determine
242  // this information at this stage, so do not return it. Only older devices
243  // look for it. Newer devices use the information provided in the UPnP
244  // response
245 
246 // QString sValue = GetHeaderValue( "getContentFeatures.dlna.org", "0" );
247 //
248 // if (sValue == "1")
249 // sHeader += "contentFeatures.dlna.org: DLNA.ORG_OP=01;DLNA.ORG_CI=0;"
250 // "DLNA.ORG_FLAGS=01500000000000000000000000000000\r\n";
251 
252 
253  // DLNA 7.5.4.3.2.33 MT transfer mode indication
254  QString sTransferMode = GetRequestHeader( "transferMode.dlna.org", "" );
255 
256  if (sTransferMode.isEmpty())
257  {
258  if (m_sResponseTypeText.startsWith("video/") ||
259  m_sResponseTypeText.startsWith("audio/"))
260  sTransferMode = "Streaming";
261  else
262  sTransferMode = "Interactive";
263  }
264 
265  if (sTransferMode == "Streaming")
266  SetResponseHeader("transferMode.dlna.org", "Streaming");
267  else if (sTransferMode == "Background")
268  SetResponseHeader("transferMode.dlna.org", "Background");
269  else if (sTransferMode == "Interactive")
270  SetResponseHeader("transferMode.dlna.org", "Interactive");
271 
272  // HACK Temporary hack for Samsung TVs - Needs to be moved later as it's not entirely DLNA compliant
273  if (!GetRequestHeader( "getcontentFeatures.dlna.org", "" ).isEmpty())
274  SetResponseHeader("contentFeatures.dlna.org", "DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01500000000000000000000000000000");
275  }
276 
277  auto values = m_mapHeaders.values("origin");
278  for (const auto & value : std::as_const(values))
279  AddCORSHeaders(value);
280 
281  if (qEnvironmentVariableIsSet("HTTPREQUEST_DEBUG"))
282  {
283  // Dump response header
284  QMap<QString, QString>::iterator it;
285  for ( it = m_mapRespHeaders.begin(); it != m_mapRespHeaders.end(); ++it )
286  {
287  LOG(VB_HTTP, LOG_INFO, QString("(Response Header) %1: %2").arg(it.key(), it.value()));
288  }
289  }
290 
291  sHeader += GetResponseHeaders();
292  sHeader += "\r\n";
293 
294  return sHeader;
295 }
296 
298 //
300 
302 {
303  qint64 nBytes = 0;
304 
305  switch( m_eResponseType )
306  {
307  // The following are all eligable for gzip compression
308  case ResponseTypeUnknown:
309  case ResponseTypeNone:
310  LOG(VB_HTTP, LOG_INFO,
311  QString("HTTPRequest::SendResponse( None ) :%1 -> %2:")
312  .arg(GetResponseStatus(), GetPeerAddress()));
313  return( -1 );
314  case ResponseTypeJS:
315  case ResponseTypeCSS:
316  case ResponseTypeText:
317  case ResponseTypeSVG:
318  case ResponseTypeXML:
319  case ResponseTypeHTML:
320  // If the reponse isn't already in the buffer, then load it
321  if (m_sFileName.isEmpty() || !m_response.buffer().isEmpty())
322  break;
323  {
324  QFile file(m_sFileName);
325  if (file.exists() && file.size() < (2LL * 1024 * 1024) && // For security/stability, limit size of files read into buffer to 2MiB
326  file.open(QIODevice::ReadOnly | QIODevice::Text))
327  m_response.buffer() = file.readAll();
328 
329  if (!m_response.buffer().isEmpty())
330  break;
331 
332  // Let SendResponseFile try or send a 404
334  }
335  [[fallthrough]];
336  case ResponseTypeFile: // Binary files
337  LOG(VB_HTTP, LOG_INFO,
338  QString("HTTPRequest::SendResponse( File ) :%1 -> %2:")
339  .arg(GetResponseStatus(), GetPeerAddress()));
340  return( SendResponseFile( m_sFileName ));
341  case ResponseTypeOther:
342  case ResponseTypeHeader:
343  default:
344  break;
345  }
346 
347  LOG(VB_HTTP, LOG_INFO,
348  QString("HTTPRequest::SendResponse(xml/html) (%1) :%2 -> %3: %4")
350  QString::number(m_eResponseType)));
351 
352  // ----------------------------------------------------------------------
353  // Check for ETag match...
354  // ----------------------------------------------------------------------
355 
356  QString sETag = GetRequestHeader( "If-None-Match", "" );
357 
358  if ( !sETag.isEmpty() && sETag == m_mapRespHeaders[ "ETag" ] )
359  {
360  LOG(VB_HTTP, LOG_INFO,
361  QString("HTTPRequest::SendResponse(%1) - Cached")
362  .arg(sETag));
363 
364  m_nResponseStatus = 304;
365  m_eResponseType = ResponseTypeHeader; // No entity headers
366 
367  // no content can be returned.
368  m_response.buffer().clear();
369  }
370 
371  // ----------------------------------------------------------------------
372 
373  int nContentLen = m_response.buffer().length();
374 
375  QBuffer *pBuffer = &m_response;
376 
377  // ----------------------------------------------------------------------
378  // DEBUGGING
379  if (qEnvironmentVariableIsSet("HTTPREQUEST_DEBUG"))
380  std::cout << m_response.buffer().constData() << std::endl;
381  // ----------------------------------------------------------------------
382 
383  LOG(VB_HTTP, LOG_DEBUG, QString("Reponse Content Length: %1").arg(nContentLen));
384 
385  // ----------------------------------------------------------------------
386  // Should we try to return data gzip'd?
387  // ----------------------------------------------------------------------
388 
389  QBuffer compBuffer;
390 
391  auto values = m_mapHeaders.values("accept-encoding");
392  bool gzip_found = std::any_of(values.cbegin(), values.cend(),
393  [](const auto & value)
394  {return value.contains( "gzip" ); });
395 
396  if (( nContentLen > 0 ) && gzip_found)
397  {
398  QByteArray compressed = gzipCompress( m_response.buffer() );
399  compBuffer.setData( compressed );
400 
401  if (!compBuffer.buffer().isEmpty())
402  {
403  pBuffer = &compBuffer;
404 
405  SetResponseHeader( "Content-Encoding", "gzip" );
406  LOG(VB_HTTP, LOG_DEBUG, QString("Reponse Compressed Content Length: %1").arg(compBuffer.buffer().length()));
407  }
408  }
409 
410  // ----------------------------------------------------------------------
411  // Write out Header.
412  // ----------------------------------------------------------------------
413 
414  nContentLen = pBuffer->buffer().length();
415 
416  QString rHeader = BuildResponseHeader( nContentLen );
417 
418  QByteArray sHeader = rHeader.toUtf8();
419  LOG(VB_HTTP, LOG_DEBUG, QString("Response header size: %1 bytes").arg(sHeader.length()));
420  nBytes = WriteBlock( sHeader.constData(), sHeader.length() );
421 
422  if (nBytes < sHeader.length())
423  {
424  LOG( VB_HTTP, LOG_ERR, QString("HttpRequest::SendResponse(): "
425  "Incomplete write of header, "
426  "%1 written of %2")
427  .arg(nBytes).arg(sHeader.length()));
428  }
429 
430  // ----------------------------------------------------------------------
431  // Write out Response buffer.
432  // ----------------------------------------------------------------------
433 
434  if (( m_eType != RequestTypeHead ) &&
435  ( nContentLen > 0 ))
436  {
437  qint64 bytesWritten = SendData( pBuffer, 0, nContentLen );
438  //qint64 bytesWritten = WriteBlock( pBuffer->buffer(), pBuffer->buffer().length() );
439 
440  if (bytesWritten != nContentLen)
441  LOG(VB_HTTP, LOG_ERR, "HttpRequest::SendResponse(): Error occurred while writing response body.");
442  else
443  nBytes += bytesWritten;
444  }
445 
446  return( nBytes );
447 }
448 
450 //
452 
453 qint64 HTTPRequest::SendResponseFile( const QString& sFileName )
454 {
455  qint64 nBytes = 0;
456  long long llSize = 0;
457  long long llStart = 0;
458  long long llEnd = 0;
459 
460  LOG(VB_HTTP, LOG_INFO, QString("SendResponseFile ( %1 )").arg(sFileName));
461 
463  m_sResponseTypeText = "text/plain";
464 
465  QFile tmpFile( sFileName );
466  if (tmpFile.exists( ) && tmpFile.open( QIODevice::ReadOnly ))
467  {
468 
469  m_sResponseTypeText = TestMimeType( sFileName );
470 
471  // ------------------------------------------------------------------
472  // Get File size
473  // ------------------------------------------------------------------
474 
475  llSize = llEnd = tmpFile.size( );
476 
477  m_nResponseStatus = 200;
478 
479  // ------------------------------------------------------------------
480  // Process any Range Header
481  // ------------------------------------------------------------------
482 
483  bool bRange = false;
484  QString sRange = GetRequestHeader( "range", "" );
485 
486  if (!sRange.isEmpty())
487  {
488  bRange = ParseRange( sRange, llSize, &llStart, &llEnd );
489 
490  // Adjust ranges that are too long.
491 
492  if (llEnd >= llSize)
493  llEnd = llSize-1;
494 
495  if ((llSize > llStart) && (llSize > llEnd) && (llEnd > llStart))
496  {
497  if (bRange)
498  {
499  m_nResponseStatus = 206;
500  m_mapRespHeaders[ "Content-Range" ] = QString("bytes %1-%2/%3")
501  .arg( llStart )
502  .arg( llEnd )
503  .arg( llSize );
504  llSize = (llEnd - llStart) + 1;
505  }
506  }
507  else
508  {
509  m_nResponseStatus = 416;
510  // RFC 7233 - A server generating a 416 (Range Not Satisfiable)
511  // response to a byte-range request SHOULD send a Content-Range
512  // header field with an unsatisfied-range value
513  m_mapRespHeaders[ "Content-Range" ] = QString("bytes */%3")
514  .arg( llSize );
515  llSize = 0;
516  LOG(VB_HTTP, LOG_INFO,
517  QString("HTTPRequest::SendResponseFile(%1) - "
518  "invalid byte range %2-%3/%4")
519  .arg(sFileName) .arg(llStart) .arg(llEnd)
520  .arg(llSize));
521  }
522  }
523 
524  // HACK: D-Link DSM-320
525  // The following headers are only required by servers which don't support
526  // http keep alive. We do support it, so we don't need it. Keeping it in
527  // place to prevent someone re-adding it in future
528  //m_mapRespHeaders[ "X-User-Agent" ] = "redsonic";
529 
530  // ------------------------------------------------------------------
531  //
532  // ------------------------------------------------------------------
533 
534  }
535  else
536  {
537  LOG(VB_HTTP, LOG_INFO,
538  QString("HTTPRequest::SendResponseFile(%1) - cannot find file!")
539  .arg(sFileName));
540  m_nResponseStatus = 404;
541  m_response.write( GetResponsePage() );
542  }
543 
544  // -=>TODO: Should set "Content-Length: *" if file is still recording
545 
546  // ----------------------------------------------------------------------
547  // Write out Header.
548  // ----------------------------------------------------------------------
549 
550  QString rHeader = BuildResponseHeader( llSize );
551  QByteArray sHeader = rHeader.toUtf8();
552  LOG(VB_HTTP, LOG_DEBUG, QString("Response header size: %1 bytes").arg(sHeader.length()));
553  nBytes = WriteBlock( sHeader.constData(), sHeader.length() );
554 
555  if (nBytes < sHeader.length())
556  {
557  LOG( VB_HTTP, LOG_ERR, QString("HttpRequest::SendResponseFile(): "
558  "Incomplete write of header, "
559  "%1 written of %2")
560  .arg(nBytes).arg(sHeader.length()));
561  }
562 
563  // ----------------------------------------------------------------------
564  // Write out File.
565  // ----------------------------------------------------------------------
566 
567 #if 0
568  LOG(VB_HTTP, LOG_DEBUG,
569  QString("SendResponseFile : size = %1, start = %2, end = %3")
570  .arg(llSize).arg(llStart).arg(llEnd));
571 #endif
572  if (( m_eType != RequestTypeHead ) && (llSize != 0))
573  {
574  long long sent = SendFile( tmpFile, llStart, llSize );
575 
576  if (sent == -1)
577  {
578  LOG(VB_HTTP, LOG_INFO,
579  QString("SendResponseFile( %1 ) Error: %2 [%3]" )
580  .arg(sFileName) .arg(errno) .arg(strerror(errno)));
581 
582  nBytes = -1;
583  }
584  }
585 
586  // -=>TODO: Only returns header length...
587  // should we change to return total bytes?
588 
589  return nBytes;
590 }
591 
593 //
595 
596 static constexpr size_t SENDFILE_BUFFER_SIZE { 65536 };
597 
598 qint64 HTTPRequest::SendData( QIODevice *pDevice, qint64 llStart, qint64 llBytes )
599 {
600  bool bShouldClose = false;
601  qint64 sent = 0;
602 
603  if (!pDevice->isOpen())
604  {
605  pDevice->open( QIODevice::ReadOnly );
606  bShouldClose = true;
607  }
608 
609  // ----------------------------------------------------------------------
610  // Set out file position to requested start location.
611  // ----------------------------------------------------------------------
612 
613  if ( !pDevice->seek( llStart ))
614  return -1;
615 
616  std::array<char,SENDFILE_BUFFER_SIZE> aBuffer {};
617 
618  qint64 llBytesRemaining = llBytes;
619  qint64 llBytesToRead = 0;
620  qint64 llBytesRead = 0;
621 
622  while ((sent < llBytes) && !pDevice->atEnd())
623  {
624  llBytesToRead = std::min( (qint64)SENDFILE_BUFFER_SIZE, llBytesRemaining );
625  llBytesRead = pDevice->read( aBuffer.data(), llBytesToRead );
626  if ( llBytesRead != -1 )
627  {
628  if ( WriteBlock( aBuffer.data(), llBytesRead ) == -1)
629  return -1;
630 
631  // -=>TODO: We don't handle the situation where we read more than was sent.
632 
633  sent += llBytesRead;
634  llBytesRemaining -= llBytesRead;
635  }
636  }
637 
638  if (bShouldClose)
639  pDevice->close();
640 
641  return sent;
642 }
643 
645 //
647 
648 qint64 HTTPRequest::SendFile( QFile &file, qint64 llStart, qint64 llBytes )
649 {
650  qint64 sent = SendData( (QIODevice *)(&file), llStart, llBytes );
651 
652  return( sent );
653 }
654 
655 
657 //
659 
660 void HTTPRequest::FormatErrorResponse( bool bServerError,
661  const QString &sFaultString,
662  const QString &sDetails )
663 {
665  m_nResponseStatus = 500;
666 
667  QTextStream stream( &m_response );
668 
669  stream << R"(<?xml version="1.0" encoding="utf-8"?>)";
670 
671  QString sWhere = ( bServerError ) ? "s:Server" : "s:Client";
672 
673  if (m_bSOAPRequest)
674  {
675  m_mapRespHeaders[ "EXT" ] = "";
676 
677  stream << SOAP_ENVELOPE_BEGIN
678  << "<s:Fault>"
679  << "<faultcode>" << sWhere << "</faultcode>"
680  << "<faultstring>" << sFaultString << "</faultstring>";
681  }
682 
683  if (!sDetails.isEmpty())
684  {
685  stream << "<detail>" << sDetails << "</detail>";
686  }
687 
688  if (m_bSOAPRequest)
689  {
690  stream << "</s:Fault>" << SOAP_ENVELOPE_END;
691  }
692 
693  stream.flush();
694 }
695 
697 //
699 
701 {
704  m_nResponseStatus = 200;
705 
706  pSer->AddHeaders( m_mapRespHeaders );
707 
708  //m_response << pFormatter->ToString();
709 }
710 
712 //
714 
716 {
718  m_nResponseStatus = 200;
719 
720  QTextStream stream( &m_response );
721 
722  stream << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n";
723 
724  if (m_bSOAPRequest)
725  {
726  m_mapRespHeaders[ "EXT" ] = "";
727 
728  stream << SOAP_ENVELOPE_BEGIN
729  << "<u:" << m_sMethod << "Response xmlns:u=\""
730  << m_sNameSpace << "\">\r\n";
731  }
732  else
733  {
734  stream << "<" << m_sMethod << "Response>\r\n";
735  }
736 
737  for (const auto & arg : std::as_const(args))
738  {
739  stream << "<" << arg.m_sName;
740 
741  if (arg.m_pAttributes)
742  {
743  for (const auto & attr : std::as_const(*arg.m_pAttributes))
744  {
745  stream << " " << attr.m_sName << "='"
746  << Encode( attr.m_sValue ) << "'";
747  }
748  }
749 
750  stream << ">";
751 
752  if (m_bSOAPRequest)
753  stream << Encode( arg.m_sValue );
754  else
755  stream << arg.m_sValue;
756 
757  stream << "</" << arg.m_sName << ">\r\n";
758  }
759 
760  if (m_bSOAPRequest)
761  {
762  stream << "</u:" << m_sMethod << "Response>\r\n"
764  }
765  else
766  {
767  stream << "</" << m_sMethod << "Response>\r\n";
768  }
769 
770  stream.flush();
771 }
772 
774 //
776 
777 void HTTPRequest::FormatRawResponse(const QString &sXML)
778 {
780  m_nResponseStatus = 200;
781 
782  QTextStream stream( &m_response );
783 
784  stream << sXML;
785 
786  stream.flush();
787 }
789 //
791 
792 void HTTPRequest::FormatFileResponse( const QString &sFileName )
793 {
794  m_sFileName = sFileName;
795  QFileInfo file(m_sFileName);
796 
797  if (!m_sFileName.isEmpty() && file.exists())
798  {
799  QDateTime ims = QDateTime::fromString(GetRequestHeader("if-modified-since", ""), Qt::RFC2822Date);
800  ims.setTimeSpec(Qt::OffsetFromUTC);
801  if (ims.isValid() && ims <= file.lastModified()) // Strong validator
802  {
804  m_nResponseStatus = 304; // Not Modified
805  }
806  else
807  {
810  m_nResponseStatus = 200; // OK
811  SetResponseHeader("Last-Modified", MythDate::toString(file.lastModified(),
813  MythDate::kRFC822))); // RFC 822
814  SetResponseHeader("Cache-Control", "no-cache=\"Ext\", max-age = 7200"); // 2 Hours
815  }
816  }
817  else
818  {
820  m_nResponseStatus = 404; // Resource not found
821  m_response.write( GetResponsePage() );
822  LOG(VB_HTTP, LOG_INFO,
823  QString("HTTPRequest::FormatFileResponse('%1') - cannot find file")
824  .arg(sFileName));
825  }
826 }
827 
829 //
831 
832 void HTTPRequest::SetRequestProtocol( const QString &sLine )
833 {
834  m_sProtocol = sLine.section( '/', 0, 0 ).trimmed();
835  QString sVersion = sLine.section( '/', 1 ).trimmed();
836 
837  m_nMajor = sVersion.section( '.', 0, 0 ).toInt();
838  m_nMinor = sVersion.section( '.', 1 ).toInt();
839 }
840 
842 //
844 
846 {
847  return QString("%1/%2.%3").arg(m_sProtocol,
848  QString::number(m_nMajor),
849  QString::number(m_nMinor));
850 }
851 
853 //
855 
857 {
858  // RFC 2145
859  //
860  // An HTTP server SHOULD send a response version equal to the highest
861  // version for which the server is at least conditionally compliant, and
862  // whose major version is less than or equal to the one received in the
863  // request.
864 
865 // if (m_nMajor == 1)
866 // QString("HTTP/1.1");
867 // else if (m_nMajor == 2)
868 // QString("HTTP/2.0");
869 
870  return {"HTTP/1.1"};
871 }
872 
874 //
876 
878 {
879  if ((sType == "application/x-www-form-urlencoded" ) ||
880  (sType.startsWith("application/x-www-form-urlencoded;")))
882 
883  if ((sType == "text/xml" ) ||
884  (sType.startsWith("text/xml;") ))
885  return( m_eContentType = ContentType_XML );
886 
887  if ((sType == "application/json") ||
888  sType.startsWith("application/json;"))
889  return( m_eContentType = ContentType_JSON);
890 
892 }
893 
894 
896 //
898 
899 QString HTTPRequest::GetResponseStatus( void ) const
900 {
901  switch( m_nResponseStatus )
902  {
903  case 200: return( "200 OK" );
904  case 201: return( "201 Created" );
905  case 202: return( "202 Accepted" );
906  case 204: return( "204 No Content" );
907  case 205: return( "205 Reset Content" );
908  case 206: return( "206 Partial Content" );
909  case 300: return( "300 Multiple Choices" );
910  case 301: return( "301 Moved Permanently" );
911  case 302: return( "302 Found" );
912  case 303: return( "303 See Other" );
913  case 304: return( "304 Not Modified" );
914  case 305: return( "305 Use Proxy" );
915  case 307: return( "307 Temporary Redirect" );
916  case 308: return( "308 Permanent Redirect" );
917  case 400: return( "400 Bad Request" );
918  case 401: return( "401 Unauthorized" );
919  case 403: return( "403 Forbidden" );
920  case 404: return( "404 Not Found" );
921  case 405: return( "405 Method Not Allowed" );
922  case 406: return( "406 Not Acceptable" );
923  case 408: return( "408 Request Timeout" );
924  case 410: return( "410 Gone" );
925  case 411: return( "411 Length Required" );
926  case 412: return( "412 Precondition Failed" );
927  case 413: return( "413 Request Entity Too Large" );
928  case 414: return( "414 Request-URI Too Long" );
929  case 415: return( "415 Unsupported Media Type" );
930  case 416: return( "416 Requested Range Not Satisfiable" );
931  case 417: return( "417 Expectation Failed" );
932  // I'm a teapot
933  case 428: return( "428 Precondition Required" ); // RFC 6585
934  case 429: return( "429 Too Many Requests" ); // RFC 6585
935  case 431: return( "431 Request Header Fields Too Large" ); // RFC 6585
936  case 500: return( "500 Internal Server Error" );
937  case 501: return( "501 Not Implemented" );
938  case 502: return( "502 Bad Gateway" );
939  case 503: return( "503 Service Unavailable" );
940  case 504: return( "504 Gateway Timeout" );
941  case 505: return( "505 HTTP Version Not Supported" );
942  case 510: return( "510 Not Extended" );
943  case 511: return( "511 Network Authentication Required" ); // RFC 6585
944  }
945 
946  return( QString( "%1 Unknown" ).arg( m_nResponseStatus ));
947 }
948 
950 //
952 
954 {
955  return StaticPage.arg(QString::number(m_nResponseStatus), GetResponseStatus()).toUtf8();
956 }
957 
959 //
961 
962 QString HTTPRequest::GetResponseType( void ) const
963 {
964  switch( m_eResponseType )
965  {
966  case ResponseTypeXML : return( "text/xml; charset=\"UTF-8\"" );
967  case ResponseTypeHTML : return( "text/html; charset=\"UTF-8\"" );
968  case ResponseTypeCSS : return( "text/css; charset=\"UTF-8\"" );
969  case ResponseTypeJS : return( "application/javascript" );
970  case ResponseTypeText : return( "text/plain; charset=\"UTF-8\"" );
971  case ResponseTypeSVG : return( "image/svg+xml" );
972  default: break;
973  }
974 
975  return( "text/plain" );
976 }
977 
979 //
981 
982 QString HTTPRequest::GetMimeType( const QString &sFileExtension )
983 {
984  QString ext;
985 
986  for (const auto & type : g_MIMETypes)
987  {
988  ext = type.pszExtension;
989 
990  if ( sFileExtension.compare(ext, Qt::CaseInsensitive) == 0 )
991  return( type.pszType );
992  }
993 
994  return( "text/plain" );
995 }
996 
998 //
1000 
1002 {
1003  QStringList mimeTypes;
1004 
1005  for (const auto & type : g_MIMETypes)
1006  {
1007  if (!mimeTypes.contains( type.pszType ))
1008  mimeTypes.append( type.pszType );
1009  }
1010 
1011  return mimeTypes;
1012 }
1013 
1015 //
1017 
1018 QString HTTPRequest::TestMimeType( const QString &sFileName )
1019 {
1020  QFileInfo info( sFileName );
1021  QString sLOC = "HTTPRequest::TestMimeType(" + sFileName + ") - ";
1022  QString sSuffix = info.suffix().toLower();
1023  QString sMIME = GetMimeType( sSuffix );
1024 
1025  if ( sSuffix == "nuv" ) // If a very old recording, might be an MPEG?
1026  {
1027  // Read the header to find out:
1028  QFile file( sFileName );
1029 
1030  if ( file.open(QIODevice::ReadOnly | QIODevice::Text) )
1031  {
1032  QByteArray head = file.read(8);
1033  QString sHex = head.toHex();
1034 
1035  LOG(VB_HTTP, LOG_DEBUG, sLOC + "file starts with " + sHex);
1036 
1037  if ( sHex == "000001ba44000400" ) // MPEG2 PS
1038  sMIME = "video/mp2p";
1039 
1040  if ( head == "MythTVVi" )
1041  {
1042  file.seek(100);
1043  head = file.read(4);
1044 
1045  if ( head == "DIVX" )
1046  {
1047  LOG(VB_HTTP, LOG_DEBUG, sLOC + "('MythTVVi...DIVXLAME')");
1048  sMIME = "video/mp4";
1049  }
1050  // NuppelVideo is "RJPG" at byte 612
1051  // We could also check the audio (LAME or RAWA),
1052  // but since most UPnP clients choke on Nuppel, no need
1053  }
1054 
1055  file.close();
1056  }
1057  else
1058  {
1059  LOG(VB_GENERAL, LOG_ERR, sLOC + "Could not read file");
1060  }
1061  }
1062 
1063  LOG(VB_HTTP, LOG_INFO, sLOC + "type is " + sMIME);
1064  return sMIME;
1065 }
1066 
1068 //
1070 
1071 long HTTPRequest::GetParameters( QString sParams, QStringMap &mapParams )
1072 {
1073  long nCount = 0;
1074 
1075  LOG(VB_HTTP, LOG_INFO, QString("sParams: '%1'").arg(sParams));
1076 
1077  // This looks odd, but it is here to cope with stupid UPnP clients that
1078  // forget to de-escape the URLs. We can't map %26 here as well, as that
1079  // breaks anything that is trying to pass & as part of a name or value.
1080  sParams.replace( "&amp;", "&" );
1081 
1082  if (!sParams.isEmpty())
1083  {
1084  QStringList params = sParams.split('&', Qt::SkipEmptyParts);
1085  for (const auto & param : std::as_const(params))
1086  {
1087  QString sName = param.section( '=', 0, 0 );
1088  QString sValue = param.section( '=', 1 );
1089  sValue.replace("+"," ");
1090 
1091  if (!sName.isEmpty())
1092  {
1093  sName = QUrl::fromPercentEncoding(sName.toUtf8());
1094  sValue = QUrl::fromPercentEncoding(sValue.toUtf8());
1095 
1096  mapParams.insert( sName.trimmed(), sValue );
1097  nCount++;
1098  }
1099  }
1100  }
1101 
1102  return nCount;
1103 }
1104 
1105 
1107 //
1109 
1110 QString HTTPRequest::GetRequestHeader( const QString &sKey, const QString &sDefault )
1111 {
1112  auto it = m_mapHeaders.find( sKey.toLower() );
1113 
1114  if ( it == m_mapHeaders.end())
1115  return( sDefault );
1116 
1117  return *it;
1118 }
1119 
1120 
1122 //
1124 
1126 {
1127  QString sHeader = s_szServerHeaders;
1128 
1129  for ( QStringMap::iterator it = m_mapRespHeaders.begin();
1130  it != m_mapRespHeaders.end();
1131  ++it )
1132  {
1133  sHeader += it.key() + ": ";
1134  sHeader += *it + "\r\n";
1135  }
1136 
1137  return( sHeader );
1138 }
1139 
1141 //
1143 
1145 {
1146  // TODO: Think about whether we should use a longer timeout if the client
1147  // has explicitly specified 'Keep-alive'
1148 
1149  // HTTP 1.1 ... server may assume keep-alive
1150  bool bKeepAlive = true;
1151 
1152  // if HTTP/1.0... must default to false
1153  if ((m_nMajor == 1) && (m_nMinor == 0))
1154  bKeepAlive = false;
1155 
1156  // Read Connection Header to see whether the client has explicitly
1157  // asked for the connection to be kept alive or closed after the response
1158  // is sent
1159  QString sConnection = GetRequestHeader( "connection", "default" ).toLower();
1160 
1161  QStringList sValueList = sConnection.split(",");
1162 
1163  if ( sValueList.contains("close") )
1164  {
1165  LOG(VB_HTTP, LOG_DEBUG, "Client requested the connection be closed");
1166  bKeepAlive = false;
1167  }
1168  else if (sValueList.contains("keep-alive"))
1169  {
1170  bKeepAlive = true;
1171  }
1172 
1173  return bKeepAlive;
1174 }
1175 
1177 //
1179 
1181 {
1182  QStringList sCookieList = m_mapHeaders.values("cookie");
1183 
1184  QStringList::iterator it;
1185  for (it = sCookieList.begin(); it != sCookieList.end(); ++it)
1186  {
1187  QString key = (*it).section('=', 0, 0);
1188  QString value = (*it).section('=', 1);
1189 
1190  m_mapCookies.insert(key, value);
1191  }
1192 }
1193 
1195 //
1197 
1199 {
1200  bool bSuccess = false;
1201 
1202  try
1203  {
1204  // Read first line to determine requestType
1205  QString sRequestLine = ReadLine( 2s );
1206 
1207  if ( sRequestLine.isEmpty() )
1208  {
1209  LOG(VB_GENERAL, LOG_ERR, "Timeout reading first line of request." );
1210  return false;
1211  }
1212 
1213  // -=>TODO: Should read lines until a valid request???
1214  ProcessRequestLine( sRequestLine );
1215 
1216  if (m_nMajor > 1 || m_nMajor < 0)
1217  {
1219  m_nResponseStatus = 505;
1220  m_response.write( GetResponsePage() );
1221 
1222  return true;
1223  }
1224 
1225  if (m_eType == RequestTypeUnknown)
1226  {
1228  m_nResponseStatus = 501; // Not Implemented
1229  // Conservative list, we can't really know what methods we
1230  // actually allow for an arbitrary resource without some sort of
1231  // high maintenance database
1232  SetResponseHeader("Allow", "GET, HEAD");
1233  m_response.write( GetResponsePage() );
1234  return true;
1235  }
1236 
1237  // Read Header
1238  bool bDone = false;
1239  QString sLine = ReadLine( 2s );
1240 
1241  while (( !sLine.isEmpty() ) && !bDone )
1242  {
1243  if (sLine != "\r\n")
1244  {
1245  QString sName = sLine.section( ':', 0, 0 ).trimmed();
1246  QString sValue = sLine.section( ':', 1 );
1247 
1248  sValue.truncate( sValue.length() - 2 );
1249 
1250  if (!sName.isEmpty() && !sValue.isEmpty())
1251  {
1252  m_mapHeaders.insert(sName.toLower(), sValue.trimmed());
1253  }
1254 
1255  sLine = ReadLine( 2s );
1256  }
1257  else
1258  {
1259  bDone = true;
1260  }
1261  }
1262 
1263  // Dump request header
1264  for ( auto it = m_mapHeaders.begin(); it != m_mapHeaders.end(); ++it )
1265  {
1266  LOG(VB_HTTP, LOG_INFO, QString("(Request Header) %1: %2")
1267  .arg(it.key(), *it));
1268  }
1269 
1270  // Parse Cookies
1271  ParseCookies();
1272 
1273  // Parse out keep alive
1275 
1276  // Check to see if we found the end of the header or we timed out.
1277  if (!bDone)
1278  {
1279  LOG(VB_GENERAL, LOG_INFO, "Timeout waiting for request header." );
1280  return false;
1281  }
1282 
1283  // HTTP/1.1 requires that the Host header be present, even if empty
1284  if ((m_nMinor == 1) && !m_mapHeaders.contains("host"))
1285  {
1287  m_nResponseStatus = 400;
1288  m_response.write( GetResponsePage() );
1289 
1290  return true;
1291  }
1292 
1293  // Destroy session if requested
1294  if (m_mapHeaders.contains("x-myth-clear-session"))
1295  {
1296  SetCookie("sessionToken", "", MythDate::current().addDays(-2), true);
1297  m_mapCookies.remove("sessionToken");
1298  }
1299 
1300  // Allow session resumption for TLS connections
1301  if (m_mapCookies.contains("sessionToken"))
1302  {
1303  QString sessionToken = m_mapCookies["sessionToken"];
1304  MythSessionManager *sessionManager = gCoreContext->GetSessionManager();
1305  MythUserSession session = sessionManager->GetSession(sessionToken);
1306 
1307  if (session.IsValid())
1308  m_userSession = session;
1309  }
1310 
1311  if (IsUrlProtected( m_sBaseUrl ))
1312  {
1313  if (!Authenticated())
1314  {
1316  m_nResponseStatus = 401;
1317  m_response.write( GetResponsePage() );
1318  // Since this may not be the first attempt at authentication,
1319  // Authenticated may have set the header with the appropriate
1320  // stale attribute
1321  SetResponseHeader("WWW-Authenticate", GetAuthenticationHeader(false));
1322 
1323  return true;
1324  }
1325 
1326  m_bProtected = true;
1327  }
1328 
1329  bSuccess = true;
1330 
1331  SetContentType( GetLastHeader( "content-type" ) );
1332  // Lets load payload if any.
1333  long nPayloadSize = GetLastHeader( "content-length" ).toLong();
1334 
1335  if (nPayloadSize > 0)
1336  {
1337  char *pszPayload = new char[ nPayloadSize + 2 ];
1338  long nBytes = 0;
1339 
1340  nBytes = ReadBlock( pszPayload, nPayloadSize, 5s );
1341  if (nBytes == nPayloadSize )
1342  {
1343  m_sPayload = QString::fromUtf8( pszPayload, nPayloadSize );
1344 
1345  // See if the payload is just data from a form post
1349  m_mapParams.insert( "json", m_sPayload );
1350  }
1351  else
1352  {
1353  LOG(VB_GENERAL, LOG_ERR,
1354  QString("Unable to read entire payload (read %1 of %2 bytes)")
1355  .arg( nBytes ) .arg( nPayloadSize ) );
1356  bSuccess = false;
1357  }
1358 
1359  delete [] pszPayload;
1360  }
1361 
1362  // Check to see if this is a SOAP encoded message
1363  QString sSOAPAction = GetRequestHeader( "SOAPACTION", "" );
1364 
1365  if (!sSOAPAction.isEmpty())
1366  bSuccess = ProcessSOAPPayload( sSOAPAction );
1367  else
1369 
1370 #if 0
1371  if (m_sMethod != "*" )
1372  LOG(VB_HTTP, LOG_DEBUG,
1373  QString("HTTPRequest::ParseRequest - Socket (%1) Base (%2) "
1374  "Method (%3) - Bytes in Socket Buffer (%4)")
1375  .arg(getSocketHandle()) .arg(m_sBaseUrl)
1376  .arg(m_sMethod) .arg(BytesAvailable()));
1377 #endif
1378  }
1379  catch(...)
1380  {
1381  LOG(VB_GENERAL, LOG_WARNING,
1382  "Unexpected exception in HTTPRequest::ParseRequest" );
1383  }
1384 
1385  return bSuccess;
1386 }
1387 
1389 //
1391 
1392 void HTTPRequest::ProcessRequestLine( const QString &sLine )
1393 {
1394  m_sRawRequest = sLine;
1395 
1396  QStringList tokens = sLine.split(m_procReqLineExp, Qt::SkipEmptyParts);
1397  int nCount = tokens.count();
1398 
1399  // ----------------------------------------------------------------------
1400 
1401  if ( sLine.startsWith( QString("HTTP/") ))
1403  else
1405 
1406  // ----------------------------------------------------------------------
1407  // if this is actually a response, then sLine's format will be:
1408  // HTTP/m.n <response code> <response text>
1409  // otherwise:
1410  // <method> <Resource URI> HTTP/m.n
1411  // ----------------------------------------------------------------------
1412 
1414  {
1415  // ------------------------------------------------------------------
1416  // Process as a request
1417  // ------------------------------------------------------------------
1418 
1419  if (nCount > 0)
1420  SetRequestType( tokens[0].trimmed() );
1421 
1422  if (nCount > 1)
1423  {
1424  m_sOriginalUrl = tokens[1].toUtf8(); // Used by authorization check
1425  m_sRequestUrl = QUrl::fromPercentEncoding(tokens[1].toUtf8());
1426  m_sBaseUrl = m_sRequestUrl.section( '?', 0, 0).trimmed();
1427 
1428  m_sResourceUrl = m_sBaseUrl; // Save complete url without parameters
1429 
1430  // Process any Query String Parameters
1431  QString sQueryStr = tokens[1].section( '?', 1, 1 );
1432 
1433  if (!sQueryStr.isEmpty())
1434  GetParameters( sQueryStr, m_mapParams );
1435  }
1436 
1437  if (nCount > 2)
1438  SetRequestProtocol( tokens[2].trimmed() );
1439  }
1440  else
1441  {
1442  // ------------------------------------------------------------------
1443  // Process as a Response
1444  // ------------------------------------------------------------------
1445  if (nCount > 0)
1446  SetRequestProtocol( tokens[0].trimmed() );
1447 
1448  if (nCount > 1)
1449  m_nResponseStatus = tokens[1].toInt();
1450  }
1451 
1452 
1453 }
1454 
1456 //
1458 
1459 bool HTTPRequest::ParseRange( QString sRange,
1460  long long llSize,
1461  long long *pllStart,
1462  long long *pllEnd )
1463 {
1464  // ----------------------------------------------------------------------
1465  // -=>TODO: Only handle 1 range at this time...
1466  // should make work with full spec.
1467  // ----------------------------------------------------------------------
1468 
1469  if (sRange.isEmpty())
1470  return false;
1471 
1472  // ----------------------------------------------------------------------
1473  // remove any "bytes="
1474  // ----------------------------------------------------------------------
1475  int nIdx = sRange.indexOf(m_parseRangeExp);
1476 
1477  if (nIdx < 0)
1478  return false;
1479 
1480  if (nIdx > 0)
1481  sRange.remove( 0, nIdx );
1482 
1483  // ----------------------------------------------------------------------
1484  // Split multiple ranges
1485  // ----------------------------------------------------------------------
1486 
1487  QStringList ranges = sRange.split(',', Qt::SkipEmptyParts);
1488  if (ranges.count() == 0)
1489  return false;
1490 
1491  // ----------------------------------------------------------------------
1492  // Split first range into its components
1493  // ----------------------------------------------------------------------
1494 
1495  QStringList parts = ranges[0].split('-');
1496 
1497  if (parts.count() != 2)
1498  return false;
1499 
1500  if (parts[0].isEmpty() && parts[1].isEmpty())
1501  return false;
1502 
1503  // ----------------------------------------------------------------------
1504  //
1505  // ----------------------------------------------------------------------
1506 
1507  bool conv_ok = false;
1508  if (parts[0].isEmpty())
1509  {
1510  // ------------------------------------------------------------------
1511  // Does it match "-####"
1512  // ------------------------------------------------------------------
1513 
1514  long long llValue = parts[1].toLongLong(&conv_ok);
1515  if (!conv_ok) return false;
1516 
1517  *pllStart = llSize - llValue;
1518  *pllEnd = llSize - 1;
1519  }
1520  else if (parts[1].isEmpty())
1521  {
1522  // ------------------------------------------------------------------
1523  // Does it match "####-"
1524  // ------------------------------------------------------------------
1525 
1526  *pllStart = parts[0].toLongLong(&conv_ok);
1527 
1528  if (!conv_ok)
1529  return false;
1530 
1531  *pllEnd = llSize - 1;
1532  }
1533  else
1534  {
1535  // ------------------------------------------------------------------
1536  // Must be "####-####"
1537  // ------------------------------------------------------------------
1538 
1539  *pllStart = parts[0].toLongLong(&conv_ok);
1540  if (!conv_ok) return false;
1541  *pllEnd = parts[1].toLongLong(&conv_ok);
1542  if (!conv_ok) return false;
1543 
1544  if (*pllStart > *pllEnd)
1545  return false;
1546  }
1547 
1548  LOG(VB_HTTP, LOG_DEBUG, QString("%1 Range Requested %2 - %3")
1549  .arg(getSocketHandle()) .arg(*pllStart) .arg(*pllEnd));
1550 
1551  return true;
1552 }
1553 
1555 //
1557 
1559 {
1560  // Strip out leading http://192.168.1.1:6544/ -> /
1561  // Should fix #8678
1562  // FIXME what about https?
1563  static const QRegularExpression re {"^http[s]?://.*?/"};
1564  m_sBaseUrl.replace(re, "/");
1565 
1566  QStringList sList = m_sBaseUrl.split('/', Qt::SkipEmptyParts);
1567  m_sMethod = "";
1568 
1569  if (!sList.isEmpty())
1570  {
1571  m_sMethod = sList.last();
1572  sList.pop_back();
1573  }
1574 
1575  m_sBaseUrl = '/' + sList.join( "/" );
1576  LOG(VB_HTTP, LOG_INFO, QString("ExtractMethodFromURL(end) : %1 : %2")
1577  .arg(m_sMethod, m_sBaseUrl));
1578 }
1579 
1581 //
1583 
1584 bool HTTPRequest::ProcessSOAPPayload( const QString &sSOAPAction )
1585 {
1586  bool bSuccess = false;
1587 
1588  // ----------------------------------------------------------------------
1589  // Open Supplied XML uPnp Description file.
1590  // ----------------------------------------------------------------------
1591 
1592  LOG(VB_HTTP, LOG_INFO,
1593  QString("HTTPRequest::ProcessSOAPPayload : %1 : ").arg(sSOAPAction));
1594  QDomDocument doc ( "request" );
1595 
1596  QString sErrMsg;
1597  int nErrLine = 0;
1598  int nErrCol = 0;
1599 
1600  if (!doc.setContent( m_sPayload, true, &sErrMsg, &nErrLine, &nErrCol ))
1601  {
1602  LOG(VB_GENERAL, LOG_ERR,
1603  QString( "Error parsing request at line: %1 column: %2 : %3" )
1604  .arg(nErrLine) .arg(nErrCol) .arg(sErrMsg));
1605  return( false );
1606  }
1607 
1608  // --------------------------------------------------------------
1609  // XML Document Loaded... now parse it
1610  // --------------------------------------------------------------
1611 
1612  QString sService;
1613 
1614  if (sSOAPAction.contains( '#' ))
1615  {
1616  m_sNameSpace = sSOAPAction.section( '#', 0, 0).remove( 0, 1);
1617  m_sMethod = sSOAPAction.section( '#', 1 );
1618  m_sMethod.remove( m_sMethod.length()-1, 1 );
1619  }
1620  else
1621  {
1622  if (sSOAPAction.contains( '/' ))
1623  {
1624  int nPos = sSOAPAction.lastIndexOf( '/' );
1625  m_sNameSpace = sSOAPAction.mid(1, nPos);
1626  m_sMethod = sSOAPAction.mid(nPos + 1,
1627  sSOAPAction.length() - nPos - 2);
1628 
1629  nPos = m_sNameSpace.lastIndexOf( '/', -2);
1630  sService = m_sNameSpace.mid(nPos + 1,
1631  m_sNameSpace.length() - nPos - 2);
1632  m_sNameSpace = m_sNameSpace.mid( 0, nPos );
1633  }
1634  else
1635  {
1636  m_sNameSpace.clear();
1637  m_sMethod = sSOAPAction;
1638  m_sMethod.remove( QChar( '\"' ) );
1639  }
1640  }
1641 
1642  QDomNodeList oNodeList = doc.elementsByTagNameNS( m_sNameSpace, m_sMethod );
1643 
1644  if (oNodeList.count() == 0)
1645  {
1646  oNodeList =
1647  doc.elementsByTagNameNS("http://schemas.xmlsoap.org/soap/envelope/",
1648  "Body");
1649  }
1650 
1651  if (oNodeList.count() > 0)
1652  {
1653  QDomNode oMethod = oNodeList.item(0);
1654 
1655  if (!oMethod.isNull())
1656  {
1657  m_bSOAPRequest = true;
1658 
1659  for ( QDomNode oNode = oMethod.firstChild(); !oNode.isNull();
1660  oNode = oNode.nextSibling() )
1661  {
1662  QDomElement e = oNode.toElement();
1663 
1664  if (!e.isNull())
1665  {
1666  QString sName = e.tagName();
1667  QString sValue = "";
1668 
1669  QDomText oText = oNode.firstChild().toText();
1670 
1671  if (!oText.isNull())
1672  sValue = oText.nodeValue();
1673 
1674  sName = QUrl::fromPercentEncoding(sName.toUtf8());
1675  sValue = QUrl::fromPercentEncoding(sValue.toUtf8());
1676 
1677  m_mapParams.insert( sName.trimmed().toLower(), sValue );
1678  }
1679  }
1680 
1681  bSuccess = true;
1682  }
1683  }
1684 
1685  return bSuccess;
1686 }
1687 
1689 //
1691 
1693 {
1694  Serializer *pSerializer = nullptr;
1695 
1696  if (m_bSOAPRequest)
1697  {
1698  pSerializer = (Serializer *)new SoapSerializer(&m_response,
1700  }
1701  else
1702  {
1703  QString sAccept = GetRequestHeader( "Accept", "*/*" );
1704 
1705  if (sAccept.contains( "application/json", Qt::CaseInsensitive ) ||
1706  sAccept.contains( "text/javascript", Qt::CaseInsensitive ))
1707  {
1708  pSerializer = (Serializer *)new JSONSerializer(&m_response,
1709  m_sMethod);
1710  }
1711  else if (sAccept.contains( "text/x-apple-plist+xml", Qt::CaseInsensitive ))
1712  {
1713  pSerializer = (Serializer *)new XmlPListSerializer(&m_response);
1714  }
1715  }
1716 
1717  // Default to XML
1718 
1719  if (pSerializer == nullptr)
1720  pSerializer = (Serializer *)new XmlSerializer(&m_response, m_sMethod);
1721 
1722  return pSerializer;
1723 }
1724 
1726 //
1728 
1729 QString HTTPRequest::Encode(const QString &sIn)
1730 {
1731  QString sStr = sIn;
1732 #if 0
1733  LOG(VB_HTTP, LOG_DEBUG,
1734  QString("HTTPRequest::Encode Input : %1").arg(sStr));
1735 #endif
1736  sStr.replace('&', "&amp;" ); // This _must_ come first
1737  sStr.replace('<', "&lt;" );
1738  sStr.replace('>', "&gt;" );
1739  sStr.replace('"', "&quot;");
1740  sStr.replace("'", "&apos;");
1741 
1742 #if 0
1743  LOG(VB_HTTP, LOG_DEBUG,
1744  QString("HTTPRequest::Encode Output : %1").arg(sStr));
1745 #endif
1746  return sStr;
1747 }
1748 
1750 //
1752 
1753 QString HTTPRequest::Decode(const QString& sIn)
1754 {
1755  QString sStr = sIn;
1756  sStr.replace("&amp;", "&");
1757  sStr.replace("&lt;", "<");
1758  sStr.replace("&gt;", ">");
1759  sStr.replace("&quot;", "\"");
1760  sStr.replace("&apos;", "'");
1761 
1762  return sStr;
1763 }
1764 
1766 //
1768 
1769 QString HTTPRequest::GetETagHash(const QByteArray &data)
1770 {
1771  QByteArray hash = QCryptographicHash::hash( data.data(), QCryptographicHash::Sha1);
1772 
1773  return ("\"" + hash.toHex() + "\"");
1774 }
1775 
1777 //
1779 
1780 bool HTTPRequest::IsUrlProtected( const QString &sBaseUrl )
1781 {
1782  QString sProtected = XmlConfiguration().GetValue("HTTP/Protected/Urls", "/setup;/Config");
1783 
1784  QStringList oList = sProtected.split( ';' );
1785 
1786  for( int nIdx = 0; nIdx < oList.count(); nIdx++)
1787  {
1788  if (sBaseUrl.startsWith( oList[nIdx], Qt::CaseInsensitive ))
1789  return true;
1790  }
1791 
1792  return false;
1793 }
1794 
1796 //
1798 
1800 {
1801  QString authHeader;
1802 
1803  // For now we support a single realm, that will change
1804  QString realm = "MythTV";
1805 
1806  // Always use digest authentication where supported, it may be available
1807  // with HTTP 1.0 client as an extension, but we can't tell if that's the
1808  // case. It's guaranteed to be available for HTTP 1.1+
1809  if (m_nMajor >= 1 && m_nMinor > 0)
1810  {
1812  QString stale = isStale ? "true" : "false"; // FIXME
1813  authHeader = QString("Digest realm=\"%1\",nonce=\"%2\","
1814  "qop=\"auth\",stale=\"%3\",algorithm=\"MD5\"")
1815  .arg(realm, nonce, stale);
1816  }
1817  else
1818  {
1819  authHeader = QString("Basic realm=\"%1\"").arg(realm);
1820  }
1821 
1822  return authHeader;
1823 }
1824 
1826 //
1828 
1829 QString HTTPRequest::CalculateDigestNonce(const QString& timeStamp) const
1830 {
1831  QString uniqueID = QString("%1:%2").arg(timeStamp, m_sPrivateToken);
1832  QString hash = QCryptographicHash::hash( uniqueID.toLatin1(), QCryptographicHash::Sha1).toHex(); // TODO: Change to Sha2 with QT5?
1833  QString nonce = QString("%1%2").arg(timeStamp, hash); // Note: since this is going in a header it should avoid illegal chars
1834  return nonce;
1835 }
1836 
1838 //
1840 
1842 {
1843  LOG(VB_HTTP, LOG_NOTICE, "Attempting HTTP Basic Authentication");
1844  QStringList oList = GetLastHeader( "authorization" ).split( ' ' );
1845 
1846  if (m_nMajor == 1 && m_nMinor == 0) // We only support Basic auth for http 1.0 clients
1847  {
1848  LOG(VB_GENERAL, LOG_WARNING, "Basic authentication is only allowed for HTTP 1.0");
1849  return false;
1850  }
1851 
1852  QString sCredentials = QByteArray::fromBase64( oList[1].toUtf8() );
1853 
1854  oList = sCredentials.split( ':' );
1855 
1856  if (oList.count() < 2)
1857  {
1858  LOG(VB_GENERAL, LOG_WARNING, "Authorization attempt with invalid number of tokens");
1859  return false;
1860  }
1861 
1862  QString sUsername = oList[0];
1863  QString sPassword = oList[1];
1864 
1865  if (sUsername == "nouser") // Special logout username
1866  return false;
1867 
1868  MythSessionManager *sessionManager = gCoreContext->GetSessionManager();
1869  if (!MythSessionManager::IsValidUser(sUsername))
1870  {
1871  LOG(VB_GENERAL, LOG_WARNING, "Authorization attempt with invalid username");
1872  return false;
1873  }
1874 
1875  QString client = QString("WebFrontend_%1").arg(GetPeerAddress());
1876  MythUserSession session = sessionManager->LoginUser(sUsername, sPassword,
1877  client);
1878 
1879  if (!session.IsValid())
1880  {
1881  LOG(VB_GENERAL, LOG_WARNING, "Authorization attempt with invalid password");
1882  return false;
1883  }
1884 
1885  LOG(VB_HTTP, LOG_NOTICE, "Valid Authorization received");
1886 
1887  if (IsEncrypted()) // Only set a session cookie for encrypted connections, not safe otherwise
1888  SetCookie("sessionToken", session.GetSessionToken(),
1889  session.GetSessionExpires(), true);
1890 
1891  m_userSession = session;
1892 
1893  return false;
1894 }
1895 
1897 //
1899 
1901 {
1902  LOG(VB_HTTP, LOG_NOTICE, "Attempting HTTP Digest Authentication");
1903  QString realm = "MythTV"; // TODO Check which realm applies for the request path
1904 
1905  QString authMethod = GetLastHeader( "authorization" ).section(' ', 0, 0).toLower();
1906 
1907  if (authMethod != "digest")
1908  {
1909  LOG(VB_GENERAL, LOG_WARNING, "Invalid method in Authorization header");
1910  return false;
1911  }
1912 
1913  QString parameterStr = GetLastHeader( "authorization" ).section(' ', 1);
1914 
1915  QMap<QString, QString> paramMap;
1916  QStringList paramList = parameterStr.split(',');
1917  QStringList::iterator it;
1918  for (it = paramList.begin(); it != paramList.end(); ++it)
1919  {
1920  QString key = (*it).section('=', 0, 0).toLower().trimmed();
1921  // Since the value may contain '=' return everything after first occurence
1922  QString value = (*it).section('=', 1).trimmed();
1923  // Remove any quotes surrounding the value
1924  value.remove("\"");
1925  paramMap[key] = value;
1926  }
1927 
1928  if (paramMap.size() < 8)
1929  {
1930  LOG(VB_GENERAL, LOG_WARNING, "Invalid number of parameters in Authorization header");
1931  return false;
1932  }
1933 
1934  if (paramMap["nonce"].isEmpty() || paramMap["username"].isEmpty() ||
1935  paramMap["realm"].isEmpty() || paramMap["uri"].isEmpty() ||
1936  paramMap["response"].isEmpty() || paramMap["qop"].isEmpty() ||
1937  paramMap["cnonce"].isEmpty() || paramMap["nc"].isEmpty())
1938  {
1939  LOG(VB_GENERAL, LOG_WARNING, "Missing required parameters in Authorization header");
1940  return false;
1941  }
1942 
1943  if (paramMap["username"] == "nouser") // Special logout username
1944  return false;
1945 
1946  if (paramMap["uri"] != m_sOriginalUrl)
1947  {
1948  LOG(VB_GENERAL, LOG_WARNING, "Authorization URI doesn't match the "
1949  "request URI");
1950  m_nResponseStatus = 400; // Bad Request
1951  return false;
1952  }
1953 
1954  if (paramMap["realm"] != realm)
1955  {
1956  LOG(VB_GENERAL, LOG_WARNING, "Authorization realm doesn't match the "
1957  "realm of the requested content");
1958  return false;
1959  }
1960 
1961  QByteArray nonce = paramMap["nonce"].toLatin1();
1962  if (nonce.length() < 20)
1963  {
1964  LOG(VB_GENERAL, LOG_WARNING, "Authorization nonce is too short");
1965  return false;
1966  }
1967 
1968  QString nonceTimeStampStr = nonce.left(20); // ISO 8601 fixed length
1969  if (nonce != CalculateDigestNonce(nonceTimeStampStr))
1970  {
1971  LOG(VB_GENERAL, LOG_WARNING, "Authorization nonce doesn't match reference");
1972  LOG(VB_HTTP, LOG_DEBUG, QString("%1 vs %2").arg(QString(nonce),
1973  CalculateDigestNonce(nonceTimeStampStr)));
1974  return false;
1975  }
1976 
1977  constexpr std::chrono::seconds AUTH_TIMEOUT { 2min }; // 2 Minute timeout to login, to reduce replay attack window
1978  QDateTime nonceTimeStamp = MythDate::fromString(nonceTimeStampStr);
1979  if (!nonceTimeStamp.isValid())
1980  {
1981  LOG(VB_GENERAL, LOG_WARNING, "Authorization nonce timestamp is invalid.");
1982  LOG(VB_HTTP, LOG_DEBUG, QString("Timestamp was '%1'").arg(nonceTimeStampStr));
1983  return false;
1984  }
1985 
1986  if (MythDate::secsInPast(nonceTimeStamp) > AUTH_TIMEOUT)
1987  {
1988  LOG(VB_HTTP, LOG_NOTICE, "Authorization nonce timestamp is invalid or too old.");
1989  // Tell the client that the submitted nonce has expired at which
1990  // point they may wish to try again with a fresh nonce instead of
1991  // telling the user that their credentials were invalid
1992  SetResponseHeader("WWW-Authenticate", GetAuthenticationHeader(true), true);
1993  return false;
1994  }
1995 
1996  MythSessionManager *sessionManager = gCoreContext->GetSessionManager();
1997  if (!MythSessionManager::IsValidUser(paramMap["username"]))
1998  {
1999  LOG(VB_GENERAL, LOG_WARNING, "Authorization attempt with invalid username");
2000  return false;
2001  }
2002 
2003  if (paramMap["response"].length() != 32)
2004  {
2005  LOG(VB_GENERAL, LOG_WARNING, "Authorization response field is invalid length");
2006  return false;
2007  }
2008 
2009  // If you're still reading this, well done, not far to go now
2010 
2011  QByteArray a1 = MythSessionManager::GetPasswordDigest(paramMap["username"]).toLatin1();
2012  //QByteArray a1 = "bcd911b2ecb15ffbd6d8e6e744d60cf6";
2013  QString methodDigest = QString("%1:%2").arg(GetRequestType(), paramMap["uri"]);
2014  QByteArray a2 = QCryptographicHash::hash(methodDigest.toLatin1(),
2015  QCryptographicHash::Md5).toHex();
2016 
2017  QString responseDigest = QString("%1:%2:%3:%4:%5:%6").arg(a1,
2018  paramMap["nonce"],
2019  paramMap["nc"],
2020  paramMap["cnonce"],
2021  paramMap["qop"],
2022  a2);
2023  QByteArray kd = QCryptographicHash::hash(responseDigest.toLatin1(),
2024  QCryptographicHash::Md5).toHex();
2025 
2026  if (paramMap["response"].toLatin1() == kd)
2027  {
2028  LOG(VB_HTTP, LOG_NOTICE, "Valid Authorization received");
2029  QString client = QString("WebFrontend_%1").arg(GetPeerAddress());
2030  MythUserSession session = sessionManager->LoginUser(paramMap["username"],
2031  a1,
2032  client);
2033  if (!session.IsValid())
2034  {
2035  LOG(VB_GENERAL, LOG_ERR, "Valid Authorization received, but we "
2036  "failed to create a valid session");
2037  return false;
2038  }
2039 
2040  if (IsEncrypted()) // Only set a session cookie for encrypted connections, not safe otherwise
2041  SetCookie("sessionToken", session.GetSessionToken(),
2042  session.GetSessionExpires(), true);
2043 
2044  m_userSession = session;
2045 
2046  return true;
2047  }
2048 
2049  LOG(VB_GENERAL, LOG_WARNING, "Authorization attempt with invalid password digest");
2050  LOG(VB_HTTP, LOG_DEBUG, QString("Received hash was '%1', calculated hash was '%2'")
2051  .arg(paramMap["response"], QString(kd)));
2052 
2053  return false;
2054 }
2055 
2057 //
2059 
2061 {
2062  // Check if the existing user has permission to access this resource
2063  if (m_userSession.IsValid()) //m_userSession.CheckPermission())
2064  return true;
2065 
2066  QStringList oList = GetLastHeader( "authorization" ).split( ' ' );
2067 
2068  if (oList.count() < 2)
2069  return false;
2070 
2071  if (oList[0].compare( "basic", Qt::CaseInsensitive ) == 0)
2072  return BasicAuthentication();
2073  if (oList[0].compare( "digest", Qt::CaseInsensitive ) == 0)
2074  return DigestAuthentication();
2075 
2076  return false;
2077 }
2078 
2080 //
2082 
2083 void HTTPRequest::SetResponseHeader(const QString& sKey, const QString& sValue,
2084  bool replace)
2085 {
2086  if (!replace && m_mapRespHeaders.contains(sKey))
2087  return;
2088 
2089  m_mapRespHeaders[sKey] = sValue;
2090 }
2091 
2093 //
2095 
2096 void HTTPRequest::SetCookie(const QString &sKey, const QString &sValue,
2097  const QDateTime &expiryDate, bool secure)
2098 {
2099  if (secure && !IsEncrypted())
2100  {
2101  LOG(VB_GENERAL, LOG_WARNING, QString("HTTPRequest::SetCookie(%1=%2): "
2102  "A secure cookie cannot be set on an unencrypted connection.")
2103  .arg(sKey, sValue));
2104  return;
2105  }
2106 
2107  QStringList cookieAttributes;
2108 
2109  // Key=Value
2110  cookieAttributes.append(QString("%1=%2").arg(sKey, sValue));
2111 
2112  // Domain - Most browsers have problems with a hostname, so it's better to omit this
2113 // cookieAttributes.append(QString("Domain=%1").arg(GetHostName()));
2114 
2115  // Path - Fix to root, no call for restricting to other paths yet
2116  cookieAttributes.append("Path=/");
2117 
2118  // Expires - Expiry date, always set one, just good practice
2119  QString expires = MythDate::toString(expiryDate, MythDate::kRFC822); // RFC 822
2120  cookieAttributes.append(QString("Expires=%1").arg(expires)); // Cookie Expiry date
2121 
2122  // Secure - Only send this cookie over encrypted connections, it contains
2123  // sensitive info SECURITY
2124  if (secure)
2125  cookieAttributes.append("Secure");
2126 
2127  // HttpOnly - No cookie stealing javascript SECURITY
2128  cookieAttributes.append("HttpOnly");
2129 
2130  SetResponseHeader("Set-Cookie", cookieAttributes.join("; "));
2131 }
2132 
2134 //
2136 
2138 {
2139  // TODO: This only deals with the HTTP 1.1 case, 1.0 should be rare but we
2140  // should probably still handle it
2141 
2142  // RFC 3875 - The is the hostname or ip address in the client request, not
2143  // the name or ip we might otherwise know for this server
2144  QString hostname = GetLastHeader("host");
2145  if (!hostname.isEmpty())
2146  {
2147  // Strip the port
2148  if (hostname.contains("]:")) // IPv6 port
2149  {
2150  return hostname.section("]:", 0 , 0);
2151  }
2152  if (hostname.contains(":")) // IPv4 port
2153  {
2154  return hostname.section(":", 0 , 0);
2155  }
2156  return hostname;
2157  }
2158 
2159  return GetHostAddress();
2160 }
2161 
2162 
2164 {
2165  QString type;
2166  switch ( m_eType )
2167  {
2168  case RequestTypeUnknown :
2169  type = "UNKNOWN";
2170  break;
2171  case RequestTypeGet :
2172  type = "GET";
2173  break;
2174  case RequestTypeHead :
2175  type = "HEAD";
2176  break;
2177  case RequestTypePost :
2178  type = "POST";
2179  break;
2180  case RequestTypeOptions:
2181  type = "OPTIONS";
2182  break;
2183  case RequestTypeMSearch:
2184  type = "M-SEARCH";
2185  break;
2186  case RequestTypeNotify:
2187  type = "NOTIFY";
2188  break;
2189  case RequestTypeSubscribe :
2190  type = "SUBSCRIBE";
2191  break;
2192  case RequestTypeUnsubscribe :
2193  type = "UNSUBSCRIBE";
2194  break;
2195  case RequestTypeResponse :
2196  type = "RESPONSE";
2197  break;
2198  }
2199 
2200  return type;
2201 }
2202 
2203 void HTTPRequest::AddCORSHeaders( const QString &sOrigin )
2204 {
2205  // ----------------------------------------------------------------------
2206  // SECURITY: Access-Control-Allow-Origin Wildcard
2207  //
2208  // This is a REALLY bad idea, so bad in fact that I'm including it here but
2209  // commented out in the hope that anyone thinking of adding it in the future
2210  // will see it and then read this comment.
2211  //
2212  // Browsers do not verify that the origin is on the same network. This means
2213  // that a malicious script embedded or included into ANY webpage you visit
2214  // could then access servers on your local network including MythTV. They
2215  // can grab data, delete data including recordings and videos, schedule
2216  // recordings and generally ruin your day.
2217  //
2218  // This might seem paranoid and a remote possibility, but then that's how
2219  // a lot of exploits are born. Do NOT allow wildcards.
2220  //
2221  //m_mapRespHeaders[ "Access-Control-Allow-Origin" ] = "*";
2222  // ----------------------------------------------------------------------
2223 
2224  // ----------------------------------------------------------------------
2225  // SECURITY: Allow the WebFrontend on the Master backend and ONLY this
2226  // machine to access resources on a frontend or slave web server
2227  //
2228  // http://www.w3.org/TR/cors/#introduction
2229  // ----------------------------------------------------------------------
2230 
2231  QStringList allowedOrigins;
2232 
2233  int serverStatusPort = gCoreContext->GetMasterServerStatusPort();
2234  int backendSSLPort = gCoreContext->GetNumSetting( "BackendSSLPort",
2235  serverStatusPort + 10);
2236 
2237  QString masterAddrPort = QString("%1:%2")
2239  .arg(serverStatusPort);
2240  QString masterTLSAddrPort = QString("%1:%2")
2242  .arg(backendSSLPort);
2243 
2244  allowedOrigins << QString("http://%1").arg(masterAddrPort);
2245  allowedOrigins << QString("https://%2").arg(masterTLSAddrPort);
2246 
2247  QString localhostname = QHostInfo::localHostName();
2248  if (!localhostname.isEmpty())
2249  {
2250  allowedOrigins << QString("http://%1:%2")
2251  .arg(localhostname).arg(serverStatusPort);
2252  allowedOrigins << QString("https://%1:%2")
2253  .arg(localhostname).arg(backendSSLPort);
2254  }
2255 
2256  QStringList allowedOriginsList =
2257  gCoreContext->GetSetting("AllowedOriginsList", QString(
2258  "https://chromecast.mythtv.org")).split(",");
2259 
2260  for (const auto & origin : std::as_const(allowedOriginsList))
2261  {
2262  if (origin.isEmpty())
2263  continue;
2264 
2265  if (origin == "*" || (!origin.startsWith("http://") &&
2266  !origin.startsWith("https://")))
2267  {
2268  LOG(VB_GENERAL, LOG_ERR, QString("Illegal AllowedOriginsList"
2269  " entry '%1'. Must start with http[s]:// and not be *")
2270  .arg(origin));
2271  }
2272  else
2273  {
2274  allowedOrigins << origin;
2275  }
2276  }
2277 
2278  if (VERBOSE_LEVEL_CHECK(VB_HTTP, LOG_DEBUG))
2279  {
2280  for (const auto & origin : std::as_const(allowedOrigins))
2281  LOG(VB_HTTP, LOG_DEBUG, QString("Will allow Origin: %1").arg(origin));
2282  }
2283 
2284  if (allowedOrigins.contains(sOrigin))
2285  {
2286  SetResponseHeader( "Access-Control-Allow-Origin" , sOrigin);
2287  SetResponseHeader( "Access-Control-Allow-Credentials" , "true");
2288  SetResponseHeader( "Access-Control-Allow-Headers" , "Content-Type");
2289  LOG(VB_HTTP, LOG_DEBUG, QString("Allow-Origin: %1)").arg(sOrigin));
2290  }
2291  else
2292  {
2293  LOG(VB_GENERAL, LOG_CRIT, QString("HTTPRequest: Cross-origin request "
2294  "received with origin (%1)")
2295  .arg(sOrigin));
2296  }
2297 }
2298 
2301 //
2302 // BufferedSocketDeviceRequest Class Implementation
2303 //
2306 
2307 QString BufferedSocketDeviceRequest::ReadLine( std::chrono::milliseconds msecs )
2308 {
2309  QString sLine;
2310 
2311  if (m_pSocket && m_pSocket->isValid() &&
2312  m_pSocket->state() == QAbstractSocket::ConnectedState)
2313  {
2314  bool timeout = false;
2315  MythTimer timer;
2316  timer.start();
2317  while (!m_pSocket->canReadLine() && !timeout)
2318  {
2319  timeout = !(m_pSocket->waitForReadyRead( msecs.count() ));
2320 
2321  if ( timer.elapsed() >= msecs )
2322  {
2323  timeout = true;
2324  LOG(VB_HTTP, LOG_INFO, "BufferedSocketDeviceRequest::ReadLine() - Exceeded Total Elapsed Wait Time." );
2325  }
2326  }
2327 
2328  if (!timeout)
2329  sLine = m_pSocket->readLine();
2330  }
2331 
2332  return( sLine );
2333 }
2334 
2336 //
2338 
2339 qint64 BufferedSocketDeviceRequest::ReadBlock(char *pData, qint64 nMaxLen,
2340  std::chrono::milliseconds msecs)
2341 {
2342  if (m_pSocket && m_pSocket->isValid() &&
2343  m_pSocket->state() == QAbstractSocket::ConnectedState)
2344  {
2345  if (msecs == 0ms)
2346  return( m_pSocket->read( pData, nMaxLen ));
2347 
2348  bool bTimeout = false;
2349  MythTimer timer;
2350  timer.start();
2351  while ( (m_pSocket->bytesAvailable() < (int)nMaxLen) && !bTimeout ) // This can end up waiting far longer than msecs
2352  {
2353  bTimeout = !(m_pSocket->waitForReadyRead( msecs.count() ));
2354 
2355  if ( timer.elapsed() >= msecs )
2356  {
2357  bTimeout = true;
2358  LOG(VB_HTTP, LOG_INFO, "BufferedSocketDeviceRequest::ReadBlock() - Exceeded Total Elapsed Wait Time." );
2359  }
2360  }
2361 
2362  // Just return what we have even if timed out.
2363 
2364  return( m_pSocket->read( pData, nMaxLen ));
2365  }
2366 
2367  return( -1 );
2368 }
2369 
2371 //
2373 
2374 qint64 BufferedSocketDeviceRequest::WriteBlock(const char *pData, qint64 nLen)
2375 {
2376  qint64 bytesWritten = -1;
2377  if (m_pSocket && m_pSocket->isValid() &&
2378  m_pSocket->state() == QAbstractSocket::ConnectedState)
2379  {
2380  bytesWritten = m_pSocket->write( pData, nLen );
2381  m_pSocket->waitForBytesWritten();
2382  }
2383 
2384  return( bytesWritten );
2385 }
2386 
2388 //
2390 
2392 {
2393  return( m_pSocket->localAddress().toString() );
2394 }
2395 
2397 //
2399 
2401 {
2402  return( m_pSocket->localPort() );
2403 }
2404 
2405 
2407 //
2409 
2411 {
2412  return( m_pSocket->peerAddress().toString() );
2413 }
jsonSerializer.h
HTTPRequest::GetRequestHeader
QString GetRequestHeader(const QString &sKey, const QString &sDefault)
Definition: httprequest.cpp:1110
MythSessionManager::IsValidUser
static bool IsValidUser(const QString &username)
Check if the given user exists but not whether there is a valid session open for them!
Definition: mythsession.cpp:151
build_compdb.args
args
Definition: build_compdb.py:11
ContentType_XML
@ ContentType_XML
Definition: httprequest.h:70
HTTPRequest::m_sBaseUrl
QString m_sBaseUrl
Definition: httprequest.h:127
MythTimer::elapsed
std::chrono::milliseconds elapsed(void)
Returns milliseconds elapsed since last start() or restart()
Definition: mythtimer.cpp:91
MythSessionManager::GetPasswordDigest
static QString GetPasswordDigest(const QString &username)
Load the password digest for comparison in the HTTP Auth code.
Definition: mythsession.cpp:224
HttpContentType
HttpContentType
Definition: httprequest.h:66
HTTPRequest::SetContentType
HttpContentType SetContentType(const QString &sType)
Definition: httprequest.cpp:877
MythDate::toString
QString toString(const QDateTime &raw_dt, uint format)
Returns formatted string representing the time.
Definition: mythdate.cpp:84
RequestTypeResponse
@ RequestTypeResponse
Definition: httprequest.h:62
HTTPRequest::FormatRawResponse
void FormatRawResponse(const QString &sXML)
Definition: httprequest.cpp:777
hardwareprofile.smolt.timeout
float timeout
Definition: smolt.py:102
HTTPRequest::SetRequestProtocol
void SetRequestProtocol(const QString &sLine)
Definition: httprequest.cpp:832
ResponseTypeOther
@ ResponseTypeOther
Definition: httprequest.h:85
unziputil.h
ContentType_JSON
@ ContentType_JSON
Definition: httprequest.h:71
Serializer
Definition: serializer.h:31
HttpServer::GetServerVersion
static QString GetServerVersion(void)
Definition: httpserver.cpp:288
MythTimer
A QElapsedTimer based timer to replace use of QTime as a timer.
Definition: mythtimer.h:13
HTTPRequest::ParseRequest
bool ParseRequest()
Definition: httprequest.cpp:1198
BufferedSocketDeviceRequest::GetHostPort
quint16 GetHostPort() override
Definition: httprequest.cpp:2400
XmlPListSerializer
Definition: xmlplistSerializer.h:12
BufferedSocketDeviceRequest::GetPeerAddress
QString GetPeerAddress() override
Definition: httprequest.cpp:2410
HTTPRequest::m_sMethod
QString m_sMethod
Definition: httprequest.h:129
RequestTypeUnknown
@ RequestTypeUnknown
Definition: httprequest.h:46
RequestTypeGet
@ RequestTypeGet
Definition: httprequest.h:48
HTTPRequest::m_sResourceUrl
QString m_sResourceUrl
Definition: httprequest.h:128
BufferedSocketDeviceRequest::GetHostAddress
QString GetHostAddress() override
Definition: httprequest.cpp:2391
JSONSerializer
Definition: jsonSerializer.h:31
HTTPRequest::IsEncrypted
bool IsEncrypted() const
Definition: httprequest.h:198
HTTPRequest::m_sProtocol
QString m_sProtocol
Definition: httprequest.h:137
HTTPRequest::m_sResponseTypeText
QString m_sResponseTypeText
Definition: httprequest.h:150
HTTPRequest::GetResponseProtocol
static QString GetResponseProtocol()
Definition: httprequest.cpp:856
HTTPRequest::m_sOriginalUrl
QString m_sOriginalUrl
Definition: httprequest.h:125
VERBOSE_LEVEL_CHECK
static bool VERBOSE_LEVEL_CHECK(uint64_t mask, LogLevel_t level)
Definition: mythlogging.h:29
HTTPRequest::GetPeerAddress
virtual QString GetPeerAddress()=0
HTTPRequest::GetSupportedMimeTypes
static QStringList GetSupportedMimeTypes()
Definition: httprequest.cpp:1001
MythDate::kOverrideUTC
@ kOverrideUTC
Present date/time in UTC.
Definition: mythdate.h:31
HTTPRequest::Authenticated
bool Authenticated()
Definition: httprequest.cpp:2060
HTTPRequest::SendResponseFile
qint64 SendResponseFile(const QString &sFileName)
Definition: httprequest.cpp:453
MythTimer::start
void start(void)
starts measuring elapsed time.
Definition: mythtimer.cpp:47
LOG
#define LOG(_MASK_, _LEVEL_, _QSTRING_)
Definition: mythlogging.h:39
HTTPRequest::DigestAuthentication
bool DigestAuthentication()
Definition: httprequest.cpp:1900
HTTPRequest::m_userSession
MythUserSession m_userSession
Definition: httprequest.h:162
build_compdb.file
file
Definition: build_compdb.py:55
HTTPRequest::BasicAuthentication
bool BasicAuthentication()
Definition: httprequest.cpp:1841
HTTPRequest::m_bProtected
bool m_bProtected
Definition: httprequest.h:141
HTTPRequest::TestMimeType
static QString TestMimeType(const QString &sFileName)
Definition: httprequest.cpp:1018
HTTPRequest::Encode
static QString Encode(const QString &sIn)
Definition: httprequest.cpp:1729
HTTPRequest::SetCookie
void SetCookie(const QString &sKey, const QString &sValue, const QDateTime &expiryDate, bool secure)
Definition: httprequest.cpp:2096
ResponseTypeJS
@ ResponseTypeJS
Definition: httprequest.h:80
HTTPRequest::m_procReqLineExp
QRegularExpression m_procReqLineExp
Definition: httprequest.h:115
xmlSerializer.h
ResponseTypeFile
@ ResponseTypeFile
Definition: httprequest.h:84
MythDate::current
QDateTime current(bool stripped)
Returns current Date and Time in UTC.
Definition: mythdate.cpp:14
HTTPRequest::Decode
static QString Decode(const QString &sIn)
Definition: httprequest.cpp:1753
HTTPRequest::GetSerializer
Serializer * GetSerializer()
Definition: httprequest.cpp:1692
MythCoreContext::GetMasterServerStatusPort
int GetMasterServerStatusPort(void)
Returns the Master Backend status port If no master server status port has been defined in the databa...
Definition: mythcorecontext.cpp:997
SoapSerializer
Definition: soapSerializer.h:29
HTTPRequest::GetResponseHeaders
QString GetResponseHeaders(void)
Definition: httprequest.cpp:1125
XmlConfiguration
Definition: configuration.h:38
RequestTypePost
@ RequestTypePost
Definition: httprequest.h:50
HTTPRequest::ExtractMethodFromURL
void ExtractMethodFromURL()
Definition: httprequest.cpp:1558
HTTPRequest::m_sPrivateToken
QString m_sPrivateToken
Definition: httprequest.h:161
HTTPRequest::m_nMajor
int m_nMajor
Definition: httprequest.h:138
HTTPRequest::ReadLine
virtual QString ReadLine(std::chrono::milliseconds msecs)=0
MythUserSession
Definition: mythsession.h:18
HTTPRequest::m_mapRespHeaders
QStringMap m_mapRespHeaders
Definition: httprequest.h:153
HTTPRequest::WriteBlock
virtual qint64 WriteBlock(const char *pData, qint64 nLen)=0
NameValues
Definition: upnputil.h:77
HTTPRequest::FormatActionResponse
void FormatActionResponse(Serializer *ser)
Definition: httprequest.cpp:700
MythSessionManager::GetSession
MythUserSession GetSession(const QString &sessionToken)
Load the session details and return.
Definition: mythsession.cpp:175
hardwareprofile.smolt.secure
secure
Definition: smolt.py:94
Serializer::GetContentType
virtual QString GetContentType()=0
mythdate.h
HTTPRequest::s_szServerHeaders
static const char * s_szServerHeaders
Definition: httprequest.h:113
ResponseTypeCSS
@ ResponseTypeCSS
Definition: httprequest.h:81
upnp.h
HTTPRequest::m_nResponseStatus
long m_nResponseStatus
Definition: httprequest.h:152
mythlogging.h
HTTPRequest::ReadBlock
virtual qint64 ReadBlock(char *pData, qint64 nMaxLen, std::chrono::milliseconds msecs=0ms)=0
SOAP_ENVELOPE_BEGIN
static constexpr const char * SOAP_ENVELOPE_BEGIN
Definition: httprequest.h:34
HTTPRequest::GetResponsePage
QByteArray GetResponsePage(void)
Definition: httprequest.cpp:953
XmlSerializer
Definition: xmlSerializer.h:32
MythCoreContext::GetMasterServerIP
QString GetMasterServerIP(void)
Returns the Master Backend IP address If the address is an IPv6 address, the scope Id is removed.
Definition: mythcorecontext.cpp:970
HTTPRequest::GetMimeType
static QString GetMimeType(const QString &sFileExtension)
Definition: httprequest.cpp:982
MythUserSession::IsValid
bool IsValid(void) const
Check if this session object appears properly constructed, it DOES NOT validate whether it is a valid...
Definition: mythsession.cpp:15
HTTPRequest::m_mapParams
QStringMap m_mapParams
Definition: httprequest.h:131
HTTPRequest::m_parseRangeExp
QRegularExpression m_parseRangeExp
Definition: httprequest.h:116
compat.h
ContentType_Unknown
@ ContentType_Unknown
Definition: httprequest.h:68
QStringMap
QMap< QString, QString > QStringMap
Definition: upnputil.h:32
RequestTypeUnsubscribe
@ RequestTypeUnsubscribe
Definition: httprequest.h:59
RequestTypeMSearch
@ RequestTypeMSearch
Definition: httprequest.h:57
MythCoreContext::GetDurSetting
std::enable_if_t< std::chrono::__is_duration< T >::value, T > GetDurSetting(const QString &key, T defaultval=T::zero())
Definition: mythcorecontext.h:168
ResponseTypeHeader
@ ResponseTypeHeader
Definition: httprequest.h:86
BufferedSocketDeviceRequest::ReadBlock
qint64 ReadBlock(char *pData, qint64 nMaxLen, std::chrono::milliseconds msecs=0ms) override
Definition: httprequest.cpp:2339
HTTPRequest::BuildResponseHeader
QString BuildResponseHeader(long long nSize)
Definition: httprequest.cpp:193
gzipCompress
QByteArray gzipCompress(const QByteArray &data)
Definition: unziputil.cpp:93
ResponseTypeSVG
@ ResponseTypeSVG
Definition: httprequest.h:83
SENDFILE_BUFFER_SIZE
static constexpr size_t SENDFILE_BUFFER_SIZE
Definition: httprequest.cpp:596
Serializer::AddHeaders
virtual void AddHeaders(QStringMap &headers)
Definition: serializer.cpp:22
HTTPRequest::m_bKeepAlive
bool m_bKeepAlive
Definition: httprequest.h:166
HTTPRequest::m_sRequestUrl
QString m_sRequestUrl
Definition: httprequest.h:126
RequestTypeNotify
@ RequestTypeNotify
Definition: httprequest.h:60
MythUserSession::GetSessionToken
QString GetSessionToken(void) const
Definition: mythsession.h:44
HTTPRequest::ParseRange
bool ParseRange(QString sRange, long long llSize, long long *pllStart, long long *pllEnd)
Definition: httprequest.cpp:1459
HTTPRequest::GetETagHash
static QString GetETagHash(const QByteArray &data)
Definition: httprequest.cpp:1769
HTTPRequest::m_sRawRequest
QString m_sRawRequest
Definition: httprequest.h:123
HTTPRequest::ProcessRequestLine
void ProcessRequestLine(const QString &sLine)
Definition: httprequest.cpp:1392
gCoreContext
MythCoreContext * gCoreContext
This global variable contains the MythCoreContext instance for the app.
Definition: mythcorecontext.cpp:55
HTTPRequest::m_mapHeaders
QStringMultiMap m_mapHeaders
Definition: httprequest.h:132
HTTPRequest::GetHostName
virtual QString GetHostName()
Definition: httprequest.cpp:2137
MythUserSession::GetSessionExpires
QDateTime GetSessionExpires() const
Definition: mythsession.h:49
RequestTypeOptions
@ RequestTypeOptions
Definition: httprequest.h:54
MythCoreContext::GetNumSetting
int GetNumSetting(const QString &key, int defaultval=0)
Definition: mythcorecontext.cpp:916
ResponseTypeHTML
@ ResponseTypeHTML
Definition: httprequest.h:79
HTTPRequest::SendData
qint64 SendData(QIODevice *pDevice, qint64 llStart, qint64 llBytes)
Definition: httprequest.cpp:598
HTTPRequest::m_sFileName
QString m_sFileName
Definition: httprequest.h:155
HTTPRequest::GetResponseStatus
QString GetResponseStatus(void) const
Definition: httprequest.cpp:899
MythSessionManager::LoginUser
MythUserSession LoginUser(const QString &username, const QByteArray &digest, const QString &client="")
Login user by digest.
Definition: mythsession.cpp:282
MythDate::fromString
QDateTime fromString(const QString &dtstr)
Converts kFilename && kISODate formats to QDateTime.
Definition: mythdate.cpp:34
HTTPRequest::ParseCookies
void ParseCookies(void)
Definition: httprequest.cpp:1180
HTTPRequest::m_bSOAPRequest
bool m_bSOAPRequest
Definition: httprequest.h:144
RequestTypeHead
@ RequestTypeHead
Definition: httprequest.h:49
SOAP_ENVELOPE_END
static constexpr const char * SOAP_ENVELOPE_END
Definition: httprequest.h:37
HTTPRequest::CalculateDigestNonce
QString CalculateDigestNonce(const QString &timeStamp) const
Definition: httprequest.cpp:1829
BufferedSocketDeviceRequest::WriteBlock
qint64 WriteBlock(const char *pData, qint64 nLen) override
Definition: httprequest.cpp:2374
XmlConfiguration::GetValue
QString GetValue(const QString &setting)
Definition: configuration.cpp:185
MythDate::secsInPast
std::chrono::seconds secsInPast(const QDateTime &past)
Definition: mythdate.cpp:203
HTTPRequest::FormatErrorResponse
void FormatErrorResponse(bool bServerError, const QString &sFaultString, const QString &sDetails)
Definition: httprequest.cpp:660
HTTPRequest::GetLastHeader
QString GetLastHeader(const QString &sType) const
Definition: httprequest.cpp:154
mythcorecontext.h
g_MIMETypes
static std::array< const MIMETypes, 66 > g_MIMETypes
Definition: httprequest.cpp:57
HTTPRequest::FormatFileResponse
void FormatFileResponse(const QString &sFileName)
Definition: httprequest.cpp:792
HTTPRequest::SetResponseHeader
void SetResponseHeader(const QString &sKey, const QString &sValue, bool replace=false)
Definition: httprequest.cpp:2083
MythDate::kRFC822
@ kRFC822
HTTP Date format.
Definition: mythdate.h:30
HTTPRequest::m_eContentType
HttpContentType m_eContentType
Definition: httprequest.h:121
HTTPRequest::SendFile
qint64 SendFile(QFile &file, qint64 llStart, qint64 llBytes)
Definition: httprequest.cpp:648
MythCoreContext::GetLanguageAndVariant
QString GetLanguageAndVariant(void)
Returns the user-set language and variant.
Definition: mythcorecontext.cpp:1787
HTTPRequest::getSocketHandle
virtual int getSocketHandle()=0
HTTPRequest::m_eResponseType
HttpResponseType m_eResponseType
Definition: httprequest.h:149
ResponseTypeText
@ ResponseTypeText
Definition: httprequest.h:82
HTTPRequest::m_nMinor
int m_nMinor
Definition: httprequest.h:139
HTTPRequest::m_sPayload
QString m_sPayload
Definition: httprequest.h:135
HttpRequestType
HttpRequestType
Definition: httprequest.h:44
configuration.h
ResponseTypeNone
@ ResponseTypeNone
Definition: httprequest.h:76
ResponseTypeUnknown
@ ResponseTypeUnknown
Definition: httprequest.h:77
HTTPRequest::GetRequestProtocol
QString GetRequestProtocol() const
Definition: httprequest.cpp:845
StaticPage
static QString StaticPage
Definition: httprequest.cpp:138
HTTPRequest::GetParameters
static long GetParameters(QString sParams, QStringMap &mapParams)
Definition: httprequest.cpp:1071
BufferedSocketDeviceRequest::ReadLine
QString ReadLine(std::chrono::milliseconds msecs) override
Definition: httprequest.cpp:2307
MythDate::current_iso_string
QString current_iso_string(bool stripped)
Returns current Date and Time in UTC as a string.
Definition: mythdate.cpp:22
HTTPRequest::m_sNameSpace
QString m_sNameSpace
Definition: httprequest.h:145
mythtimer.h
HTTPRequest::AddCORSHeaders
void AddCORSHeaders(const QString &sOrigin)
Definition: httprequest.cpp:2203
BufferedSocketDeviceRequest::m_pSocket
QTcpSocket * m_pSocket
Definition: httprequest.h:282
azlyrics.info
dictionary info
Definition: azlyrics.py:7
HTTPRequest::GetResponseType
QString GetResponseType(void) const
Definition: httprequest.cpp:962
musicbrainzngs.caa.hostname
string hostname
Definition: caa.py:17
HTTPRequest::SendResponse
qint64 SendResponse(void)
Definition: httprequest.cpp:301
HTTPRequest::ProcessSOAPPayload
bool ProcessSOAPPayload(const QString &sSOAPAction)
Definition: httprequest.cpp:1584
HTTPRequest::GetAuthenticationHeader
QString GetAuthenticationHeader(bool isStale=false)
Definition: httprequest.cpp:1799
MythCoreContext::GetSessionManager
MythSessionManager * GetSessionManager(void)
Definition: mythcorecontext.cpp:2079
xmlplistSerializer.h
HTTPRequest::IsUrlProtected
static bool IsUrlProtected(const QString &sBaseUrl)
Definition: httprequest.cpp:1780
HTTPRequest::GetHostAddress
virtual QString GetHostAddress()=0
build_compdb.filename
filename
Definition: build_compdb.py:21
httprequest.h
RequestTypeSubscribe
@ RequestTypeSubscribe
Definition: httprequest.h:58
HTTPRequest::m_response
QBuffer m_response
Definition: httprequest.h:157
ResponseTypeXML
@ ResponseTypeXML
Definition: httprequest.h:78
HTTPRequest::ParseKeepAlive
bool ParseKeepAlive(void)
Definition: httprequest.cpp:1144
HTTPRequest::SetRequestType
HttpRequestType SetRequestType(const QString &sType)
Definition: httprequest.cpp:166
ContentType_Urlencoded
@ ContentType_Urlencoded
Definition: httprequest.h:69
HTTPRequest::GetRequestType
QString GetRequestType() const
Definition: httprequest.cpp:2163
soapSerializer.h
MythCoreContext::GetSetting
QString GetSetting(const QString &key, const QString &defaultval="")
Definition: mythcorecontext.cpp:902
HTTPRequest::m_nKeepAliveTimeout
std::chrono::seconds m_nKeepAliveTimeout
Definition: httprequest.h:167
MythSessionManager
Definition: mythsession.h:104
HTTPRequest::m_eType
HttpRequestType m_eType
Definition: httprequest.h:120
HTTPRequest::m_mapCookies
QStringMap m_mapCookies
Definition: httprequest.h:133