Project

General

Profile

mod_mysql_vhost.c

tronox@hotmail.com, 2013-09-09 00:25

 
1
#include <unistd.h>
2
#include <stdio.h>
3
// end added by Shinrai
4
#include <string.h>
5
#include <stdlib.h>
6
// end added by Shinrai
7
#include <errno.h>
8
#include <fcntl.h>
9
#include <strings.h>
10

    
11
#ifdef HAVE_CONFIG_H
12
#include "config.h"
13
#endif
14

    
15
#ifdef HAVE_MYSQL
16
#include <mysql.h>
17
#endif
18

    
19
#include "plugin.h"
20
#include "log.h"
21

    
22
#include "stat_cache.h"
23
#ifdef DEBUG_MOD_MYSQL_VHOST
24
#define DEBUG
25
#endif
26

    
27
// added by Shinrai
28
char *
29
str_replace ( const char *string, const char *substr, const char *replacement ){
30
  char *tok = NULL;
31
  char *newstr = NULL;
32
  char *oldstr = NULL;
33
  char *head = NULL;
34
 
35
  /* if either substr or replacement is NULL, duplicate string a let caller handle it */
36
  if ( substr == NULL || replacement == NULL ) return strdup (string);
37
  newstr = strdup (string);
38
  head = newstr;
39
  while ( (tok = strstr ( head, substr ))){
40
    oldstr = newstr;
41
    newstr = malloc ( strlen ( oldstr ) - strlen ( substr ) + strlen ( replacement ) + 1 );
42
    /*failed to alloc mem, free old string and return NULL */
43
    if ( newstr == NULL ){
44
      free (oldstr);
45
      return NULL;
46
    }
47
    memcpy ( newstr, oldstr, tok - oldstr );
48
    memcpy ( newstr + (tok - oldstr), replacement, strlen ( replacement ) );
49
    memcpy ( newstr + (tok - oldstr) + strlen( replacement ), tok + strlen ( substr ), strlen ( oldstr ) - strlen ( substr ) - ( tok - oldstr ) );
50
    memset ( newstr + strlen ( oldstr ) - strlen ( substr ) + strlen ( replacement ) , 0, 1 );
51
    /* move back head right after the last replacement */
52
    head = newstr + (tok - oldstr) + strlen( replacement );
53
    free (oldstr);
54
  }
55
  return newstr;
56
}
57
// end added by Shinrai
58
        
59
/*
60
 * Plugin for lighttpd to use MySQL
61
 *   for domain to directory lookups,
62
 *   i.e virtual hosts (vhosts).
63
 *
64
 * Optionally sets fcgi_offset and fcgi_arg
65
 *   in preparation for fcgi.c to handle
66
 *   per-user fcgi chroot jails.
67
 *
68
 * /ada@riksnet.se 2004-12-06
69
 */
70

    
71
#ifdef HAVE_MYSQL
72
typedef struct {
73
        MYSQL         *mysql;
74

    
75
        buffer  *mydb;
76
        buffer  *myuser;
77
        buffer  *mypass;
78
        buffer  *mysock;
79

    
80
        buffer  *hostname;
81
        unsigned short port;
82

    
83
        buffer  *mysql_pre;
84
        buffer  *mysql_post;
85
} plugin_config;
86

    
87
/* global plugin data */
88
typedef struct {
89
        PLUGIN_DATA;
90

    
91
        buffer         *tmp_buf;
92

    
93
        plugin_config **config_storage;
94

    
95
        plugin_config conf;
96
} plugin_data;
97

    
98
/* per connection plugin data */
99
typedef struct {
100
        buffer        *server_name;
101
        buffer        *document_root;
102
        buffer        *fcgi_arg;
103
        unsigned fcgi_offset;
104
} plugin_connection_data;
105

    
106
/* init the plugin data */
107
INIT_FUNC(mod_mysql_vhost_init) {
108
        plugin_data *p;
109

    
110
        p = calloc(1, sizeof(*p));
111

    
112
        p->tmp_buf = buffer_init();
113

    
114
        return p;
115
}
116

    
117
/* cleanup the plugin data */
118
SERVER_FUNC(mod_mysql_vhost_cleanup) {
119
        plugin_data *p = p_d;
120

    
121
        UNUSED(srv);
122

    
123
#ifdef DEBUG
124
        log_error_write(srv, __FILE__, __LINE__, "ss",
125
                "mod_mysql_vhost_cleanup", p ? "yes" : "NO");
126
#endif
127
        if (!p) return HANDLER_GO_ON;
128

    
129
        if (p->config_storage) {
130
                size_t i;
131
                for (i = 0; i < srv->config_context->used; i++) {
132
                        plugin_config *s = p->config_storage[i];
133

    
134
                        if (!s) continue;
135

    
136
                        mysql_close(s->mysql);
137

    
138
                        buffer_free(s->mydb);
139
                        buffer_free(s->myuser);
140
                        buffer_free(s->mypass);
141
                        buffer_free(s->mysock);
142
                        buffer_free(s->mysql_pre);
143
                        buffer_free(s->mysql_post);
144
                        buffer_free(s->hostname);
145

    
146
                        free(s);
147
                }
148
                free(p->config_storage);
149
        }
150
        buffer_free(p->tmp_buf);
151

    
152
        free(p);
153

    
154
        return HANDLER_GO_ON;
155
}
156

    
157
/* handle the plugin per connection data */
158
static void* mod_mysql_vhost_connection_data(server *srv, connection *con, void *p_d)
159
{
160
        plugin_data *p = p_d;
161
        plugin_connection_data *c = con->plugin_ctx[p->id];
162

    
163
        UNUSED(srv);
164

    
165
#ifdef DEBUG
166
        log_error_write(srv, __FILE__, __LINE__, "ss",
167
                "mod_mysql_connection_data", c ? "old" : "NEW");
168
#endif
169

    
170
        if (c) return c;
171
        c = calloc(1, sizeof(*c));
172

    
173
        c->server_name = buffer_init();
174
        c->document_root = buffer_init();
175
        c->fcgi_arg = buffer_init();
176
        c->fcgi_offset = 0;
177

    
178
        return con->plugin_ctx[p->id] = c;
179
}
180

    
181
/* destroy the plugin per connection data */
182
CONNECTION_FUNC(mod_mysql_vhost_handle_connection_close) {
183
        plugin_data *p = p_d;
184
        plugin_connection_data *c = con->plugin_ctx[p->id];
185

    
186
        UNUSED(srv);
187

    
188
#ifdef DEBUG
189
        log_error_write(srv, __FILE__, __LINE__, "ss",
190
                "mod_mysql_vhost_handle_connection_close", c ? "yes" : "NO");
191
#endif
192

    
193
        if (!c) return HANDLER_GO_ON;
194

    
195
        buffer_free(c->server_name);
196
        buffer_free(c->document_root);
197
        buffer_free(c->fcgi_arg);
198
        c->fcgi_offset = 0;
199

    
200
        free(c);
201

    
202
        con->plugin_ctx[p->id] = NULL;
203
        return HANDLER_GO_ON;
204
}
205

    
206
/* set configuration values */
207
SERVER_FUNC(mod_mysql_vhost_set_defaults) {
208
        plugin_data *p = p_d;
209

    
210
        // char *qmark;
211
        size_t i = 0;
212

    
213
        config_values_t cv[] = {
214
                { "mysql-vhost.db",        NULL, T_CONFIG_STRING,         T_CONFIG_SCOPE_SERVER },
215
                { "mysql-vhost.user",        NULL, T_CONFIG_STRING,         T_CONFIG_SCOPE_SERVER },
216
                { "mysql-vhost.pass",        NULL, T_CONFIG_STRING,         T_CONFIG_SCOPE_SERVER },
217
                { "mysql-vhost.sock",        NULL, T_CONFIG_STRING,         T_CONFIG_SCOPE_SERVER },
218
                { "mysql-vhost.sql",        NULL, T_CONFIG_STRING,         T_CONFIG_SCOPE_SERVER },
219
                { "mysql-vhost.hostname", NULL, T_CONFIG_STRING,T_CONFIG_SCOPE_SERVER },
220
                { "mysql-vhost.port",   NULL, T_CONFIG_SHORT,   T_CONFIG_SCOPE_SERVER },
221
                { NULL,                        NULL, T_CONFIG_UNSET,        T_CONFIG_SCOPE_UNSET }
222
        };
223

    
224
        p->config_storage = calloc(1, srv->config_context->used * sizeof(specific_config *));
225

    
226
        for (i = 0; i < srv->config_context->used; i++) {
227
                plugin_config *s;
228
                buffer *sel;
229

    
230

    
231
                s = calloc(1, sizeof(plugin_config));
232
                s->mydb = buffer_init();
233
                s->myuser = buffer_init();
234
                s->mypass = buffer_init();
235
                s->mysock = buffer_init();
236
                s->hostname = buffer_init();
237
                s->port   = 0;               /* default port for mysql */
238
                sel = buffer_init();
239
                s->mysql = NULL;
240

    
241
                s->mysql_pre = buffer_init();
242
                s->mysql_post = buffer_init();
243

    
244
                cv[0].destination = s->mydb;
245
                cv[1].destination = s->myuser;
246
                cv[2].destination = s->mypass;
247
                cv[3].destination = s->mysock;
248
                cv[4].destination = sel;
249
                cv[5].destination = s->hostname;
250
                cv[6].destination = &(s->port);
251

    
252
                p->config_storage[i] = s;
253

    
254
                if (config_insert_values_global(srv,
255
                        ((data_config *)srv->config_context->data[i])->value,
256
                        cv)) return HANDLER_ERROR;
257

    
258
                s->mysql_pre = buffer_init();
259
                s->mysql_post = buffer_init();
260

    
261
                // Old code from Lighttpd developers
262
                // if (sel->used && (qmark = strchr(sel->ptr, '?'))) {
263
                        // *qmark = '\0';
264
                        // buffer_copy_string(s->mysql_pre, sel->ptr);
265
                        // buffer_copy_string(s->mysql_post, qmark+1);
266
                // } else {
267
                        // buffer_copy_string_buffer(s->mysql_pre, sel);
268
                // }
269
                // added by Shinrai
270
                buffer_copy_string_buffer(s->mysql_pre, sel);
271
                // end added by Shinrai
272
                
273
                /* required:
274
                 * - username
275
                 * - database
276
                 *
277
                 * optional:
278
                 * - password, default: empty
279
                 * - socket, default: mysql default
280
                 * - hostname, if set overrides socket
281
                 * - port, default: 3306
282
                 */
283

    
284
                /* all have to be set */
285
                if (!(buffer_is_empty(s->myuser) ||
286
                      buffer_is_empty(s->mydb))) {
287
                        my_bool reconnect = 1;
288

    
289
                        if (NULL == (s->mysql = mysql_init(NULL))) {
290
                                log_error_write(srv, __FILE__, __LINE__, "s", "mysql_init() failed, exiting...");
291

    
292
                                return HANDLER_ERROR;
293
                        }
294

    
295
#if MYSQL_VERSION_ID >= 50013
296
                        /* in mysql versions above 5.0.3 the reconnect flag is off by default */
297
                        mysql_options(s->mysql, MYSQL_OPT_RECONNECT, &reconnect);
298
#endif
299

    
300
#define FOO(x) (s->x->used ? s->x->ptr : NULL)
301

    
302
#if MYSQL_VERSION_ID >= 40100
303
                        /* CLIENT_MULTI_STATEMENTS first appeared in 4.1 */ 
304
                        if (!mysql_real_connect(s->mysql, FOO(hostname), FOO(myuser), FOO(mypass),
305
                                                FOO(mydb), s->port, FOO(mysock), CLIENT_MULTI_STATEMENTS)) {
306
#else
307
                        if (!mysql_real_connect(s->mysql, FOO(hostname), FOO(myuser), FOO(mypass),
308
                                                FOO(mydb), s->port, FOO(mysock), 0)) {
309
#endif
310
                                log_error_write(srv, __FILE__, __LINE__, "s", mysql_error(s->mysql));
311

    
312
                                return HANDLER_ERROR;
313
                        }
314
#undef FOO
315

    
316
#if 0
317
                        /* set close_on_exec for mysql the hard way */
318
                        /* Note: this only works as it is done during startup, */
319
                        /* otherwise we cannot be sure that mysql is fd i-1 */
320
                        { int fd;
321
                        if (-1 != (fd = open("/dev/null", 0))) {
322
                                close(fd);
323
#ifdef FD_CLOEXEC
324
                                fcntl(fd-1, F_SETFD, FD_CLOEXEC);
325
#endif
326
                        } }
327
#else
328
#ifdef FD_CLOEXEC
329
                        fcntl(s->mysql->net.fd, F_SETFD, FD_CLOEXEC);
330
#endif
331
#endif
332
                }
333
        }
334

    
335
        return HANDLER_GO_ON;
336
}
337

    
338
#define PATCH(x) \
339
        p->conf.x = s->x;
340
static int mod_mysql_vhost_patch_connection(server *srv, connection *con, plugin_data *p) {
341
        size_t i, j;
342
        plugin_config *s = p->config_storage[0];
343

    
344
        PATCH(mysql_pre);
345
        PATCH(mysql_post);
346
#ifdef HAVE_MYSQL
347
        PATCH(mysql);
348
#endif
349

    
350
        /* skip the first, the global context */
351
        for (i = 1; i < srv->config_context->used; i++) {
352
                data_config *dc = (data_config *)srv->config_context->data[i];
353
                s = p->config_storage[i];
354

    
355
                /* condition didn't match */
356
                if (!config_check_cond(srv, con, dc)) continue;
357

    
358
                /* merge config */
359
                for (j = 0; j < dc->value->used; j++) {
360
                        data_unset *du = dc->value->data[j];
361

    
362
                        if (buffer_is_equal_string(du->key, CONST_STR_LEN("mysql-vhost.sql"))) {
363
                                PATCH(mysql_pre);
364
                                PATCH(mysql_post);
365
                        }
366
                }
367

    
368
                if (s->mysql) {
369
                        PATCH(mysql);
370
                }
371
        }
372

    
373
        return 0;
374
}
375
#undef PATCH
376

    
377

    
378
/* handle document root request */
379
CONNECTION_FUNC(mod_mysql_vhost_handle_docroot) {
380
        plugin_data *p = p_d;
381
        plugin_connection_data *c;
382
        stat_cache_entry *sce;
383

    
384
        unsigned  cols;
385
        MYSQL_ROW row;
386
        MYSQL_RES *result = NULL;
387

    
388
        /* no host specified? */
389
        if (!con->uri.authority->used) return HANDLER_GO_ON;
390

    
391
        mod_mysql_vhost_patch_connection(srv, con, p);
392

    
393
        if (!p->conf.mysql) return HANDLER_GO_ON;
394

    
395
        /* sets up connection data if not done yet */
396
        c = mod_mysql_vhost_connection_data(srv, con, p_d);
397

    
398
        /* check if cached this connection */
399
        if (c->server_name->used && /* con->uri.authority->used && */
400
            buffer_is_equal(c->server_name, con->uri.authority)) goto GO_ON;
401

    
402
        /* build and run SQL query */
403
        /* Old Lttpd Developed Code
404
        buffer_copy_string_buffer(p->tmp_buf, p->conf.mysql_pre);
405
        if (p->conf.mysql_post->used) {
406
                buffer_append_string_buffer(p->tmp_buf, con->uri.authority);
407
                buffer_append_string_buffer(p->tmp_buf, p->conf.mysql_post);
408
        }
409
        */
410
        // added by Shinrai
411
        // char *basestring = "";
412
// #ifdef HAVE_MYSQL_REAL_ESCAPE_STRING
413
        // char *sqlquery = mysql_real_escape_string(p->conf.mysql, basestring, con->uri.authority->ptr, strlen(con->uri.authority->ptr));
414
// #else
415
        // char *sqlquery = mysql_escape_string(basestring, con->uri.authority->ptr, strlen(con->uri.authority->ptr));
416
// #endif
417
        buffer_copy_string(p->tmp_buf, str_replace(p->conf.mysql_pre->ptr,"?",con->uri.authority->ptr));
418
        // end added by Shinrai
419
        
420
           if (mysql_query(p->conf.mysql, p->tmp_buf->ptr)) {
421
                log_error_write(srv, __FILE__, __LINE__, "s", mysql_error(p->conf.mysql));
422
                goto ERR500;
423
        }
424
        result = mysql_store_result(p->conf.mysql);
425
        cols = mysql_num_fields(result);
426
        row = mysql_fetch_row(result);
427
        // Check for null value, seems to crash.
428
        // if ((!row || row[0] == NULL) || cols < 1) {
429
        if (!row || cols < 1) {
430
                /* no such virtual host */
431
                mysql_free_result(result);
432
#if MYSQL_VERSION_ID >= 40100
433
                while (mysql_next_result(p->conf.mysql) == 0);
434
#endif
435
                return HANDLER_GO_ON;
436
        }
437

    
438
        /* sanity check that really is a directory */
439
        buffer_copy_string(p->tmp_buf, row[0]);
440
        BUFFER_APPEND_SLASH(p->tmp_buf);
441

    
442
        if (HANDLER_ERROR == stat_cache_get_entry(srv, con, p->tmp_buf, &sce)) {
443
                log_error_write(srv, __FILE__, __LINE__, "sb", strerror(errno), p->tmp_buf);
444
                goto ERR500;
445
        }
446
        if (!S_ISDIR(sce->st.st_mode)) {
447
                log_error_write(srv, __FILE__, __LINE__, "sb", "Not a directory", p->tmp_buf);
448
                goto ERR500;
449
        }
450

    
451
        /* cache the data */
452
        buffer_copy_string_buffer(c->server_name, con->uri.authority);
453
        buffer_copy_string_buffer(c->document_root, p->tmp_buf);
454

    
455
        /* fcgi_offset and fcgi_arg are optional */
456
        if (cols > 1 && row[1]) {
457
                c->fcgi_offset = atoi(row[1]);
458

    
459
                if (cols > 2 && row[2]) {
460
                        buffer_copy_string(c->fcgi_arg, row[2]);
461
                } else {
462
                        c->fcgi_arg->used = 0;
463
                }
464
        } else {
465
                c->fcgi_offset = c->fcgi_arg->used = 0;
466
        }
467
        mysql_free_result(result);
468
#if MYSQL_VERSION_ID >= 40100
469
        while (mysql_next_result(p->conf.mysql) == 0);
470
#endif
471

    
472
        /* fix virtual server and docroot */
473
GO_ON:        buffer_copy_string_buffer(con->server_name, c->server_name);
474
        buffer_copy_string_buffer(con->physical.doc_root, c->document_root);
475

    
476
#ifdef DEBUG
477
        log_error_write(srv, __FILE__, __LINE__, "sbbdb",
478
                result ? "NOT CACHED" : "cached",
479
                con->server_name, con->physical.doc_root,
480
                c->fcgi_offset, c->fcgi_arg);
481
#endif
482
        return HANDLER_GO_ON;
483

    
484
ERR500:        if (result) mysql_free_result(result);
485
#if MYSQL_VERSION_ID >= 40100
486
        while (mysql_next_result(p->conf.mysql) == 0);
487
#endif
488
        con->http_status = 500; /* Internal Error */
489
        con->mode = DIRECT;
490
        return HANDLER_FINISHED;
491
}
492

    
493
/* this function is called at dlopen() time and inits the callbacks */
494
int mod_mysql_vhost_plugin_init(plugin *p);
495
int mod_mysql_vhost_plugin_init(plugin *p) {
496
        p->version        = LIGHTTPD_VERSION_ID;
497
        p->name           = buffer_init_string("mysql_vhost");
498

    
499
        p->init           = mod_mysql_vhost_init;
500
        p->cleanup        = mod_mysql_vhost_cleanup;
501
        p->connection_reset = mod_mysql_vhost_handle_connection_close;
502

    
503
        p->set_defaults   = mod_mysql_vhost_set_defaults;
504
        p->handle_docroot = mod_mysql_vhost_handle_docroot;
505

    
506
        return 0;
507
}
508
#else
509
/* we don't have mysql support, this plugin does nothing */
510
int mod_mysql_vhost_plugin_init(plugin *p);
511
int mod_mysql_vhost_plugin_init(plugin *p) {
512
        p->version     = LIGHTTPD_VERSION_ID;
513
        p->name        = buffer_init_string("mysql_vhost");
514

    
515
        return 0;
516
}
517
#endif