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 
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 : std::as_const(args))
736  {
737  stream << "<" << arg.m_sName;
738 
739  if (arg.m_pAttributes)
740  {
741  for (const auto & attr : std::as_const(*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 {"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  QStringList params = sParams.split('&', Qt::SkipEmptyParts);
1079  for (const auto & param : std::as_const(params))
1080  {
1081  QString sName = param.section( '=', 0, 0 );
1082  QString sValue = param.section( '=', 1 );
1083  sValue.replace("+"," ");
1084 
1085  if (!sName.isEmpty())
1086  {
1087  sName = QUrl::fromPercentEncoding(sName.toUtf8());
1088  sValue = QUrl::fromPercentEncoding(sValue.toUtf8());
1089 
1090  mapParams.insert( sName.trimmed(), sValue );
1091  nCount++;
1092  }
1093  }
1094  }
1095 
1096  return nCount;
1097 }
1098 
1099 
1101 //
1103 
1104 QString HTTPRequest::GetRequestHeader( const QString &sKey, const QString &sDefault )
1105 {
1106  auto it = m_mapHeaders.find( sKey.toLower() );
1107 
1108  if ( it == m_mapHeaders.end())
1109  return( sDefault );
1110 
1111  return *it;
1112 }
1113 
1114 
1116 //
1118 
1120 {
1121  QString sHeader = s_szServerHeaders;
1122 
1123  for ( QStringMap::iterator it = m_mapRespHeaders.begin();
1124  it != m_mapRespHeaders.end();
1125  ++it )
1126  {
1127  sHeader += it.key() + ": ";
1128  sHeader += *it + "\r\n";
1129  }
1130 
1131  return( sHeader );
1132 }
1133 
1135 //
1137 
1139 {
1140  // TODO: Think about whether we should use a longer timeout if the client
1141  // has explicitly specified 'Keep-alive'
1142 
1143  // HTTP 1.1 ... server may assume keep-alive
1144  bool bKeepAlive = true;
1145 
1146  // if HTTP/1.0... must default to false
1147  if ((m_nMajor == 1) && (m_nMinor == 0))
1148  bKeepAlive = false;
1149 
1150  // Read Connection Header to see whether the client has explicitly
1151  // asked for the connection to be kept alive or closed after the response
1152  // is sent
1153  QString sConnection = GetRequestHeader( "connection", "default" ).toLower();
1154 
1155  QStringList sValueList = sConnection.split(",");
1156 
1157  if ( sValueList.contains("close") )
1158  {
1159  LOG(VB_HTTP, LOG_DEBUG, "Client requested the connection be closed");
1160  bKeepAlive = false;
1161  }
1162  else if (sValueList.contains("keep-alive"))
1163  bKeepAlive = true;
1164 
1165  return bKeepAlive;
1166 }
1167 
1169 //
1171 
1173 {
1174  QStringList sCookieList = m_mapHeaders.values("cookie");
1175 
1176  QStringList::iterator it;
1177  for (it = sCookieList.begin(); it != sCookieList.end(); ++it)
1178  {
1179  QString key = (*it).section('=', 0, 0);
1180  QString value = (*it).section('=', 1);
1181 
1182  m_mapCookies.insert(key, value);
1183  }
1184 }
1185 
1187 //
1189 
1191 {
1192  bool bSuccess = false;
1193 
1194  try
1195  {
1196  // Read first line to determine requestType
1197  QString sRequestLine = ReadLine( 2s );
1198 
1199  if ( sRequestLine.isEmpty() )
1200  {
1201  LOG(VB_GENERAL, LOG_ERR, "Timeout reading first line of request." );
1202  return false;
1203  }
1204 
1205  // -=>TODO: Should read lines until a valid request???
1206  ProcessRequestLine( sRequestLine );
1207 
1208  if (m_nMajor > 1 || m_nMajor < 0)
1209  {
1211  m_nResponseStatus = 505;
1212  m_response.write( GetResponsePage() );
1213 
1214  return true;
1215  }
1216 
1217  if (m_eType == RequestTypeUnknown)
1218  {
1220  m_nResponseStatus = 501; // Not Implemented
1221  // Conservative list, we can't really know what methods we
1222  // actually allow for an arbitrary resource without some sort of
1223  // high maintenance database
1224  SetResponseHeader("Allow", "GET, HEAD");
1225  m_response.write( GetResponsePage() );
1226  return true;
1227  }
1228 
1229  // Read Header
1230  bool bDone = false;
1231  QString sLine = ReadLine( 2s );
1232 
1233  while (( !sLine.isEmpty() ) && !bDone )
1234  {
1235  if (sLine != "\r\n")
1236  {
1237  QString sName = sLine.section( ':', 0, 0 ).trimmed();
1238  QString sValue = sLine.section( ':', 1 );
1239 
1240  sValue.truncate( sValue.length() - 2 );
1241 
1242  if (!sName.isEmpty() && !sValue.isEmpty())
1243  {
1244  m_mapHeaders.insert(sName.toLower(), sValue.trimmed());
1245  }
1246 
1247  sLine = ReadLine( 2s );
1248  }
1249  else
1250  bDone = true;
1251  }
1252 
1253  // Dump request header
1254  for ( auto it = m_mapHeaders.begin(); it != m_mapHeaders.end(); ++it )
1255  {
1256  LOG(VB_HTTP, LOG_INFO, QString("(Request Header) %1: %2")
1257  .arg(it.key(), *it));
1258  }
1259 
1260  // Parse Cookies
1261  ParseCookies();
1262 
1263  // Parse out keep alive
1265 
1266  // Check to see if we found the end of the header or we timed out.
1267  if (!bDone)
1268  {
1269  LOG(VB_GENERAL, LOG_INFO, "Timeout waiting for request header." );
1270  return false;
1271  }
1272 
1273  // HTTP/1.1 requires that the Host header be present, even if empty
1274  if ((m_nMinor == 1) && !m_mapHeaders.contains("host"))
1275  {
1277  m_nResponseStatus = 400;
1278  m_response.write( GetResponsePage() );
1279 
1280  return true;
1281  }
1282 
1283  // Destroy session if requested
1284  if (m_mapHeaders.contains("x-myth-clear-session"))
1285  {
1286  SetCookie("sessionToken", "", MythDate::current().addDays(-2), true);
1287  m_mapCookies.remove("sessionToken");
1288  }
1289 
1290  // Allow session resumption for TLS connections
1291  if (m_mapCookies.contains("sessionToken"))
1292  {
1293  QString sessionToken = m_mapCookies["sessionToken"];
1294  MythSessionManager *sessionManager = gCoreContext->GetSessionManager();
1295  MythUserSession session = sessionManager->GetSession(sessionToken);
1296 
1297  if (session.IsValid())
1298  m_userSession = session;
1299  }
1300 
1301  if (IsUrlProtected( m_sBaseUrl ))
1302  {
1303  if (!Authenticated())
1304  {
1306  m_nResponseStatus = 401;
1307  m_response.write( GetResponsePage() );
1308  // Since this may not be the first attempt at authentication,
1309  // Authenticated may have set the header with the appropriate
1310  // stale attribute
1311  SetResponseHeader("WWW-Authenticate", GetAuthenticationHeader(false));
1312 
1313  return true;
1314  }
1315 
1316  m_bProtected = true;
1317  }
1318 
1319  bSuccess = true;
1320 
1321  SetContentType( GetLastHeader( "content-type" ) );
1322  // Lets load payload if any.
1323  long nPayloadSize = GetLastHeader( "content-length" ).toLong();
1324 
1325  if (nPayloadSize > 0)
1326  {
1327  char *pszPayload = new char[ nPayloadSize + 2 ];
1328  long nBytes = 0;
1329 
1330  nBytes = ReadBlock( pszPayload, nPayloadSize, 5s );
1331  if (nBytes == nPayloadSize )
1332  {
1333  m_sPayload = QString::fromUtf8( pszPayload, nPayloadSize );
1334 
1335  // See if the payload is just data from a form post
1339  m_mapParams.insert( "json", m_sPayload );
1340  }
1341  else
1342  {
1343  LOG(VB_GENERAL, LOG_ERR,
1344  QString("Unable to read entire payload (read %1 of %2 bytes)")
1345  .arg( nBytes ) .arg( nPayloadSize ) );
1346  bSuccess = false;
1347  }
1348 
1349  delete [] pszPayload;
1350  }
1351 
1352  // Check to see if this is a SOAP encoded message
1353  QString sSOAPAction = GetRequestHeader( "SOAPACTION", "" );
1354 
1355  if (!sSOAPAction.isEmpty())
1356  bSuccess = ProcessSOAPPayload( sSOAPAction );
1357  else
1359 
1360 #if 0
1361  if (m_sMethod != "*" )
1362  LOG(VB_HTTP, LOG_DEBUG,
1363  QString("HTTPRequest::ParseRequest - Socket (%1) Base (%2) "
1364  "Method (%3) - Bytes in Socket Buffer (%4)")
1365  .arg(getSocketHandle()) .arg(m_sBaseUrl)
1366  .arg(m_sMethod) .arg(BytesAvailable()));
1367 #endif
1368  }
1369  catch(...)
1370  {
1371  LOG(VB_GENERAL, LOG_WARNING,
1372  "Unexpected exception in HTTPRequest::ParseRequest" );
1373  }
1374 
1375  return bSuccess;
1376 }
1377 
1379 //
1381 
1382 void HTTPRequest::ProcessRequestLine( const QString &sLine )
1383 {
1384  m_sRawRequest = sLine;
1385 
1386  QStringList tokens = sLine.split(m_procReqLineExp, Qt::SkipEmptyParts);
1387  int nCount = tokens.count();
1388 
1389  // ----------------------------------------------------------------------
1390 
1391  if ( sLine.startsWith( QString("HTTP/") ))
1393  else
1395 
1396  // ----------------------------------------------------------------------
1397  // if this is actually a response, then sLine's format will be:
1398  // HTTP/m.n <response code> <response text>
1399  // otherwise:
1400  // <method> <Resource URI> HTTP/m.n
1401  // ----------------------------------------------------------------------
1402 
1404  {
1405  // ------------------------------------------------------------------
1406  // Process as a request
1407  // ------------------------------------------------------------------
1408 
1409  if (nCount > 0)
1410  SetRequestType( tokens[0].trimmed() );
1411 
1412  if (nCount > 1)
1413  {
1414  m_sOriginalUrl = tokens[1].toUtf8(); // Used by authorization check
1415  m_sRequestUrl = QUrl::fromPercentEncoding(tokens[1].toUtf8());
1416  m_sBaseUrl = m_sRequestUrl.section( '?', 0, 0).trimmed();
1417 
1418  m_sResourceUrl = m_sBaseUrl; // Save complete url without parameters
1419 
1420  // Process any Query String Parameters
1421  QString sQueryStr = tokens[1].section( '?', 1, 1 );
1422 
1423  if (!sQueryStr.isEmpty())
1424  GetParameters( sQueryStr, m_mapParams );
1425  }
1426 
1427  if (nCount > 2)
1428  SetRequestProtocol( tokens[2].trimmed() );
1429  }
1430  else
1431  {
1432  // ------------------------------------------------------------------
1433  // Process as a Response
1434  // ------------------------------------------------------------------
1435  if (nCount > 0)
1436  SetRequestProtocol( tokens[0].trimmed() );
1437 
1438  if (nCount > 1)
1439  m_nResponseStatus = tokens[1].toInt();
1440  }
1441 
1442 
1443 }
1444 
1446 //
1448 
1449 bool HTTPRequest::ParseRange( QString sRange,
1450  long long llSize,
1451  long long *pllStart,
1452  long long *pllEnd )
1453 {
1454  // ----------------------------------------------------------------------
1455  // -=>TODO: Only handle 1 range at this time...
1456  // should make work with full spec.
1457  // ----------------------------------------------------------------------
1458 
1459  if (sRange.isEmpty())
1460  return false;
1461 
1462  // ----------------------------------------------------------------------
1463  // remove any "bytes="
1464  // ----------------------------------------------------------------------
1465  int nIdx = sRange.indexOf(m_parseRangeExp);
1466 
1467  if (nIdx < 0)
1468  return false;
1469 
1470  if (nIdx > 0)
1471  sRange.remove( 0, nIdx );
1472 
1473  // ----------------------------------------------------------------------
1474  // Split multiple ranges
1475  // ----------------------------------------------------------------------
1476 
1477  QStringList ranges = sRange.split(',', Qt::SkipEmptyParts);
1478  if (ranges.count() == 0)
1479  return false;
1480 
1481  // ----------------------------------------------------------------------
1482  // Split first range into its components
1483  // ----------------------------------------------------------------------
1484 
1485  QStringList parts = ranges[0].split('-');
1486 
1487  if (parts.count() != 2)
1488  return false;
1489 
1490  if (parts[0].isEmpty() && parts[1].isEmpty())
1491  return false;
1492 
1493  // ----------------------------------------------------------------------
1494  //
1495  // ----------------------------------------------------------------------
1496 
1497  bool conv_ok = false;
1498  if (parts[0].isEmpty())
1499  {
1500  // ------------------------------------------------------------------
1501  // Does it match "-####"
1502  // ------------------------------------------------------------------
1503 
1504  long long llValue = parts[1].toLongLong(&conv_ok);
1505  if (!conv_ok) return false;
1506 
1507  *pllStart = llSize - llValue;
1508  *pllEnd = llSize - 1;
1509  }
1510  else if (parts[1].isEmpty())
1511  {
1512  // ------------------------------------------------------------------
1513  // Does it match "####-"
1514  // ------------------------------------------------------------------
1515 
1516  *pllStart = parts[0].toLongLong(&conv_ok);
1517 
1518  if (!conv_ok)
1519  return false;
1520 
1521  *pllEnd = llSize - 1;
1522  }
1523  else
1524  {
1525  // ------------------------------------------------------------------
1526  // Must be "####-####"
1527  // ------------------------------------------------------------------
1528 
1529  *pllStart = parts[0].toLongLong(&conv_ok);
1530  if (!conv_ok) return false;
1531  *pllEnd = parts[1].toLongLong(&conv_ok);
1532  if (!conv_ok) return false;
1533 
1534  if (*pllStart > *pllEnd)
1535  return false;
1536  }
1537 
1538  LOG(VB_HTTP, LOG_DEBUG, QString("%1 Range Requested %2 - %3")
1539  .arg(getSocketHandle()) .arg(*pllStart) .arg(*pllEnd));
1540 
1541  return true;
1542 }
1543 
1545 //
1547 
1549 {
1550  // Strip out leading http://192.168.1.1:6544/ -> /
1551  // Should fix #8678
1552  // FIXME what about https?
1553  static const QRegularExpression re {"^http[s]?://.*?/"};
1554  m_sBaseUrl.replace(re, "/");
1555 
1556  QStringList sList = m_sBaseUrl.split('/', Qt::SkipEmptyParts);
1557  m_sMethod = "";
1558 
1559  if (!sList.isEmpty())
1560  {
1561  m_sMethod = sList.last();
1562  sList.pop_back();
1563  }
1564 
1565  m_sBaseUrl = '/' + sList.join( "/" );
1566  LOG(VB_HTTP, LOG_INFO, QString("ExtractMethodFromURL(end) : %1 : %2")
1567  .arg(m_sMethod, m_sBaseUrl));
1568 }
1569 
1571 //
1573 
1574 bool HTTPRequest::ProcessSOAPPayload( const QString &sSOAPAction )
1575 {
1576  bool bSuccess = false;
1577 
1578  // ----------------------------------------------------------------------
1579  // Open Supplied XML uPnp Description file.
1580  // ----------------------------------------------------------------------
1581 
1582  LOG(VB_HTTP, LOG_INFO,
1583  QString("HTTPRequest::ProcessSOAPPayload : %1 : ").arg(sSOAPAction));
1584  QDomDocument doc ( "request" );
1585 
1586  QString sErrMsg;
1587  int nErrLine = 0;
1588  int nErrCol = 0;
1589 
1590  if (!doc.setContent( m_sPayload, true, &sErrMsg, &nErrLine, &nErrCol ))
1591  {
1592  LOG(VB_GENERAL, LOG_ERR,
1593  QString( "Error parsing request at line: %1 column: %2 : %3" )
1594  .arg(nErrLine) .arg(nErrCol) .arg(sErrMsg));
1595  return( false );
1596  }
1597 
1598  // --------------------------------------------------------------
1599  // XML Document Loaded... now parse it
1600  // --------------------------------------------------------------
1601 
1602  QString sService;
1603 
1604  if (sSOAPAction.contains( '#' ))
1605  {
1606  m_sNameSpace = sSOAPAction.section( '#', 0, 0).remove( 0, 1);
1607  m_sMethod = sSOAPAction.section( '#', 1 );
1608  m_sMethod.remove( m_sMethod.length()-1, 1 );
1609  }
1610  else
1611  {
1612  if (sSOAPAction.contains( '/' ))
1613  {
1614  int nPos = sSOAPAction.lastIndexOf( '/' );
1615  m_sNameSpace = sSOAPAction.mid(1, nPos);
1616  m_sMethod = sSOAPAction.mid(nPos + 1,
1617  sSOAPAction.length() - nPos - 2);
1618 
1619  nPos = m_sNameSpace.lastIndexOf( '/', -2);
1620  sService = m_sNameSpace.mid(nPos + 1,
1621  m_sNameSpace.length() - nPos - 2);
1622  m_sNameSpace = m_sNameSpace.mid( 0, nPos );
1623  }
1624  else
1625  {
1626  m_sNameSpace.clear();
1627  m_sMethod = sSOAPAction;
1628  m_sMethod.remove( QChar( '\"' ) );
1629  }
1630  }
1631 
1632  QDomNodeList oNodeList = doc.elementsByTagNameNS( m_sNameSpace, m_sMethod );
1633 
1634  if (oNodeList.count() == 0)
1635  {
1636  oNodeList =
1637  doc.elementsByTagNameNS("http://schemas.xmlsoap.org/soap/envelope/",
1638  "Body");
1639  }
1640 
1641  if (oNodeList.count() > 0)
1642  {
1643  QDomNode oMethod = oNodeList.item(0);
1644 
1645  if (!oMethod.isNull())
1646  {
1647  m_bSOAPRequest = true;
1648 
1649  for ( QDomNode oNode = oMethod.firstChild(); !oNode.isNull();
1650  oNode = oNode.nextSibling() )
1651  {
1652  QDomElement e = oNode.toElement();
1653 
1654  if (!e.isNull())
1655  {
1656  QString sName = e.tagName();
1657  QString sValue = "";
1658 
1659  QDomText oText = oNode.firstChild().toText();
1660 
1661  if (!oText.isNull())
1662  sValue = oText.nodeValue();
1663 
1664  sName = QUrl::fromPercentEncoding(sName.toUtf8());
1665  sValue = QUrl::fromPercentEncoding(sValue.toUtf8());
1666 
1667  m_mapParams.insert( sName.trimmed().toLower(), sValue );
1668  }
1669  }
1670 
1671  bSuccess = true;
1672  }
1673  }
1674 
1675  return bSuccess;
1676 }
1677 
1679 //
1681 
1683 {
1684  Serializer *pSerializer = nullptr;
1685 
1686  if (m_bSOAPRequest)
1687  {
1688  pSerializer = (Serializer *)new SoapSerializer(&m_response,
1690  }
1691  else
1692  {
1693  QString sAccept = GetRequestHeader( "Accept", "*/*" );
1694 
1695  if (sAccept.contains( "application/json", Qt::CaseInsensitive ) ||
1696  sAccept.contains( "text/javascript", Qt::CaseInsensitive ))
1697  {
1698  pSerializer = (Serializer *)new JSONSerializer(&m_response,
1699  m_sMethod);
1700  }
1701  else if (sAccept.contains( "text/x-apple-plist+xml", Qt::CaseInsensitive ))
1702  {
1703  pSerializer = (Serializer *)new XmlPListSerializer(&m_response);
1704  }
1705  }
1706 
1707  // Default to XML
1708 
1709  if (pSerializer == nullptr)
1710  pSerializer = (Serializer *)new XmlSerializer(&m_response, m_sMethod);
1711 
1712  return pSerializer;
1713 }
1714 
1716 //
1718 
1719 QString HTTPRequest::Encode(const QString &sIn)
1720 {
1721  QString sStr = sIn;
1722 #if 0
1723  LOG(VB_HTTP, LOG_DEBUG,
1724  QString("HTTPRequest::Encode Input : %1").arg(sStr));
1725 #endif
1726  sStr.replace('&', "&amp;" ); // This _must_ come first
1727  sStr.replace('<', "&lt;" );
1728  sStr.replace('>', "&gt;" );
1729  sStr.replace('"', "&quot;");
1730  sStr.replace("'", "&apos;");
1731 
1732 #if 0
1733  LOG(VB_HTTP, LOG_DEBUG,
1734  QString("HTTPRequest::Encode Output : %1").arg(sStr));
1735 #endif
1736  return sStr;
1737 }
1738 
1740 //
1742 
1743 QString HTTPRequest::Decode(const QString& sIn)
1744 {
1745  QString sStr = sIn;
1746  sStr.replace("&amp;", "&");
1747  sStr.replace("&lt;", "<");
1748  sStr.replace("&gt;", ">");
1749  sStr.replace("&quot;", "\"");
1750  sStr.replace("&apos;", "'");
1751 
1752  return sStr;
1753 }
1754 
1756 //
1758 
1759 QString HTTPRequest::GetETagHash(const QByteArray &data)
1760 {
1761  QByteArray hash = QCryptographicHash::hash( data.data(), QCryptographicHash::Sha1);
1762 
1763  return ("\"" + hash.toHex() + "\"");
1764 }
1765 
1767 //
1769 
1770 bool HTTPRequest::IsUrlProtected( const QString &sBaseUrl )
1771 {
1772  QString sProtected = XmlConfiguration().GetValue("HTTP/Protected/Urls", "/setup;/Config");
1773 
1774  QStringList oList = sProtected.split( ';' );
1775 
1776  for( int nIdx = 0; nIdx < oList.count(); nIdx++)
1777  {
1778  if (sBaseUrl.startsWith( oList[nIdx], Qt::CaseInsensitive ))
1779  return true;
1780  }
1781 
1782  return false;
1783 }
1784 
1786 //
1788 
1790 {
1791  QString authHeader;
1792 
1793  // For now we support a single realm, that will change
1794  QString realm = "MythTV";
1795 
1796  // Always use digest authentication where supported, it may be available
1797  // with HTTP 1.0 client as an extension, but we can't tell if that's the
1798  // case. It's guaranteed to be available for HTTP 1.1+
1799  if (m_nMajor >= 1 && m_nMinor > 0)
1800  {
1802  QString stale = isStale ? "true" : "false"; // FIXME
1803  authHeader = QString("Digest realm=\"%1\",nonce=\"%2\","
1804  "qop=\"auth\",stale=\"%3\",algorithm=\"MD5\"")
1805  .arg(realm, nonce, stale);
1806  }
1807  else
1808  {
1809  authHeader = QString("Basic realm=\"%1\"").arg(realm);
1810  }
1811 
1812  return authHeader;
1813 }
1814 
1816 //
1818 
1819 QString HTTPRequest::CalculateDigestNonce(const QString& timeStamp) const
1820 {
1821  QString uniqueID = QString("%1:%2").arg(timeStamp, m_sPrivateToken);
1822  QString hash = QCryptographicHash::hash( uniqueID.toLatin1(), QCryptographicHash::Sha1).toHex(); // TODO: Change to Sha2 with QT5?
1823  QString nonce = QString("%1%2").arg(timeStamp, hash); // Note: since this is going in a header it should avoid illegal chars
1824  return nonce;
1825 }
1826 
1828 //
1830 
1832 {
1833  LOG(VB_HTTP, LOG_NOTICE, "Attempting HTTP Basic Authentication");
1834  QStringList oList = GetLastHeader( "authorization" ).split( ' ' );
1835 
1836  if (m_nMajor == 1 && m_nMinor == 0) // We only support Basic auth for http 1.0 clients
1837  {
1838  LOG(VB_GENERAL, LOG_WARNING, "Basic authentication is only allowed for HTTP 1.0");
1839  return false;
1840  }
1841 
1842  QString sCredentials = QByteArray::fromBase64( oList[1].toUtf8() );
1843 
1844  oList = sCredentials.split( ':' );
1845 
1846  if (oList.count() < 2)
1847  {
1848  LOG(VB_GENERAL, LOG_WARNING, "Authorization attempt with invalid number of tokens");
1849  return false;
1850  }
1851 
1852  QString sUsername = oList[0];
1853  QString sPassword = oList[1];
1854 
1855  if (sUsername == "nouser") // Special logout username
1856  return false;
1857 
1858  MythSessionManager *sessionManager = gCoreContext->GetSessionManager();
1859  if (!MythSessionManager::IsValidUser(sUsername))
1860  {
1861  LOG(VB_GENERAL, LOG_WARNING, "Authorization attempt with invalid username");
1862  return false;
1863  }
1864 
1865  QString client = QString("WebFrontend_%1").arg(GetPeerAddress());
1866  MythUserSession session = sessionManager->LoginUser(sUsername, sPassword,
1867  client);
1868 
1869  if (!session.IsValid())
1870  {
1871  LOG(VB_GENERAL, LOG_WARNING, "Authorization attempt with invalid password");
1872  return false;
1873  }
1874 
1875  LOG(VB_HTTP, LOG_NOTICE, "Valid Authorization received");
1876 
1877  if (IsEncrypted()) // Only set a session cookie for encrypted connections, not safe otherwise
1878  SetCookie("sessionToken", session.GetSessionToken(),
1879  session.GetSessionExpires(), true);
1880 
1881  m_userSession = session;
1882 
1883  return false;
1884 }
1885 
1887 //
1889 
1891 {
1892  LOG(VB_HTTP, LOG_NOTICE, "Attempting HTTP Digest Authentication");
1893  QString realm = "MythTV"; // TODO Check which realm applies for the request path
1894 
1895  QString authMethod = GetLastHeader( "authorization" ).section(' ', 0, 0).toLower();
1896 
1897  if (authMethod != "digest")
1898  {
1899  LOG(VB_GENERAL, LOG_WARNING, "Invalid method in Authorization header");
1900  return false;
1901  }
1902 
1903  QString parameterStr = GetLastHeader( "authorization" ).section(' ', 1);
1904 
1905  QMap<QString, QString> paramMap;
1906  QStringList paramList = parameterStr.split(',');
1907  QStringList::iterator it;
1908  for (it = paramList.begin(); it != paramList.end(); ++it)
1909  {
1910  QString key = (*it).section('=', 0, 0).toLower().trimmed();
1911  // Since the value may contain '=' return everything after first occurence
1912  QString value = (*it).section('=', 1).trimmed();
1913  // Remove any quotes surrounding the value
1914  value.remove("\"");
1915  paramMap[key] = value;
1916  }
1917 
1918  if (paramMap.size() < 8)
1919  {
1920  LOG(VB_GENERAL, LOG_WARNING, "Invalid number of parameters in Authorization header");
1921  return false;
1922  }
1923 
1924  if (paramMap["nonce"].isEmpty() || paramMap["username"].isEmpty() ||
1925  paramMap["realm"].isEmpty() || paramMap["uri"].isEmpty() ||
1926  paramMap["response"].isEmpty() || paramMap["qop"].isEmpty() ||
1927  paramMap["cnonce"].isEmpty() || paramMap["nc"].isEmpty())
1928  {
1929  LOG(VB_GENERAL, LOG_WARNING, "Missing required parameters in Authorization header");
1930  return false;
1931  }
1932 
1933  if (paramMap["username"] == "nouser") // Special logout username
1934  return false;
1935 
1936  if (paramMap["uri"] != m_sOriginalUrl)
1937  {
1938  LOG(VB_GENERAL, LOG_WARNING, "Authorization URI doesn't match the "
1939  "request URI");
1940  m_nResponseStatus = 400; // Bad Request
1941  return false;
1942  }
1943 
1944  if (paramMap["realm"] != realm)
1945  {
1946  LOG(VB_GENERAL, LOG_WARNING, "Authorization realm doesn't match the "
1947  "realm of the requested content");
1948  return false;
1949  }
1950 
1951  QByteArray nonce = paramMap["nonce"].toLatin1();
1952  if (nonce.length() < 20)
1953  {
1954  LOG(VB_GENERAL, LOG_WARNING, "Authorization nonce is too short");
1955  return false;
1956  }
1957 
1958  QString nonceTimeStampStr = nonce.left(20); // ISO 8601 fixed length
1959  if (nonce != CalculateDigestNonce(nonceTimeStampStr))
1960  {
1961  LOG(VB_GENERAL, LOG_WARNING, "Authorization nonce doesn't match reference");
1962  LOG(VB_HTTP, LOG_DEBUG, QString("%1 vs %2").arg(QString(nonce),
1963  CalculateDigestNonce(nonceTimeStampStr)));
1964  return false;
1965  }
1966 
1967  constexpr std::chrono::seconds AUTH_TIMEOUT { 2min }; // 2 Minute timeout to login, to reduce replay attack window
1968  QDateTime nonceTimeStamp = MythDate::fromString(nonceTimeStampStr);
1969  if (!nonceTimeStamp.isValid())
1970  {
1971  LOG(VB_GENERAL, LOG_WARNING, "Authorization nonce timestamp is invalid.");
1972  LOG(VB_HTTP, LOG_DEBUG, QString("Timestamp was '%1'").arg(nonceTimeStampStr));
1973  return false;
1974  }
1975 
1976  if (MythDate::secsInPast(nonceTimeStamp) > AUTH_TIMEOUT)
1977  {
1978  LOG(VB_HTTP, LOG_NOTICE, "Authorization nonce timestamp is invalid or too old.");
1979  // Tell the client that the submitted nonce has expired at which
1980  // point they may wish to try again with a fresh nonce instead of
1981  // telling the user that their credentials were invalid
1982  SetResponseHeader("WWW-Authenticate", GetAuthenticationHeader(true), true);
1983  return false;
1984  }
1985 
1986  MythSessionManager *sessionManager = gCoreContext->GetSessionManager();
1987  if (!MythSessionManager::IsValidUser(paramMap["username"]))
1988  {
1989  LOG(VB_GENERAL, LOG_WARNING, "Authorization attempt with invalid username");
1990  return false;
1991  }
1992 
1993  if (paramMap["response"].length() != 32)
1994  {
1995  LOG(VB_GENERAL, LOG_WARNING, "Authorization response field is invalid length");
1996  return false;
1997  }
1998 
1999  // If you're still reading this, well done, not far to go now
2000 
2001  QByteArray a1 = MythSessionManager::GetPasswordDigest(paramMap["username"]).toLatin1();
2002  //QByteArray a1 = "bcd911b2ecb15ffbd6d8e6e744d60cf6";
2003  QString methodDigest = QString("%1:%2").arg(GetRequestType(), paramMap["uri"]);
2004  QByteArray a2 = QCryptographicHash::hash(methodDigest.toLatin1(),
2005  QCryptographicHash::Md5).toHex();
2006 
2007  QString responseDigest = QString("%1:%2:%3:%4:%5:%6").arg(a1,
2008  paramMap["nonce"],
2009  paramMap["nc"],
2010  paramMap["cnonce"],
2011  paramMap["qop"],
2012  a2);
2013  QByteArray kd = QCryptographicHash::hash(responseDigest.toLatin1(),
2014  QCryptographicHash::Md5).toHex();
2015 
2016  if (paramMap["response"].toLatin1() == kd)
2017  {
2018  LOG(VB_HTTP, LOG_NOTICE, "Valid Authorization received");
2019  QString client = QString("WebFrontend_%1").arg(GetPeerAddress());
2020  MythUserSession session = sessionManager->LoginUser(paramMap["username"],
2021  a1,
2022  client);
2023  if (!session.IsValid())
2024  {
2025  LOG(VB_GENERAL, LOG_ERR, "Valid Authorization received, but we "
2026  "failed to create a valid session");
2027  return false;
2028  }
2029 
2030  if (IsEncrypted()) // Only set a session cookie for encrypted connections, not safe otherwise
2031  SetCookie("sessionToken", session.GetSessionToken(),
2032  session.GetSessionExpires(), true);
2033 
2034  m_userSession = session;
2035 
2036  return true;
2037  }
2038 
2039  LOG(VB_GENERAL, LOG_WARNING, "Authorization attempt with invalid password digest");
2040  LOG(VB_HTTP, LOG_DEBUG, QString("Received hash was '%1', calculated hash was '%2'")
2041  .arg(paramMap["response"], QString(kd)));
2042 
2043  return false;
2044 }
2045 
2047 //
2049 
2051 {
2052  // Check if the existing user has permission to access this resource
2053  if (m_userSession.IsValid()) //m_userSession.CheckPermission())
2054  return true;
2055 
2056  QStringList oList = GetLastHeader( "authorization" ).split( ' ' );
2057 
2058  if (oList.count() < 2)
2059  return false;
2060 
2061  if (oList[0].compare( "basic", Qt::CaseInsensitive ) == 0)
2062  return BasicAuthentication();
2063  if (oList[0].compare( "digest", Qt::CaseInsensitive ) == 0)
2064  return DigestAuthentication();
2065 
2066  return false;
2067 }
2068 
2070 //
2072 
2073 void HTTPRequest::SetResponseHeader(const QString& sKey, const QString& sValue,
2074  bool replace)
2075 {
2076  if (!replace && m_mapRespHeaders.contains(sKey))
2077  return;
2078 
2079  m_mapRespHeaders[sKey] = sValue;
2080 }
2081 
2083 //
2085 
2086 void HTTPRequest::SetCookie(const QString &sKey, const QString &sValue,
2087  const QDateTime &expiryDate, bool secure)
2088 {
2089  if (secure && !IsEncrypted())
2090  {
2091  LOG(VB_GENERAL, LOG_WARNING, QString("HTTPRequest::SetCookie(%1=%2): "
2092  "A secure cookie cannot be set on an unencrypted connection.")
2093  .arg(sKey, sValue));
2094  return;
2095  }
2096 
2097  QStringList cookieAttributes;
2098 
2099  // Key=Value
2100  cookieAttributes.append(QString("%1=%2").arg(sKey, sValue));
2101 
2102  // Domain - Most browsers have problems with a hostname, so it's better to omit this
2103 // cookieAttributes.append(QString("Domain=%1").arg(GetHostName()));
2104 
2105  // Path - Fix to root, no call for restricting to other paths yet
2106  cookieAttributes.append("Path=/");
2107 
2108  // Expires - Expiry date, always set one, just good practice
2109  QString expires = MythDate::toString(expiryDate, MythDate::kRFC822); // RFC 822
2110  cookieAttributes.append(QString("Expires=%1").arg(expires)); // Cookie Expiry date
2111 
2112  // Secure - Only send this cookie over encrypted connections, it contains
2113  // sensitive info SECURITY
2114  if (secure)
2115  cookieAttributes.append("Secure");
2116 
2117  // HttpOnly - No cookie stealing javascript SECURITY
2118  cookieAttributes.append("HttpOnly");
2119 
2120  SetResponseHeader("Set-Cookie", cookieAttributes.join("; "));
2121 }
2122 
2124 //
2126 
2128 {
2129  // TODO: This only deals with the HTTP 1.1 case, 1.0 should be rare but we
2130  // should probably still handle it
2131 
2132  // RFC 3875 - The is the hostname or ip address in the client request, not
2133  // the name or ip we might otherwise know for this server
2134  QString hostname = GetLastHeader("host");
2135  if (!hostname.isEmpty())
2136  {
2137  // Strip the port
2138  if (hostname.contains("]:")) // IPv6 port
2139  {
2140  return hostname.section("]:", 0 , 0);
2141  }
2142  if (hostname.contains(":")) // IPv4 port
2143  {
2144  return hostname.section(":", 0 , 0);
2145  }
2146  return hostname;
2147  }
2148 
2149  return GetHostAddress();
2150 }
2151 
2152 
2154 {
2155  QString type;
2156  switch ( m_eType )
2157  {
2158  case RequestTypeUnknown :
2159  type = "UNKNOWN";
2160  break;
2161  case RequestTypeGet :
2162  type = "GET";
2163  break;
2164  case RequestTypeHead :
2165  type = "HEAD";
2166  break;
2167  case RequestTypePost :
2168  type = "POST";
2169  break;
2170  case RequestTypeOptions:
2171  type = "OPTIONS";
2172  break;
2173  case RequestTypeMSearch:
2174  type = "M-SEARCH";
2175  break;
2176  case RequestTypeNotify:
2177  type = "NOTIFY";
2178  break;
2179  case RequestTypeSubscribe :
2180  type = "SUBSCRIBE";
2181  break;
2182  case RequestTypeUnsubscribe :
2183  type = "UNSUBSCRIBE";
2184  break;
2185  case RequestTypeResponse :
2186  type = "RESPONSE";
2187  break;
2188  }
2189 
2190  return type;
2191 }
2192 
2193 void HTTPRequest::AddCORSHeaders( const QString &sOrigin )
2194 {
2195  // ----------------------------------------------------------------------
2196  // SECURITY: Access-Control-Allow-Origin Wildcard
2197  //
2198  // This is a REALLY bad idea, so bad in fact that I'm including it here but
2199  // commented out in the hope that anyone thinking of adding it in the future
2200  // will see it and then read this comment.
2201  //
2202  // Browsers do not verify that the origin is on the same network. This means
2203  // that a malicious script embedded or included into ANY webpage you visit
2204  // could then access servers on your local network including MythTV. They
2205  // can grab data, delete data including recordings and videos, schedule
2206  // recordings and generally ruin your day.
2207  //
2208  // This might seem paranoid and a remote possibility, but then that's how
2209  // a lot of exploits are born. Do NOT allow wildcards.
2210  //
2211  //m_mapRespHeaders[ "Access-Control-Allow-Origin" ] = "*";
2212  // ----------------------------------------------------------------------
2213 
2214  // ----------------------------------------------------------------------
2215  // SECURITY: Allow the WebFrontend on the Master backend and ONLY this
2216  // machine to access resources on a frontend or slave web server
2217  //
2218  // http://www.w3.org/TR/cors/#introduction
2219  // ----------------------------------------------------------------------
2220 
2221  QStringList allowedOrigins;
2222 
2223  int serverStatusPort = gCoreContext->GetMasterServerStatusPort();
2224  int backendSSLPort = gCoreContext->GetNumSetting( "BackendSSLPort",
2225  serverStatusPort + 10);
2226 
2227  QString masterAddrPort = QString("%1:%2")
2229  .arg(serverStatusPort);
2230  QString masterTLSAddrPort = QString("%1:%2")
2232  .arg(backendSSLPort);
2233 
2234  allowedOrigins << QString("http://%1").arg(masterAddrPort);
2235  allowedOrigins << QString("https://%2").arg(masterTLSAddrPort);
2236 
2237  QString localhostname = QHostInfo::localHostName();
2238  if (!localhostname.isEmpty())
2239  {
2240  allowedOrigins << QString("http://%1:%2")
2241  .arg(localhostname).arg(serverStatusPort);
2242  allowedOrigins << QString("https://%1:%2")
2243  .arg(localhostname).arg(backendSSLPort);
2244  }
2245 
2246  QStringList allowedOriginsList =
2247  gCoreContext->GetSetting("AllowedOriginsList", QString(
2248  "https://chromecast.mythtv.org")).split(",");
2249 
2250  for (const auto & origin : std::as_const(allowedOriginsList))
2251  {
2252  if (origin.isEmpty())
2253  continue;
2254 
2255  if (origin == "*" || (!origin.startsWith("http://") &&
2256  !origin.startsWith("https://")))
2257  {
2258  LOG(VB_GENERAL, LOG_ERR, QString("Illegal AllowedOriginsList"
2259  " entry '%1'. Must start with http[s]:// and not be *")
2260  .arg(origin));
2261  }
2262  else
2263  {
2264  allowedOrigins << origin;
2265  }
2266  }
2267 
2268  if (VERBOSE_LEVEL_CHECK(VB_HTTP, LOG_DEBUG))
2269  {
2270  for (const auto & origin : std::as_const(allowedOrigins))
2271  LOG(VB_HTTP, LOG_DEBUG, QString("Will allow Origin: %1").arg(origin));
2272  }
2273 
2274  if (allowedOrigins.contains(sOrigin))
2275  {
2276  SetResponseHeader( "Access-Control-Allow-Origin" , sOrigin);
2277  SetResponseHeader( "Access-Control-Allow-Credentials" , "true");
2278  SetResponseHeader( "Access-Control-Allow-Headers" , "Content-Type");
2279  LOG(VB_HTTP, LOG_DEBUG, QString("Allow-Origin: %1)").arg(sOrigin));
2280  }
2281  else
2282  {
2283  LOG(VB_GENERAL, LOG_CRIT, QString("HTTPRequest: Cross-origin request "
2284  "received with origin (%1)")
2285  .arg(sOrigin));
2286  }
2287 }
2288 
2291 //
2292 // BufferedSocketDeviceRequest Class Implementation
2293 //
2296 
2297 QString BufferedSocketDeviceRequest::ReadLine( std::chrono::milliseconds msecs )
2298 {
2299  QString sLine;
2300 
2301  if (m_pSocket && m_pSocket->isValid() &&
2302  m_pSocket->state() == QAbstractSocket::ConnectedState)
2303  {
2304  bool timeout = false;
2305  MythTimer timer;
2306  timer.start();
2307  while (!m_pSocket->canReadLine() && !timeout)
2308  {
2309  timeout = !(m_pSocket->waitForReadyRead( msecs.count() ));
2310 
2311  if ( timer.elapsed() >= msecs )
2312  {
2313  timeout = true;
2314  LOG(VB_HTTP, LOG_INFO, "BufferedSocketDeviceRequest::ReadLine() - Exceeded Total Elapsed Wait Time." );
2315  }
2316  }
2317 
2318  if (!timeout)
2319  sLine = m_pSocket->readLine();
2320  }
2321 
2322  return( sLine );
2323 }
2324 
2326 //
2328 
2329 qint64 BufferedSocketDeviceRequest::ReadBlock(char *pData, qint64 nMaxLen,
2330  std::chrono::milliseconds msecs)
2331 {
2332  if (m_pSocket && m_pSocket->isValid() &&
2333  m_pSocket->state() == QAbstractSocket::ConnectedState)
2334  {
2335  if (msecs == 0ms)
2336  return( m_pSocket->read( pData, nMaxLen ));
2337 
2338  bool bTimeout = false;
2339  MythTimer timer;
2340  timer.start();
2341  while ( (m_pSocket->bytesAvailable() < (int)nMaxLen) && !bTimeout ) // This can end up waiting far longer than msecs
2342  {
2343  bTimeout = !(m_pSocket->waitForReadyRead( msecs.count() ));
2344 
2345  if ( timer.elapsed() >= msecs )
2346  {
2347  bTimeout = true;
2348  LOG(VB_HTTP, LOG_INFO, "BufferedSocketDeviceRequest::ReadBlock() - Exceeded Total Elapsed Wait Time." );
2349  }
2350  }
2351 
2352  // Just return what we have even if timed out.
2353 
2354  return( m_pSocket->read( pData, nMaxLen ));
2355  }
2356 
2357  return( -1 );
2358 }
2359 
2361 //
2363 
2364 qint64 BufferedSocketDeviceRequest::WriteBlock(const char *pData, qint64 nLen)
2365 {
2366  qint64 bytesWritten = -1;
2367  if (m_pSocket && m_pSocket->isValid() &&
2368  m_pSocket->state() == QAbstractSocket::ConnectedState)
2369  {
2370  bytesWritten = m_pSocket->write( pData, nLen );
2371  m_pSocket->waitForBytesWritten();
2372  }
2373 
2374  return( bytesWritten );
2375 }
2376 
2378 //
2380 
2382 {
2383  return( m_pSocket->localAddress().toString() );
2384 }
2385 
2387 //
2389 
2391 {
2392  return( m_pSocket->localPort() );
2393 }
2394 
2395 
2397 //
2399 
2401 {
2402  return( m_pSocket->peerAddress().toString() );
2403 }
jsonSerializer.h
HTTPRequest::GetRequestHeader
QString GetRequestHeader(const QString &sKey, const QString &sDefault)
Definition: httprequest.cpp:1104
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:70
build_compdb.args
args
Definition: build_compdb.py:11
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
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:84
HTTPRequest::FormatRawResponse
void FormatRawResponse(const QString &sXML)
Definition: httprequest.cpp:773
hardwareprofile.smolt.timeout
float timeout
Definition: smolt.py:102
ContentType_Unknown
@ ContentType_Unknown
Definition: httprequest.h:68
HTTPRequest::SetRequestProtocol
void SetRequestProtocol(const QString &sLine)
Definition: httprequest.cpp:828
ContentType_Urlencoded
@ ContentType_Urlencoded
Definition: httprequest.h:69
unziputil.h
ResponseTypeCSS
@ ResponseTypeCSS
Definition: httprequest.h:81
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:1190
BufferedSocketDeviceRequest::GetHostPort
quint16 GetHostPort() override
Definition: httprequest.cpp:2390
XmlPListSerializer
Definition: xmlplistSerializer.h:12
BufferedSocketDeviceRequest::GetPeerAddress
QString GetPeerAddress() override
Definition: httprequest.cpp:2400
HTTPRequest::m_sMethod
QString m_sMethod
Definition: httprequest.h:129
HTTPRequest::m_sResourceUrl
QString m_sResourceUrl
Definition: httprequest.h:128
BufferedSocketDeviceRequest::GetHostAddress
QString GetHostAddress() override
Definition: httprequest.cpp:2381
ResponseTypeUnknown
@ ResponseTypeUnknown
Definition: httprequest.h:77
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:852
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:997
MythDate::kOverrideUTC
@ kOverrideUTC
Present date/time in UTC.
Definition: mythdate.h:31
ResponseTypeJS
@ ResponseTypeJS
Definition: httprequest.h:80
ResponseTypeNone
@ ResponseTypeNone
Definition: httprequest.h:76
RequestTypePost
@ RequestTypePost
Definition: httprequest.h:50
HTTPRequest::Authenticated
bool Authenticated()
Definition: httprequest.cpp:2050
HTTPRequest::SendResponseFile
qint64 SendResponseFile(const QString &sFileName)
Definition: httprequest.cpp:453
RequestTypeOptions
@ RequestTypeOptions
Definition: httprequest.h:54
MythTimer::start
void start(void)
starts measuring elapsed time.
Definition: mythtimer.cpp:47
ContentType_JSON
@ ContentType_JSON
Definition: httprequest.h:71
LOG
#define LOG(_MASK_, _LEVEL_, _QSTRING_)
Definition: mythlogging.h:39
RequestTypeResponse
@ RequestTypeResponse
Definition: httprequest.h:62
HTTPRequest::DigestAuthentication
bool DigestAuthentication()
Definition: httprequest.cpp:1890
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:1831
HTTPRequest::m_bProtected
bool m_bProtected
Definition: httprequest.h:141
RequestTypeSubscribe
@ RequestTypeSubscribe
Definition: httprequest.h:58
HTTPRequest::TestMimeType
static QString TestMimeType(const QString &sFileName)
Definition: httprequest.cpp:1014
HTTPRequest::Encode
static QString Encode(const QString &sIn)
Definition: httprequest.cpp:1719
HTTPRequest::SetCookie
void SetCookie(const QString &sKey, const QString &sValue, const QDateTime &expiryDate, bool secure)
Definition: httprequest.cpp:2086
RequestTypeUnsubscribe
@ RequestTypeUnsubscribe
Definition: httprequest.h:59
HTTPRequest::m_procReqLineExp
QRegularExpression m_procReqLineExp
Definition: httprequest.h:115
xmlSerializer.h
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:1743
HTTPRequest::GetSerializer
Serializer * GetSerializer()
Definition: httprequest.cpp:1682
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:993
SoapSerializer
Definition: soapSerializer.h:27
HTTPRequest::GetResponseHeaders
QString GetResponseHeaders(void)
Definition: httprequest.cpp:1119
XmlConfiguration
Definition: configuration.h:38
HTTPRequest::ExtractMethodFromURL
void ExtractMethodFromURL()
Definition: httprequest.cpp:1548
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
ResponseTypeFile
@ ResponseTypeFile
Definition: httprequest.h:84
MythUserSession
Definition: mythsession.h:16
ResponseTypeHeader
@ ResponseTypeHeader
Definition: httprequest.h:86
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
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
HttpContentType
HttpContentType
Definition: httprequest.h:66
SOAP_ENVELOPE_BEGIN
static constexpr const char * SOAP_ENVELOPE_BEGIN
Definition: httprequest.h:34
RequestTypeMSearch
@ RequestTypeMSearch
Definition: httprequest.h:57
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:966
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:131
HTTPRequest::m_parseRangeExp
QRegularExpression m_parseRangeExp
Definition: httprequest.h:116
compat.h
QStringMap
QMap< QString, QString > QStringMap
Definition: upnputil.h:32
RequestTypeHead
@ RequestTypeHead
Definition: httprequest.h:49
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
BufferedSocketDeviceRequest::ReadBlock
qint64 ReadBlock(char *pData, qint64 nMaxLen, std::chrono::milliseconds msecs=0ms) override
Definition: httprequest.cpp:2329
HTTPRequest::BuildResponseHeader
QString BuildResponseHeader(long long nSize)
Definition: httprequest.cpp:193
gzipCompress
QByteArray gzipCompress(const QByteArray &data)
Definition: unziputil.cpp:93
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
ResponseTypeXML
@ ResponseTypeXML
Definition: httprequest.h:78
MythUserSession::GetSessionToken
QString GetSessionToken(void) const
Definition: mythsession.h:42
HTTPRequest::ParseRange
bool ParseRange(QString sRange, long long llSize, long long *pllStart, long long *pllEnd)
Definition: httprequest.cpp:1449
HTTPRequest::GetETagHash
static QString GetETagHash(const QByteArray &data)
Definition: httprequest.cpp:1759
HTTPRequest::m_sRawRequest
QString m_sRawRequest
Definition: httprequest.h:123
HTTPRequest::ProcessRequestLine
void ProcessRequestLine(const QString &sLine)
Definition: httprequest.cpp:1382
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
ResponseTypeOther
@ ResponseTypeOther
Definition: httprequest.h:85
HTTPRequest::GetHostName
virtual QString GetHostName()
Definition: httprequest.cpp:2127
MythUserSession::GetSessionExpires
QDateTime GetSessionExpires() const
Definition: mythsession.h:47
MythCoreContext::GetNumSetting
int GetNumSetting(const QString &key, int defaultval=0)
Definition: mythcorecontext.cpp:912
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:895
ResponseTypeHTML
@ ResponseTypeHTML
Definition: httprequest.h:79
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:1172
HTTPRequest::m_bSOAPRequest
bool m_bSOAPRequest
Definition: httprequest.h:144
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:1819
ResponseTypeText
@ ResponseTypeText
Definition: httprequest.h:82
RequestTypeNotify
@ RequestTypeNotify
Definition: httprequest.h:60
BufferedSocketDeviceRequest::WriteBlock
qint64 WriteBlock(const char *pData, qint64 nLen) override
Definition: httprequest.cpp:2364
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:788
HTTPRequest::SetResponseHeader
void SetResponseHeader(const QString &sKey, const QString &sValue, bool replace=false)
Definition: httprequest.cpp:2073
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:1779
HTTPRequest::getSocketHandle
virtual int getSocketHandle()=0
HTTPRequest::m_eResponseType
HttpResponseType m_eResponseType
Definition: httprequest.h:149
HTTPRequest::m_nMinor
int m_nMinor
Definition: httprequest.h:139
HTTPRequest::m_sPayload
QString m_sPayload
Definition: httprequest.h:135
configuration.h
HTTPRequest::GetRequestProtocol
QString GetRequestProtocol() const
Definition: httprequest.cpp:841
StaticPage
static QString StaticPage
Definition: httprequest.cpp:138
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:2297
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:2193
RequestTypeUnknown
@ RequestTypeUnknown
Definition: httprequest.h:46
BufferedSocketDeviceRequest::m_pSocket
QTcpSocket * m_pSocket
Definition: httprequest.h:282
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:1574
HTTPRequest::GetAuthenticationHeader
QString GetAuthenticationHeader(bool isStale=false)
Definition: httprequest.cpp:1789
MythCoreContext::GetSessionManager
MythSessionManager * GetSessionManager(void)
Definition: mythcorecontext.cpp:2071
xmlplistSerializer.h
HTTPRequest::IsUrlProtected
static bool IsUrlProtected(const QString &sBaseUrl)
Definition: httprequest.cpp:1770
ResponseTypeSVG
@ ResponseTypeSVG
Definition: httprequest.h:83
HTTPRequest::GetHostAddress
virtual QString GetHostAddress()=0
RequestTypeGet
@ RequestTypeGet
Definition: httprequest.h:48
build_compdb.filename
filename
Definition: build_compdb.py:21
httprequest.h
HTTPRequest::m_response
QBuffer m_response
Definition: httprequest.h:157
HTTPRequest::ParseKeepAlive
bool ParseKeepAlive(void)
Definition: httprequest.cpp:1138
HTTPRequest::SetRequestType
HttpRequestType SetRequestType(const QString &sType)
Definition: httprequest.cpp:166
HttpRequestType
HttpRequestType
Definition: httprequest.h:44
HTTPRequest::GetRequestType
QString GetRequestType() const
Definition: httprequest.cpp:2153
soapSerializer.h
MythCoreContext::GetSetting
QString GetSetting(const QString &key, const QString &defaultval="")
Definition: mythcorecontext.cpp:898
HTTPRequest::m_nKeepAliveTimeout
std::chrono::seconds m_nKeepAliveTimeout
Definition: httprequest.h:167
MythSessionManager
Definition: mythsession.h:102
HTTPRequest::m_eType
HttpRequestType m_eType
Definition: httprequest.h:120
HTTPRequest::m_mapCookies
QStringMap m_mapCookies
Definition: httprequest.h:133