aboutsummaryrefslogtreecommitdiff
path: root/web/apache/service
blob: cd405eeffa40451da94ee5c60e7cf2141cef11df (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
// file      : web/apache/service -*- C++ -*-
// copyright : Copyright (c) 2014-2015 Code Synthesis Tools CC
// license   : MIT; see accompanying LICENSE file

#ifndef WEB_APACHE_SERVICE
#define WEB_APACHE_SERVICE

#include <string.h> // memset()
#include <unistd.h> // getppid()
#include <signal.h> // kill()

#include <httpd/httpd.h>
#include <httpd/http_config.h>

#include <string>
#include <vector>
#include <memory> // unique_ptr
#include <cassert>
#include <exception>
#include <algorithm> // move()

#include <web/module>
#include <web/apache/log>
#include <web/apache/request>

namespace web
{
  namespace apache
  {
    class service: ::module
    {
    public:

      using option_names = std::vector<std::string>;

      // Note that the module exemplar is stored by-reference.
      //
      template <typename M>
      service (const std::string& name,
               M& exemplar,
               option_names opts = option_names ())
          : ::module
            {
              STANDARD20_MODULE_STUFF,
              nullptr,
              nullptr,
              nullptr,
              nullptr,
              nullptr,
              &register_hooks<M>
            },
            name_ (name),
            exemplar_ (exemplar),
            option_names_ (std::move (opts))
// Doesn't look like handle_ member is required at all.
//          handle_ (&handle_impl<M>)
      {
        // Fill apache module directive definitions. Directives share
        // common name space in apache configuration file, so to prevent name
        // clash have to form directive name as a combination of module and
        // option names: <module name>-<option name>. This why for option
        // bar of module foo the corresponding directive will appear in apache
        // configuration file as foo-bar.
        //
        std::unique_ptr<command_rec[]> directives (
          new command_rec[option_names_.size () + 1]);

        command_rec* d = directives.get ();

        for (auto& o: option_names_)
        {
          o = name_ + "-" + o;

          *d++ =
            {
              o.c_str (),
              reinterpret_cast<cmd_func> (add_option),
              this,
              RSRC_CONF,
              TAKE1,
              nullptr
            };
        }

        *d = {};

        // instance<M> () is invented to delegate processing from apache
        // request handler C function to the service non static member
        // function. This appoach resticts number of service objects per
        // specific module implementation class with just one instance.
        //
        service*& srv = instance<M> ();
        assert (srv == nullptr);
        srv = this;

        cmds = directives.release ();
      }

      ~service ()
      {
        delete [] cmds;
      }

      static const char*
      add_option (cmd_parms *parms, void *mconfig, const char *value)
      {
        service& srv = *reinterpret_cast<service*> (parms->cmd->cmd_data);
        std::string name (parms->cmd->name + srv.name_.length () + 1);

        for (auto& v: srv.options_)
          if (v.name == name)
          {
            v.value = value;
            return 0;
          }

        srv.options_.emplace_back (name, value);
        return 0;
      }

      template <typename M>
      static service*&
      instance () noexcept
      {
        static service* instance;
        return instance;
      }

      template <typename M>
      static void
      register_hooks (apr_pool_t*) noexcept
      {
        // The registered function is called right after apache worker
        // process is started. Called for every new process spawned.
        //
        ap_hook_child_init (&worker_initializer<M>, NULL, NULL, APR_HOOK_LAST);

        // The registered function is called for each client request.
        //
        ap_hook_handler (&request_handler<M>, NULL, NULL, APR_HOOK_LAST);
      }

      template <typename M>
      static void
      worker_initializer (apr_pool_t*, server_rec* server) noexcept
      {
        auto srv = instance<M> ();
        log l (server);

        static const std::string func_name (
          "web::apache::service<" + srv->name_ + ">::worker_initializer");

        try
        {
          srv->exemplar_.init (srv->options_, l);
        }
        catch (const std::exception& e)
        {
          l.write (nullptr, 0, func_name.c_str (), APLOG_EMERG, e.what ());

          // Terminate the root apache process.
          //
          ::kill (::getppid (), SIGTERM);
        }
        catch (...)
        {
          l.write (nullptr,
                   0,
                   func_name.c_str (),
                   APLOG_EMERG,
                   "unknown error");

          // Terminate the root apache process.
          //
          ::kill (::getppid (), SIGTERM);
        }
      }

      template <typename M>
      static int
      request_handler (request_rec* r) noexcept
      {
        auto srv = instance<M> ();

        if (!r->handler || srv->name_ != r->handler)
          return DECLINED;

        static const std::string func_name (
          "web::apache::service<" + srv->name_ + ">::request_handler");

        request req (r);
        log l (r->server);

        try
        {
          M m (static_cast<const M&> (srv->exemplar_));
          static_cast<module&> (m).handle (req, req, l);
          return req.flush ();
        }
        catch (const invalid_request& e)
        {
          if (!e.content.empty () && !req.get_write_state ())
          {
            try
            {
              req.content (e.status, e.type) << e.content;
              return req.flush ();
            }
            catch (const std::exception& e)
            {
              l.write (nullptr, 0, func_name.c_str (), APLOG_ERR, e.what ());
            }
          }

          return e.status;
        }
        catch (const std::exception& e)
        {
          l.write (nullptr, 0, func_name.c_str (), APLOG_ERR, e.what ());

          if (*e.what () && !req.get_write_state ())
          {
            try
            {
              req.content (HTTP_INTERNAL_SERVER_ERROR,
                           "text/plain;charset=utf-8")
                << e.what ();

              return req.flush ();
            }
            catch (const std::exception& e)
            {
              l.write (nullptr, 0, func_name.c_str (), APLOG_ERR, e.what ());
            }
          }
        }
        catch (...)
        {
          l.write (nullptr, 0, func_name.c_str (), APLOG_ERR, "unknown error");

          if (!req.get_write_state ())
          {
            try
            {
              req.content (HTTP_INTERNAL_SERVER_ERROR,
                           "text/plain;charset=utf-8")
                << "unknown error";

              return req.flush ();
            }
            catch (const std::exception& e)
            {
              l.write (nullptr, 0, func_name.c_str (), APLOG_ERR, e.what ());
            }
          }

        }

        return HTTP_INTERNAL_SERVER_ERROR;
      }

      //@@ Implementation calls handle_ function pointer below:
      //
      // handle_ (rq, rs, l, exemplar_);
      //

    private:
/*
      template <typename M>
      static void
      handle_impl (request& rq, response& rs, log& l, const module& exemplar)
      {
        M m (static_cast<const M&> (exemplar));
        static_cast<module&> (m).handle (rq, rs, l);
      }
*/
      std::string name_;
      module& exemplar_;
      option_names option_names_;
      name_values options_;

//      void (*handle_) (request&, response&, log&, const module&);
    };
  }
}

#endif // WEB_APACHE_SERVICE