xref: /lighttpd1.4/src/mod_vhostdb_mysql.c (revision 9570cc2f)
1 /*
2  * mod_vhostdb_mysql - virtual hosts mapping from backend MySQL/MariaDB database
3  *
4  * Copyright(c) 2017 Glenn Strauss gstrauss()gluelogic.com  All rights reserved
5  * License: BSD 3-clause (same as lighttpd)
6  */
7 #include "first.h"
8 
9 #include <mysql.h>
10 
11 #include <string.h>
12 #include <stdlib.h>
13 
14 #include "base.h"
15 #include "http_vhostdb.h"
16 #include "fdevent.h"
17 #include "log.h"
18 #include "plugin.h"
19 
20 /*
21  * virtual host plugin using MySQL/MariaDB for domain to directory lookups
22  */
23 
24 typedef struct {
25     MYSQL *dbconn;
26     const buffer *sqlquery;
27 } vhostdb_config;
28 
29 typedef struct {
30     void *vdata;
31 } plugin_config;
32 
33 typedef struct {
34     PLUGIN_DATA;
35     plugin_config defaults;
36     plugin_config conf;
37 } plugin_data;
38 
39 static void mod_vhostdb_dbconf_free (void *vdata)
40 {
41     vhostdb_config *dbconf = (vhostdb_config *)vdata;
42     if (!dbconf) return;
43     mysql_close(dbconf->dbconn);
44     free(dbconf);
45 }
46 
47 static int mod_vhostdb_dbconf_setup (server *srv, const array *opts, void **vdata)
48 {
49     const buffer *sqlquery = NULL;
50     const char *dbname=NULL, *user=NULL, *pass=NULL, *host=NULL, *sock=NULL;
51     unsigned int port = 0;
52 
53     for (size_t i = 0; i < opts->used; ++i) {
54         const data_string *ds = (data_string *)opts->data[i];
55         if (ds->type == TYPE_STRING && !buffer_string_is_empty(&ds->value)) {
56             if (buffer_is_equal_caseless_string(&ds->key, CONST_STR_LEN("sql"))) {
57                 sqlquery = &ds->value;
58             } else if (buffer_is_equal_caseless_string(&ds->key, CONST_STR_LEN("dbname"))) {
59                 dbname = ds->value.ptr;
60             } else if (buffer_is_equal_caseless_string(&ds->key, CONST_STR_LEN("user"))) {
61                 user = ds->value.ptr;
62             } else if (buffer_is_equal_caseless_string(&ds->key, CONST_STR_LEN("password"))) {
63                 pass = ds->value.ptr;
64             } else if (buffer_is_equal_caseless_string(&ds->key, CONST_STR_LEN("host"))) {
65                 host = ds->value.ptr;
66             } else if (buffer_is_equal_caseless_string(&ds->key, CONST_STR_LEN("port"))) {
67                 port = strtoul(ds->value.ptr, NULL, 10);
68             } else if (buffer_is_equal_caseless_string(&ds->key, CONST_STR_LEN("sock"))) {
69                 sock = ds->value.ptr;
70             }
71         }
72     }
73 
74     /* required:
75      * - sql    (sql query)
76      * - dbname
77      * - user
78      *
79      * optional:
80      * - password, default: empty
81      * - socket, default: mysql default
82      * - hostname, if set overrides socket
83      * - port, default: 3306
84      */
85 
86     if (!buffer_string_is_empty(sqlquery)
87         && dbname && *dbname && user && *user) {
88         vhostdb_config *dbconf;
89         MYSQL *dbconn = mysql_init(NULL);
90         if (NULL == dbconn) {
91             log_error(srv->errh, __FILE__, __LINE__,
92               "mysql_init() failed, exiting...");
93             return -1;
94         }
95 
96       #if MYSQL_VERSION_ID >= 50013
97         /* in mysql versions above 5.0.3 the reconnect flag is off by default */
98         {
99             char reconnect = 1;
100             mysql_options(dbconn, MYSQL_OPT_RECONNECT, &reconnect);
101         }
102       #endif
103 
104         /* CLIENT_MULTI_STATEMENTS first appeared in 4.1 */
105       #if MYSQL_VERSION_ID < 40100
106         #ifndef CLIENT_MULTI_STATEMENTS
107         #define CLIENT_MULTI_STATEMENTS 0
108         #endif
109       #endif
110         if (!mysql_real_connect(dbconn, host, user, pass, dbname, port, sock,
111                                 CLIENT_MULTI_STATEMENTS)) {
112             log_error(srv->errh, __FILE__, __LINE__, "%s", mysql_error(dbconn));
113             mysql_close(dbconn);
114             return -1;
115         }
116 
117         fdevent_setfd_cloexec(dbconn->net.fd);
118 
119         dbconf = (vhostdb_config *)calloc(1, sizeof(*dbconf));
120         dbconf->dbconn = dbconn;
121         dbconf->sqlquery = sqlquery;
122         *vdata = dbconf;
123     }
124 
125     return 0;
126 }
127 
128 static void mod_vhostdb_patch_config (request_st * const r, plugin_data * const p);
129 
130 static int mod_vhostdb_mysql_query(request_st * const r, void *p_d, buffer *docroot)
131 {
132     plugin_data *p = (plugin_data *)p_d;
133     vhostdb_config *dbconf;
134     unsigned  cols;
135     MYSQL_ROW row;
136     MYSQL_RES *result;
137 
138     /*(reuse buffer for sql query before generating docroot result)*/
139     buffer *sqlquery = docroot;
140     buffer_clear(sqlquery); /*(also resets docroot (alias))*/
141 
142     mod_vhostdb_patch_config(r, p);
143     if (NULL == p->conf.vdata) return 0; /*(after resetting docroot)*/
144     dbconf = (vhostdb_config *)p->conf.vdata;
145 
146     for (char *b = dbconf->sqlquery->ptr, *d; *b; b = d+1) {
147         if (NULL != (d = strchr(b, '?'))) {
148             /* escape the uri.authority */
149             unsigned long len;
150             buffer_append_string_len(sqlquery, b, (size_t)(d - b));
151             buffer_string_prepare_append(sqlquery, buffer_string_length(&r->uri.authority) * 2);
152             len = mysql_real_escape_string(dbconf->dbconn,
153                     sqlquery->ptr + buffer_string_length(sqlquery),
154                     CONST_BUF_LEN(&r->uri.authority));
155             if ((unsigned long)~0 == len) return -1;
156             buffer_commit(sqlquery, len);
157         } else {
158             d = dbconf->sqlquery->ptr + buffer_string_length(dbconf->sqlquery);
159             buffer_append_string_len(sqlquery, b, (size_t)(d - b));
160             break;
161         }
162     }
163 
164     if (mysql_real_query(dbconf->dbconn, CONST_BUF_LEN(sqlquery))) {
165         log_error(r->conf.errh, __FILE__, __LINE__, "%s",
166           mysql_error(dbconf->dbconn));
167         buffer_clear(docroot); /*(reset buffer; no result)*/
168         return -1;
169     }
170 
171     buffer_clear(docroot); /*(reset buffer to store result)*/
172 
173     result = mysql_store_result(dbconf->dbconn);
174     cols = mysql_num_fields(result);
175     row = mysql_fetch_row(result);
176     if (row && cols >= 1) {
177         buffer_copy_string(docroot, row[0]);
178     } /* else no such virtual host */
179 
180     mysql_free_result(result);
181   #if MYSQL_VERSION_ID >= 40100
182     while (0 == mysql_next_result(dbconf->dbconn)) ;
183   #endif
184     return 0;
185 }
186 
187 
188 
189 
190 INIT_FUNC(mod_vhostdb_init) {
191     static http_vhostdb_backend_t http_vhostdb_backend_mysql =
192       { "mysql", mod_vhostdb_mysql_query, NULL };
193     plugin_data *p = calloc(1, sizeof(*p));
194 
195     /* register http_vhostdb_backend_mysql */
196     http_vhostdb_backend_mysql.p_d = p;
197     http_vhostdb_backend_set(&http_vhostdb_backend_mysql);
198 
199     return p;
200 }
201 
202 FREE_FUNC(mod_vhostdb_cleanup) {
203     plugin_data * const p = p_d;
204     if (NULL == p->cvlist) return;
205     /* (init i to 0 if global context; to 1 to skip empty global context) */
206     for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
207         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
208         for (; -1 != cpv->k_id; ++cpv) {
209             if (cpv->vtype != T_CONFIG_LOCAL || NULL == cpv->v.v) continue;
210             switch (cpv->k_id) {
211               case 0: /* vhostdb.<db> */
212                 mod_vhostdb_dbconf_free(cpv->v.v);
213                 break;
214               default:
215                 break;
216             }
217         }
218     }
219 }
220 
221 static void mod_vhostdb_merge_config_cpv(plugin_config * const pconf, const config_plugin_value_t * const cpv) {
222     switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
223       case 0: /* vhostdb.<db> */
224         if (cpv->vtype == T_CONFIG_LOCAL)
225             pconf->vdata = cpv->v.v;
226         break;
227       default:/* should not happen */
228         return;
229     }
230 }
231 
232 static void mod_vhostdb_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv) {
233     do {
234         mod_vhostdb_merge_config_cpv(pconf, cpv);
235     } while ((++cpv)->k_id != -1);
236 }
237 
238 static void mod_vhostdb_patch_config(request_st * const r, plugin_data * const p) {
239     p->conf = p->defaults; /* copy small struct instead of memcpy() */
240     /*memcpy(&p->conf, &p->defaults, sizeof(plugin_config));*/
241     for (int i = 1, used = p->nconfig; i < used; ++i) {
242         if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
243             mod_vhostdb_merge_config(&p->conf,p->cvlist + p->cvlist[i].v.u2[0]);
244     }
245 }
246 
247 SETDEFAULTS_FUNC(mod_vhostdb_set_defaults) {
248     static const config_plugin_keys_t cpk[] = {
249       { CONST_STR_LEN("vhostdb.mysql"),
250         T_CONFIG_ARRAY_KVSTRING,
251         T_CONFIG_SCOPE_CONNECTION }
252      ,{ NULL, 0,
253         T_CONFIG_UNSET,
254         T_CONFIG_SCOPE_UNSET }
255     };
256 
257     plugin_data * const p = p_d;
258     if (!config_plugin_values_init(srv, p, cpk, "mod_vhostdb_mysql"))
259         return HANDLER_ERROR;
260 
261     /* process and validate config directives
262      * (init i to 0 if global context; to 1 to skip empty global context) */
263     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
264         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
265         for (; -1 != cpv->k_id; ++cpv) {
266             switch (cpv->k_id) {
267               case 0: /* vhostdb.<db> */
268                 if (cpv->v.a->used) {
269                     if (0 != mod_vhostdb_dbconf_setup(srv, cpv->v.a, &cpv->v.v))
270                         return HANDLER_ERROR;
271                     if (NULL != cpv->v.v)
272                         cpv->vtype = T_CONFIG_LOCAL;
273                 }
274                 break;
275               default:/* should not happen */
276                 break;
277             }
278         }
279     }
280 
281     /* initialize p->defaults from global config context */
282     if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
283         const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
284         if (-1 != cpv->k_id)
285             mod_vhostdb_merge_config(&p->defaults, cpv);
286     }
287 
288     return HANDLER_GO_ON;
289 }
290 
291 
292 int mod_vhostdb_mysql_plugin_init (plugin *p);
293 int mod_vhostdb_mysql_plugin_init (plugin *p)
294 {
295     p->version          = LIGHTTPD_VERSION_ID;
296     p->name             = "vhostdb_mysql";
297 
298     p->init             = mod_vhostdb_init;
299     p->cleanup          = mod_vhostdb_cleanup;
300     p->set_defaults     = mod_vhostdb_set_defaults;
301 
302     return 0;
303 }
304