CgiHandler.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include <QStringBuilder>
  2. #include <QUrlQuery>
  3. #include <QFile>
  4. #include <QByteArray>
  5. #include <QStringList>
  6. #include <QJsonObject>
  7. #include <QJsonDocument>
  8. #include <QProcess>
  9. #include "CgiHandler.h"
  10. #include "QtHttpHeader.h"
  11. #include <utils/FileUtils.h>
  12. #include <utils/Process.h>
  13. #include <utils/jsonschema/QJsonFactory.h>
  14. CgiHandler::CgiHandler (QObject * parent)
  15. : QObject(parent)
  16. , _args(QStringList())
  17. , _baseUrl()
  18. , _log(Logger::getInstance("WEBSERVER"))
  19. {
  20. }
  21. void CgiHandler::setBaseUrl(const QString& url)
  22. {
  23. _baseUrl = url;
  24. }
  25. void CgiHandler::exec(const QStringList & args, QtHttpRequest * request, QtHttpReply * reply)
  26. {
  27. _args = args;
  28. _request = request;
  29. _reply = reply;
  30. if ( _args.at(0) == "cfg_jsonserver" )
  31. {
  32. cmd_cfg_jsonserver();
  33. }
  34. else if ( _args.at(0) == "run" )
  35. {
  36. cmd_runscript();
  37. }
  38. else
  39. {
  40. throw std::runtime_error("CGI command not found");
  41. }
  42. }
  43. void CgiHandler::cmd_cfg_jsonserver()
  44. {
  45. quint16 jsonPort = 19444;
  46. // send result as reply
  47. _reply->addHeader ("Content-Type", "text/plain" );
  48. _reply->appendRawData (QByteArrayLiteral(":") % QString::number(jsonPort).toUtf8() );
  49. }
  50. void CgiHandler::cmd_runscript()
  51. {
  52. QStringList scriptFilePathList(_args);
  53. scriptFilePathList.removeAt(0);
  54. QString scriptFilePath = scriptFilePathList.join('/');
  55. // relative path not allowed
  56. if ( scriptFilePath.indexOf("..") >=0 )
  57. {
  58. throw std::runtime_error("[cmd_runscript] Relative path not allowed : %s" + scriptFilePath.toStdString());
  59. }
  60. scriptFilePath = _baseUrl+"/server_scripts/"+scriptFilePath;
  61. if ( !QFile::exists(scriptFilePath) || !scriptFilePath.endsWith(".py") )
  62. {
  63. throw std::runtime_error("[cmd_runscript] Script %s doesn't exists or is no python file : " + scriptFilePath.toStdString());
  64. }
  65. QtHttpPostData postData = _request->getPostData();
  66. QByteArray inputData; // should be filled with post data
  67. QByteArray data = Process::command_exec("python " + scriptFilePath, inputData);
  68. _reply->addHeader ("Content-Type", "text/plain");
  69. _reply->appendRawData (data);
  70. }