MythTV  master
websocket.cpp
Go to the documentation of this file.
1 
2 // Own header
3 #include "websocket.h"
4 
5 // MythTV headers
6 #include "mythlogging.h"
7 #include "mythcorecontext.h"
8 #include "mythevent.h"
9 #include "codecutil.h"
11 
12 // QT headers
13 #include <QThread>
14 #include <QTcpSocket>
15 #include <QSslCipher>
16 #include <QCryptographicHash>
17 #include <QtCore>
18 #include <QtGlobal>
19 
21 //
23 
25  m_threadPool("WebSocketServerPool")
26 {
27  setObjectName("WebSocketServer");
28  // Number of connections processed concurrently
29  int maxThreads = qMax(QThread::idealThreadCount() * 2, 2); // idealThreadCount can return -1
30  // Don't allow more connections than we can process, it will simply cause
31  // browsers to stall
32  setMaxPendingConnections(maxThreads);
33  m_threadPool.setMaxThreadCount(maxThreads);
34 
35  LOG(VB_HTTP, LOG_NOTICE, QString("WebSocketServer(): Max Thread Count %1")
37 }
38 
40 {
41  m_rwlock.lockForWrite();
42  m_running = false;
43  m_rwlock.unlock();
44 
46 }
47 
49 {
50 
52  PrivTcpServer *server = dynamic_cast<PrivTcpServer *>(QObject::sender());
53  if (server)
54  type = server->GetServerType();
55 
57  new WebSocketWorkerThread(*this, socket, type
58 #ifndef QT_NO_OPENSSL
59  , m_sslConfig
60 #endif
61  ),
62  QString("WebSocketServer%1").arg(socket));
63 }
64 
66 //
68 
71 #ifndef QT_NO_OPENSSL
72  , const QSslConfiguration& sslConfig
73 #endif
74  )
75  :
76  m_webSocketServer(webSocketServer), m_socketFD(sock),
77  m_connectionType(type)
78 #ifndef QT_NO_OPENSSL
79  , m_sslConfig(sslConfig)
80 #endif
81 {
82 }
83 
85 {
88 #ifndef QT_NO_OPENSSL
89  , m_sslConfig
90 #endif
91  );
92  worker->Exec();
93 
94  worker->deleteLater();
95 }
96 
98 //
100 
103 #ifndef QT_NO_OPENSSL
104  , const QSslConfiguration& sslConfig
105 #endif
106  )
107  : m_eventLoop(new QEventLoop()),
108  m_webSocketServer(webSocketServer),
109  m_socketFD(sock), m_connectionType(type),
110  m_heartBeat(new QTimer())
111 #ifndef QT_NO_OPENSSL
112  , m_sslConfig(sslConfig)
113 #endif
114 {
115  setObjectName(QString("WebSocketWorker(%1)")
116  .arg(m_socketFD));
117  LOG(VB_HTTP, LOG_INFO, QString("WebSocketWorker(%1): New connection")
118  .arg(m_socketFD));
119 
120  // For now, until it's refactored, register the only extension here
122 
123  SetupSocket();
124 
125  m_isRunning = true;
126 }
127 
129 {
130  CleanupSocket();
131 
132  // If extensions weren't deregistered then it's our responsibility to
133  // delete them
134  while (!m_extensions.isEmpty())
135  {
136  WebSocketExtension *extension = m_extensions.takeFirst();
137  extension->deleteLater();
138  extension = nullptr;
139  }
140 
141  m_eventLoop->deleteLater();
142  m_eventLoop = nullptr;
143  delete m_heartBeat;
144 }
145 
147 {
148  m_eventLoop->exec();
149 }
150 
152 {
153  blockSignals(true);
154  m_isRunning = false;
155  LOG(VB_HTTP, LOG_INFO, "WebSocketWorker::CloseConnection()");
156  if (m_eventLoop)
157  m_eventLoop->exit();
158 }
159 
161 {
163  {
164 
165 #ifndef QT_NO_OPENSSL
166  QSslSocket *pSslSocket = new QSslSocket();
167  if (pSslSocket->setSocketDescriptor(m_socketFD)
168  && gCoreContext->CheckSubnet(pSslSocket))
169  {
170  pSslSocket->setSslConfiguration(m_sslConfig);
171  pSslSocket->startServerEncryption();
172  if (pSslSocket->waitForEncrypted(5000))
173  {
174  LOG(VB_HTTP, LOG_INFO, "SSL Handshake occurred, connection encrypted");
175  LOG(VB_HTTP, LOG_INFO, QString("Using %1 cipher").arg(pSslSocket->sessionCipher().name()));
176  }
177  else
178  {
179  LOG(VB_HTTP, LOG_WARNING, "SSL Handshake FAILED, connection terminated");
180  delete pSslSocket;
181  pSslSocket = nullptr;
182  }
183  }
184  else
185  {
186  delete pSslSocket;
187  pSslSocket = nullptr;
188  }
189 
190  if (pSslSocket)
191  m_socket = dynamic_cast<QTcpSocket *>(pSslSocket);
192  else
193  return;
194 #else
195  return;
196 #endif
197  }
198  else // Plain old unencrypted socket
199  {
200  m_socket = new QTcpSocket();
201  m_socket->setSocketDescriptor(m_socketFD);
203  {
204  delete m_socket;
205  m_socket = nullptr;
206  return;
207  }
208 
209  }
210 
211  m_socket->setSocketOption(QAbstractSocket::KeepAliveOption, QVariant(1));
212 
213  connect(m_socket, SIGNAL(readyRead()), SLOT(doRead()));
214  connect(m_socket, SIGNAL(disconnected()), SLOT(CloseConnection()));
215 
216  // Setup heartbeat
217  m_heartBeat->setInterval(20000); // 20 second
218  m_heartBeat->setSingleShot(false);
219  connect(m_heartBeat, SIGNAL(timeout()), SLOT(SendHeartBeat()));
220 }
221 
223 {
224  if (m_socket->error() != QAbstractSocket::UnknownSocketError)
225  {
226  LOG(VB_HTTP, LOG_WARNING, QString("WebSocketWorker(%1): Error %2 (%3)")
227  .arg(m_socketFD)
228  .arg(m_socket->errorString())
229  .arg(m_socket->error()));
230  }
231 
232  int writeTimeout = 5000; // 5 Seconds
233  // Make sure any data in the buffer is flushed before the socket is closed
234  while (m_webSocketServer.IsRunning() &&
235  m_socket->isValid() &&
236  m_socket->state() == QAbstractSocket::ConnectedState &&
237  m_socket->bytesToWrite() > 0)
238  {
239  LOG(VB_HTTP, LOG_DEBUG, QString("WebSocketWorker(%1): "
240  "Waiting for %2 bytes to be written "
241  "before closing the connection.")
242  .arg(m_socketFD)
243  .arg(m_socket->bytesToWrite()));
244 
245  // If the client stops reading for longer than 'writeTimeout' then
246  // stop waiting for them. We can't afford to leave the socket
247  // connected indefinitely, it could be used by another client.
248  //
249  // NOTE: Some clients deliberately stall as a way of 'pausing' A/V
250  // streaming. We should create a new server extension or adjust the
251  // timeout according to the User-Agent, instead of increasing the
252  // standard timeout. However we should ALWAYS have a timeout.
253  if (!m_socket->waitForBytesWritten(writeTimeout))
254  {
255  LOG(VB_GENERAL, LOG_WARNING, QString("WebSocketWorker(%1): "
256  "Timed out waiting to write bytes to "
257  "the socket, waited %2 seconds")
258  .arg(m_socketFD)
259  .arg(writeTimeout / 1000));
260  break;
261  }
262  }
263 
264  if (m_socket->bytesToWrite() > 0)
265  {
266  LOG(VB_HTTP, LOG_WARNING, QString("WebSocketWorker(%1): "
267  "Failed to write %2 bytes to "
268  "socket, (%3)")
269  .arg(m_socketFD)
270  .arg(m_socket->bytesToWrite())
271  .arg(m_socket->errorString()));
272  }
273 
274  LOG(VB_HTTP, LOG_INFO, QString("WebSocketWorker(%1): Connection %2 closed.")
275  .arg(m_socketFD)
276  .arg(m_socket->socketDescriptor()));
277 
278  m_socket->close();
279  m_socket->deleteLater();
280  m_socket = nullptr;
281 }
282 
284 {
285  if (!m_isRunning)
286  return;
287 
288  if (!m_webSocketServer.IsRunning() || !m_socket->isOpen())
289  {
290  CloseConnection();
291  return;
292  }
293 
294  if (m_webSocketMode)
295  {
297  }
298  else
299  {
302  }
303 
304  if (!m_webSocketMode)
305  {
306  LOG(VB_HTTP, LOG_WARNING, "WebSocketServer: Timed out waiting for connection upgrade");
307  CloseConnection();
308  }
309 }
310 
311 bool WebSocketWorker::ProcessHandshake(QTcpSocket *socket)
312 {
313  QByteArray line;
314 
315  // Minimum length of the request line is 16
316  // i.e. "GET / HTTP/1.1\r\n"
317  while (socket->bytesAvailable() < 16)
318  {
319  if (!socket->waitForReadyRead(5000)) // 5 second timeout
320  return false;
321  }
322 
323  // Set a maximum length for a request line of 255 bytes, it's an
324  // arbitrary limit but a reasonable one for now
325  line = socket->readLine(255).trimmed(); // Strip newline
326  if (line.isEmpty())
327  return false;
328 
329  QStringList tokens = QString(line).split(' ', QString::SkipEmptyParts);
330 
331  if (tokens.length() != 3) // Anything but 3 is invalid - {METHOD} {HOST/PATH} {PROTOCOL}
332  {
333  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessHandshake() - Invalid number of tokens in Request line");
334  return false;
335  }
336 
337  if (tokens[0] != "GET") // RFC 6455 - Request method MUST be GET
338  {
339  LOG(VB_GENERAL, LOG_ERR, QString("WebSocketWorker::ProcessHandshake() - Invalid method: %1").arg(tokens[0]));
340  return false;
341  }
342 
343  QString path = tokens[1];
344 
345  if (path.contains('#')) // RFC 6455 - Fragments MUST NOT be used
346  {
347  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessHandshake() - Path contains illegal fragment");
348  return false;
349  }
350 
351  if (!tokens[2].startsWith("HTTP/")) // Must be HTTP
352  {
353  LOG(VB_GENERAL, LOG_ERR, QString("WebSocketWorker::ProcessHandshake() - Invalid protocol: %1").arg(tokens[2]));
354  return false;
355  }
356 
357  QString versionStr = tokens[2].section('/', 1, 1);
358 
359  int majorVersion = versionStr.section('.', 0, 0).toInt();
360  int minorVersion = versionStr.section('.', 1, 1).toInt();
361 
362  if ((majorVersion < 1) || (minorVersion < 1)) // RFC 6455 - HTTP version MUST be at least 1.1
363  {
364  LOG(VB_GENERAL, LOG_ERR, QString("WebSocketWorker::ProcessHandshake() - Invalid HTTP version: %1.%2").arg(majorVersion).arg(minorVersion));
365  return false;
366  }
367 
368  // Read Header
369  line = socket->readLine(2000).trimmed(); // 2KB Maximum
370 
371  QMap<QString, QString> requestHeaders;
372  while (!line.isEmpty())
373  {
374  QString strLine = QString(line);
375  QString sName = strLine.section( ':', 0, 0 ).trimmed();
376  QString sValue = strLine.section( ':', 1 ).trimmed();
377  sValue.replace(" ",""); // Remove all internal whitespace
378 
379  if (!sName.isEmpty() && !sValue.isEmpty())
380  requestHeaders.insert(sName.toLower(), sValue);
381 
382  line = socket->readLine(2000).trimmed(); // 2KB Maximum
383  }
384 
385  // Dump request header
386  QMap<QString, QString>::iterator it;
387  for ( it = requestHeaders.begin();
388  it != requestHeaders.end();
389  ++it )
390  {
391  LOG(VB_HTTP, LOG_INFO, QString("(Request Header) %1: %2")
392  .arg(it.key()).arg(*it));
393  }
394 
395  if (!requestHeaders.contains("connection")) // RFC 6455 - 1.3. Opening Handshake
396  {
397  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessHandshake() - Missing 'Connection' header");
398  return false;
399  }
400 
401  QStringList connectionValues = requestHeaders["connection"].split(',', QString::SkipEmptyParts);
402  if (!connectionValues.contains("Upgrade", Qt::CaseInsensitive)) // RFC 6455 - 1.3. Opening Handshake
403  {
404  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessHandshake() - Invalid 'Connection' header");
405  return false;
406  }
407 
408  if (!requestHeaders.contains("upgrade") ||
409  requestHeaders["upgrade"].toLower() != "websocket") // RFC 6455 - 1.3. Opening Handshake
410  {
411  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessHandshake() - Missing or invalid 'Upgrade' header");
412  return false;
413  }
414 
415  if (!requestHeaders.contains("sec-websocket-version")) // RFC 6455 - 1.3. Opening Handshake
416  {
417  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessHandshake() - Missing 'Sec-WebSocket-Version' header");
418  return false;
419  }
420 
421  if (requestHeaders["sec-websocket-version"] != "13") // RFC 6455 - 1.3. Opening Handshake
422  {
423  LOG(VB_GENERAL, LOG_ERR, QString("WebSocketWorker::ProcessHandshake() - Unsupported WebSocket protocol "
424  "version. We speak '13' the client speaks '%1'")
425  .arg(requestHeaders["sec-websocket-version"]));
426  return false;
427  }
428 
429  if (!requestHeaders.contains("sec-websocket-key") ||
430  QByteArray::fromBase64(requestHeaders["sec-websocket-key"].toLatin1()).length() != 16) // RFC 6455 - 1.3. Opening Handshake
431  {
432  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessHandshake() - Missing or invalid 'sec-websocket-key' header");
433  return false;
434  }
435 
436  // If we're running the Autobahn fuzz/unit tester then we need to disable
437  // the heartbeat and 'echo' text/binary frames back to the sender
438  if (requestHeaders.contains("user-agent") &&
439  requestHeaders["user-agent"].contains("AutobahnTestSuite"))
440  m_fuzzTesting = true;
441 
442  QString key = requestHeaders["sec-websocket-key"];
443  const QString magicString = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
444 
445  // Response token - Watch very closely, there's a lot happening here
446  QString acceptToken = QCryptographicHash::hash(key.append(magicString).toUtf8(),
447  QCryptographicHash::Sha1).toBase64();
448 
449  QMap<QString, QString> responseHeaders;
450  responseHeaders.insert("Connection", "Upgrade");
451  responseHeaders.insert("Upgrade", "websocket");
452  responseHeaders.insert("Sec-WebSocket-Accept", acceptToken);
453 
454  socket->write("HTTP/1.1 101 Switching Protocols\r\n");
455 
456  QString header("%1: %2\r\n");
457  for (it = responseHeaders.begin(); it != responseHeaders.end(); ++it)
458  {
459  socket->write(header.arg(it.key()).arg(*it).toLatin1().constData());
460  LOG(VB_HTTP, LOG_INFO, QString("(Response Header) %1: %2")
461  .arg(it.key()).arg(*it));
462  }
463 
464  socket->write("\r\n");
465  socket->waitForBytesWritten();
466 
467  m_webSocketMode = true;
468  // Start the heart beat
469  if (!m_fuzzTesting)
470  m_heartBeat->start();
471 
472  return true;
473 }
474 
475 void WebSocketWorker::ProcessFrames(QTcpSocket *socket)
476 {
477  while (m_isRunning && socket && socket->bytesAvailable() >= 2) // No header? Return and wait for more
478  {
479  uint8_t headerSize = 2; // Smallest possible header size is 2 bytes, greatest is 14 bytes
480 
481  QByteArray header = socket->peek(headerSize); // Read header to establish validity and size of frame
482 
483  WebSocketFrame frame;
484  // FIN
485  frame.m_finalFrame = (bool)(header[0] & 0x80);
486  // Reserved bits
487  if (header.at(0) & 0x70)
488  {
489  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessFrames() "
490  "- Invalid data in reserved fields");
491  SendClose(kCloseProtocolError, "Invalid data in reserved fields");
492  return;
493  }
494  // Operation code
495  uint8_t opCode = (header.at(0) & 0xF);
496  if ((opCode > WebSocketFrame::kOpBinaryFrame &&
497  opCode < WebSocketFrame::kOpClose) ||
498  (opCode > WebSocketFrame::kOpPong))
499  {
500  LOG(VB_GENERAL, LOG_ERR, QString("WebSocketWorker::ProcessFrames() "
501  "- Invalid OpCode (%1)")
502  .arg(QString::number(opCode, 16)));
503  SendClose(kCloseProtocolError, "Invalid OpCode");
504  return;
505  }
506  frame.m_opCode = (WebSocketFrame::OpCode)opCode;
507  frame.m_isMasked = (((header.at(1) >> 7) & 0xFE) != 0);
508 
509  if (frame.m_isMasked)
510  headerSize += 4; // Add 4 bytes for the mask
511 
512  frame.m_payloadSize = (header.at(1) & 0x7F);
513  // Handle 16 or 64bit payload size headers
514  if (frame.m_payloadSize >= 126)
515  {
516  uint8_t payloadHeaderSize = 2; // 16bit payload size
517  if (frame.m_payloadSize == 127)
518  payloadHeaderSize = 8; // 64bit payload size
519 
520  headerSize += payloadHeaderSize; // Add bytes for extended payload size
521 
522  if (socket->bytesAvailable() < headerSize)
523  return; // Return and wait for more
524 
525  header = socket->peek(headerSize); // Peek the entire header
526  QByteArray payloadHeader = header.mid(2,payloadHeaderSize);
527  frame.m_payloadSize = 0;
528  for (int i = 0; i < payloadHeaderSize; i++)
529  {
530  frame.m_payloadSize |= ((uint8_t)payloadHeader.at(i) << ((payloadHeaderSize - (i + 1)) * 8));
531  }
532  }
533  else
534  {
535  if (socket->bytesAvailable() < headerSize)
536  return; // Return and wait for more
537  header = socket->peek(headerSize); // Peek the entire header including mask
538  }
539 
540  while ((uint64_t)socket->bytesAvailable() < (frame.m_payloadSize + header.length()))
541  {
542  if (!socket->waitForReadyRead(2000)) // Wait 2 seconds for the next chunk of the frame
543  {
544 
545  m_errorCount++;
546 
547  if (m_errorCount == 5)
548  {
549  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessFrames() - Timed out waiting for rest of frame to arrive.");
551  }
552  return;
553  }
554  }
555 
558 
559  LOG(VB_HTTP, LOG_DEBUG, QString("Read Header: %1").arg(QString(header.toHex())));
560  LOG(VB_HTTP, LOG_DEBUG, QString("Final Frame: %1").arg(frame.m_finalFrame ? "Yes" : "No"));
561  LOG(VB_HTTP, LOG_DEBUG, QString("Op Code: %1").arg(QString::number(frame.m_opCode)));
562  LOG(VB_HTTP, LOG_DEBUG, QString("Payload Size: %1 Bytes").arg(QString::number(frame.m_payloadSize)));
563  LOG(VB_HTTP, LOG_DEBUG, QString("Total Payload Size: %1 Bytes").arg(QString::number( m_readFrame.m_payloadSize)));
564 
565  if (!m_fuzzTesting &&
566  frame.m_payloadSize > qPow(2,20)) // Set 1MB limit on payload per frame
567  {
568  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessFrames() - Frame payload larger than limit of 1MB");
569  SendClose(kCloseTooLarge, "Frame payload larger than limit of 1MB");
570  return;
571  }
572 
573  if (!m_fuzzTesting &&
574  m_readFrame.m_payloadSize > qPow(2,22)) // Set 4MB limit on total payload
575  {
576  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessFrames() - Total payload larger than limit of 4MB");
577  SendClose(kCloseTooLarge, "Total payload larger than limit of 4MB");
578  return;
579  }
580 
581  socket->read(headerSize); // Discard header from read buffer
582 
583  frame.m_payload = socket->read(frame.m_payloadSize);
584 
585  // Unmask payload
586  if (frame.m_isMasked)
587  {
588  frame.m_mask = header.right(4);
589  for (uint i = 0; i < frame.m_payloadSize; i++)
590  frame.m_payload[i] = frame.m_payload.at(i) ^ frame.m_mask[i % 4];
591  }
592 
596  {
597  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker - Incomplete multi-part frame? Expected continuation.");
598  SendClose(kCloseProtocolError, "Incomplete multi-part frame? Expected continuation.");
599  return;
600  }
601 
602  // Check control frame validity
603  if (frame.m_opCode >= 0x08)
604  {
605  if (!frame.m_finalFrame)
606  {
607  SendClose(kCloseProtocolError, "Control frames MUST NOT be fragmented");
608  return;
609  }
610  if (frame.m_payloadSize > 125)
611  {
612  SendClose(kCloseProtocolError, "Control frames MUST NOT have payload greater than 125 bytes");
613  return;
614  }
615  }
616 
617  switch (frame.m_opCode)
618  {
621  {
622  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker - Received Continuation Frame out of sequence");
623  SendClose(kCloseProtocolError, "Received Continuation Frame out of sequence");
624  return;
625  }
626 
627  m_readFrame.m_payload.append(frame.m_payload);
628 
630  {
631  m_readFrame.m_finalFrame = true;
632  frame = m_readFrame;
633  // Fall through to appropriate handler for complete payload
634  }
635  else
636  break;
637  [[clang::fallthrough]];
640  HandleDataFrame(frame);
641  break;
643  SendPong(frame.m_payload);
644  break;
646  break;
648  if (!frame.m_finalFrame)
649  SendClose(kCloseProtocolError, "Control frames MUST NOT be fragmented");
650  else
652  break;
653  default:
654  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker - Received Unknown Frame Type");
655  break;
656  }
657 
658  frame.reset();
659  }
660 }
661 
663 {
664 }
665 
667 {
668  if (frame.m_finalFrame)
669  {
670  QList<WebSocketExtension*>::iterator it;
671  switch (frame.m_opCode)
672  {
674  if (!CodecUtil::isValidUTF8(frame.m_payload))
675  {
676  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker - Message is not valid UTF-8");
677  SendClose(kCloseBadData, "Message is not valid UTF-8");
678  return;
679  }
680  // For Debugging and fuzz testing
681  if (m_fuzzTesting)
682  SendText(frame.m_payload);
683  it = m_extensions.begin();
684  for (; it != m_extensions.end(); ++it)
685  {
686  if ((*it)->HandleTextFrame(frame))
687  break;
688  }
689  break;
691  if (m_fuzzTesting)
692  SendBinary(frame.m_payload);
693  it = m_extensions.begin();
694  for (; it != m_extensions.end(); ++it)
695  {
696  if ((*it)->HandleBinaryFrame(frame))
697  break;
698  }
699  break;
700  default:
701  break;
702  }
703  m_readFrame.reset();
704  }
705  else
706  {
707  // Start of new fragmented frame
708  m_readFrame.reset();
709  m_readFrame.m_opCode = frame.m_opCode;
712  m_readFrame.m_fragmented = true;
713  m_readFrame.m_finalFrame = false;
714  }
715 }
716 
717 void WebSocketWorker::HandleCloseConnection(const QByteArray &payload)
718 {
719  uint16_t code = kCloseNormal;
720 
721  if (payload.length() == 1)
722  {
723  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker - Invalid close payload");
724  SendClose(kCloseProtocolError, "Invalid close payload");
725  return;
726  }
727 
728  if (payload.length() >= 2)
729  {
730  code = (payload[0] << 8);
731  code |= payload[1] & 0xFF;
732  }
733 
734  if ((code < 1000) ||
735  ((code > 1003) && (code < 1007)) ||
736  ((code > 1011) && (code < 3000)) ||
737  (code > 4999))
738  {
739  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker - Invalid close code received");
740  SendClose(kCloseProtocolError, "Invalid close code");
741  return;
742  }
743 
744  QString closeMessage;
745  if (payload.length() > 2)
746  {
747  QByteArray messageBytes = payload.mid(2);
748  if (!CodecUtil::isValidUTF8(messageBytes))
749  {
750  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker - Message is not valid UTF-8");
751  SendClose(kCloseBadData, "Message is not valid UTF-8");
752  return;
753  }
754  closeMessage = QString(messageBytes);
755  }
756 
757  LOG(VB_HTTP, LOG_INFO, QString("WebSocketWorker - Received CLOSE frame - [%1] %2")
758  .arg(QString::number(code)).arg(closeMessage));
759  SendClose((ErrorCode)code);
760 }
761 
763  const QByteArray &payload)
764 {
765  QByteArray frame;
766 
767  int payloadSize = payload.length();
768 
769  if (payloadSize >= qPow(2,64))
770  {
771  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::CreateFrame() - Payload "
772  "exceeds the allowed size for a single frame");
773  return frame;
774  }
775 
776  if (type >= 0x08)
777  {
778  //if (!m_finalFrame)
779  // SendClose(kCloseProtocolError, "Control frames MUST NOT be fragmented");
780  if (payloadSize > 125)
781  {
782  LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::CreateFrame() - Control frames MUST NOT have payload greater than 125bytes");
783  return frame;
784  }
785  }
786 
787  uint16_t header = 0;
788  uint16_t extendedHeader = 0; // For payloads > 125 bytes
789  uint64_t superHeader = 0; // For payloads > 65,535 bytes
790 
791  // Only support single frames for now
792  header |= (1 << 15); // FIN (1 bit)
793  // RSV 1 to RSV 3 (1 bit each)
794  header |= (type << 8); // OpCode (4 bits)
795  header |= (0 << 7); // Mask (1 bit) (Off)
796  if (payloadSize < 126)
797  {
798  header |= payloadSize;
799  frame.insert(2, payload.constData(), payloadSize);
800  }
801  else if (payloadSize <= 65535)
802  {
803  header |= 126;
804  extendedHeader = payloadSize;
805  frame.insert(4, payload.constData(), payloadSize);
806  }
807  else
808  {
809  header |= 127;
810  superHeader = payloadSize;
811  frame.insert(10, payload.constData(), payloadSize);
812  }
813 
814  frame[0] = (uint8_t)((header >> 8) & 0xFF);
815  frame[1] = (uint8_t)(header & 0xFF);
816  if (extendedHeader > 0)
817  {
818  frame[2] = (extendedHeader >> 8) & 0xFF;
819  frame[3] = extendedHeader & 0xFF;
820  }
821  else if (superHeader > 0)
822  {
823  frame[2] = (superHeader >> 56) & 0xFF;
824  frame[3] = (superHeader >> 48) & 0xFF;
825  frame[4] = (superHeader >> 40) & 0xFF;
826  frame[5] = (superHeader >> 32) & 0xFF;
827  frame[6] = (superHeader >> 24) & 0xFF;
828  frame[7] = (superHeader >> 16) & 0xFF;
829  frame[8] = (superHeader >> 8) & 0xFF;
830  frame[9] = (superHeader & 0xFF);
831  }
832 
833  LOG(VB_HTTP, LOG_DEBUG, QString("WebSocketWorker::CreateFrame() - Frame size %1").arg(QString::number(frame.length())));
834 
835  return frame;
836 }
837 
838 bool WebSocketWorker::SendFrame(const QByteArray &frame)
839 {
840  if (!m_socket || !m_socket->isOpen() || !m_socket->isWritable())
841  {
843  return false;
844  }
845 
846  LOG(VB_HTTP, LOG_DEBUG, QString("WebSocketWorker::SendFrame() - '%1'...").arg(QString(frame.left(64).toHex())));
847 
848  m_socket->write(frame.constData(), frame.length());
849 
850  return true;
851 }
852 
853 bool WebSocketWorker::SendText(const QString &message)
854 {
855  return SendText(message.trimmed().toUtf8());
856 }
857 
858 bool WebSocketWorker::SendText(const QByteArray& message)
859 {
860  if (!CodecUtil::isValidUTF8(message))
861  {
862  LOG(VB_GENERAL, LOG_ERR, QString("WebSocketWorker::SendText('%1...') - "
863  "Text contains invalid UTF-8 character codes. Discarded.")
864  .arg(QString(message.left(20))));
865  return false;
866  }
867 
868  QByteArray frame = CreateFrame(WebSocketFrame::kOpTextFrame, message);
869 
870  return !frame.isEmpty() && SendFrame(frame);
871 }
872 
873 bool WebSocketWorker::SendBinary(const QByteArray& data)
874 {
875  QByteArray frame = CreateFrame(WebSocketFrame::kOpBinaryFrame, data);
876 
877  return !frame.isEmpty() && SendFrame(frame);
878 }
879 
880 bool WebSocketWorker::SendPing(const QByteArray& payload)
881 {
882  QByteArray frame = CreateFrame(WebSocketFrame::kOpPing, payload);
883 
884  return !frame.isEmpty() && SendFrame(frame);
885 }
886 
887 bool WebSocketWorker::SendPong(const QByteArray& payload)
888 {
889  QByteArray frame = CreateFrame(WebSocketFrame::kOpPong, payload);
890 
891  return !frame.isEmpty() && SendFrame(frame);
892 }
893 
895  const QString &message)
896 {
897  LOG(VB_HTTP, LOG_DEBUG, "WebSocketWorker::SendClose()");
898  QByteArray payload;
899  payload.resize(2);
900  payload[0] = (uint8_t)(errCode >> 8);
901  payload[1] = (uint8_t)(errCode & 0xFF);
902 
903  if (!message.isEmpty())
904  payload.append(message.toUtf8());
905 
906  QByteArray frame = CreateFrame(WebSocketFrame::kOpClose, payload);
907 
908  if (!frame.isEmpty() && SendFrame(frame))
909  {
910  CloseConnection();
911  return true;
912  }
913 
914  CloseConnection();
915  return false;
916 }
917 
919 {
920  SendPing(QByteArray("HeartBeat"));
921 }
922 
924 {
925  if (!extension)
926  return;
927 
928  connect(extension, SIGNAL(SendTextMessage(const QString &)),
929  this, SLOT(SendText(const QString &)));
930  connect(extension, SIGNAL(SendBinaryMessage(const QByteArray &)),
931  this, SLOT(SendBinary(const QByteArray &)));
932 
933  m_extensions.append(extension);
934 }
935 
937 {
938  if (!extension)
939  return;
940 
941  QList<WebSocketExtension*>::iterator it = m_extensions.begin();
942  for (; it != m_extensions.end(); ++it)
943  {
944  if ((*it) == extension)
945  {
946  it = m_extensions.erase(it);
947  break;
948  }
949  }
950 }
951 
952 
void setMaxThreadCount(int maxThreadCount)
int maxThreadCount(void) const
WebSocketServer & m_webSocketServer
Definition: websocket.h:274
bool SendText(const QString &message)
Definition: websocket.cpp:853
QSslConfiguration m_sslConfig
Definition: websocket.h:175
void startReserved(QRunnable *runnable, QString debugName, int waitForAvailMS=0)
bool m_finalFrame
Definition: websocket.h:113
void CleanupSocket()
Definition: websocket.cpp:222
bool IsRunning(void) const
Definition: websocket.h:45
bool m_fuzzTesting
Definition: websocket.h:292
void Stop(void)
qt_socket_fd_t m_socketFD
Definition: websocket.h:275
enum WebSocketFrame::OpCodes OpCode
QTcpSocket * m_socket
Definition: websocket.h:276
PoolServerType m_connectionType
Definition: websocket.h:277
QList< WebSocketExtension * > m_extensions
Definition: websocket.h:294
virtual ~WebSocketServer()
Definition: websocket.cpp:39
bool
Definition: pxsup2dast.c:30
QByteArray m_mask
Definition: websocket.h:118
unsigned int uint
Definition: compat.h:140
MythCoreContext * gCoreContext
This global variable contains the MythCoreContext instance for the app.
QSslConfiguration m_sslConfig
Definition: websocket.h:62
PoolServerType GetServerType(void)
Definition: serverpool.h:47
qintptr qt_socket_fd_t
Definition: mythqtcompat.h:4
bool SendFrame(const QByteArray &frame)
Definition: websocket.cpp:838
static bool isValidUTF8(const QByteArray &data)
Definition: codecutil.cpp:6
WebSocketWorker(WebSocketServer &webSocketServer, qt_socket_fd_t sock, PoolServerType type, const QSslConfiguration &sslConfig)
Definition: websocket.cpp:101
WebSocketWorkerThread(WebSocketServer &webSocketServer, qt_socket_fd_t sock, PoolServerType type, const QSslConfiguration &sslConfig)
Definition: websocket.cpp:69
QSslConfiguration m_sslConfig
Definition: websocket.h:289
QByteArray m_payload
Definition: websocket.h:114
uint64_t m_payloadSize
Definition: websocket.h:115
QReadWriteLock m_rwlock
Definition: websocket.h:57
Performs all the protocol-level work for a single websocket connection.
Definition: websocket.h:197
WebSocketFrame m_readFrame
Definition: websocket.h:281
void HandleControlFrame(const WebSocketFrame &frame)
Returns false if an error occurs.
Definition: websocket.cpp:662
void CloseConnection()
Definition: websocket.cpp:151
bool SendClose(ErrorCode errCode, const QString &message=QString())
Definition: websocket.cpp:894
QByteArray CreateFrame(WebSocketFrame::OpCode type, const QByteArray &payload)
Definition: websocket.cpp:762
void run(void) override
Definition: websocket.cpp:84
unsigned short uint16_t
Definition: iso6937tables.h:1
qt_socket_fd_t m_socketFD
Definition: websocket.h:172
bool m_fragmented
Definition: websocket.h:119
bool ProcessHandshake(QTcpSocket *)
Definition: websocket.cpp:311
The thread in which WebSocketWorker does it's thing.
Definition: websocket.h:157
virtual ~WebSocketWorker()
Definition: websocket.cpp:128
The WebSocket server, which listens for connections.
Definition: websocket.h:37
bool SendBinary(const QByteArray &data)
Definition: websocket.cpp:873
PoolServerType m_connectionType
Definition: websocket.h:173
enum WebSocketWorker::ErrorCodes ErrorCode
void SetupSocket()
Definition: websocket.cpp:160
Extension for sending MythEvents over WebSocketServer.
#define LOG(_MASK_, _LEVEL_, _STRING_)
Definition: mythlogging.h:41
MThreadPool m_threadPool
Definition: websocket.h:58
enum PoolServerTypes PoolServerType
uint8_t m_errorCount
Definition: websocket.h:283
Base class for extensions.
Definition: websocket.h:136
void setMaxPendingConnections(int n)
Definition: serverpool.h:94
void reset(void)
Definition: websocket.h:89
OpCode m_opCode
Definition: websocket.h:116
void RegisterExtension(WebSocketExtension *extension)
Definition: websocket.cpp:923
void DeregisterExtension(WebSocketExtension *extension)
Definition: websocket.cpp:936
bool SendPong(const QByteArray &payload)
Definition: websocket.cpp:887
void ProcessFrames(QTcpSocket *)
Returns false if an error occurs.
Definition: websocket.cpp:475
bool m_webSocketMode
Definition: websocket.h:280
bool SendPing(const QByteArray &payload)
Definition: websocket.cpp:880
void HandleDataFrame(const WebSocketFrame &frame)
Definition: websocket.cpp:666
void HandleCloseConnection(const QByteArray &payload)
Definition: websocket.cpp:717
void newTcpConnection(qt_socket_fd_t socket) override
Definition: websocket.cpp:48
QTimer * m_heartBeat
Definition: websocket.h:286
WebSocketServer & m_webSocketServer
Definition: websocket.h:171
A representation of a single WebSocket frame.
Definition: websocket.h:75
void SendHeartBeat()
Definition: websocket.cpp:918
QEventLoop * m_eventLoop
Definition: websocket.h:273
bool CheckSubnet(const QAbstractSocket *socket)
Check if a socket is connected to an approved peer.