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"
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 QString();
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 : 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  [[clang::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 #define 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 
626  if (( llBytesRead = pDevice->read( aBuffer.data(), llBytesToRead )) != -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  stream << "<" << m_sMethod << "Response>\r\n";
734 
735  for (const auto & arg : qAsConst(args))
736  {
737  stream << "<" << arg.m_sName;
738 
739  if (arg.m_pAttributes)
740  {
741  for (const auto & attr : qAsConst(*arg.m_pAttributes))
742  {
743  stream << " " << attr.m_sName << "='"
744  << Encode( attr.m_sValue ) << "'";
745  }
746  }
747 
748  stream << ">";
749 
750  if (m_bSOAPRequest)
751  stream << Encode( arg.m_sValue );
752  else
753  stream << arg.m_sValue;
754 
755  stream << "</" << arg.m_sName << ">\r\n";
756  }
757 
758  if (m_bSOAPRequest)
759  {
760  stream << "</u:" << m_sMethod << "Response>\r\n"
762  }
763  else
764  stream << "</" << m_sMethod << "Response>\r\n";
765 
766  stream.flush();
767 }
768 
770 //
772 
773 void HTTPRequest::FormatRawResponse(const QString &sXML)
774 {
776  m_nResponseStatus = 200;
777 
778  QTextStream stream( &m_response );
779 
780  stream << sXML;
781 
782  stream.flush();
783 }
785 //
787 
788 void HTTPRequest::FormatFileResponse( const QString &sFileName )
789 {
790  m_sFileName = sFileName;
791  QFileInfo file(m_sFileName);
792 
793  if (!m_sFileName.isEmpty() && file.exists())
794  {
795  QDateTime ims = QDateTime::fromString(GetRequestHeader("if-modified-since", ""), Qt::RFC2822Date);
796  ims.setTimeSpec(Qt::OffsetFromUTC);
797  if (ims.isValid() && ims <= file.lastModified()) // Strong validator
798  {
800  m_nResponseStatus = 304; // Not Modified
801  }
802  else
803  {
806  m_nResponseStatus = 200; // OK
807  SetResponseHeader("Last-Modified", MythDate::toString(file.lastModified(),
809  MythDate::kRFC822))); // RFC 822
810  SetResponseHeader("Cache-Control", "no-cache=\"Ext\", max-age = 7200"); // 2 Hours
811  }
812  }
813  else
814  {
816  m_nResponseStatus = 404; // Resource not found
817  m_response.write( GetResponsePage() );
818  LOG(VB_HTTP, LOG_INFO,
819  QString("HTTPRequest::FormatFileResponse('%1') - cannot find file")
820  .arg(sFileName));
821  }
822 }
823 
825 //
827 
828 void HTTPRequest::SetRequestProtocol( const QString &sLine )
829 {
830  m_sProtocol = sLine.section( '/', 0, 0 ).trimmed();
831  QString sVersion = sLine.section( '/', 1 ).trimmed();
832 
833  m_nMajor = sVersion.section( '.', 0, 0 ).toInt();
834  m_nMinor = sVersion.section( '.', 1 ).toInt();
835 }
836 
838 //
840 
842 {
843  return QString("%1/%2.%3").arg(m_sProtocol,
844  QString::number(m_nMajor),
845  QString::number(m_nMinor));
846 }
847 
849 //
851 
853 {
854  // RFC 2145
855  //
856  // An HTTP server SHOULD send a response version equal to the highest
857  // version for which the server is at least conditionally compliant, and
858  // whose major version is less than or equal to the one received in the
859  // request.
860 
861 // if (m_nMajor == 1)
862 // QString("HTTP/1.1");
863 // else if (m_nMajor == 2)
864 // QString("HTTP/2.0");
865 
866  return QString("HTTP/1.1");
867 }
868 
870 //
872 
874 {
875  if ((sType == "application/x-www-form-urlencoded" ) ||
876  (sType.startsWith("application/x-www-form-urlencoded;")))
878 
879  if ((sType == "text/xml" ) ||
880  (sType.startsWith("text/xml;") ))
881  return( m_eContentType = ContentType_XML );
882 
883  if ((sType == "application/json") ||
884  sType.startsWith("application/json;"))
885  return( m_eContentType = ContentType_JSON);
886 
888 }
889 
890 
892 //
894 
895 QString HTTPRequest::GetResponseStatus( void ) const
896 {
897  switch( m_nResponseStatus )
898  {
899  case 200: return( "200 OK" );
900  case 201: return( "201 Created" );
901  case 202: return( "202 Accepted" );
902  case 204: return( "204 No Content" );
903  case 205: return( "205 Reset Content" );
904  case 206: return( "206 Partial Content" );
905  case 300: return( "300 Multiple Choices" );
906  case 301: return( "301 Moved Permanently" );
907  case 302: return( "302 Found" );
908  case 303: return( "303 See Other" );
909  case 304: return( "304 Not Modified" );
910  case 305: return( "305 Use Proxy" );
911  case 307: return( "307 Temporary Redirect" );
912  case 308: return( "308 Permanent Redirect" );
913  case 400: return( "400 Bad Request" );
914  case 401: return( "401 Unauthorized" );
915  case 403: return( "403 Forbidden" );
916  case 404: return( "404 Not Found" );
917  case 405: return( "405 Method Not Allowed" );
918  case 406: return( "406 Not Acceptable" );
919  case 408: return( "408 Request Timeout" );
920  case 410: return( "410 Gone" );
921  case 411: return( "411 Length Required" );
922  case 412: return( "412 Precondition Failed" );
923  case 413: return( "413 Request Entity Too Large" );
924  case 414: return( "414 Request-URI Too Long" );
925  case 415: return( "415 Unsupported Media Type" );
926  case 416: return( "416 Requested Range Not Satisfiable" );
927  case 417: return( "417 Expectation Failed" );
928  // I'm a teapot
929  case 428: return( "428 Precondition Required" ); // RFC 6585
930  case 429: return( "429 Too Many Requests" ); // RFC 6585
931  case 431: return( "431 Request Header Fields Too Large" ); // RFC 6585
932  case 500: return( "500 Internal Server Error" );
933  case 501: return( "501 Not Implemented" );
934  case 502: return( "502 Bad Gateway" );
935  case 503: return( "503 Service Unavailable" );
936  case 504: return( "504 Gateway Timeout" );
937  case 505: return( "505 HTTP Version Not Supported" );
938  case 510: return( "510 Not Extended" );
939  case 511: return( "511 Network Authentication Required" ); // RFC 6585
940  }
941 
942  return( QString( "%1 Unknown" ).arg( m_nResponseStatus ));
943 }
944 
946 //
948 
950 {
951  return StaticPage.arg(QString::number(m_nResponseStatus), GetResponseStatus()).toUtf8();
952 }
953 
955 //
957 
958 QString HTTPRequest::GetResponseType( void ) const
959 {
960  switch( m_eResponseType )
961  {
962  case ResponseTypeXML : return( "text/xml; charset=\"UTF-8\"" );
963  case ResponseTypeHTML : return( "text/html; charset=\"UTF-8\"" );
964  case ResponseTypeCSS : return( "text/css; charset=\"UTF-8\"" );
965  case ResponseTypeJS : return( "application/javascript" );
966  case ResponseTypeText : return( "text/plain; charset=\"UTF-8\"" );
967  case ResponseTypeSVG : return( "image/svg+xml" );
968  default: break;
969  }
970 
971  return( "text/plain" );
972 }
973 
975 //
977 
978 QString HTTPRequest::GetMimeType( const QString &sFileExtension )
979 {
980  QString ext;
981 
982  for (const auto & type : g_MIMETypes)
983  {
984  ext = type.pszExtension;
985 
986  if ( sFileExtension.compare(ext, Qt::CaseInsensitive) == 0 )
987  return( type.pszType );
988  }
989 
990  return( "text/plain" );
991 }
992 
994 //
996 
998 {
999  QStringList mimeTypes;
1000 
1001  for (const auto & type : g_MIMETypes)
1002  {
1003  if (!mimeTypes.contains( type.pszType ))
1004  mimeTypes.append( type.pszType );
1005  }
1006 
1007  return mimeTypes;
1008 }
1009 
1011 //
1013 
1014 QString HTTPRequest::TestMimeType( const QString &sFileName )
1015 {
1016  QFileInfo info( sFileName );
1017  QString sLOC = "HTTPRequest::TestMimeType(" + sFileName + ") - ";
1018  QString sSuffix = info.suffix().toLower();
1019  QString sMIME = GetMimeType( sSuffix );
1020 
1021  if ( sSuffix == "nuv" ) // If a very old recording, might be an MPEG?
1022  {
1023  // Read the header to find out:
1024  QFile file( sFileName );
1025 
1026  if ( file.open(QIODevice::ReadOnly | QIODevice::Text) )
1027  {
1028  QByteArray head = file.read(8);
1029  QString sHex = head.toHex();
1030 
1031  LOG(VB_HTTP, LOG_DEBUG, sLOC + "file starts with " + sHex);
1032 
1033  if ( sHex == "000001ba44000400" ) // MPEG2 PS
1034  sMIME = "video/mp2p";
1035 
1036  if ( head == "MythTVVi" )
1037  {
1038  file.seek(100);
1039  head = file.read(4);
1040 
1041  if ( head == "DIVX" )
1042  {
1043  LOG(VB_HTTP, LOG_DEBUG, sLOC + "('MythTVVi...DIVXLAME')");
1044  sMIME = "video/mp4";
1045  }
1046  // NuppelVideo is "RJPG" at byte 612
1047  // We could also check the audio (LAME or RAWA),
1048  // but since most UPnP clients choke on Nuppel, no need
1049  }
1050 
1051  file.close();
1052  }
1053  else
1054  LOG(VB_GENERAL, LOG_ERR, sLOC + "Could not read file");
1055  }
1056 
1057  LOG(VB_HTTP, LOG_INFO, sLOC + "type is " + sMIME);
1058  return sMIME;
1059 }
1060 
1062 //
1064 
1065 long HTTPRequest::GetParameters( QString sParams, QStringMap &mapParams )
1066 {
1067  long nCount = 0;
1068 
1069  LOG(VB_HTTP, LOG_INFO, QString("sParams: '%1'").arg(sParams));
1070 
1071  // This looks odd, but it is here to cope with stupid UPnP clients that
1072  // forget to de-escape the URLs. We can't map %26 here as well, as that
1073  // breaks anything that is trying to pass & as part of a name or value.
1074  sParams.replace( "&amp;", "&" );
1075 
1076  if (!sParams.isEmpty())
1077  {
1078 #if QT_VERSION < QT_VERSION_CHECK(5,14,0)
1079  QStringList params = sParams.split('&', QString::SkipEmptyParts);
1080 #else
1081  QStringList params = sParams.split('&', Qt::SkipEmptyParts);
1082 #endif
1083 
1084  for (const auto & param : qAsConst(params))
1085  {
1086  QString sName = param.section( '=', 0, 0 );
1087  QString sValue = param.section( '=', 1 );
1088  sValue.replace("+"," ");
1089 
1090  if (!sName.isEmpty())
1091  {
1092  sName = QUrl::fromPercentEncoding(sName.toUtf8());
1093  sValue = QUrl::fromPercentEncoding(sValue.toUtf8());
1094 
1095  mapParams.insert( sName.trimmed(), sValue );
1096  nCount++;
1097  }
1098  }
1099  }
1100 
1101  return nCount;
1102 }
1103 
1104 
1106 //
1108 
1109 QString HTTPRequest::GetRequestHeader( const QString &sKey, const QString &sDefault )
1110 {
1111  auto it = m_mapHeaders.find( sKey.toLower() );
1112 
1113  if ( it == m_mapHeaders.end())
1114  return( sDefault );
1115 
1116  return *it;
1117 }
1118 
1119 
1121 //
1123 
1125 {
1126  QString sHeader = s_szServerHeaders;
1127 
1128  for ( QStringMap::iterator it = m_mapRespHeaders.begin();
1129  it != m_mapRespHeaders.end();
1130  ++it )
1131  {
1132  sHeader += it.key() + ": ";
1133  sHeader += *it + "\r\n";
1134  }
1135 
1136  return( sHeader );
1137 }
1138 
1140 //
1142 
1144 {
1145  // TODO: Think about whether we should use a longer timeout if the client
1146  // has explicitly specified 'Keep-alive'
1147 
1148  // HTTP 1.1 ... server may assume keep-alive
1149  bool bKeepAlive = true;
1150 
1151  // if HTTP/1.0... must default to false
1152  if ((m_nMajor == 1) && (m_nMinor == 0))
1153  bKeepAlive = false;
1154 
1155  // Read Connection Header to see whether the client has explicitly
1156  // asked for the connection to be kept alive or closed after the response
1157  // is sent
1158  QString sConnection = GetRequestHeader( "connection", "default" ).toLower();
1159 
1160  QStringList sValueList = sConnection.split(",");
1161 
1162  if ( sValueList.contains("close") )
1163  {
1164  LOG(VB_HTTP, LOG_DEBUG, "Client requested the connection be closed");
1165  bKeepAlive = false;
1166  }
1167  else if (sValueList.contains("keep-alive"))
1168  bKeepAlive = true;
1169 
1170  return bKeepAlive;
1171 }
1172 
1174 //
1176 
1178 {
1179  QStringList sCookieList = m_mapHeaders.values("cookie");
1180 
1181  QStringList::iterator it;
1182  for (it = sCookieList.begin(); it != sCookieList.end(); ++it)
1183  {
1184  QString key = (*it).section('=', 0, 0);
1185  QString value = (*it).section('=', 1);
1186 
1187  m_mapCookies.insert(key, value);
1188  }
1189 }
1190 
1192 //
1194 
1196 {
1197  bool bSuccess = false;
1198 
1199  try
1200  {
1201  // Read first line to determine requestType
1202  QString sRequestLine = ReadLine( 2s );
1203 
1204  if ( sRequestLine.isEmpty() )
1205  {
1206  LOG(VB_GENERAL, LOG_ERR, "Timeout reading first line of request." );
1207  return false;
1208  }
1209 
1210  // -=>TODO: Should read lines until a valid request???
1211  ProcessRequestLine( sRequestLine );
1212 
1213  if (m_nMajor > 1 || m_nMajor < 0)
1214  {
1216  m_nResponseStatus = 505;
1217  m_response.write( GetResponsePage() );
1218 
1219  return true;
1220  }
1221 
1222  if (m_eType == RequestTypeUnknown)
1223  {
1225  m_nResponseStatus = 501; // Not Implemented
1226  // Conservative list, we can't really know what methods we
1227  // actually allow for an arbitrary resource without some sort of
1228  // high maintenance database
1229  SetResponseHeader("Allow", "GET, HEAD");
1230  m_response.write( GetResponsePage() );
1231  return true;
1232  }
1233 
1234  // Read Header
1235  bool bDone = false;
1236  QString sLine = ReadLine( 2s );
1237 
1238  while (( !sLine.isEmpty() ) && !bDone )
1239  {
1240  if (sLine != "\r\n")
1241  {
1242  QString sName = sLine.section( ':', 0, 0 ).trimmed();
1243  QString sValue = sLine.section( ':', 1 );
1244 
1245  sValue.truncate( sValue.length() - 2 );
1246 
1247  if (!sName.isEmpty() && !sValue.isEmpty())
1248  {
1249  m_mapHeaders.insert(sName.toLower(), sValue.trimmed());
1250  }
1251 
1252  sLine = ReadLine( 2s );
1253  }
1254  else
1255  bDone = true;
1256  }
1257 
1258  // Dump request header
1259  for ( auto it = m_mapHeaders.begin(); it != m_mapHeaders.end(); ++it )
1260  {
1261  LOG(VB_HTTP, LOG_INFO, QString("(Request Header) %1: %2")
1262  .arg(it.key(), *it));
1263  }
1264 
1265  // Parse Cookies
1266  ParseCookies();
1267 
1268  // Parse out keep alive
1270 
1271  // Check to see if we found the end of the header or we timed out.
1272  if (!bDone)
1273  {
1274  LOG(VB_GENERAL, LOG_INFO, "Timeout waiting for request header." );
1275  return false;
1276  }
1277 
1278  // HTTP/1.1 requires that the Host header be present, even if empty
1279  if ((m_nMinor == 1) && !m_mapHeaders.contains("host"))
1280  {
1282  m_nResponseStatus = 400;
1283  m_response.write( GetResponsePage() );
1284 
1285  return true;
1286  }
1287 
1288  // Destroy session if requested
1289  if (m_mapHeaders.contains("x-myth-clear-session"))
1290  {
1291  SetCookie("sessionToken", "", MythDate::current().addDays(-2), true);
1292  m_mapCookies.remove("sessionToken");
1293  }
1294 
1295  // Allow session resumption for TLS connections
1296  if (m_mapCookies.contains("sessionToken"))
1297  {
1298  QString sessionToken = m_mapCookies["sessionToken"];
1299  MythSessionManager *sessionManager = gCoreContext->GetSessionManager();
1300  MythUserSession session = sessionManager->GetSession(sessionToken);
1301 
1302  if (session.IsValid())
1303  m_userSession = session;
1304  }
1305 
1306  if (IsUrlProtected( m_sBaseUrl ))
1307  {
1308  if (!Authenticated())
1309  {
1311  m_nResponseStatus = 401;
1312  m_response.write( GetResponsePage() );
1313  // Since this may not be the first attempt at authentication,
1314  // Authenticated may have set the header with the appropriate
1315  // stale attribute
1316  SetResponseHeader("WWW-Authenticate", GetAuthenticationHeader(false));
1317 
1318  return true;
1319  }
1320 
1321  m_bProtected = true;
1322  }
1323 
1324  bSuccess = true;
1325 
1326  SetContentType( GetLastHeader( "content-type" ) );
1327  // Lets load payload if any.
1328  long nPayloadSize = GetLastHeader( "content-length" ).toLong();
1329 
1330  if (nPayloadSize > 0)
1331  {
1332  char *pszPayload = new char[ nPayloadSize + 2 ];
1333  long nBytes = 0;
1334 
1335  nBytes = ReadBlock( pszPayload, nPayloadSize, 5s );
1336  if (nBytes == nPayloadSize )
1337  {
1338  m_sPayload = QString::fromUtf8( pszPayload, nPayloadSize );
1339 
1340  // See if the payload is just data from a form post
1344  m_mapParams.insert( "json", m_sPayload );
1345  }
1346  else
1347  {
1348  LOG(VB_GENERAL, LOG_ERR,
1349  QString("Unable to read entire payload (read %1 of %2 bytes)")
1350  .arg( nBytes ) .arg( nPayloadSize ) );
1351  bSuccess = false;
1352  }
1353 
1354  delete [] pszPayload;
1355  }
1356 
1357  // Check to see if this is a SOAP encoded message
1358  QString sSOAPAction = GetRequestHeader( "SOAPACTION", "" );
1359 
1360  if (!sSOAPAction.isEmpty())
1361  bSuccess = ProcessSOAPPayload( sSOAPAction );
1362  else
1364 
1365 #if 0
1366  if (m_sMethod != "*" )
1367  LOG(VB_HTTP, LOG_DEBUG,
1368  QString("HTTPRequest::ParseRequest - Socket (%1) Base (%2) "
1369  "Method (%3) - Bytes in Socket Buffer (%4)")
1370  .arg(getSocketHandle()) .arg(m_sBaseUrl)
1371  .arg(m_sMethod) .arg(BytesAvailable()));
1372 #endif
1373  }
1374  catch(...)
1375  {
1376  LOG(VB_GENERAL, LOG_WARNING,
1377  "Unexpected exception in HTTPRequest::ParseRequest" );
1378  }
1379 
1380  return bSuccess;
1381 }
1382 
1384 //
1386 
1387 void HTTPRequest::ProcessRequestLine( const QString &sLine )
1388 {
1389  m_sRawRequest = sLine;
1390 
1391 #if QT_VERSION < QT_VERSION_CHECK(5,14,0)
1392  QStringList tokens = sLine.split(m_procReqLineExp, QString::SkipEmptyParts);
1393 #else
1394  QStringList tokens = sLine.split(m_procReqLineExp, Qt::SkipEmptyParts);
1395 #endif
1396  int nCount = tokens.count();
1397 
1398  // ----------------------------------------------------------------------
1399 
1400  if ( sLine.startsWith( QString("HTTP/") ))
1402  else
1404 
1405  // ----------------------------------------------------------------------
1406  // if this is actually a response, then sLine's format will be:
1407  // HTTP/m.n <response code> <response text>
1408  // otherwise:
1409  // <method> <Resource URI> HTTP/m.n
1410  // ----------------------------------------------------------------------
1411 
1413  {
1414  // ------------------------------------------------------------------
1415  // Process as a request
1416  // ------------------------------------------------------------------
1417 
1418  if (nCount > 0)
1419  SetRequestType( tokens[0].trimmed() );
1420 
1421  if (nCount > 1)
1422  {
1423  m_sOriginalUrl = tokens[1].toUtf8(); // Used by authorization check
1424  m_sRequestUrl = QUrl::fromPercentEncoding(tokens[1].toUtf8());
1425  m_sBaseUrl = m_sRequestUrl.section( '?', 0, 0).trimmed();
1426 
1427  m_sResourceUrl = m_sBaseUrl; // Save complete url without parameters
1428 
1429  // Process any Query String Parameters
1430  QString sQueryStr = tokens[1].section( '?', 1, 1 );
1431 
1432  if (!sQueryStr.isEmpty())
1433  GetParameters( sQueryStr, m_mapParams );
1434  }
1435 
1436  if (nCount > 2)
1437  SetRequestProtocol( tokens[2].trimmed() );
1438  }
1439  else
1440  {
1441  // ------------------------------------------------------------------
1442  // Process as a Response
1443  // ------------------------------------------------------------------
1444  if (nCount > 0)
1445  SetRequestProtocol( tokens[0].trimmed() );
1446 
1447  if (nCount > 1)
1448  m_nResponseStatus = tokens[1].toInt();
1449  }
1450 
1451 
1452 }
1453 
1455 //
1457 
1458 bool HTTPRequest::ParseRange( QString sRange,
1459  long long llSize,
1460  long long *pllStart,
1461  long long *pllEnd )
1462 {
1463  // ----------------------------------------------------------------------
1464  // -=>TODO: Only handle 1 range at this time...
1465  // should make work with full spec.
1466  // ----------------------------------------------------------------------
1467 
1468  if (sRange.isEmpty())
1469  return false;
1470 
1471  // ----------------------------------------------------------------------
1472  // remove any "bytes="
1473  // ----------------------------------------------------------------------
1474  int nIdx = sRange.indexOf(m_parseRangeExp);
1475 
1476  if (nIdx < 0)
1477  return false;
1478 
1479  if (nIdx > 0)
1480  sRange.remove( 0, nIdx );
1481 
1482  // ----------------------------------------------------------------------
1483  // Split multiple ranges
1484  // ----------------------------------------------------------------------
1485 
1486 #if QT_VERSION < QT_VERSION_CHECK(5,14,0)
1487  QStringList ranges = sRange.split(',', QString::SkipEmptyParts);
1488 #else
1489  QStringList ranges = sRange.split(',', Qt::SkipEmptyParts);
1490 #endif
1491 
1492  if (ranges.count() == 0)
1493  return false;
1494 
1495  // ----------------------------------------------------------------------
1496  // Split first range into its components
1497  // ----------------------------------------------------------------------
1498 
1499  QStringList parts = ranges[0].split('-');
1500 
1501  if (parts.count() != 2)
1502  return false;
1503 
1504  if (parts[0].isEmpty() && parts[1].isEmpty())
1505  return false;
1506 
1507  // ----------------------------------------------------------------------
1508  //
1509  // ----------------------------------------------------------------------
1510 
1511  bool conv_ok = false;
1512  if (parts[0].isEmpty())
1513  {
1514  // ------------------------------------------------------------------
1515  // Does it match "-####"
1516  // ------------------------------------------------------------------
1517 
1518  long long llValue = parts[1].toLongLong(&conv_ok);
1519  if (!conv_ok) return false;
1520 
1521  *pllStart = llSize - llValue;
1522  *pllEnd = llSize - 1;
1523  }
1524  else if (parts[1].isEmpty())
1525  {
1526  // ------------------------------------------------------------------
1527  // Does it match "####-"
1528  // ------------------------------------------------------------------
1529 
1530  *pllStart = parts[0].toLongLong(&conv_ok);
1531 
1532  if (!conv_ok)
1533  return false;
1534 
1535  *pllEnd = llSize - 1;
1536  }
1537  else
1538  {
1539  // ------------------------------------------------------------------
1540  // Must be "####-####"
1541  // ------------------------------------------------------------------
1542 
1543  *pllStart = parts[0].toLongLong(&conv_ok);
1544  if (!conv_ok) return false;
1545  *pllEnd = parts[1].toLongLong(&conv_ok);
1546  if (!conv_ok) return false;
1547 
1548  if (*pllStart > *pllEnd)
1549  return false;
1550  }
1551 
1552  LOG(VB_HTTP, LOG_DEBUG, QString("%1 Range Requested %2 - %3")
1553  .arg(getSocketHandle()) .arg(*pllStart) .arg(*pllEnd));
1554 
1555  return true;
1556 }
1557 
1559 //
1561 
1563 {
1564  // Strip out leading http://192.168.1.1:6544/ -> /
1565  // Should fix #8678
1566  // FIXME what about https?
1567  QRegularExpression re {"^http[s]?://.*?/"};
1568  m_sBaseUrl.replace(re, "/");
1569 
1570 #if QT_VERSION < QT_VERSION_CHECK(5,14,0)
1571  QStringList sList = m_sBaseUrl.split('/', QString::SkipEmptyParts);
1572 #else
1573  QStringList sList = m_sBaseUrl.split('/', Qt::SkipEmptyParts);
1574 #endif
1575 
1576  m_sMethod = "";
1577 
1578  if (!sList.isEmpty())
1579  {
1580  m_sMethod = sList.last();
1581  sList.pop_back();
1582  }
1583 
1584  m_sBaseUrl = '/' + sList.join( "/" );
1585  LOG(VB_HTTP, LOG_INFO, QString("ExtractMethodFromURL(end) : %1 : %2")
1586  .arg(m_sMethod, m_sBaseUrl));
1587 }
1588 
1590 //
1592 
1593 bool HTTPRequest::ProcessSOAPPayload( const QString &sSOAPAction )
1594 {
1595  bool bSuccess = false;
1596 
1597  // ----------------------------------------------------------------------
1598  // Open Supplied XML uPnp Description file.
1599  // ----------------------------------------------------------------------
1600 
1601  LOG(VB_HTTP, LOG_INFO,
1602  QString("HTTPRequest::ProcessSOAPPayload : %1 : ").arg(sSOAPAction));
1603  QDomDocument doc ( "request" );
1604 
1605  QString sErrMsg;
1606  int nErrLine = 0;
1607  int nErrCol = 0;
1608 
1609  if (!doc.setContent( m_sPayload, true, &sErrMsg, &nErrLine, &nErrCol ))
1610  {
1611  LOG(VB_GENERAL, LOG_ERR,
1612  QString( "Error parsing request at line: %1 column: %2 : %3" )
1613  .arg(nErrLine) .arg(nErrCol) .arg(sErrMsg));
1614  return( false );
1615  }
1616 
1617  // --------------------------------------------------------------
1618  // XML Document Loaded... now parse it
1619  // --------------------------------------------------------------
1620 
1621  QString sService;
1622 
1623  if (sSOAPAction.contains( '#' ))
1624  {
1625  m_sNameSpace = sSOAPAction.section( '#', 0, 0).remove( 0, 1);
1626  m_sMethod = sSOAPAction.section( '#', 1 );
1627  m_sMethod.remove( m_sMethod.length()-1, 1 );
1628  }
1629  else
1630  {
1631  if (sSOAPAction.contains( '/' ))
1632  {
1633  int nPos = sSOAPAction.lastIndexOf( '/' );
1634  m_sNameSpace = sSOAPAction.mid(1, nPos);
1635  m_sMethod = sSOAPAction.mid(nPos + 1,
1636  sSOAPAction.length() - nPos - 2);
1637 
1638  nPos = m_sNameSpace.lastIndexOf( '/', -2);
1639  sService = m_sNameSpace.mid(nPos + 1,
1640  m_sNameSpace.length() - nPos - 2);
1641  m_sNameSpace = m_sNameSpace.mid( 0, nPos );
1642  }
1643  else
1644  {
1645  m_sNameSpace.clear();
1646  m_sMethod = sSOAPAction;
1647  m_sMethod.remove( QChar( '\"' ) );
1648  }
1649  }
1650 
1651  QDomNodeList oNodeList = doc.elementsByTagNameNS( m_sNameSpace, m_sMethod );
1652 
1653  if (oNodeList.count() == 0)
1654  {
1655  oNodeList =
1656  doc.elementsByTagNameNS("http://schemas.xmlsoap.org/soap/envelope/",
1657  "Body");
1658  }
1659 
1660  if (oNodeList.count() > 0)
1661  {
1662  QDomNode oMethod = oNodeList.item(0);
1663 
1664  if (!oMethod.isNull())
1665  {
1666  m_bSOAPRequest = true;
1667 
1668  for ( QDomNode oNode = oMethod.firstChild(); !oNode.isNull();
1669  oNode = oNode.nextSibling() )
1670  {
1671  QDomElement e = oNode.toElement();
1672 
1673  if (!e.isNull())
1674  {
1675  QString sName = e.tagName();
1676  QString sValue = "";
1677 
1678  QDomText oText = oNode.firstChild().toText();
1679 
1680  if (!oText.isNull())
1681  sValue = oText.nodeValue();
1682 
1683  sName = QUrl::fromPercentEncoding(sName.toUtf8());
1684  sValue = QUrl::fromPercentEncoding(sValue.toUtf8());
1685 
1686  m_mapParams.insert( sName.trimmed().toLower(), sValue );
1687  }
1688  }
1689 
1690  bSuccess = true;
1691  }
1692  }
1693 
1694  return bSuccess;
1695 }
1696 
1698 //
1700 
1702 {
1703  Serializer *pSerializer = nullptr;
1704 
1705  if (m_bSOAPRequest)
1706  {
1707  pSerializer = (Serializer *)new SoapSerializer(&m_response,
1709  }
1710  else
1711  {
1712  QString sAccept = GetRequestHeader( "Accept", "*/*" );
1713 
1714  if (sAccept.contains( "application/json", Qt::CaseInsensitive ) ||
1715  sAccept.contains( "text/javascript", Qt::CaseInsensitive ))
1716  {
1717  pSerializer = (Serializer *)new JSONSerializer(&m_response,
1718  m_sMethod);
1719  }
1720  else if (sAccept.contains( "text/x-apple-plist+xml", Qt::CaseInsensitive ))
1721  {
1722  pSerializer = (Serializer *)new XmlPListSerializer(&m_response);
1723  }
1724  }
1725 
1726  // Default to XML
1727 
1728  if (pSerializer == nullptr)
1729  pSerializer = (Serializer *)new XmlSerializer(&m_response, m_sMethod);
1730 
1731  return pSerializer;
1732 }
1733 
1735 //
1737 
1738 QString HTTPRequest::Encode(const QString &sIn)
1739 {
1740  QString sStr = sIn;
1741 #if 0
1742  LOG(VB_HTTP, LOG_DEBUG,
1743  QString("HTTPRequest::Encode Input : %1").arg(sStr));
1744 #endif
1745  sStr.replace('&', "&amp;" ); // This _must_ come first
1746  sStr.replace('<', "&lt;" );
1747  sStr.replace('>', "&gt;" );
1748  sStr.replace('"', "&quot;");
1749  sStr.replace("'", "&apos;");
1750 
1751 #if 0
1752  LOG(VB_HTTP, LOG_DEBUG,
1753  QString("HTTPRequest::Encode Output : %1").arg(sStr));
1754 #endif
1755  return sStr;
1756 }
1757 
1759 //
1761 
1762 QString HTTPRequest::Decode(const QString& sIn)
1763 {
1764  QString sStr = sIn;
1765  sStr.replace("&amp;", "&");
1766  sStr.replace("&lt;", "<");
1767  sStr.replace("&gt;", ">");
1768  sStr.replace("&quot;", "\"");
1769  sStr.replace("&apos;", "'");
1770 
1771  return sStr;
1772 }
1773 
1775 //
1777 
1778 QString HTTPRequest::GetETagHash(const QByteArray &data)
1779 {
1780  QByteArray hash = QCryptographicHash::hash( data.data(), QCryptographicHash::Sha1);
1781 
1782  return ("\"" + hash.toHex() + "\"");
1783 }
1784 
1786 //
1788 
1789 bool HTTPRequest::IsUrlProtected( const QString &sBaseUrl )
1790 {
1791  QString sProtected = MythCoreContext::GetConfiguration()->GetValue( "HTTP/Protected/Urls", "/setup;/Config" );
1792 
1793  QStringList oList = sProtected.split( ';' );
1794 
1795  for( int nIdx = 0; nIdx < oList.count(); nIdx++)
1796  {
1797  if (sBaseUrl.startsWith( oList[nIdx], Qt::CaseInsensitive ))
1798  return true;
1799  }
1800 
1801  return false;
1802 }
1803 
1805 //
1807 
1809 {
1810  QString authHeader;
1811 
1812  // For now we support a single realm, that will change
1813  QString realm = "MythTV";
1814 
1815  // Always use digest authentication where supported, it may be available
1816  // with HTTP 1.0 client as an extension, but we can't tell if that's the
1817  // case. It's guaranteed to be available for HTTP 1.1+
1818  if (m_nMajor >= 1 && m_nMinor > 0)
1819  {
1821  QString stale = isStale ? "true" : "false"; // FIXME
1822  authHeader = QString("Digest realm=\"%1\",nonce=\"%2\","
1823  "qop=\"auth\",stale=\"%3\",algorithm=\"MD5\"")
1824  .arg(realm, nonce, stale);
1825  }
1826  else
1827  {
1828  authHeader = QString("Basic realm=\"%1\"").arg(realm);
1829  }
1830 
1831  return authHeader;
1832 }
1833 
1835 //
1837 
1838 QString HTTPRequest::CalculateDigestNonce(const QString& timeStamp) const
1839 {
1840  QString uniqueID = QString("%1:%2").arg(timeStamp, m_sPrivateToken);
1841  QString hash = QCryptographicHash::hash( uniqueID.toLatin1(), QCryptographicHash::Sha1).toHex(); // TODO: Change to Sha2 with QT5?
1842  QString nonce = QString("%1%2").arg(timeStamp, hash); // Note: since this is going in a header it should avoid illegal chars
1843  return nonce;
1844 }
1845 
1847 //
1849 
1851 {
1852  LOG(VB_HTTP, LOG_NOTICE, "Attempting HTTP Basic Authentication");
1853  QStringList oList = GetLastHeader( "authorization" ).split( ' ' );
1854 
1855  if (m_nMajor == 1 && m_nMinor == 0) // We only support Basic auth for http 1.0 clients
1856  {
1857  LOG(VB_GENERAL, LOG_WARNING, "Basic authentication is only allowed for HTTP 1.0");
1858  return false;
1859  }
1860 
1861  QString sCredentials = QByteArray::fromBase64( oList[1].toUtf8() );
1862 
1863  oList = sCredentials.split( ':' );
1864 
1865  if (oList.count() < 2)
1866  {
1867  LOG(VB_GENERAL, LOG_WARNING, "Authorization attempt with invalid number of tokens");
1868  return false;
1869  }
1870 
1871  QString sUsername = oList[0];
1872  QString sPassword = oList[1];
1873 
1874  if (sUsername == "nouser") // Special logout username
1875  return false;
1876 
1877  MythSessionManager *sessionManager = gCoreContext->GetSessionManager();
1878  if (!MythSessionManager::IsValidUser(sUsername))
1879  {
1880  LOG(VB_GENERAL, LOG_WARNING, "Authorization attempt with invalid username");
1881  return false;
1882  }
1883 
1884  QString client = QString("WebFrontend_%1").arg(GetPeerAddress());
1885  MythUserSession session = sessionManager->LoginUser(sUsername, sPassword,
1886  client);
1887 
1888  if (!session.IsValid())
1889  {
1890  LOG(VB_GENERAL, LOG_WARNING, "Authorization attempt with invalid password");
1891  return false;
1892  }
1893 
1894  LOG(VB_HTTP, LOG_NOTICE, "Valid Authorization received");
1895 
1896  if (IsEncrypted()) // Only set a session cookie for encrypted connections, not safe otherwise
1897  SetCookie("sessionToken", session.GetSessionToken(),
1898  session.GetSessionExpires(), true);
1899 
1900  m_userSession = session;
1901 
1902  return false;
1903 }
1904 
1906 //
1908 
1910 {
1911  LOG(VB_HTTP, LOG_NOTICE, "Attempting HTTP Digest Authentication");
1912  QString realm = "MythTV"; // TODO Check which realm applies for the request path
1913 
1914  QString authMethod = GetLastHeader( "authorization" ).section(' ', 0, 0).toLower();
1915 
1916  if (authMethod != "digest")
1917  {
1918  LOG(VB_GENERAL, LOG_WARNING, "Invalid method in Authorization header");
1919  return false;
1920  }
1921 
1922  QString parameterStr = GetLastHeader( "authorization" ).section(' ', 1);
1923 
1924  QMap<QString, QString> paramMap;
1925  QStringList paramList = parameterStr.split(',');
1926  QStringList::iterator it;
1927  for (it = paramList.begin(); it != paramList.end(); ++it)
1928  {
1929  QString key = (*it).section('=', 0, 0).toLower().trimmed();
1930  // Since the value may contain '=' return everything after first occurence
1931  QString value = (*it).section('=', 1).trimmed();
1932  // Remove any quotes surrounding the value
1933  value.remove("\"");
1934  paramMap[key] = value;
1935  }
1936 
1937  if (paramMap.size() < 8)
1938  {
1939  LOG(VB_GENERAL, LOG_WARNING, "Invalid number of parameters in Authorization header");
1940  return false;
1941  }
1942 
1943  if (paramMap["nonce"].isEmpty() || paramMap["username"].isEmpty() ||
1944  paramMap["realm"].isEmpty() || paramMap["uri"].isEmpty() ||
1945  paramMap["response"].isEmpty() || paramMap["qop"].isEmpty() ||
1946  paramMap["cnonce"].isEmpty() || paramMap["nc"].isEmpty())
1947  {
1948  LOG(VB_GENERAL, LOG_WARNING, "Missing required parameters in Authorization header");
1949  return false;
1950  }
1951 
1952  if (paramMap["username"] == "nouser") // Special logout username
1953  return false;
1954 
1955  if (paramMap["uri"] != m_sOriginalUrl)
1956  {
1957  LOG(VB_GENERAL, LOG_WARNING, "Authorization URI doesn't match the "
1958  "request URI");
1959  m_nResponseStatus = 400; // Bad Request
1960  return false;
1961  }
1962 
1963  if (paramMap["realm"] != realm)
1964  {
1965  LOG(VB_GENERAL, LOG_WARNING, "Authorization realm doesn't match the "
1966  "realm of the requested content");
1967  return false;
1968  }
1969 
1970  QByteArray nonce = paramMap["nonce"].toLatin1();
1971  if (nonce.length() < 20)
1972  {
1973  LOG(VB_GENERAL, LOG_WARNING, "Authorization nonce is too short");
1974  return false;
1975  }
1976 
1977  QString nonceTimeStampStr = nonce.left(20); // ISO 8601 fixed length
1978  if (nonce != CalculateDigestNonce(nonceTimeStampStr))
1979  {
1980  LOG(VB_GENERAL, LOG_WARNING, "Authorization nonce doesn't match reference");
1981  LOG(VB_HTTP, LOG_DEBUG, QString("%1 vs %2").arg(QString(nonce),
1982  CalculateDigestNonce(nonceTimeStampStr)));
1983  return false;
1984  }
1985 
1986  constexpr std::chrono::seconds AUTH_TIMEOUT { 2min }; // 2 Minute timeout to login, to reduce replay attack window
1987  QDateTime nonceTimeStamp = MythDate::fromString(nonceTimeStampStr);
1988  if (!nonceTimeStamp.isValid())
1989  {
1990  LOG(VB_GENERAL, LOG_WARNING, "Authorization nonce timestamp is invalid.");
1991  LOG(VB_HTTP, LOG_DEBUG, QString("Timestamp was '%1'").arg(nonceTimeStampStr));
1992  return false;
1993  }
1994 
1995  if (MythDate::secsInPast(nonceTimeStamp) > AUTH_TIMEOUT)
1996  {
1997  LOG(VB_HTTP, LOG_NOTICE, "Authorization nonce timestamp is invalid or too old.");
1998  // Tell the client that the submitted nonce has expired at which
1999  // point they may wish to try again with a fresh nonce instead of
2000  // telling the user that their credentials were invalid
2001  SetResponseHeader("WWW-Authenticate", GetAuthenticationHeader(true), true);
2002  return false;
2003  }
2004 
2005  MythSessionManager *sessionManager = gCoreContext->GetSessionManager();
2006  if (!MythSessionManager::IsValidUser(paramMap["username"]))
2007  {
2008  LOG(VB_GENERAL, LOG_WARNING, "Authorization attempt with invalid username");
2009  return false;
2010  }
2011 
2012  if (paramMap["response"].length() != 32)
2013  {
2014  LOG(VB_GENERAL, LOG_WARNING, "Authorization response field is invalid length");
2015  return false;
2016  }
2017 
2018  // If you're still reading this, well done, not far to go now
2019 
2020  QByteArray a1 = MythSessionManager::GetPasswordDigest(paramMap["username"]).toLatin1();
2021  //QByteArray a1 = "bcd911b2ecb15ffbd6d8e6e744d60cf6";
2022  QString methodDigest = QString("%1:%2").arg(GetRequestType(), paramMap["uri"]);
2023  QByteArray a2 = QCryptographicHash::hash(methodDigest.toLatin1(),
2024  QCryptographicHash::Md5).toHex();
2025 
2026  QString responseDigest = QString("%1:%2:%3:%4:%5:%6").arg(a1,
2027  paramMap["nonce"],
2028  paramMap["nc"],
2029  paramMap["cnonce"],
2030  paramMap["qop"],
2031  a2);
2032  QByteArray kd = QCryptographicHash::hash(responseDigest.toLatin1(),
2033  QCryptographicHash::Md5).toHex();
2034 
2035  if (paramMap["response"].toLatin1() == kd)
2036  {
2037  LOG(VB_HTTP, LOG_NOTICE, "Valid Authorization received");
2038  QString client = QString("WebFrontend_%1").arg(GetPeerAddress());
2039  MythUserSession session = sessionManager->LoginUser(paramMap["username"],
2040  a1,
2041  client);
2042  if (!session.IsValid())
2043  {
2044  LOG(VB_GENERAL, LOG_ERR, "Valid Authorization received, but we "
2045  "failed to create a valid session");
2046  return false;
2047  }
2048 
2049  if (IsEncrypted()) // Only set a session cookie for encrypted connections, not safe otherwise
2050  SetCookie("sessionToken", session.GetSessionToken(),
2051  session.GetSessionExpires(), true);
2052 
2053  m_userSession = session;
2054 
2055  return true;
2056  }
2057 
2058  LOG(VB_GENERAL, LOG_WARNING, "Authorization attempt with invalid password digest");
2059  LOG(VB_HTTP, LOG_DEBUG, QString("Received hash was '%1', calculated hash was '%2'")
2060  .arg(paramMap["response"], QString(kd)));
2061 
2062  return false;
2063 }
2064 
2066 //
2068 
2070 {
2071  // Check if the existing user has permission to access this resource
2072  if (m_userSession.IsValid()) //m_userSession.CheckPermission())
2073  return true;
2074 
2075  QStringList oList = GetLastHeader( "authorization" ).split( ' ' );
2076 
2077  if (oList.count() < 2)
2078  return false;
2079 
2080  if (oList[0].compare( "basic", Qt::CaseInsensitive ) == 0)
2081  return BasicAuthentication();
2082  if (oList[0].compare( "digest", Qt::CaseInsensitive ) == 0)
2083  return DigestAuthentication();
2084 
2085  return false;
2086 }
2087 
2089 //
2091 
2092 void HTTPRequest::SetResponseHeader(const QString& sKey, const QString& sValue,
2093  bool replace)
2094 {
2095  if (!replace && m_mapRespHeaders.contains(sKey))
2096  return;
2097 
2098  m_mapRespHeaders[sKey] = sValue;
2099 }
2100 
2102 //
2104 
2105 void HTTPRequest::SetCookie(const QString &sKey, const QString &sValue,
2106  const QDateTime &expiryDate, bool secure)
2107 {
2108  if (secure && !IsEncrypted())
2109  {
2110  LOG(VB_GENERAL, LOG_WARNING, QString("HTTPRequest::SetCookie(%1=%2): "
2111  "A secure cookie cannot be set on an unencrypted connection.")
2112  .arg(sKey, sValue));
2113  return;
2114  }
2115 
2116  QStringList cookieAttributes;
2117 
2118  // Key=Value
2119  cookieAttributes.append(QString("%1=%2").arg(sKey, sValue));
2120 
2121  // Domain - Most browsers have problems with a hostname, so it's better to omit this
2122 // cookieAttributes.append(QString("Domain=%1").arg(GetHostName()));
2123 
2124  // Path - Fix to root, no call for restricting to other paths yet
2125  cookieAttributes.append("Path=/");
2126 
2127  // Expires - Expiry date, always set one, just good practice
2128  QString expires = MythDate::toString(expiryDate, MythDate::kRFC822); // RFC 822
2129  cookieAttributes.append(QString("Expires=%1").arg(expires)); // Cookie Expiry date
2130 
2131  // Secure - Only send this cookie over encrypted connections, it contains
2132  // sensitive info SECURITY
2133  if (secure)
2134  cookieAttributes.append("Secure");
2135 
2136  // HttpOnly - No cookie stealing javascript SECURITY
2137  cookieAttributes.append("HttpOnly");
2138 
2139  SetResponseHeader("Set-Cookie", cookieAttributes.join("; "));
2140 }
2141 
2143 //
2145 
2147 {
2148  // TODO: This only deals with the HTTP 1.1 case, 1.0 should be rare but we
2149  // should probably still handle it
2150 
2151  // RFC 3875 - The is the hostname or ip address in the client request, not
2152  // the name or ip we might otherwise know for this server
2153  QString hostname = GetLastHeader("host");
2154  if (!hostname.isEmpty())
2155  {
2156  // Strip the port
2157  if (hostname.contains("]:")) // IPv6 port
2158  {
2159  return hostname.section("]:", 0 , 0);
2160  }
2161  if (hostname.contains(":")) // IPv4 port
2162  {
2163  return hostname.section(":", 0 , 0);
2164  }
2165  return hostname;
2166  }
2167 
2168  return GetHostAddress();
2169 }
2170 
2171 
2173 {
2174  QString type;
2175  switch ( m_eType )
2176  {
2177  case RequestTypeUnknown :
2178  type = "UNKNOWN";
2179  break;
2180  case RequestTypeGet :
2181  type = "GET";
2182  break;
2183  case RequestTypeHead :
2184  type = "HEAD";
2185  break;
2186  case RequestTypePost :
2187  type = "POST";
2188  break;
2189  case RequestTypeOptions:
2190  type = "OPTIONS";
2191  break;
2192  case RequestTypeMSearch:
2193  type = "M-SEARCH";
2194  break;
2195  case RequestTypeNotify:
2196  type = "NOTIFY";
2197  break;
2198  case RequestTypeSubscribe :
2199  type = "SUBSCRIBE";
2200  break;
2201  case RequestTypeUnsubscribe :
2202  type = "UNSUBSCRIBE";
2203  break;
2204  case RequestTypeResponse :
2205  type = "RESPONSE";
2206  break;
2207  }
2208 
2209  return type;
2210 }
2211 
2212 void HTTPRequest::AddCORSHeaders( const QString &sOrigin )
2213 {
2214  // ----------------------------------------------------------------------
2215  // SECURITY: Access-Control-Allow-Origin Wildcard
2216  //
2217  // This is a REALLY bad idea, so bad in fact that I'm including it here but
2218  // commented out in the hope that anyone thinking of adding it in the future
2219  // will see it and then read this comment.
2220  //
2221  // Browsers do not verify that the origin is on the same network. This means
2222  // that a malicious script embedded or included into ANY webpage you visit
2223  // could then access servers on your local network including MythTV. They
2224  // can grab data, delete data including recordings and videos, schedule
2225  // recordings and generally ruin your day.
2226  //
2227  // This might seem paranoid and a remote possibility, but then that's how
2228  // a lot of exploits are born. Do NOT allow wildcards.
2229  //
2230  //m_mapRespHeaders[ "Access-Control-Allow-Origin" ] = "*";
2231  // ----------------------------------------------------------------------
2232 
2233  // ----------------------------------------------------------------------
2234  // SECURITY: Allow the WebFrontend on the Master backend and ONLY this
2235  // machine to access resources on a frontend or slave web server
2236  //
2237  // http://www.w3.org/TR/cors/#introduction
2238  // ----------------------------------------------------------------------
2239 
2240  QStringList allowedOrigins;
2241 
2242  int serverStatusPort = gCoreContext->GetMasterServerStatusPort();
2243  int backendSSLPort = gCoreContext->GetNumSetting( "BackendSSLPort",
2244  serverStatusPort + 10);
2245 
2246  QString masterAddrPort = QString("%1:%2")
2248  .arg(serverStatusPort);
2249  QString masterTLSAddrPort = QString("%1:%2")
2251  .arg(backendSSLPort);
2252 
2253  allowedOrigins << QString("http://%1").arg(masterAddrPort);
2254  allowedOrigins << QString("https://%2").arg(masterTLSAddrPort);
2255 
2256  QString localhostname = QHostInfo::localHostName();
2257  if (!localhostname.isEmpty())
2258  {
2259  allowedOrigins << QString("http://%1:%2")
2260  .arg(localhostname).arg(serverStatusPort);
2261  allowedOrigins << QString("https://%1:%2")
2262  .arg(localhostname).arg(backendSSLPort);
2263  }
2264 
2265  QStringList allowedOriginsList =
2266  gCoreContext->GetSetting("AllowedOriginsList", QString(
2267  "https://chromecast.mythtv.org")).split(",");
2268 
2269  for (const auto & origin : qAsConst(allowedOriginsList))
2270  {
2271  if (origin.isEmpty())
2272  continue;
2273 
2274  if (origin == "*" || (!origin.startsWith("http://") &&
2275  !origin.startsWith("https://")))
2276  {
2277  LOG(VB_GENERAL, LOG_ERR, QString("Illegal AllowedOriginsList"
2278  " entry '%1'. Must start with http[s]:// and not be *")
2279  .arg(origin));
2280  }
2281  else
2282  {
2283  allowedOrigins << origin;
2284  }
2285  }
2286 
2287  if (VERBOSE_LEVEL_CHECK(VB_HTTP, LOG_DEBUG))
2288  {
2289  for (const auto & origin : qAsConst(allowedOrigins))
2290  LOG(VB_HTTP, LOG_DEBUG, QString("Will allow Origin: %1").arg(origin));
2291  }
2292 
2293  if (allowedOrigins.contains(sOrigin))
2294  {
2295  SetResponseHeader( "Access-Control-Allow-Origin" , sOrigin);
2296  SetResponseHeader( "Access-Control-Allow-Credentials" , "true");
2297  SetResponseHeader( "Access-Control-Allow-Headers" , "Content-Type");
2298  LOG(VB_HTTP, LOG_DEBUG, QString("Allow-Origin: %1)").arg(sOrigin));
2299  }
2300  else
2301  {
2302  LOG(VB_GENERAL, LOG_CRIT, QString("HTTPRequest: Cross-origin request "
2303  "received with origin (%1)")
2304  .arg(sOrigin));
2305  }
2306 }
2307 
2310 //
2311 // BufferedSocketDeviceRequest Class Implementation
2312 //
2315 
2316 QString BufferedSocketDeviceRequest::ReadLine( std::chrono::milliseconds msecs )
2317 {
2318  QString sLine;
2319 
2320  if (m_pSocket && m_pSocket->isValid() &&
2321  m_pSocket->state() == QAbstractSocket::ConnectedState)
2322  {
2323  bool timeout = false;
2324  MythTimer timer;
2325  timer.start();
2326  while (!m_pSocket->canReadLine() && !timeout)
2327  {
2328  timeout = !(m_pSocket->waitForReadyRead( msecs.count() ));
2329 
2330  if ( timer.elapsed() >= msecs )
2331  {
2332  timeout = true;
2333  LOG(VB_HTTP, LOG_INFO, "BufferedSocketDeviceRequest::ReadLine() - Exceeded Total Elapsed Wait Time." );
2334  }
2335  }
2336 
2337  if (!timeout)
2338  sLine = m_pSocket->readLine();
2339  }
2340 
2341  return( sLine );
2342 }
2343 
2345 //
2347 
2348 qint64 BufferedSocketDeviceRequest::ReadBlock(char *pData, qint64 nMaxLen,
2349  std::chrono::milliseconds msecs)
2350 {
2351  if (m_pSocket && m_pSocket->isValid() &&
2352  m_pSocket->state() == QAbstractSocket::ConnectedState)
2353  {
2354  if (msecs == 0ms)
2355  return( m_pSocket->read( pData, nMaxLen ));
2356 
2357  bool bTimeout = false;
2358  MythTimer timer;
2359  timer.start();
2360  while ( (m_pSocket->bytesAvailable() < (int)nMaxLen) && !bTimeout ) // This can end up waiting far longer than msecs
2361  {
2362  bTimeout = !(m_pSocket->waitForReadyRead( msecs.count() ));
2363 
2364  if ( timer.elapsed() >= msecs )
2365  {
2366  bTimeout = true;
2367  LOG(VB_HTTP, LOG_INFO, "BufferedSocketDeviceRequest::ReadBlock() - Exceeded Total Elapsed Wait Time." );
2368  }
2369  }
2370 
2371  // Just return what we have even if timed out.
2372 
2373  return( m_pSocket->read( pData, nMaxLen ));
2374  }
2375 
2376  return( -1 );
2377 }
2378 
2380 //
2382 
2383 qint64 BufferedSocketDeviceRequest::WriteBlock(const char *pData, qint64 nLen)
2384 {
2385  qint64 bytesWritten = -1;
2386  if (m_pSocket && m_pSocket->isValid() &&
2387  m_pSocket->state() == QAbstractSocket::ConnectedState)
2388  {
2389  bytesWritten = m_pSocket->write( pData, nLen );
2390  m_pSocket->waitForBytesWritten();
2391  }
2392 
2393  return( bytesWritten );
2394 }
2395 
2397 //
2399 
2401 {
2402  return( m_pSocket->localAddress().toString() );
2403 }
2404 
2406 //
2408 
2410 {
2411  return( m_pSocket->localPort() );
2412 }
2413 
2414 
2416 //
2418 
2420 {
2421  return( m_pSocket->peerAddress().toString() );
2422 }
jsonSerializer.h
HTTPRequest::GetRequestHeader
QString GetRequestHeader(const QString &sKey, const QString &sDefault)
Definition: httprequest.cpp:1109
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
ContentType_XML
@ ContentType_XML
Definition: httprequest.h:69
build_compdb.args
args
Definition: build_compdb.py:11
HTTPRequest::m_sBaseUrl
QString m_sBaseUrl
Definition: httprequest.h:126
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
HTTPRequest::SetContentType
HttpContentType SetContentType(const QString &sType)
Definition: httprequest.cpp:873
MythDate::toString
QString toString(const QDateTime &raw_dt, uint format)
Returns formatted string representing the time.
Definition: mythdate.cpp:85
HTTPRequest::FormatRawResponse
void FormatRawResponse(const QString &sXML)
Definition: httprequest.cpp:773
hardwareprofile.smolt.timeout
float timeout
Definition: smolt.py:103
ContentType_Unknown
@ ContentType_Unknown
Definition: httprequest.h:67
HTTPRequest::SetRequestProtocol
void SetRequestProtocol(const QString &sLine)
Definition: httprequest.cpp:828
ContentType_Urlencoded
@ ContentType_Urlencoded
Definition: httprequest.h:68
unziputil.h
ResponseTypeCSS
@ ResponseTypeCSS
Definition: httprequest.h:80
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:1195
BufferedSocketDeviceRequest::GetHostPort
quint16 GetHostPort() override
Definition: httprequest.cpp:2409
XmlPListSerializer
Definition: xmlplistSerializer.h:12
BufferedSocketDeviceRequest::GetPeerAddress
QString GetPeerAddress() override
Definition: httprequest.cpp:2419
HTTPRequest::m_sMethod
QString m_sMethod
Definition: httprequest.h:128
HTTPRequest::m_sResourceUrl
QString m_sResourceUrl
Definition: httprequest.h:127
BufferedSocketDeviceRequest::GetHostAddress
QString GetHostAddress() override
Definition: httprequest.cpp:2400
ResponseTypeUnknown
@ ResponseTypeUnknown
Definition: httprequest.h:76
JSONSerializer
Definition: jsonSerializer.h:31
HTTPRequest::IsEncrypted
bool IsEncrypted() const
Definition: httprequest.h:197
HTTPRequest::m_sProtocol
QString m_sProtocol
Definition: httprequest.h:136
HTTPRequest::m_sResponseTypeText
QString m_sResponseTypeText
Definition: httprequest.h:149
HTTPRequest::GetResponseProtocol
static QString GetResponseProtocol()
Definition: httprequest.cpp:852
HTTPRequest::m_sOriginalUrl
QString m_sOriginalUrl
Definition: httprequest.h:124
HTTPRequest::GetPeerAddress
virtual QString GetPeerAddress()=0
HTTPRequest::GetSupportedMimeTypes
static QStringList GetSupportedMimeTypes()
Definition: httprequest.cpp:997
MythDate::kOverrideUTC
@ kOverrideUTC
Present date/time in UTC.
Definition: mythdate.h:31
ResponseTypeJS
@ ResponseTypeJS
Definition: httprequest.h:79
ResponseTypeNone
@ ResponseTypeNone
Definition: httprequest.h:75
RequestTypePost
@ RequestTypePost
Definition: httprequest.h:49
HTTPRequest::Authenticated
bool Authenticated()
Definition: httprequest.cpp:2069
HTTPRequest::SendResponseFile
qint64 SendResponseFile(const QString &sFileName)
Definition: httprequest.cpp:453
RequestTypeOptions
@ RequestTypeOptions
Definition: httprequest.h:53
MythTimer::start
void start(void)
starts measuring elapsed time.
Definition: mythtimer.cpp:47
ContentType_JSON
@ ContentType_JSON
Definition: httprequest.h:70
LOG
#define LOG(_MASK_, _LEVEL_, _QSTRING_)
Definition: mythlogging.h:23
RequestTypeResponse
@ RequestTypeResponse
Definition: httprequest.h:61
HTTPRequest::DigestAuthentication
bool DigestAuthentication()
Definition: httprequest.cpp:1909
HTTPRequest::m_userSession
MythUserSession m_userSession
Definition: httprequest.h:161
build_compdb.file
file
Definition: build_compdb.py:55
HTTPRequest::BasicAuthentication
bool BasicAuthentication()
Definition: httprequest.cpp:1850
HTTPRequest::m_bProtected
bool m_bProtected
Definition: httprequest.h:140
RequestTypeSubscribe
@ RequestTypeSubscribe
Definition: httprequest.h:57
HTTPRequest::TestMimeType
static QString TestMimeType(const QString &sFileName)
Definition: httprequest.cpp:1014
HTTPRequest::Encode
static QString Encode(const QString &sIn)
Definition: httprequest.cpp:1738
HTTPRequest::SetCookie
void SetCookie(const QString &sKey, const QString &sValue, const QDateTime &expiryDate, bool secure)
Definition: httprequest.cpp:2105
RequestTypeUnsubscribe
@ RequestTypeUnsubscribe
Definition: httprequest.h:58
HTTPRequest::m_procReqLineExp
QRegularExpression m_procReqLineExp
Definition: httprequest.h:114
xmlSerializer.h
MythDate::current
QDateTime current(bool stripped)
Returns current Date and Time in UTC.
Definition: mythdate.cpp:15
HTTPRequest::Decode
static QString Decode(const QString &sIn)
Definition: httprequest.cpp:1762
HTTPRequest::GetSerializer
Serializer * GetSerializer()
Definition: httprequest.cpp:1701
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:1016
SoapSerializer
Definition: soapSerializer.h:27
HTTPRequest::GetResponseHeaders
QString GetResponseHeaders(void)
Definition: httprequest.cpp:1124
HTTPRequest::ExtractMethodFromURL
void ExtractMethodFromURL()
Definition: httprequest.cpp:1562
HTTPRequest::m_sPrivateToken
QString m_sPrivateToken
Definition: httprequest.h:160
mythversion.h
HTTPRequest::m_nMajor
int m_nMajor
Definition: httprequest.h:137
HTTPRequest::ReadLine
virtual QString ReadLine(std::chrono::milliseconds msecs)=0
ResponseTypeFile
@ ResponseTypeFile
Definition: httprequest.h:83
MythUserSession
Definition: mythsession.h:16
ResponseTypeHeader
@ ResponseTypeHeader
Definition: httprequest.h:85
HTTPRequest::m_mapRespHeaders
QStringMap m_mapRespHeaders
Definition: httprequest.h:152
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:95
Serializer::GetContentType
virtual QString GetContentType()=0
mythdate.h
HTTPRequest::s_szServerHeaders
static const char * s_szServerHeaders
Definition: httprequest.h:112
upnp.h
HTTPRequest::m_nResponseStatus
long m_nResponseStatus
Definition: httprequest.h:151
mythlogging.h
HTTPRequest::ReadBlock
virtual qint64 ReadBlock(char *pData, qint64 nMaxLen, std::chrono::milliseconds msecs=0ms)=0
HttpContentType
HttpContentType
Definition: httprequest.h:65
RequestTypeMSearch
@ RequestTypeMSearch
Definition: httprequest.h:56
HTTPRequest::GetResponsePage
QByteArray GetResponsePage(void)
Definition: httprequest.cpp:949
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:989
HTTPRequest::GetMimeType
static QString GetMimeType(const QString &sFileExtension)
Definition: httprequest.cpp:978
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:130
HTTPRequest::m_parseRangeExp
QRegularExpression m_parseRangeExp
Definition: httprequest.h:115
compat.h
QStringMap
QMap< QString, QString > QStringMap
Definition: upnputil.h:32
RequestTypeHead
@ RequestTypeHead
Definition: httprequest.h:48
MythCoreContext::GetDurSetting
std::enable_if_t< std::chrono::__is_duration< T >::value, T > GetDurSetting(const QString &key, T defaultval=T::zero())
Definition: mythcorecontext.h:172
BufferedSocketDeviceRequest::ReadBlock
qint64 ReadBlock(char *pData, qint64 nMaxLen, std::chrono::milliseconds msecs=0ms) override
Definition: httprequest.cpp:2348
HTTPRequest::BuildResponseHeader
QString BuildResponseHeader(long long nSize)
Definition: httprequest.cpp:193
gzipCompress
QByteArray gzipCompress(const QByteArray &data)
Definition: unziputil.cpp:89
Serializer::AddHeaders
virtual void AddHeaders(QStringMap &headers)
Definition: serializer.cpp:22
HTTPRequest::m_bKeepAlive
bool m_bKeepAlive
Definition: httprequest.h:165
HTTPRequest::m_sRequestUrl
QString m_sRequestUrl
Definition: httprequest.h:125
ResponseTypeXML
@ ResponseTypeXML
Definition: httprequest.h:77
MythUserSession::GetSessionToken
QString GetSessionToken(void) const
Definition: mythsession.h:38
HTTPRequest::ParseRange
bool ParseRange(QString sRange, long long llSize, long long *pllStart, long long *pllEnd)
Definition: httprequest.cpp:1458
HTTPRequest::GetETagHash
static QString GetETagHash(const QByteArray &data)
Definition: httprequest.cpp:1778
HTTPRequest::m_sRawRequest
QString m_sRawRequest
Definition: httprequest.h:122
HTTPRequest::ProcessRequestLine
void ProcessRequestLine(const QString &sLine)
Definition: httprequest.cpp:1387
gCoreContext
MythCoreContext * gCoreContext
This global variable contains the MythCoreContext instance for the app.
Definition: mythcorecontext.cpp:61
SENDFILE_BUFFER_SIZE
#define SENDFILE_BUFFER_SIZE
Definition: httprequest.cpp:596
HTTPRequest::m_mapHeaders
QStringMultiMap m_mapHeaders
Definition: httprequest.h:131
ResponseTypeOther
@ ResponseTypeOther
Definition: httprequest.h:84
HTTPRequest::GetHostName
virtual QString GetHostName()
Definition: httprequest.cpp:2146
MythUserSession::GetSessionExpires
QDateTime GetSessionExpires() const
Definition: mythsession.h:43
SOAP_ENVELOPE_END
#define SOAP_ENVELOPE_END
Definition: httprequest.h:36
MythCoreContext::GetNumSetting
int GetNumSetting(const QString &key, int defaultval=0)
Definition: mythcorecontext.cpp:935
HTTPRequest::SendData
qint64 SendData(QIODevice *pDevice, qint64 llStart, qint64 llBytes)
Definition: httprequest.cpp:598
HTTPRequest::m_sFileName
QString m_sFileName
Definition: httprequest.h:154
HTTPRequest::GetResponseStatus
QString GetResponseStatus(void) const
Definition: httprequest.cpp:895
ResponseTypeHTML
@ ResponseTypeHTML
Definition: httprequest.h:78
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:35
HTTPRequest::ParseCookies
void ParseCookies(void)
Definition: httprequest.cpp:1177
HTTPRequest::m_bSOAPRequest
bool m_bSOAPRequest
Definition: httprequest.h:143
HTTPRequest::CalculateDigestNonce
QString CalculateDigestNonce(const QString &timeStamp) const
Definition: httprequest.cpp:1838
ResponseTypeText
@ ResponseTypeText
Definition: httprequest.h:81
RequestTypeNotify
@ RequestTypeNotify
Definition: httprequest.h:59
VERBOSE_LEVEL_CHECK
#define VERBOSE_LEVEL_CHECK(_MASK_, _LEVEL_)
Definition: mythlogging.h:14
BufferedSocketDeviceRequest::WriteBlock
qint64 WriteBlock(const char *pData, qint64 nLen) override
Definition: httprequest.cpp:2383
MythDate::secsInPast
std::chrono::seconds secsInPast(const QDateTime &past)
Definition: mythdate.cpp:204
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:788
SOAP_ENVELOPE_BEGIN
#define SOAP_ENVELOPE_BEGIN
Definition: httprequest.h:33
HTTPRequest::SetResponseHeader
void SetResponseHeader(const QString &sKey, const QString &sValue, bool replace=false)
Definition: httprequest.cpp:2092
MythDate::kRFC822
@ kRFC822
HTTP Date format.
Definition: mythdate.h:30
HTTPRequest::m_eContentType
HttpContentType m_eContentType
Definition: httprequest.h:120
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:1808
HTTPRequest::getSocketHandle
virtual int getSocketHandle()=0
HTTPRequest::m_eResponseType
HttpResponseType m_eResponseType
Definition: httprequest.h:148
HTTPRequest::m_nMinor
int m_nMinor
Definition: httprequest.h:138
HTTPRequest::m_sPayload
QString m_sPayload
Definition: httprequest.h:134
configuration.h
HTTPRequest::GetRequestProtocol
QString GetRequestProtocol() const
Definition: httprequest.cpp:841
StaticPage
static QString StaticPage
Definition: httprequest.cpp:138
Configuration::GetValue
virtual int GetValue(const QString &sSetting, int Default)=0
HTTPRequest::GetParameters
static long GetParameters(QString sParams, QStringMap &mapParams)
Definition: httprequest.cpp:1065
BufferedSocketDeviceRequest::ReadLine
QString ReadLine(std::chrono::milliseconds msecs) override
Definition: httprequest.cpp:2316
MythDate::current_iso_string
QString current_iso_string(bool stripped)
Returns current Date and Time in UTC as a string.
Definition: mythdate.cpp:23
HTTPRequest::m_sNameSpace
QString m_sNameSpace
Definition: httprequest.h:144
mythtimer.h
HTTPRequest::AddCORSHeaders
void AddCORSHeaders(const QString &sOrigin)
Definition: httprequest.cpp:2212
RequestTypeUnknown
@ RequestTypeUnknown
Definition: httprequest.h:45
BufferedSocketDeviceRequest::m_pSocket
QTcpSocket * m_pSocket
Definition: httprequest.h:281
HTTPRequest::GetResponseType
QString GetResponseType(void) const
Definition: httprequest.cpp:958
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:1593
HTTPRequest::GetAuthenticationHeader
QString GetAuthenticationHeader(bool isStale=false)
Definition: httprequest.cpp:1808
MythCoreContext::GetSessionManager
MythSessionManager * GetSessionManager(void)
Definition: mythcorecontext.cpp:2083
xmlplistSerializer.h
HTTPRequest::IsUrlProtected
static bool IsUrlProtected(const QString &sBaseUrl)
Definition: httprequest.cpp:1789
ResponseTypeSVG
@ ResponseTypeSVG
Definition: httprequest.h:82
HTTPRequest::GetHostAddress
virtual QString GetHostAddress()=0
RequestTypeGet
@ RequestTypeGet
Definition: httprequest.h:47
build_compdb.filename
filename
Definition: build_compdb.py:21
httprequest.h
HTTPRequest::m_response
QBuffer m_response
Definition: httprequest.h:156
HTTPRequest::ParseKeepAlive
bool ParseKeepAlive(void)
Definition: httprequest.cpp:1143
HTTPRequest::SetRequestType
HttpRequestType SetRequestType(const QString &sType)
Definition: httprequest.cpp:166
HttpRequestType
HttpRequestType
Definition: httprequest.h:43
HTTPRequest::GetRequestType
QString GetRequestType() const
Definition: httprequest.cpp:2172
soapSerializer.h
MythCoreContext::GetSetting
QString GetSetting(const QString &key, const QString &defaultval="")
Definition: mythcorecontext.cpp:921
HTTPRequest::m_nKeepAliveTimeout
std::chrono::seconds m_nKeepAliveTimeout
Definition: httprequest.h:166
MythSessionManager
Definition: mythsession.h:98
HTTPRequest::m_eType
HttpRequestType m_eType
Definition: httprequest.h:119
HTTPRequest::m_mapCookies
QStringMap m_mapCookies
Definition: httprequest.h:132
MythCoreContext::GetConfiguration
static Configuration * GetConfiguration()
Definition: mythcorecontext.cpp:1838