1/* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements.  See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License.  You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <ctype.h>
18#include <stdio.h>
19
20#include "apu_config.h"
21#include "apu.h"
22
23#include "apr_pools.h"
24#include "apr_dso.h"
25#include "apr_strings.h"
26#include "apr_hash.h"
27#include "apr_thread_mutex.h"
28#include "apr_lib.h"
29#include "apr_atomic.h"
30
31#include "apu_internal.h"
32#include "apr_dbd_internal.h"
33#include "apr_dbd.h"
34#include "apu_version.h"
35
36static apr_hash_t *drivers = NULL;
37static apr_uint32_t initialised = 0, in_init = 1;
38
39#define CLEANUP_CAST (apr_status_t (*)(void*))
40
41#if APR_HAS_THREADS
42/* deprecated, but required for existing providers.  Existing and new
43 * providers should be refactored to use a provider-specific mutex so
44 * that different providers do not block one another.
45 * In APR 1.3 this is no longer used for dso module loading, and
46 * apu_dso_mutex_[un]lock is used instead.
47 * In APR 2.0 this should become entirely local to libaprutil-2.so and
48 * no longer be exported.
49 */
50static apr_thread_mutex_t* mutex = NULL;
51APU_DECLARE(apr_status_t) apr_dbd_mutex_lock()
52{
53    return apr_thread_mutex_lock(mutex);
54}
55APU_DECLARE(apr_status_t) apr_dbd_mutex_unlock()
56{
57    return apr_thread_mutex_unlock(mutex);
58}
59#else
60APU_DECLARE(apr_status_t) apr_dbd_mutex_lock() {
61    return APR_SUCCESS;
62}
63APU_DECLARE(apr_status_t) apr_dbd_mutex_unlock() {
64    return APR_SUCCESS;
65}
66#endif
67
68#if !APU_DSO_BUILD
69#define DRIVER_LOAD(name,driver,pool) \
70    {   \
71        extern const apr_dbd_driver_t driver; \
72        apr_hash_set(drivers,name,APR_HASH_KEY_STRING,&driver); \
73        if (driver.init) {     \
74            driver.init(pool); \
75        }  \
76    }
77#endif
78
79static apr_status_t apr_dbd_term(void *ptr)
80{
81    /* set drivers to NULL so init can work again */
82    drivers = NULL;
83
84    /* Everything else we need is handled by cleanups registered
85     * when we created mutexes and loaded DSOs
86     */
87    return APR_SUCCESS;
88}
89
90APU_DECLARE(apr_status_t) apr_dbd_init(apr_pool_t *pool)
91{
92    apr_status_t ret = APR_SUCCESS;
93    apr_pool_t *parent;
94
95    if (apr_atomic_inc32(&initialised)) {
96        apr_atomic_set32(&initialised, 1); /* prevent wrap-around */
97
98        while (apr_atomic_read32(&in_init)) /* wait until we get fully inited */
99            ;
100
101        return APR_SUCCESS;
102    }
103
104    /* Top level pool scope, need process-scope lifetime */
105    for (parent = apr_pool_parent_get(pool);
106        parent && parent != pool;
107        parent = apr_pool_parent_get(pool))
108       pool = parent;
109#if APU_DSO_BUILD
110    /* deprecate in 2.0 - permit implicit initialization */
111    apu_dso_init(pool);
112#endif
113
114    drivers = apr_hash_make(pool);
115
116#if APR_HAS_THREADS
117    ret = apr_thread_mutex_create(&mutex, APR_THREAD_MUTEX_DEFAULT, pool);
118    /* This already registers a pool cleanup */
119#endif
120
121#if !APU_DSO_BUILD
122
123    /* Load statically-linked drivers: */
124#if APU_HAVE_MYSQL
125    DRIVER_LOAD("mysql", apr_dbd_mysql_driver, pool);
126#endif
127#if APU_HAVE_PGSQL
128    DRIVER_LOAD("pgsql", apr_dbd_pgsql_driver, pool);
129#endif
130#if APU_HAVE_SQLITE3
131    DRIVER_LOAD("sqlite3", apr_dbd_sqlite3_driver, pool);
132#endif
133#if APU_HAVE_SQLITE2
134    DRIVER_LOAD("sqlite2", apr_dbd_sqlite2_driver, pool);
135#endif
136#if APU_HAVE_ORACLE
137    DRIVER_LOAD("oracle", apr_dbd_oracle_driver, pool);
138#endif
139#if APU_HAVE_ODBC
140    DRIVER_LOAD("odbc", apr_dbd_odbc_driver, pool);
141#endif
142#if APU_HAVE_SOME_OTHER_BACKEND
143    DRIVER_LOAD("firebird", apr_dbd_other_driver, pool);
144#endif
145#endif /* APU_DSO_BUILD */
146
147    apr_pool_cleanup_register(pool, NULL, apr_dbd_term,
148                              apr_pool_cleanup_null);
149
150    apr_atomic_dec32(&in_init);
151
152    return ret;
153}
154
155APU_DECLARE(apr_status_t) apr_dbd_get_driver(apr_pool_t *pool, const char *name,
156                                             const apr_dbd_driver_t **driver)
157{
158#if APU_DSO_BUILD
159    char modname[32];
160    char symname[34];
161    apr_dso_handle_sym_t symbol;
162#endif
163    apr_status_t rv;
164
165#if APU_DSO_BUILD
166    rv = apu_dso_mutex_lock();
167    if (rv) {
168        return rv;
169    }
170#endif
171    *driver = apr_hash_get(drivers, name, APR_HASH_KEY_STRING);
172    if (*driver) {
173#if APU_DSO_BUILD
174        apu_dso_mutex_unlock();
175#endif
176        return APR_SUCCESS;
177    }
178
179#if APU_DSO_BUILD
180    /* The driver DSO must have exactly the same lifetime as the
181     * drivers hash table; ignore the passed-in pool */
182    pool = apr_hash_pool_get(drivers);
183
184#if defined(NETWARE)
185    apr_snprintf(modname, sizeof(modname), "dbd%s.nlm", name);
186#elif defined(WIN32) || defined(__CYGWIN__)
187    apr_snprintf(modname, sizeof(modname),
188                 "apr_dbd_%s-" APU_STRINGIFY(APU_MAJOR_VERSION) ".dll", name);
189#else
190    apr_snprintf(modname, sizeof(modname),
191                 "apr_dbd_%s-" APU_STRINGIFY(APU_MAJOR_VERSION) ".so", name);
192#endif
193    apr_snprintf(symname, sizeof(symname), "apr_dbd_%s_driver", name);
194    rv = apu_dso_load(NULL, &symbol, modname, symname, pool);
195    if (rv == APR_SUCCESS || rv == APR_EINIT) { /* previously loaded?!? */
196        *driver = symbol;
197        name = apr_pstrdup(pool, name);
198        apr_hash_set(drivers, name, APR_HASH_KEY_STRING, *driver);
199        rv = APR_SUCCESS;
200        if ((*driver)->init) {
201            (*driver)->init(pool);
202        }
203    }
204    apu_dso_mutex_unlock();
205
206#else /* not builtin and !APU_DSO_BUILD => not implemented */
207    rv = APR_ENOTIMPL;
208#endif
209
210    return rv;
211}
212
213APU_DECLARE(apr_status_t) apr_dbd_open_ex(const apr_dbd_driver_t *driver,
214                                          apr_pool_t *pool, const char *params,
215                                          apr_dbd_t **handle,
216                                          const char **error)
217{
218    apr_status_t rv;
219    *handle = (driver->open)(pool, params, error);
220    if (*handle == NULL) {
221        return APR_EGENERAL;
222    }
223    rv = apr_dbd_check_conn(driver, pool, *handle);
224    if ((rv != APR_SUCCESS) && (rv != APR_ENOTIMPL)) {
225        /* XXX: rv is APR error code, but apr_dbd_error() takes int! */
226        if (error) {
227            *error = apr_dbd_error(driver, *handle, rv);
228        }
229        apr_dbd_close(driver, *handle);
230        return APR_EGENERAL;
231    }
232    return APR_SUCCESS;
233}
234
235APU_DECLARE(apr_status_t) apr_dbd_open(const apr_dbd_driver_t *driver,
236                                       apr_pool_t *pool, const char *params,
237                                       apr_dbd_t **handle)
238{
239    return apr_dbd_open_ex(driver,pool,params,handle,NULL);
240}
241
242APU_DECLARE(int) apr_dbd_transaction_start(const apr_dbd_driver_t *driver,
243                                           apr_pool_t *pool, apr_dbd_t *handle,
244                                           apr_dbd_transaction_t **trans)
245{
246    int ret = driver->start_transaction(pool, handle, trans);
247    if (*trans) {
248        apr_pool_cleanup_register(pool, *trans,
249                                  CLEANUP_CAST driver->end_transaction,
250                                  apr_pool_cleanup_null);
251    }
252    return ret;
253}
254
255APU_DECLARE(int) apr_dbd_transaction_end(const apr_dbd_driver_t *driver,
256                                         apr_pool_t *pool,
257                                         apr_dbd_transaction_t *trans)
258{
259    apr_pool_cleanup_kill(pool, trans, CLEANUP_CAST driver->end_transaction);
260    return driver->end_transaction(trans);
261}
262
263APU_DECLARE(int) apr_dbd_transaction_mode_get(const apr_dbd_driver_t *driver,
264                                              apr_dbd_transaction_t *trans)
265{
266    return driver->transaction_mode_get(trans);
267}
268
269APU_DECLARE(int) apr_dbd_transaction_mode_set(const apr_dbd_driver_t *driver,
270                                              apr_dbd_transaction_t *trans,
271                                              int mode)
272{
273    return driver->transaction_mode_set(trans, mode);
274}
275
276APU_DECLARE(apr_status_t) apr_dbd_close(const apr_dbd_driver_t *driver,
277                                        apr_dbd_t *handle)
278{
279    return driver->close(handle);
280}
281
282APU_DECLARE(const char*) apr_dbd_name(const apr_dbd_driver_t *driver)
283{
284    return driver->name;
285}
286
287APU_DECLARE(void*) apr_dbd_native_handle(const apr_dbd_driver_t *driver,
288                                         apr_dbd_t *handle)
289{
290    return driver->native_handle(handle);
291}
292
293APU_DECLARE(int) apr_dbd_check_conn(const apr_dbd_driver_t *driver,
294                                    apr_pool_t *pool,
295                                    apr_dbd_t *handle)
296{
297    return driver->check_conn(pool, handle);
298}
299
300APU_DECLARE(int) apr_dbd_set_dbname(const apr_dbd_driver_t *driver,
301                                    apr_pool_t *pool,
302                                    apr_dbd_t *handle, const char *name)
303{
304    return driver->set_dbname(pool,handle,name);
305}
306
307APU_DECLARE(int) apr_dbd_query(const apr_dbd_driver_t *driver,
308                               apr_dbd_t *handle,
309                               int *nrows, const char *statement)
310{
311    return driver->query(handle,nrows,statement);
312}
313
314APU_DECLARE(int) apr_dbd_select(const apr_dbd_driver_t *driver,
315                                apr_pool_t *pool,
316                                apr_dbd_t *handle, apr_dbd_results_t **res,
317                                const char *statement, int random)
318{
319    return driver->select(pool,handle,res,statement,random);
320}
321
322APU_DECLARE(int) apr_dbd_num_cols(const apr_dbd_driver_t *driver,
323                                  apr_dbd_results_t *res)
324{
325    return driver->num_cols(res);
326}
327
328APU_DECLARE(int) apr_dbd_num_tuples(const apr_dbd_driver_t *driver,
329                                    apr_dbd_results_t *res)
330{
331    return driver->num_tuples(res);
332}
333
334APU_DECLARE(int) apr_dbd_get_row(const apr_dbd_driver_t *driver,
335                                 apr_pool_t *pool,
336                                 apr_dbd_results_t *res, apr_dbd_row_t **row,
337                                 int rownum)
338{
339    return driver->get_row(pool,res,row,rownum);
340}
341
342APU_DECLARE(const char*) apr_dbd_get_entry(const apr_dbd_driver_t *driver,
343                                           apr_dbd_row_t *row, int col)
344{
345    return driver->get_entry(row,col);
346}
347
348APU_DECLARE(const char*) apr_dbd_get_name(const apr_dbd_driver_t *driver,
349                                          apr_dbd_results_t *res, int col)
350{
351    return driver->get_name(res,col);
352}
353
354APU_DECLARE(const char*) apr_dbd_error(const apr_dbd_driver_t *driver,
355                                       apr_dbd_t *handle, int errnum)
356{
357    return driver->error(handle,errnum);
358}
359
360APU_DECLARE(const char*) apr_dbd_escape(const apr_dbd_driver_t *driver,
361                                        apr_pool_t *pool, const char *string,
362                                        apr_dbd_t *handle)
363{
364    return driver->escape(pool,string,handle);
365}
366
367APU_DECLARE(int) apr_dbd_prepare(const apr_dbd_driver_t *driver,
368                                 apr_pool_t *pool,
369                                 apr_dbd_t *handle, const char *query,
370                                 const char *label,
371                                 apr_dbd_prepared_t **statement)
372{
373    size_t qlen;
374    int i, nargs = 0, nvals = 0;
375    char *p, *pq;
376    const char *q;
377    apr_dbd_type_e *t;
378
379    if (!driver->pformat) {
380        return APR_ENOTIMPL;
381    }
382
383    /* find the number of parameters in the query */
384    for (q = query; *q; q++) {
385        if (q[0] == '%') {
386            if (apr_isalpha(q[1])) {
387                nargs++;
388            } else if (q[1] == '%') {
389                q++;
390            }
391        }
392    }
393    nvals = nargs;
394
395    qlen = strlen(query) +
396           nargs * (strlen(driver->pformat) + sizeof(nargs) * 3 + 2) + 1;
397    pq = apr_palloc(pool, qlen);
398    t = apr_pcalloc(pool, sizeof(*t) * nargs);
399
400    for (p = pq, q = query, i = 0; *q; q++) {
401        if (q[0] == '%') {
402            if (apr_isalpha(q[1])) {
403                switch (q[1]) {
404                case 'd': t[i] = APR_DBD_TYPE_INT;   break;
405                case 'u': t[i] = APR_DBD_TYPE_UINT;  break;
406                case 'f': t[i] = APR_DBD_TYPE_FLOAT; break;
407                case 'h':
408                    switch (q[2]) {
409                    case 'h':
410                        switch (q[3]){
411                        case 'd': t[i] = APR_DBD_TYPE_TINY;  q += 2; break;
412                        case 'u': t[i] = APR_DBD_TYPE_UTINY; q += 2; break;
413                        }
414                        break;
415                    case 'd': t[i] = APR_DBD_TYPE_SHORT;  q++; break;
416                    case 'u': t[i] = APR_DBD_TYPE_USHORT; q++; break;
417                    }
418                    break;
419                case 'l':
420                    switch (q[2]) {
421                    case 'l':
422                        switch (q[3]){
423                        case 'd': t[i] = APR_DBD_TYPE_LONGLONG;  q += 2; break;
424                        case 'u': t[i] = APR_DBD_TYPE_ULONGLONG; q += 2; break;
425                        }
426                        break;
427                    case 'd': t[i] = APR_DBD_TYPE_LONG;   q++; break;
428                    case 'u': t[i] = APR_DBD_TYPE_ULONG;  q++; break;
429                    case 'f': t[i] = APR_DBD_TYPE_DOUBLE; q++; break;
430                    }
431                    break;
432                case 'p':
433                    if (q[2] == 'D') {
434                        switch (q[3]) {
435                        case 't': t[i] = APR_DBD_TYPE_TEXT;       q += 2; break;
436                        case 'i': t[i] = APR_DBD_TYPE_TIME;       q += 2; break;
437                        case 'd': t[i] = APR_DBD_TYPE_DATE;       q += 2; break;
438                        case 'a': t[i] = APR_DBD_TYPE_DATETIME;   q += 2; break;
439                        case 's': t[i] = APR_DBD_TYPE_TIMESTAMP;  q += 2; break;
440                        case 'z': t[i] = APR_DBD_TYPE_ZTIMESTAMP; q += 2; break;
441                        case 'b': t[i] = APR_DBD_TYPE_BLOB;       q += 2; break;
442                        case 'c': t[i] = APR_DBD_TYPE_CLOB;       q += 2; break;
443                        case 'n': t[i] = APR_DBD_TYPE_NULL;       q += 2; break;
444                        }
445                    }
446                    break;
447                }
448                q++;
449
450                switch (t[i]) {
451                case APR_DBD_TYPE_NONE: /* by default, we expect strings */
452                    t[i] = APR_DBD_TYPE_STRING;
453                    break;
454                case APR_DBD_TYPE_BLOB:
455                case APR_DBD_TYPE_CLOB: /* three (3) more values passed in */
456                    nvals += 3;
457                    break;
458                default:
459                    break;
460                }
461
462                /* insert database specific parameter reference */
463                p += apr_snprintf(p, qlen - (p - pq), driver->pformat, ++i);
464            } else if (q[1] == '%') { /* reduce %% to % */
465                *p++ = *q++;
466            } else {
467                *p++ = *q;
468            }
469        } else {
470            *p++ = *q;
471        }
472    }
473    *p = '\0';
474
475    return driver->prepare(pool,handle,pq,label,nargs,nvals,t,statement);
476}
477
478APU_DECLARE(int) apr_dbd_pquery(const apr_dbd_driver_t *driver,
479                                apr_pool_t *pool,
480                                apr_dbd_t *handle, int *nrows,
481                                apr_dbd_prepared_t *statement,
482                                int nargs, const char **args)
483{
484    return driver->pquery(pool,handle,nrows,statement,args);
485}
486
487APU_DECLARE(int) apr_dbd_pselect(const apr_dbd_driver_t *driver,
488                                 apr_pool_t *pool,
489                                 apr_dbd_t *handle, apr_dbd_results_t **res,
490                                 apr_dbd_prepared_t *statement, int random,
491                                 int nargs, const char **args)
492{
493    return driver->pselect(pool,handle,res,statement,random,args);
494}
495
496APU_DECLARE_NONSTD(int) apr_dbd_pvquery(const apr_dbd_driver_t *driver,
497                                        apr_pool_t *pool,
498                                        apr_dbd_t *handle, int *nrows,
499                                        apr_dbd_prepared_t *statement, ...)
500{
501    int ret;
502    va_list args;
503    va_start(args, statement);
504    ret = driver->pvquery(pool,handle,nrows,statement,args);
505    va_end(args);
506    return ret;
507}
508
509APU_DECLARE_NONSTD(int) apr_dbd_pvselect(const apr_dbd_driver_t *driver,
510                                         apr_pool_t *pool, apr_dbd_t *handle,
511                                         apr_dbd_results_t **res,
512                                         apr_dbd_prepared_t *statement,
513                                         int random, ...)
514{
515    int ret;
516    va_list args;
517    va_start(args, random);
518    ret = driver->pvselect(pool,handle,res,statement,random,args);
519    va_end(args);
520    return ret;
521}
522
523APU_DECLARE(int) apr_dbd_pbquery(const apr_dbd_driver_t *driver,
524                                 apr_pool_t *pool,
525                                 apr_dbd_t *handle, int *nrows,
526                                 apr_dbd_prepared_t *statement,
527                                 const void **args)
528{
529    return driver->pbquery(pool,handle,nrows,statement,args);
530}
531
532APU_DECLARE(int) apr_dbd_pbselect(const apr_dbd_driver_t *driver,
533                                  apr_pool_t *pool,
534                                  apr_dbd_t *handle, apr_dbd_results_t **res,
535                                  apr_dbd_prepared_t *statement, int random,
536                                  const void **args)
537{
538    return driver->pbselect(pool,handle,res,statement,random,args);
539}
540
541APU_DECLARE_NONSTD(int) apr_dbd_pvbquery(const apr_dbd_driver_t *driver,
542                                         apr_pool_t *pool,
543                                         apr_dbd_t *handle, int *nrows,
544                                         apr_dbd_prepared_t *statement, ...)
545{
546    int ret;
547    va_list args;
548    va_start(args, statement);
549    ret = driver->pvbquery(pool,handle,nrows,statement,args);
550    va_end(args);
551    return ret;
552}
553
554APU_DECLARE_NONSTD(int) apr_dbd_pvbselect(const apr_dbd_driver_t *driver,
555                                          apr_pool_t *pool, apr_dbd_t *handle,
556                                          apr_dbd_results_t **res,
557                                          apr_dbd_prepared_t *statement,
558                                          int random, ...)
559{
560    int ret;
561    va_list args;
562    va_start(args, random);
563    ret = driver->pvbselect(pool,handle,res,statement,random,args);
564    va_end(args);
565    return ret;
566}
567
568APU_DECLARE(apr_status_t) apr_dbd_datum_get(const apr_dbd_driver_t *driver,
569                                            apr_dbd_row_t *row, int col,
570                                            apr_dbd_type_e type, void *data)
571{
572    return driver->datum_get(row,col,type,data);
573}
574