aboutsummaryrefslogtreecommitdiff
path: root/mod/mod-repository-root.cxx
blob: 27901d741c13e52ac7a2c09943f1d6b778b42034 (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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
// file      : mod/mod-repository-root.cxx -*- C++ -*-
// copyright : Copyright (c) 2014-2018 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

#include <mod/mod-repository-root.hxx>

#include <time.h> // tzset()

#include <sstream>

#include <web/module.hxx>

#include <mod/module.hxx>
#include <mod/options.hxx>
#include <mod/mod-submit.hxx>
#include <mod/mod-builds.hxx>
#include <mod/mod-build-log.hxx>
#include <mod/mod-build-task.hxx>
#include <mod/mod-build-force.hxx>
#include <mod/mod-build-result.hxx>
#include <mod/mod-package-search.hxx>
#include <mod/mod-package-details.hxx>
#include <mod/mod-repository-details.hxx>
#include <mod/mod-package-version-details.hxx>

using namespace std;
using namespace brep::cli;

namespace brep
{
  // Request proxy.
  //
  // Removes the first parameter, that is assumed to be a function name, if its
  // value is not present. Otherwise, considers it as the handler's "default"
  // parameter value and renames the parameter to "_".
  //
  class request_proxy: public request
  {
  public:
    request_proxy (request& r): request_ (r) {}

    virtual const path_type&
    path () {return request_.path ();}

    virtual const name_values&
    parameters (size_t limit, bool url_only)
    {
      if (!parameters_ || url_only < url_only_parameters_)
      {
        parameters_ = request_.parameters (limit, url_only);
        assert (!parameters_->empty ()); // Always starts with a function name.

        auto i (parameters_->begin ());
        removed_ = !i->value;

        if (removed_)
          parameters_->erase (i);
        else
          i->name = "_";

        url_only_parameters_ = url_only;
      }

      return *parameters_;
    }

    istream&
    open_upload (size_t index)
    {
      // Shift the index if the function name parameter was removed.
      //
      return request_.open_upload (index + (removed_ ? 1 : 0));
    }

    istream&
    open_upload (const string& name)
    {
      // We don't expect the function name here as a parameter name.
      //
      return request_.open_upload (name);
    }

    virtual const name_values&
    headers () {return request_.headers ();}

    virtual const name_values&
    cookies () {return request_.cookies ();}

    virtual istream&
    content (size_t limit, size_t buffer)
    {
      return request_.content (limit, buffer);
    }

  private:
    request& request_;
    optional<name_values> parameters_;
    bool url_only_parameters_; // Meaningless if parameters_ is not present.
    bool removed_ = false;     // If the function name parameter was removed.
  };

  // repository_root
  //
  repository_root::
  repository_root ()
      : package_search_ (make_shared<package_search> ()),
        package_details_ (make_shared<package_details> ()),
        package_version_details_ (make_shared<package_version_details> ()),
        repository_details_ (make_shared<repository_details> ()),
        build_task_ (make_shared<build_task> ()),
        build_result_ (make_shared<build_result> ()),
        build_force_ (make_shared<build_force> ()),
        build_log_ (make_shared<build_log> ()),
        builds_ (make_shared<builds> ()),
        submit_ (make_shared<submit> ())
  {
  }

  repository_root::
  repository_root (const repository_root& r)
      : handler (r),
        //
        // Deep/shallow-copy sub-handlers depending on whether this is an
        // exemplar/handler.
        //
        package_search_ (
          r.initialized_
          ? r.package_search_
          : make_shared<package_search> (*r.package_search_)),
        package_details_ (
          r.initialized_
          ? r.package_details_
          : make_shared<package_details> (*r.package_details_)),
        package_version_details_ (
          r.initialized_
          ? r.package_version_details_
          : make_shared<package_version_details> (
              *r.package_version_details_)),
        repository_details_ (
          r.initialized_
          ? r.repository_details_
          : make_shared<repository_details> (*r.repository_details_)),
        build_task_ (
          r.initialized_
          ? r.build_task_
          : make_shared<build_task> (*r.build_task_)),
        build_result_ (
          r.initialized_
          ? r.build_result_
          : make_shared<build_result> (*r.build_result_)),
        build_force_ (
          r.initialized_
          ? r.build_force_
          : make_shared<build_force> (*r.build_force_)),
        build_log_ (
          r.initialized_
          ? r.build_log_
          : make_shared<build_log> (*r.build_log_)),
        builds_ (
          r.initialized_
          ? r.builds_
          : make_shared<builds> (*r.builds_)),
        submit_ (
          r.initialized_
          ? r.submit_
          : make_shared<submit> (*r.submit_)),
        options_ (
          r.initialized_
          ? r.options_
          : nullptr)
  {
  }

  // Return amalgamation of repository_root and all its sub-handlers option
  // descriptions.
  //
  option_descriptions repository_root::
  options ()
  {
    option_descriptions r (handler::options ());
    append (r, package_search_->options ());
    append (r, package_details_->options ());
    append (r, package_version_details_->options ());
    append (r, repository_details_->options ());
    append (r, build_task_->options ());
    append (r, build_result_->options ());
    append (r, build_force_->options ());
    append (r, build_log_->options ());
    append (r, builds_->options ());
    append (r, submit_->options ());
    return r;
  }

  // Initialize sub-handlers and parse own configuration options.
  //
  void repository_root::
  init (const name_values& v)
  {
    auto sub_init = [this, &v] (handler& m, const char* name)
    {
      // Initialize sub-handler. Intercept exception handling to add
      // sub-handler attribution.
      //
      try
      {
        m.init (filter (v, m.options ()), *log_);
      }
      catch (const std::exception& e)
      {
        // Any exception thrown by this function terminates the web server. All
        // exception types inherited from std::exception are handled by the web
        // server as std::exception. The only sensible way to handle them is to
        // log the error prior terminating. By that reason it is valid to
        // reduce all these types to a single one.
        //
        ostringstream os;
        os << name << ": " << e;
        throw runtime_error (os.str ());
      }
    };

    // Initialize sub-handlers.
    //
    sub_init (*package_search_, "package_search");
    sub_init (*package_details_, "package_details");
    sub_init (*package_version_details_, "package_version_details");
    sub_init (*repository_details_, "repository_details");
    sub_init (*build_task_, "build_task");
    sub_init (*build_result_, "build_result");
    sub_init (*build_force_, "build_force");
    sub_init (*build_log_, "build_log");
    sub_init (*builds_, "builds");
    sub_init (*submit_, "submit");

    // Parse own configuration options.
    //
    handler::init (
      filter (v, convert (options::repository_root::description ())));
  }

  void repository_root::
  init (scanner& s)
  {
    HANDLER_DIAG;

    options_ = make_shared<options::repository_root> (
      s, unknown_mode::fail, unknown_mode::fail);

    if (options_->root ().empty ())
      options_->root (dir_path ("/"));

    // To use libbutl timestamp printing functions later on (specifically in
    // sub-handlers, while handling requests).
    //
    tzset ();
  }

  bool repository_root::
  handle (request& rq, response& rs)
  {
    HANDLER_DIAG;

    const dir_path& root (options_->root ());

    const path& rpath (rq.path ());
    if (!rpath.sub (root))
      return false;

    const path& lpath (rpath.leaf (root));

    // Delegate the request handling to the selected sub-handler. Intercept
    // exception handling to add sub-handler attribution.
    //
    auto handle = [&rq, &rs, this] (const char* nm, bool fn = false) -> bool
    {
      try
      {
        // Delegate the handling straight away if the sub-handler is not a
        // function. Otherwise, cleanup the request not to confuse the
        // sub-handler with the unknown parameter.
        //
        if (!fn)
          return handler_->handle (rq, rs, *log_);

        request_proxy rp (rq);
        return handler_->handle (rp, rs, *log_);
      }
      catch (const invalid_request&)
      {
        // Preserve invalid_request exception type, so the web server can
        // properly respond to the client with a 4XX error code.
        //
        throw;
      }
      catch (const std::exception& e)
      {
        // All exception types inherited from std::exception (and different
        // from invalid_request) are handled by the web server as
        // std::exception. The only sensible way to handle them is to respond
        // to the client with the internal server error (500) code. By that
        // reason it is valid to reduce all these types to a single one. Note
        // that the server_error exception is handled internally by the
        // handler::handle() function call.
        //
        ostringstream os;
        os << nm << ": " << e;
        throw runtime_error (os.str ());
      }
    };

    // Note that while selecting the sub-handler type for handling the request,
    // we rely on the fact that the initial and all the subsequent function
    // calls (that may take place after the retry exception is thrown) will
    // end-up with the same type, and so using the single handler instance for
    // all of these calls is safe. Note that the selection also sets up the
    // handling context (sub-handler name and optionally the request proxy).
    //
    if (lpath.empty ())
    {
      // Dispatch request handling to the repository_details or the one of
      // build_* handlers depending on the function name passed as a first HTTP
      // request parameter (example: cppget.org/?about). Dispatch to the
      // package_search handler if the function name is unavailable (no
      // parameters) or is not recognized.
      //
      const name_values& params (rq.parameters (0 /* limit */,
                                                true /* url_only */));
      if (!params.empty ())
      {
        const string& fn (params.front ().name);

        if (fn == "about")
        {
          if (handler_ == nullptr)
            handler_.reset (new repository_details (*repository_details_));

          return handle ("repository_details", true);
        }
        else if (fn == "build-task")
        {
          if (handler_ == nullptr)
            handler_.reset (new build_task (*build_task_));

          return handle ("build_task", true);
        }
        else if (fn == "build-result")
        {
          if (handler_ == nullptr)
            handler_.reset (new build_result (*build_result_));

          return handle ("build_result", true);
        }
        else if (fn == "build-force")
        {
          if (handler_ == nullptr)
            handler_.reset (new build_force (*build_force_));

          return handle ("build_force", true);
        }
        else if (fn == "builds")
        {
          if (handler_ == nullptr)
            handler_.reset (new builds (*builds_));

          return handle ("builds", true);
        }
        else if (fn == "submit")
        {
          if (handler_ == nullptr)
            handler_.reset (new submit (*submit_));

          return handle ("submit", true);
        }
      }

      if (handler_ == nullptr)
        handler_.reset (new package_search (*package_search_));

      return handle ("package_search");
    }
    else
    {
      // Dispatch request handling to the package_details, the
      // package_version_details or the build_log handler depending on the HTTP
      // request URL path.
      //
      auto i (lpath.begin ());
      assert (i != lpath.end ());

      const string& n (*i++); // Package name.

      // Check if this is a package name and not a brep static content files
      // (CSS) directory name, a repository directory name, or a special file
      // name (the one starting with '.'). Note that HTTP request URL path
      // (without the root directory) must also have one of the following
      // layouts:
      //
      // <package-name>
      // <package-name>/<package-version>
      // <package-name>/<package-version>/log[/...]
      //
      // If any of the checks fails, then the handling is declined.
      //
      if (n != "@" && n.find_first_not_of ("0123456789") != string::npos &&
          n[0] != '.')
      {
        if (i == lpath.end ())
        {
          if (handler_ == nullptr)
            handler_.reset (new package_details (*package_details_));

          return handle ("package_details");
        }
        else if (++i == lpath.end ())
        {
          if (handler_ == nullptr)
            handler_.reset (
              new package_version_details (*package_version_details_));

          return handle ("package_version_details");
        }
        else if (*i == "log")
        {
          if (handler_ == nullptr)
            handler_.reset (new build_log (*build_log_));

          return handle ("build_log");
        }
      }
    }

    // We shouldn't be selecting a handler if decline to handle the request.
    //
    assert (handler_ == nullptr);
    return false;
  }

  void repository_root::
  version ()
  {
    HANDLER_DIAG;

    info << "module " << BREP_VERSION_ID
         << ", libbrep " << LIBBREP_VERSION_ID
         << ", libbbot " << LIBBBOT_VERSION_ID
         << ", libbpkg " << LIBBPKG_VERSION_ID
         << ", libbutl " << LIBBUTL_VERSION_ID;
  }
}