summaryrefslogtreecommitdiffhomepage
path: root/plugins/cgi/cgi.cpp
blob: 23c9bc4ba6af8f6011d94518285f7330308fba7c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#include "cgi.h"

#include "libreichwein/mime.h"

#include <boost/algorithm/string/predicate.hpp>
#include <boost/coroutine2/coroutine.hpp>
#include <boost/process.hpp>

#include <algorithm>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <unordered_map>

using namespace std::string_literals;
namespace bp = boost::process;
namespace fs = std::filesystem;
using namespace Reichwein::Mime;

namespace {

 const std::string gateway_interface{"CGI/1.1"};

 struct CGIContext
 {
   std::function<std::string(const std::string& key)>& GetServerParam;
   std::function<std::string(const std::string& key)>& GetRequestParam; // request including body (POST...)
   std::function<void(const std::string& key, const std::string& value)>& SetResponseHeader; // to be added to result string
   fs::path& path;
   fs::path& file_path;
   fs::path& path_info;

   CGIContext(std::function<std::string(const std::string& key)>& p_GetServerParam,
              std::function<std::string(const std::string& key)>& p_GetRequestParam,
              std::function<void(const std::string& key, const std::string& value)>& p_SetResponseHeader,
              fs::path& p_path,
              fs::path& p_file_path,
              fs::path& p_path_info
              )
    : GetServerParam(p_GetServerParam)
    , GetRequestParam(p_GetRequestParam)
    , SetResponseHeader(p_SetResponseHeader)
    , path(p_path)
    , file_path(p_file_path)
    , path_info(p_path_info)
  {
  }
 };

 typedef boost::coroutines2::coroutine<std::string> coro_t;

 // returns true iff std::string is empty or contains newline
 bool isEmpty(const std::string& s)
 {
  return s.empty() || s == "\r" || s == "\n"s || s == "\r\n"s;
 }

 void trimLinebreak(std::string& s)
 {
  size_t pos = s.find_last_not_of("\r\n");
  if (pos != s.npos)
   s = s.substr(0, pos + 1);
 }

 std::unordered_map<std::string, std::function<void(std::string&, CGIContext&)>> headerMap {
  { "CACHE-CONTROL", [](std::string& v, CGIContext& c){ c.SetResponseHeader("cache_control", v); } },

  { "CONTENT-TYPE", [](std::string& v, CGIContext& c){ c.SetResponseHeader("content_type", v); } },

  { "SET-COOKIE", [](std::string& v, CGIContext& c){ c.SetResponseHeader("set_cookie", v); } },
  
  { "STATUS", [](std::string& v, CGIContext& c) {
      std::string status{"500"};
      if (v.size() >= 3) {
       status = v.substr(0, 3);
      }
      c.SetResponseHeader("status", status);
  } }
 };

 void handleHeader(const std::string& s, CGIContext& context)
 {
  size_t pos = s.find(": ");
  if (pos == s.npos)
   return;

  std::string key {s.substr(0, pos)};
  std::string value {s.substr(pos + 2)};

  std::transform(key.begin(), key.end(), key.begin(), ::toupper);
  auto it {headerMap.find(key)};
  if (it == headerMap.end())
   std::cout << "Warning: Unhandled CGI header: " << s << std::endl;
  else
   it->second(value, context);
 }

 void setCGIEnvironment(bp::environment& env, CGIContext& c)
 {
  std::string authorization {c.GetRequestParam("authorization")};
  if (!authorization.empty())
   env["AUTH_TYPE"] = c.GetRequestParam("authorization");

  env["CONTENT_LENGTH"] = c.GetRequestParam("content_length");
  env["CONTENT_TYPE"] = c.GetRequestParam("content_type");
  env["GATEWAY_INTERFACE"] = gateway_interface;

  std::string target {c.GetRequestParam("target")};
  size_t query_pos {target.find("?")};
  std::string query;
  if (query_pos != target.npos) {
   query = target.substr(query_pos + 1);
   target = target.substr(0, query_pos);
  }

  env["PATH_INFO"] = c.path_info.string();
  env["PATH_TRANSLATED"] = c.path.string();
  env["QUERY_STRING"] = query;
  env["REMOTE_ADDR"] = "";
  env["REMOTE_HOST"] = "";
  env["REMOTE_IDENT"] = "";
  env["REMOTE_USER"] = "";
  env["REQUEST_METHOD"] = c.GetRequestParam("method");
  env["REQUEST_URI"] = target;
  env["SCRIPT_NAME"] = c.file_path;
  env["SERVER_NAME"] = c.GetRequestParam("host");
  env["SERVER_PORT"] = c.GetServerParam("port");
  env["SERVER_PROTOCOL"] = c.GetRequestParam("http_version");
  env["SERVER_SOFTWARE"] = c.GetServerParam("version");

  env["HTTP_ACCEPT"] = c.GetRequestParam("http_accept");
  env["HTTP_ACCEPT_CHARSET"] = c.GetRequestParam("http_accept_charset");
  env["HTTP_ACCEPT_ENCODING"] = c.GetRequestParam("http_accept_encoding");
  env["HTTP_ACCEPT_LANGUAGE"] = c.GetRequestParam("http_accept_language");
  env["HTTP_CONNECTION"] = c.GetRequestParam("http_connection");
  env["HTTP_HOST"] = c.GetRequestParam("http_host");
  env["HTTP_USER_AGENT"] = c.GetRequestParam("http_user_agent");
  env["HTTP_REFERER"] = c.GetRequestParam("referer");
  env["HTTP_COOKIE"] = c.GetRequestParam("cookie");
  env["HTTPS"] = c.GetRequestParam("https");
 }

 std::string executeFile(CGIContext& context)
 {
  bp::pipe is_in;
  bp::ipstream is_out;

  bp::environment env {boost::this_process::environment()};
  setCGIEnvironment(env, context);

  bp::child child(context.path.string(), env, bp::std_out > is_out, bp::std_err > stderr, bp::std_in < is_in);

  std::string body{ context.GetRequestParam("body") };
  is_in.write(body.data(), body.size());
  is_in.close();

  std::string output;
  std::string line;

  coro_t::push_type processLine( [&](coro_t::pull_type& in){
                                std::string line;
                                // read header lines
                                while (in && !isEmpty(line = in.get())) {
                                 trimLinebreak(line);
                                 handleHeader(line, context);
                                 in();
                                }
                                
                                // read empty line
                                if (!isEmpty(line))
                                 throw std::runtime_error("Missing empty line between CGI header and body");
                                if (in)
                                 in();

                                // read remainder
                                while (in) {
                                 line = in.get();
                                 output += line + '\n';
                                 in();
                                }

                                throw std::runtime_error("Input missing on processing CGI body");
  });

  while (std::getline(is_out, line) && !is_out.eof()) {
   processLine(line);
  }

  child.wait();

  return output;
 }

 // Used to return errors by generating response page and HTTP status code
 std::string HttpStatus(std::string status, std::string message, std::function<plugin_interface_setter_type>& SetResponseHeader)
 {
  SetResponseHeader("status", status);
  SetResponseHeader("content_type", "text/html");
  return status + " " + message;
 }

} // anonymous namespace

std::string cgi_plugin::name()
{
 return "cgi";
}

cgi_plugin::cgi_plugin()
{
 //std::cout << "Plugin constructor" << std::endl;
}

cgi_plugin::~cgi_plugin()
{
 //std::cout << "Plugin destructor" << std::endl;
}

std::string cgi_plugin::generate_page(
  std::function<std::string(const std::string& key)>& GetServerParam,
  std::function<std::string(const std::string& key)>& GetRequestParam, // request including body (POST...)
  std::function<void(const std::string& key, const std::string& value)>& SetResponseHeader // to be added to result string
)
{
 try {
  // Request path must not contain "..".
  std::string rel_target{GetRequestParam("rel_target")};
  size_t query_pos{rel_target.find("?")};
  if (query_pos != rel_target.npos)
   rel_target = rel_target.substr(0, query_pos);

  std::string target{GetRequestParam("target")};
  if (rel_target.find("..") != std::string::npos) {
   return HttpStatus("400", "Illegal request: "s + target, SetResponseHeader);
  }

  // Build the path to the requested file
  std::string doc_root{GetRequestParam("doc_root")};
  fs::path path {fs::path{doc_root} / rel_target};
  if (target.size() && target.back() != '/' && fs::is_directory(path)) {
   std::string location{GetRequestParam("location") + "/"s};
   SetResponseHeader("location", location);
   return HttpStatus("301", "Correcting directory path", SetResponseHeader);
  }

  fs::path path_info{};
  fs::path file_path{target};
  try {
   // file file name part and separate path_info
   while (!fs::is_regular_file(path) && path != "/" && path != "") {
    if (path_info.string() == "")
     path_info = fs::path{"/"} / path.filename();
    else
     path_info = fs::path{"/"} / path.filename() / path_info.relative_path();

    path = path.parent_path();
    file_path = file_path.parent_path();
   }

   if (!fs::is_regular_file(path)) {
    return HttpStatus("500", "Bad Script: "s + rel_target, SetResponseHeader);
   }
  } catch (const std::exception& ex) {
   return HttpStatus("500", "Bad file access: "s + rel_target, SetResponseHeader);
  }

  try {
   if ((fs::status(path).permissions() & fs::perms::others_exec) == fs::perms::none) {
     return HttpStatus("500", "Script not executable: "s + rel_target, SetResponseHeader);
   }
  } catch (const std::exception& ex) {
    return HttpStatus("500", "Bad file status access: "s + rel_target, SetResponseHeader);
  }

  SetResponseHeader("content_type", mime_type(path.string()));

  CGIContext context(GetServerParam, GetRequestParam, SetResponseHeader, path, file_path, path_info);

  try {
   return executeFile(context);
  } catch (const std::runtime_error& ex) {
   return HttpStatus("404", "Not found: "s + GetRequestParam("target"), SetResponseHeader);
  } catch (const std::exception& ex) {
   return HttpStatus("500", "Internal Server Error: "s + ex.what(), SetResponseHeader);
  }

 } catch (const std::exception& ex) {
  return HttpStatus("500", "Unknown Error: "s + ex.what(), SetResponseHeader);
 }
}

bool cgi_plugin::has_own_authentication()
{
 return false;
}