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 = pool;  parent; parent = apr_pool_parent_get(pool))
106         pool = parent;
107#if APU_DSO_BUILD
108    /* deprecate in 2.0 - permit implicit initialization */
109    apu_dso_init(pool);
110#endif
111
112    drivers = apr_hash_make(pool);
113
114#if APR_HAS_THREADS
115    ret = apr_thread_mutex_create(&mutex, APR_THREAD_MUTEX_DEFAULT, pool);
116    /* This already registers a pool cleanup */
117#endif
118
119#if !APU_DSO_BUILD
120
121    /* Load statically-linked drivers: */
122#if APU_HAVE_MYSQL
123    DRIVER_LOAD("mysql", apr_dbd_mysql_driver, pool);
124#endif
125#if APU_HAVE_PGSQL
126    DRIVER_LOAD("pgsql", apr_dbd_pgsql_driver, pool);
127#endif
128#if APU_HAVE_SQLITE3
129    DRIVER_LOAD("sqlite3", apr_dbd_sqlite3_driver, pool);
130#endif
131#if APU_HAVE_SQLITE2
132    DRIVER_LOAD("sqlite2", apr_dbd_sqlite2_driver, pool);
133#endif
134#if APU_HAVE_ORACLE
135    DRIVER_LOAD("oracle", apr_dbd_oracle_driver, pool);
136#endif
137#if APU_HAVE_FREETDS
138    DRIVER_LOAD("freetds", apr_dbd_freetds_driver, pool);
139#endif
140#if APU_HAVE_ODBC
141    DRIVER_LOAD("odbc", apr_dbd_odbc_driver, pool);
142#endif
143#if APU_HAVE_SOME_OTHER_BACKEND
144    DRIVER_LOAD("firebird", apr_dbd_other_driver, pool);
145#endif
146#endif /* APU_DSO_BUILD */
147
148    apr_pool_cleanup_register(pool, NULL, apr_dbd_term,
149                              apr_pool_cleanup_null);
150
151    apr_atomic_dec32(&in_init);
152
153    return ret;
154}
155
156APU_DECLARE(apr_status_t) apr_dbd_get_driver(apr_pool_t *pool, const char *name,
157                                             const apr_dbd_driver_t **driver)
158{
159#if APU_DSO_BUILD
160    char modname[32];
161    char symname[34];
162    apr_dso_handle_sym_t symbol;
163#endif
164    apr_status_t rv;
165
166#if APU_DSO_BUILD
167    rv = apu_dso_mutex_lock();
168    if (rv) {
169        return rv;
170    }
171#endif
172    *driver = apr_hash_get(drivers, name, APR_HASH_KEY_STRING);
173    if (*driver) {
174#if APU_DSO_BUILD
175        apu_dso_mutex_unlock();
176#endif
177        return APR_SUCCESS;
178    }
179
180#if APU_DSO_BUILD
181    /* The driver DSO must have exactly the same lifetime as the
182     * drivers hash table; ignore the passed-in pool */
183    pool = apr_hash_pool_get(drivers);
184
185#if defined(NETWARE)
186    apr_snprintf(modname, sizeof(modname), "dbd%s.nlm", name);
187#elif defined(WIN32)
188    apr_snprintf(modname, sizeof(modname),
189                 "apr_dbd_%s-" APU_STRINGIFY(APU_MAJOR_VERSION) ".dll", name);
190#else
191    apr_snprintf(modname, sizeof(modname),
192                 "apr_dbd_%s-" APU_STRINGIFY(APU_MAJOR_VERSION) ".so", name);
193#endif
194    apr_snprintf(symname, sizeof(symname), "apr_dbd_%s_driver", name);
195    rv = apu_dso_load(&symbol, modname, symname, pool);
196    if (rv == APR_SUCCESS || rv == APR_EINIT) { /* previously loaded?!? */
197        *driver = symbol;
198        name = apr_pstrdup(pool, name);
199        apr_hash_set(drivers, name, APR_HASH_KEY_STRING, *driver);
200        rv = APR_SUCCESS;
201        if ((*driver)->init) {
202            (*driver)->init(pool);
203        }
204        goto unlock;
205    }
206    name = apr_pstrdup(pool, name);
207    apr_hash_set(drivers, name, APR_HASH_KEY_STRING, *driver);
208
209unlock:
210    apu_dso_mutex_unlock();
211
212#else /* not builtin and !APR_HAS_DSO => not implemented */
213    rv = APR_ENOTIMPL;
214#endif
215
216    return rv;
217}
218
219APU_DECLARE(apr_status_t) apr_dbd_open_ex(const apr_dbd_driver_t *driver,
220                                          apr_pool_t *pool, const char *params,
221                                          apr_dbd_t **handle,
222                                          const char **error)
223{
224    apr_status_t rv;
225    *handle = (driver->open)(pool, params, error);
226    if (*handle == NULL) {
227        return APR_EGENERAL;
228    }
229    rv = apr_dbd_check_conn(driver, pool, *handle);
230    if ((rv != APR_SUCCESS) && (rv != APR_ENOTIMPL)) {
231        /* XXX: rv is APR error code, but apr_dbd_error() takes int! */
232        if (error) {
233            *error = apr_dbd_error(driver, *handle, rv);
234        }
235        apr_dbd_close(driver, *handle);
236        return APR_EGENERAL;
237    }
238    return APR_SUCCESS;
239}
240
241APU_DECLARE(apr_status_t) apr_dbd_open(const apr_dbd_driver_t *driver,
242                                       apr_pool_t *pool, const char *params,
243                                       apr_dbd_t **handle)
244{
245    return apr_dbd_open_ex(driver,pool,params,handle,NULL);
246}
247
248APU_DECLARE(int) apr_dbd_transaction_start(const apr_dbd_driver_t *driver,
249                                           apr_pool_t *pool, apr_dbd_t *handle,
250                                           apr_dbd_transaction_t **trans)
251{
252    int ret = driver->start_transaction(pool, handle, trans);
253    if (*trans) {
254        apr_pool_cleanup_register(pool, *trans,
255                                  CLEANUP_CAST driver->end_transaction,
256                                  apr_pool_cleanup_null);
257    }
258    return ret;
259}
260
261APU_DECLARE(int) apr_dbd_transaction_end(const apr_dbd_driver_t *driver,
262                                         apr_pool_t *pool,
263                                         apr_dbd_transaction_t *trans)
264{
265    apr_pool_cleanup_kill(pool, trans, CLEANUP_CAST driver->end_transaction);
266    return driver->end_transaction(trans);
267}
268
269APU_DECLARE(int) apr_dbd_transaction_mode_get(const apr_dbd_driver_t *driver,
270                                              apr_dbd_transaction_t *trans)
271{
272    return driver->transaction_mode_get(trans);
273}
274
275APU_DECLARE(int) apr_dbd_transaction_mode_set(const apr_dbd_driver_t *driver,
276                                              apr_dbd_transaction_t *trans,
277                                              int mode)
278{
279    return driver->transaction_mode_set(trans, mode);
280}
281
282APU_DECLARE(apr_status_t) apr_dbd_close(const apr_dbd_driver_t *driver,
283                                        apr_dbd_t *handle)
284{
285    return driver->close(handle);
286}
287
288APU_DECLARE(const char*) apr_dbd_name(const apr_dbd_driver_t *driver)
289{
290    return driver->name;
291}
292
293APU_DECLARE(void*) apr_dbd_native_handle(const apr_dbd_driver_t *driver,
294                                         apr_dbd_t *handle)
295{
296    return driver->native_handle(handle);
297}
298
299APU_DECLARE(int) apr_dbd_check_conn(const apr_dbd_driver_t *driver,
300                                    apr_pool_t *pool,
301                                    apr_dbd_t *handle)
302{
303    return driver->check_conn(pool, handle);
304}
305
306APU_DECLARE(int) apr_dbd_set_dbname(const apr_dbd_driver_t *driver,
307                                    apr_pool_t *pool,
308                                    apr_dbd_t *handle, const char *name)
309{
310    return driver->set_dbname(pool,handle,name);
311}
312
313APU_DECLARE(int) apr_dbd_query(const apr_dbd_driver_t *driver,
314                               apr_dbd_t *handle,
315                               int *nrows, const char *statement)
316{
317    return driver->query(handle,nrows,statement);
318}
319
320APU_DECLARE(int) apr_dbd_select(const apr_dbd_driver_t *driver,
321                                apr_pool_t *pool,
322                                apr_dbd_t *handle, apr_dbd_results_t **res,
323                                const char *statement, int random)
324{
325    return driver->select(pool,handle,res,statement,random);
326}
327
328APU_DECLARE(int) apr_dbd_num_cols(const apr_dbd_driver_t *driver,
329                                  apr_dbd_results_t *res)
330{
331    return driver->num_cols(res);
332}
333
334APU_DECLARE(int) apr_dbd_num_tuples(const apr_dbd_driver_t *driver,
335                                    apr_dbd_results_t *res)
336{
337    return driver->num_tuples(res);
338}
339
340APU_DECLARE(int) apr_dbd_get_row(const apr_dbd_driver_t *driver,
341                                 apr_pool_t *pool,
342                                 apr_dbd_results_t *res, apr_dbd_row_t **row,
343                                 int rownum)
344{
345    return driver->get_row(pool,res,row,rownum);
346}
347
348APU_DECLARE(const char*) apr_dbd_get_entry(const apr_dbd_driver_t *driver,
349                                           apr_dbd_row_t *row, int col)
350{
351    return driver->get_entry(row,col);
352}
353
354APU_DECLARE(const char*) apr_dbd_get_name(const apr_dbd_driver_t *driver,
355                                          apr_dbd_results_t *res, int col)
356{
357    return driver->get_name(res,col);
358}
359
360APU_DECLARE(const char*) apr_dbd_error(const apr_dbd_driver_t *driver,
361                                       apr_dbd_t *handle, int errnum)
362{
363    return driver->error(handle,errnum);
364}
365
366APU_DECLARE(const char*) apr_dbd_escape(const apr_dbd_driver_t *driver,
367                                        apr_pool_t *pool, const char *string,
368                                        apr_dbd_t *handle)
369{
370    return driver->escape(pool,string,handle);
371}
372
373APU_DECLARE(int) apr_dbd_prepare(const apr_dbd_driver_t *driver,
374                                 apr_pool_t *pool,
375                                 apr_dbd_t *handle, const char *query,
376                                 const char *label,
377                                 apr_dbd_prepared_t **statement)
378{
379    size_t qlen;
380    int i, nargs = 0, nvals = 0;
381    char *p, *pq;
382    const char *q;
383    apr_dbd_type_e *t;
384
385    if (!driver->pformat) {
386        return APR_ENOTIMPL;
387    }
388
389    /* find the number of parameters in the query */
390    for (q = query; *q; q++) {
391        if (q[0] == '%') {
392            if (apr_isalpha(q[1])) {
393                nargs++;
394            } else if (q[1] == '%') {
395                q++;
396            }
397        }
398    }
399    nvals = nargs;
400
401    qlen = strlen(query) +
402           nargs * (strlen(driver->pformat) + sizeof(nargs) * 3 + 2) + 1;
403    pq = apr_palloc(pool, qlen);
404    t = apr_pcalloc(pool, sizeof(*t) * nargs);
405
406    for (p = pq, q = query, i = 0; *q; q++) {
407        if (q[0] == '%') {
408            if (apr_isalpha(q[1])) {
409                switch (q[1]) {
410                case 'd': t[i] = APR_DBD_TYPE_INT;   break;
411                case 'u': t[i] = APR_DBD_TYPE_UINT;  break;
412                case 'f': t[i] = APR_DBD_TYPE_FLOAT; break;
413                case 'h':
414                    switch (q[2]) {
415                    case 'h':
416                        switch (q[3]){
417                        case 'd': t[i] = APR_DBD_TYPE_TINY;  q += 2; break;
418                        case 'u': t[i] = APR_DBD_TYPE_UTINY; q += 2; break;
419                        }
420                        break;
421                    case 'd': t[i] = APR_DBD_TYPE_SHORT;  q++; break;
422                    case 'u': t[i] = APR_DBD_TYPE_USHORT; q++; break;
423                    }
424                    break;
425                case 'l':
426                    switch (q[2]) {
427                    case 'l':
428                        switch (q[3]){
429                        case 'd': t[i] = APR_DBD_TYPE_LONGLONG;  q += 2; break;
430                        case 'u': t[i] = APR_DBD_TYPE_ULONGLONG; q += 2; break;
431                        }
432                        break;
433                    case 'd': t[i] = APR_DBD_TYPE_LONG;   q++; break;
434                    case 'u': t[i] = APR_DBD_TYPE_ULONG;  q++; break;
435                    case 'f': t[i] = APR_DBD_TYPE_DOUBLE; q++; break;
436                    }
437                    break;
438                case 'p':
439                    if (q[2] == 'D') {
440                        switch (q[3]) {
441                        case 't': t[i] = APR_DBD_TYPE_TEXT;       q += 2; break;
442                        case 'i': t[i] = APR_DBD_TYPE_TIME;       q += 2; break;
443                        case 'd': t[i] = APR_DBD_TYPE_DATE;       q += 2; break;
444                        case 'a': t[i] = APR_DBD_TYPE_DATETIME;   q += 2; break;
445                        case 's': t[i] = APR_DBD_TYPE_TIMESTAMP;  q += 2; break;
446                        case 'z': t[i] = APR_DBD_TYPE_ZTIMESTAMP; q += 2; break;
447                        case 'b': t[i] = APR_DBD_TYPE_BLOB;       q += 2; break;
448                        case 'c': t[i] = APR_DBD_TYPE_CLOB;       q += 2; break;
449                        case 'n': t[i] = APR_DBD_TYPE_NULL;       q += 2; break;
450                        }
451                    }
452                    break;
453                }
454                q++;
455
456                switch (t[i]) {
457                case APR_DBD_TYPE_NONE: /* by default, we expect strings */
458                    t[i] = APR_DBD_TYPE_STRING;
459                    break;
460                case APR_DBD_TYPE_BLOB:
461                case APR_DBD_TYPE_CLOB: /* three (3) more values passed in */
462                    nvals += 3;
463                    break;
464                default:
465                    break;
466                }
467
468                /* insert database specific parameter reference */
469                p += apr_snprintf(p, qlen - (p - pq), driver->pformat, ++i);
470            } else if (q[1] == '%') { /* reduce %% to % */
471                *p++ = *q++;
472            } else {
473                *p++ = *q;
474            }
475        } else {
476            *p++ = *q;
477        }
478    }
479    *p = '\0';
480
481    return driver->prepare(pool,handle,pq,label,nargs,nvals,t,statement);
482}
483
484APU_DECLARE(int) apr_dbd_pquery(const apr_dbd_driver_t *driver,
485                                apr_pool_t *pool,
486                                apr_dbd_t *handle, int *nrows,
487                                apr_dbd_prepared_t *statement,
488                                int nargs, const char **args)
489{
490    return driver->pquery(pool,handle,nrows,statement,args);
491}
492
493APU_DECLARE(int) apr_dbd_pselect(const apr_dbd_driver_t *driver,
494                                 apr_pool_t *pool,
495                                 apr_dbd_t *handle, apr_dbd_results_t **res,
496                                 apr_dbd_prepared_t *statement, int random,
497                                 int nargs, const char **args)
498{
499    return driver->pselect(pool,handle,res,statement,random,args);
500}
501
502APU_DECLARE_NONSTD(int) apr_dbd_pvquery(const apr_dbd_driver_t *driver,
503                                        apr_pool_t *pool,
504                                        apr_dbd_t *handle, int *nrows,
505                                        apr_dbd_prepared_t *statement, ...)
506{
507    int ret;
508    va_list args;
509    va_start(args, statement);
510    ret = driver->pvquery(pool,handle,nrows,statement,args);
511    va_end(args);
512    return ret;
513}
514
515APU_DECLARE_NONSTD(int) apr_dbd_pvselect(const apr_dbd_driver_t *driver,
516                                         apr_pool_t *pool, apr_dbd_t *handle,
517                                         apr_dbd_results_t **res,
518                                         apr_dbd_prepared_t *statement,
519                                         int random, ...)
520{
521    int ret;
522    va_list args;
523    va_start(args, random);
524    ret = driver->pvselect(pool,handle,res,statement,random,args);
525    va_end(args);
526    return ret;
527}
528
529APU_DECLARE(int) apr_dbd_pbquery(const apr_dbd_driver_t *driver,
530                                 apr_pool_t *pool,
531                                 apr_dbd_t *handle, int *nrows,
532                                 apr_dbd_prepared_t *statement,
533                                 const void **args)
534{
535    return driver->pbquery(pool,handle,nrows,statement,args);
536}
537
538APU_DECLARE(int) apr_dbd_pbselect(const apr_dbd_driver_t *driver,
539                                  apr_pool_t *pool,
540                                  apr_dbd_t *handle, apr_dbd_results_t **res,
541                                  apr_dbd_prepared_t *statement, int random,
542                                  const void **args)
543{
544    return driver->pbselect(pool,handle,res,statement,random,args);
545}
546
547APU_DECLARE_NONSTD(int) apr_dbd_pvbquery(const apr_dbd_driver_t *driver,
548                                         apr_pool_t *pool,
549                                         apr_dbd_t *handle, int *nrows,
550                                         apr_dbd_prepared_t *statement, ...)
551{
552    int ret;
553    va_list args;
554    va_start(args, statement);
555    ret = driver->pvbquery(pool,handle,nrows,statement,args);
556    va_end(args);
557    return ret;
558}
559
560APU_DECLARE_NONSTD(int) apr_dbd_pvbselect(const apr_dbd_driver_t *driver,
561                                          apr_pool_t *pool, apr_dbd_t *handle,
562                                          apr_dbd_results_t **res,
563                                          apr_dbd_prepared_t *statement,
564                                          int random, ...)
565{
566    int ret;
567    va_list args;
568    va_start(args, random);
569    ret = driver->pvbselect(pool,handle,res,statement,random,args);
570    va_end(args);
571    return ret;
572}
573
574APU_DECLARE(apr_status_t) apr_dbd_datum_get(const apr_dbd_driver_t *driver,
575                                            apr_dbd_row_t *row, int col,
576                                            apr_dbd_type_e type, void *data)
577{
578    return driver->datum_get(row,col,type,data);
579}
580