aboutsummaryrefslogtreecommitdiff
path: root/mod/module.cxx
blob: 2fcadd2a6f1e9938630c1c839431925861807f5a (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
// file      : mod/module.cxx -*- C++ -*-
// license   : MIT; see accompanying LICENSE file

#include <mod/module.hxx>

#include <httpd.h>
#include <http_log.h>

#include <sstream>
#include <cstring>    // strchr()
#include <functional> // bind()

#include <web/server/module.hxx>
#include <web/server/apache/log.hxx>

#include <mod/module-options.hxx>

using namespace std;
using namespace placeholders; // For std::bind's _1, etc.

namespace brep
{
  // handler
  //
  bool handler::
  handle (request& rq, response& rs, log& l)
  {
    log_ = &l;

    try
    {
      // Web server should terminate if initialization failed.
      //
      assert (initialized_);

      return handle (rq, rs);
    }
    catch (const server_error& e)
    {
      log_write (e.data);

      try
      {
        static const char* sev_str[] = {"error", "warning", "info", "trace"};
        ostream& o (rs.content (500, "text/plain;charset=utf-8"));

        for (const auto& d: e.data)
        {
          string name;

          try
          {
            name = func_name (d.name);
          }
          catch (const invalid_argument&)
          {
            // Log "pretty" function description, see in log file & fix.
            name = d.name;
          }

          o << name << ": " << sev_str[static_cast<size_t> (d.sev)] << ": "
            << d.msg << endl;
        }
      }
      catch (const sequence_error&)
      {
        // We tried to return the error status/description but some
        // content has already been written. Nothing we can do about
        // it.
      }
    }

    return true;
  }

  option_descriptions handler::
  convert (const cli::options& o)
  {
    option_descriptions r;
    append (r, o);
    return r;
  }

  void handler::
  append (option_descriptions& dst, const cli::options& src)
  {
    for (const auto& o: src)
    {
      bool v (!o.flag ());
      auto i (dst.emplace (o.name (), v));
      assert (i.first->second == v); // Consistent option/flag.

      for (const auto& a: o.aliases ())
      {
        i = dst.emplace (a, v);
        assert (i.first->second == v);
      }
    }
  }

  void handler::
  append (option_descriptions& dst, const option_descriptions& src)
  {
    for (const auto& o: src)
    {
      auto i (dst.emplace (o));
      assert (i.first->second == o.second); // Consistent option/flag.
    }
  }

  name_values handler::
  filter (const name_values& v, const option_descriptions& d)
  {
    name_values r;
    for (const auto& nv: v)
    {
      if (d.find (nv.name) != d.end ())
        r.push_back (nv);
    }

    return r;
  }

  // Convert CLI option descriptions to the general interface of option
  // descriptions, extend with brep::handler own option descriptions.
  //
  option_descriptions handler::
  options ()
  {
    option_descriptions r ({{"conf", true}});
    append (r, options::handler::description ());
    append (r, cli_options ());
    return r;
  }

  // Expand option list parsing configuration files.
  //
  name_values handler::
  expand_options (const name_values& v)
  {
    using namespace cli;

    vector<const char*> argv;
    for (const auto& nv: v)
    {
      argv.push_back (nv.name.c_str ());

      if (nv.value)
        argv.push_back (nv.value->c_str ());
    }

    int argc (argv.size ());
    argv_file_scanner s (0, argc, const_cast<char**> (argv.data ()), "conf");

    name_values r;
    const option_descriptions& o (options ());

    while (s.more ())
    {
      string n (s.next ());
      auto i (o.find (n));

      if (i == o.end ())
        throw unknown_argument (n);

      optional<string> v;
      if (i->second)
        v = s.next ();

      r.emplace_back (move (n), move (v));
    }

    return r;
  }

  // Parse options with a cli-generated scanner. Options verb and conf are
  // recognized by brep::handler::init while others to be interpreted by the
  // derived init(). If there is an option which can not be interpreted
  // neither by brep::handler nor by the derived class, then the web server
  // is terminated with a corresponding error message being logged. Though
  // this should not happen if the options() function returned the correct
  // set of options.
  //
  void handler::
  init (const name_values& options, log& log)
  {
    assert (!initialized_);

    log_ = &log;

    try
    {
      name_values opts (expand_options (options));

      // Read handler implementation configuration.
      //
      init (opts);

      // Read brep::handler configuration.
      //
      static option_descriptions od (
        convert (options::handler::description ()));

      name_values mo (filter (opts, od));
      name_value_scanner s (mo);
      options::handler o (s, cli::unknown_mode::fail, cli::unknown_mode::fail);

      verb_ = o.verbosity ();
      initialized_ = true;
    }
    catch (const server_error& e)
    {
      log_write (e.data);
      throw runtime_error ("initialization failed");
    }
    catch (const cli::exception& e)
    {
      ostringstream o;
      e.print (o);
      throw runtime_error (o.str ());
    }
  }

  void handler::
  init (const name_values& options)
  {
    name_value_scanner s (options);
    init (s);
    assert (!s.more ()); // Handler didn't handle its options.
  }

  handler::
  handler (): log_writer_ (bind (&handler::log_write, this, _1)) {}

  // Custom copy constructor is required to initialize log_writer_ properly.
  //
  handler::
  handler (const handler& m): handler ()
  {
    verb_ = m.verb_;
    initialized_ = m.initialized_;
  }

// For function func declared like this:
// using B = std::string (*)(int);
// using A = B (*)(int,int);
// A func(B (*)(char),B (*)(wchar_t));
// __PRETTY_FUNCTION__ looks like this:
// virtual std::string (* (* brep::search::func(std::string (* (*)(char))(int)
// ,std::string (* (*)(wchar_t))(int)) const)(int, int))(int)
//
  string handler::
  func_name (const char* pretty_name)
  {
    const char* e (strchr (pretty_name, ')'));

    if (e && e > pretty_name)
    {
      // Position e at last matching '(' which is the beginning of the
      // argument list..
      //
      size_t d (1);

      do
      {
        switch (*--e)
        {
        case ')': ++d; break;
        case '(': --d; break;
        }
      }
      while (d && e > pretty_name);

      if (!d && e > pretty_name)
      {
        // Position e at the character following the function name.
        //
        while (e > pretty_name &&
               (*e != '(' || *(e - 1) == ' ' || *(e - 1) == ')'))
          --e;

        if (e > pretty_name)
        {
          // Position b at the beginning of the qualified function name.
          //
          const char* b (e);
          while (--b > pretty_name && *b != ' ');
          if (*b == ' ') ++b;

          return string (b, e - b);
        }
      }
    }

    throw invalid_argument ("::brep::handler::func_name");
  }

  void handler::
  log_write (const diag_data& d) const
  {
    if (log_ == nullptr)
      return; // No backend yet.

    //@@ Cast log_ to apache::log and write the records.
    //
    auto al (dynamic_cast<web::apache::log*> (log_));

    if (al)
    {
      // Considered using lambda for mapping but looks too verbose while can
      // be a bit safer in runtime.
      //
      // Use APLOG_INFO (as opposed to APLOG_TRACE1) as a mapping for
      // severity::trace. "LogLevel trace1" configuration directive switches
      // on the avalanche of log messages from various handlers. Would be good
      // to avoid wading through them.
      //
      static int s[] = {APLOG_ERR, APLOG_WARNING, APLOG_INFO, APLOG_INFO};

      for (const auto& e: d)
      {
        string name;

        try
        {
          name = func_name (e.name);
        }
        catch (const invalid_argument&)
        {
          // Log "pretty" function description, see in log file & fix.
          name = e.name;
        }

        al->write (e.loc.file.c_str (),
                   e.loc.line,
                   name.c_str (),
                   s[static_cast<size_t> (e.sev)],
                   e.msg.c_str ());
      }
    }
  }

  void handler::
  version (log& l)
  {
    log_ = &l;
    version ();
  }

  // handler::name_value_scanner
  //
  handler::name_value_scanner::
  name_value_scanner (const name_values& nv) noexcept
      : name_values_ (nv),
        i_ (nv.begin ()),
        name_ (true)
  {
  }

  bool handler::name_value_scanner::
  more ()
  {
    return i_ != name_values_.end ();
  }

  const char* handler::name_value_scanner::
  peek ()
  {
    if (i_ != name_values_.end ())
      return name_ ? i_->name.c_str () : i_->value->c_str ();
    else
      throw cli::eos_reached ();
  }

  const char* handler::name_value_scanner::
  next ()
  {
    if (i_ != name_values_.end ())
    {
      const char* r (name_ ? i_->name.c_str () : i_->value->c_str ());
      skip ();
      return r;
    }
    else
      throw cli::eos_reached ();
  }

  void handler::name_value_scanner::
  skip ()
  {
    if (i_ != name_values_.end ())
    {
      if (name_)
      {
        if (i_->value)
          name_ = false;
        else
          ++i_;
      }
      else
      {
        ++i_;
        name_ = true;
      }
    }
    else
      throw cli::eos_reached ();
  }

  size_t handler::name_value_scanner::
  position ()
  {
    return (i_ - name_values_.begin ()) * 2 + (name_ ? 0 : 1);
  }
}