httpserver.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright (C) by Daniel Molkentin <danimo@owncloud.com>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  11. * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  12. * for more details.
  13. */
  14. #include "httpserver.h"
  15. HttpServer::HttpServer(quint16 port, QObject* parent)
  16. : QTcpServer(parent)
  17. {
  18. listen(QHostAddress::Any, port);
  19. }
  20. void HttpServer::readClient()
  21. {
  22. QTcpSocket* socket = (QTcpSocket*)sender();
  23. if (socket->canReadLine()) {
  24. QStringList tokens = QString(socket->readLine()).split(QRegularExpression("[ \r\n][ \r\n]*"));
  25. if (tokens[0] == "GET") {
  26. QTextStream os(socket);
  27. os.setAutoDetectUnicode(true);
  28. os << "HTTP/1.0 200 Ok\r\n"
  29. "Content-Type: text/html; charset=\"utf-8\"\r\n"
  30. "\r\n"
  31. "<h1>Nothing to see here</h1>\n"
  32. << QDateTime::currentDateTimeUtc().toString() << "\n";
  33. socket->close();
  34. QtServiceBase::instance()->logMessage("Wrote to client");
  35. if (socket->state() == QTcpSocket::UnconnectedState) {
  36. delete socket;
  37. QtServiceBase::instance()->logMessage("Connection closed");
  38. }
  39. }
  40. }
  41. }
  42. void HttpServer::discardClient()
  43. {
  44. QTcpSocket* socket = (QTcpSocket*)sender();
  45. socket->deleteLater();
  46. QtServiceBase::instance()->logMessage("Connection closed");
  47. }
  48. void HttpServer::incomingConnection(int socket)
  49. {
  50. if (disabled)
  51. return;
  52. QTcpSocket* s = new QTcpSocket(this);
  53. connect(s, SIGNAL(readyRead()), this, SLOT(readClient()));
  54. connect(s, SIGNAL(disconnected()), this, SLOT(discardClient()));
  55. s->setSocketDescriptor(socket);
  56. }