forked from asterisk/asterisk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathres_odbc.c
1917 lines (1708 loc) · 61.1 KB
/
res_odbc.c
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Asterisk -- An open source telephony toolkit.
*
* Copyright (C) 1999 - 2012, Digium, Inc.
*
* Mark Spencer <[email protected]>
*
* res_odbc.c <ODBC resource manager>
* Copyright (C) 2004 - 2005 Anthony Minessale II <[email protected]>
*
* See http://www.asterisk.org for more information about
* the Asterisk project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, mailing lists and IRC
* channels for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*! \file
*
* \brief ODBC resource manager
*
* \author Mark Spencer <[email protected]>
* \author Anthony Minessale II <[email protected]>
* \author Tilghman Lesher <[email protected]>
*
* \arg See also: \ref cdr_odbc
*/
/*! \li \ref res_odbc.c uses the configuration file \ref res_odbc.conf
* \addtogroup configuration_file Configuration Files
*/
/*!
* \page res_odbc.conf res_odbc.conf
* \verbinclude res_odbc.conf.sample
*/
/*** MODULEINFO
<depend>generic_odbc</depend>
<depend>ltdl</depend>
<support_level>core</support_level>
***/
#include "asterisk.h"
ASTERISK_REGISTER_FILE()
#include "asterisk/file.h"
#include "asterisk/channel.h"
#include "asterisk/config.h"
#include "asterisk/pbx.h"
#include "asterisk/module.h"
#include "asterisk/cli.h"
#include "asterisk/lock.h"
#include "asterisk/res_odbc.h"
#include "asterisk/time.h"
#include "asterisk/astobj2.h"
#include "asterisk/app.h"
#include "asterisk/strings.h"
#include "asterisk/threadstorage.h"
#include "asterisk/data.h"
/*** DOCUMENTATION
<function name="ODBC" language="en_US">
<synopsis>
Controls ODBC transaction properties.
</synopsis>
<syntax>
<parameter name="property" required="true">
<enumlist>
<enum name="transaction">
<para>Gets or sets the active transaction ID. If set, and the transaction ID does not
exist and a <replaceable>database name</replaceable> is specified as an argument, it will be created.</para>
</enum>
<enum name="forcecommit">
<para>Controls whether a transaction will be automatically committed when the channel
hangs up. Defaults to false. If a <replaceable>transaction ID</replaceable> is specified in the optional argument,
the property will be applied to that ID, otherwise to the current active ID.</para>
</enum>
<enum name="isolation">
<para>Controls the data isolation on uncommitted transactions. May be one of the
following: <literal>read_committed</literal>, <literal>read_uncommitted</literal>,
<literal>repeatable_read</literal>, or <literal>serializable</literal>. Defaults to the
database setting in <filename>res_odbc.conf</filename> or <literal>read_committed</literal>
if not specified. If a <replaceable>transaction ID</replaceable> is specified as an optional argument, it will be
applied to that ID, otherwise the current active ID.</para>
</enum>
</enumlist>
</parameter>
<parameter name="argument" required="false" />
</syntax>
<description>
<para>The ODBC() function allows setting several properties to influence how a connected
database processes transactions.</para>
</description>
</function>
<application name="ODBC_Commit" language="en_US">
<synopsis>
Commits a currently open database transaction.
</synopsis>
<syntax>
<parameter name="transaction ID" required="no" />
</syntax>
<description>
<para>Commits the database transaction specified by <replaceable>transaction ID</replaceable>
or the current active transaction, if not specified.</para>
</description>
</application>
<application name="ODBC_Rollback" language="en_US">
<synopsis>
Rollback a currently open database transaction.
</synopsis>
<syntax>
<parameter name="transaction ID" required="no" />
</syntax>
<description>
<para>Rolls back the database transaction specified by <replaceable>transaction ID</replaceable>
or the current active transaction, if not specified.</para>
</description>
</application>
***/
struct odbc_class
{
AST_LIST_ENTRY(odbc_class) list;
char name[80];
char dsn[80];
char *username;
char *password;
char *sanitysql;
SQLHENV env;
unsigned int haspool:1; /*!< Boolean - TDS databases need this */
unsigned int delme:1; /*!< Purge the class */
unsigned int backslash_is_escape:1; /*!< On this database, the backslash is a native escape sequence */
unsigned int forcecommit:1; /*!< Should uncommitted transactions be auto-committed on handle release? */
unsigned int isolation; /*!< Flags for how the DB should deal with data in other, uncommitted transactions */
unsigned int limit; /*!< Maximum number of database handles we will allow */
int count; /*!< Running count of pooled connections */
unsigned int idlecheck; /*!< Recheck the connection if it is idle for this long (in seconds) */
unsigned int conntimeout; /*!< Maximum time the connection process should take */
/*! When a connection fails, cache that failure for how long? */
struct timeval negative_connection_cache;
/*! When a connection fails, when did that last occur? */
struct timeval last_negative_connect;
/*! List of handles associated with this class */
struct ao2_container *obj_container;
};
static struct ao2_container *class_container;
static AST_RWLIST_HEAD_STATIC(odbc_tables, odbc_cache_tables);
static odbc_status odbc_obj_connect(struct odbc_obj *obj);
static odbc_status odbc_obj_disconnect(struct odbc_obj *obj);
static int odbc_register_class(struct odbc_class *class, int connect);
static void odbc_txn_free(void *data);
static void odbc_release_obj2(struct odbc_obj *obj, struct odbc_txn_frame *tx);
AST_THREADSTORAGE(errors_buf);
static const struct ast_datastore_info txn_info = {
.type = "ODBC_Transaction",
.destroy = odbc_txn_free,
};
struct odbc_txn_frame {
AST_LIST_ENTRY(odbc_txn_frame) list;
struct ast_channel *owner;
struct odbc_obj *obj; /*!< Database handle within which transacted statements are run */
/*!\brief Is this record the current active transaction within the channel?
* Note that the active flag is really only necessary for statements which
* are triggered from the dialplan, as there isn't a direct correlation
* between multiple statements. Applications wishing to use transactions
* may simply perform each statement on the same odbc_obj, which keeps the
* transaction persistent.
*/
unsigned int active:1;
unsigned int forcecommit:1; /*!< Should uncommitted transactions be auto-committed on handle release? */
unsigned int isolation; /*!< Flags for how the DB should deal with data in other, uncommitted transactions */
char name[0]; /*!< Name of this transaction ID */
};
#define DATA_EXPORT_ODBC_CLASS(MEMBER) \
MEMBER(odbc_class, name, AST_DATA_STRING) \
MEMBER(odbc_class, dsn, AST_DATA_STRING) \
MEMBER(odbc_class, username, AST_DATA_STRING) \
MEMBER(odbc_class, password, AST_DATA_PASSWORD) \
MEMBER(odbc_class, limit, AST_DATA_INTEGER) \
MEMBER(odbc_class, count, AST_DATA_INTEGER) \
MEMBER(odbc_class, forcecommit, AST_DATA_BOOLEAN)
AST_DATA_STRUCTURE(odbc_class, DATA_EXPORT_ODBC_CLASS);
static const char *isolation2text(int iso)
{
if (iso == SQL_TXN_READ_COMMITTED) {
return "read_committed";
} else if (iso == SQL_TXN_READ_UNCOMMITTED) {
return "read_uncommitted";
} else if (iso == SQL_TXN_SERIALIZABLE) {
return "serializable";
} else if (iso == SQL_TXN_REPEATABLE_READ) {
return "repeatable_read";
} else {
return "unknown";
}
}
static int text2isolation(const char *txt)
{
if (strncasecmp(txt, "read_", 5) == 0) {
if (strncasecmp(txt + 5, "c", 1) == 0) {
return SQL_TXN_READ_COMMITTED;
} else if (strncasecmp(txt + 5, "u", 1) == 0) {
return SQL_TXN_READ_UNCOMMITTED;
} else {
return 0;
}
} else if (strncasecmp(txt, "ser", 3) == 0) {
return SQL_TXN_SERIALIZABLE;
} else if (strncasecmp(txt, "rep", 3) == 0) {
return SQL_TXN_REPEATABLE_READ;
} else {
return 0;
}
}
static struct odbc_txn_frame *find_transaction(struct ast_channel *chan, struct odbc_obj *obj, const char *name, int active)
{
struct ast_datastore *txn_store;
AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
struct odbc_txn_frame *txn = NULL;
if (!chan && obj && obj->txf && obj->txf->owner) {
chan = obj->txf->owner;
} else if (!chan) {
/* No channel == no transaction */
return NULL;
}
ast_channel_lock(chan);
if ((txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
oldlist = txn_store->data;
} else {
/* Need to create a new datastore */
if (!(txn_store = ast_datastore_alloc(&txn_info, NULL))) {
ast_log(LOG_ERROR, "Unable to allocate a new datastore. Cannot create a new transaction.\n");
ast_channel_unlock(chan);
return NULL;
}
if (!(oldlist = ast_calloc(1, sizeof(*oldlist)))) {
ast_log(LOG_ERROR, "Unable to allocate datastore list head. Cannot create a new transaction.\n");
ast_datastore_free(txn_store);
ast_channel_unlock(chan);
return NULL;
}
txn_store->data = oldlist;
AST_LIST_HEAD_INIT(oldlist);
ast_channel_datastore_add(chan, txn_store);
}
AST_LIST_LOCK(oldlist);
ast_channel_unlock(chan);
/* Scanning for an object is *fast*. Scanning for a name is much slower. */
if (obj != NULL || active == 1) {
AST_LIST_TRAVERSE(oldlist, txn, list) {
if (txn->obj == obj || txn->active) {
AST_LIST_UNLOCK(oldlist);
return txn;
}
}
}
if (name != NULL) {
AST_LIST_TRAVERSE(oldlist, txn, list) {
if (!strcasecmp(txn->name, name)) {
AST_LIST_UNLOCK(oldlist);
return txn;
}
}
}
/* Nothing found, create one */
if (name && obj && (txn = ast_calloc(1, sizeof(*txn) + strlen(name) + 1))) {
struct odbc_txn_frame *otxn;
strcpy(txn->name, name); /* SAFE */
txn->obj = obj;
txn->isolation = obj->parent->isolation;
txn->forcecommit = obj->parent->forcecommit;
txn->owner = chan;
txn->active = 1;
/* On creation, the txn becomes active, and all others inactive */
AST_LIST_TRAVERSE(oldlist, otxn, list) {
otxn->active = 0;
}
AST_LIST_INSERT_TAIL(oldlist, txn, list);
obj->txf = txn;
obj->tx = 1;
}
AST_LIST_UNLOCK(oldlist);
return txn;
}
static struct odbc_txn_frame *release_transaction(struct odbc_txn_frame *tx)
{
if (!tx) {
return NULL;
}
ast_debug(2, "release_transaction(%p) called (tx->obj = %p, tx->obj->txf = %p)\n", tx, tx->obj, tx->obj ? tx->obj->txf : NULL);
/* If we have an owner, disassociate */
if (tx->owner) {
struct ast_datastore *txn_store;
AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
ast_channel_lock(tx->owner);
if ((txn_store = ast_channel_datastore_find(tx->owner, &txn_info, NULL))) {
oldlist = txn_store->data;
AST_LIST_LOCK(oldlist);
AST_LIST_REMOVE(oldlist, tx, list);
AST_LIST_UNLOCK(oldlist);
}
ast_channel_unlock(tx->owner);
tx->owner = NULL;
}
if (tx->obj) {
/* If we have any uncommitted transactions, they are handled when we release the object */
struct odbc_obj *obj = tx->obj;
/* Prevent recursion during destruction */
tx->obj->txf = NULL;
tx->obj = NULL;
odbc_release_obj2(obj, tx);
}
ast_free(tx);
return NULL;
}
static void odbc_txn_free(void *vdata)
{
struct odbc_txn_frame *tx;
AST_LIST_HEAD(, odbc_txn_frame) *oldlist = vdata;
ast_debug(2, "odbc_txn_free(%p) called\n", vdata);
AST_LIST_LOCK(oldlist);
while ((tx = AST_LIST_REMOVE_HEAD(oldlist, list))) {
release_transaction(tx);
}
AST_LIST_UNLOCK(oldlist);
AST_LIST_HEAD_DESTROY(oldlist);
ast_free(oldlist);
}
static int mark_transaction_active(struct ast_channel *chan, struct odbc_txn_frame *tx)
{
struct ast_datastore *txn_store;
AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
struct odbc_txn_frame *active = NULL, *txn;
if (!chan && tx && tx->owner) {
chan = tx->owner;
}
if (!chan) {
return -1;
}
ast_channel_lock(chan);
if (!(txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
ast_channel_unlock(chan);
return -1;
}
oldlist = txn_store->data;
AST_LIST_LOCK(oldlist);
AST_LIST_TRAVERSE(oldlist, txn, list) {
if (txn == tx) {
txn->active = 1;
active = txn;
} else {
txn->active = 0;
}
}
AST_LIST_UNLOCK(oldlist);
ast_channel_unlock(chan);
return active ? 0 : -1;
}
static void odbc_class_destructor(void *data)
{
struct odbc_class *class = data;
/* Due to refcounts, we can safely assume that any objects with a reference
* to us will prevent our destruction, so we don't need to worry about them.
*/
if (class->username) {
ast_free(class->username);
}
if (class->password) {
ast_free(class->password);
}
if (class->sanitysql) {
ast_free(class->sanitysql);
}
ao2_ref(class->obj_container, -1);
SQLFreeHandle(SQL_HANDLE_ENV, class->env);
}
static int null_hash_fn(const void *obj, const int flags)
{
return 0;
}
static void odbc_obj_destructor(void *data)
{
struct odbc_obj *obj = data;
struct odbc_class *class = obj->parent;
obj->parent = NULL;
odbc_obj_disconnect(obj);
ao2_ref(class, -1);
}
static void destroy_table_cache(struct odbc_cache_tables *table) {
struct odbc_cache_columns *col;
ast_debug(1, "Destroying table cache for %s\n", table->table);
AST_RWLIST_WRLOCK(&table->columns);
while ((col = AST_RWLIST_REMOVE_HEAD(&table->columns, list))) {
ast_free(col);
}
AST_RWLIST_UNLOCK(&table->columns);
AST_RWLIST_HEAD_DESTROY(&table->columns);
ast_free(table);
}
/*!
* \brief Find or create an entry describing the table specified.
* \param database Name of an ODBC class on which to query the table
* \param tablename Tablename to describe
* \retval A structure describing the table layout, or NULL, if the table is not found or another error occurs.
* When a structure is returned, the contained columns list will be
* rdlock'ed, to ensure that it will be retained in memory.
* \since 1.6.1
*/
struct odbc_cache_tables *ast_odbc_find_table(const char *database, const char *tablename)
{
struct odbc_cache_tables *tableptr;
struct odbc_cache_columns *entry;
char columnname[80];
SQLLEN sqlptr;
SQLHSTMT stmt = NULL;
int res = 0, error = 0, try = 0;
struct odbc_obj *obj;
AST_RWLIST_RDLOCK(&odbc_tables);
AST_RWLIST_TRAVERSE(&odbc_tables, tableptr, list) {
if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
break;
}
}
if (tableptr) {
AST_RWLIST_RDLOCK(&tableptr->columns);
AST_RWLIST_UNLOCK(&odbc_tables);
return tableptr;
}
if (!(obj = ast_odbc_request_obj(database, 0))) {
ast_log(LOG_WARNING, "Unable to retrieve database handle for table description '%s@%s'\n", tablename, database);
AST_RWLIST_UNLOCK(&odbc_tables);
return NULL;
}
/* Table structure not already cached; build it now. */
ao2_lock(obj);
do {
res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
if (try == 0) {
try = 1;
ast_odbc_sanity_check(obj);
continue;
}
ast_log(LOG_WARNING, "SQL Alloc Handle failed on connection '%s'!\n", database);
break;
}
res = SQLColumns(stmt, NULL, 0, NULL, 0, (unsigned char *)tablename, SQL_NTS, (unsigned char *)"%", SQL_NTS);
if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
if (try == 0) {
try = 1;
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
ast_odbc_sanity_check(obj);
continue;
}
ast_log(LOG_ERROR, "Unable to query database columns on connection '%s'.\n", database);
break;
}
if (!(tableptr = ast_calloc(sizeof(char), sizeof(*tableptr) + strlen(database) + 1 + strlen(tablename) + 1))) {
ast_log(LOG_ERROR, "Out of memory creating entry for table '%s' on connection '%s'\n", tablename, database);
break;
}
tableptr->connection = (char *)tableptr + sizeof(*tableptr);
tableptr->table = (char *)tableptr + sizeof(*tableptr) + strlen(database) + 1;
strcpy(tableptr->connection, database); /* SAFE */
strcpy(tableptr->table, tablename); /* SAFE */
AST_RWLIST_HEAD_INIT(&(tableptr->columns));
while ((res = SQLFetch(stmt)) != SQL_NO_DATA && res != SQL_ERROR) {
SQLGetData(stmt, 4, SQL_C_CHAR, columnname, sizeof(columnname), &sqlptr);
if (!(entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(columnname) + 1))) {
ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s' on connection '%s'\n", columnname, tablename, database);
error = 1;
break;
}
entry->name = (char *)entry + sizeof(*entry);
strcpy(entry->name, columnname);
SQLGetData(stmt, 5, SQL_C_SHORT, &entry->type, sizeof(entry->type), NULL);
SQLGetData(stmt, 7, SQL_C_LONG, &entry->size, sizeof(entry->size), NULL);
SQLGetData(stmt, 9, SQL_C_SHORT, &entry->decimals, sizeof(entry->decimals), NULL);
SQLGetData(stmt, 10, SQL_C_SHORT, &entry->radix, sizeof(entry->radix), NULL);
SQLGetData(stmt, 11, SQL_C_SHORT, &entry->nullable, sizeof(entry->nullable), NULL);
SQLGetData(stmt, 16, SQL_C_LONG, &entry->octetlen, sizeof(entry->octetlen), NULL);
/* Specification states that the octenlen should be the maximum number of bytes
* returned in a char or binary column, but it seems that some drivers just set
* it to NULL. (Bad Postgres! No biscuit!) */
if (entry->octetlen == 0) {
entry->octetlen = entry->size;
}
ast_debug(3, "Found %s column with type %hd with len %ld, octetlen %ld, and numlen (%hd,%hd)\n", entry->name, entry->type, (long) entry->size, (long) entry->octetlen, entry->decimals, entry->radix);
/* Insert column info into column list */
AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
}
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
AST_RWLIST_INSERT_TAIL(&odbc_tables, tableptr, list);
AST_RWLIST_RDLOCK(&(tableptr->columns));
break;
} while (1);
ao2_unlock(obj);
AST_RWLIST_UNLOCK(&odbc_tables);
if (error) {
destroy_table_cache(tableptr);
tableptr = NULL;
}
ast_odbc_release_obj(obj);
return tableptr;
}
struct odbc_cache_columns *ast_odbc_find_column(struct odbc_cache_tables *table, const char *colname)
{
struct odbc_cache_columns *col;
AST_RWLIST_TRAVERSE(&table->columns, col, list) {
if (strcasecmp(col->name, colname) == 0) {
return col;
}
}
return NULL;
}
int ast_odbc_clear_cache(const char *database, const char *tablename)
{
struct odbc_cache_tables *tableptr;
AST_RWLIST_WRLOCK(&odbc_tables);
AST_RWLIST_TRAVERSE_SAFE_BEGIN(&odbc_tables, tableptr, list) {
if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
AST_LIST_REMOVE_CURRENT(list);
destroy_table_cache(tableptr);
break;
}
}
AST_RWLIST_TRAVERSE_SAFE_END
AST_RWLIST_UNLOCK(&odbc_tables);
return tableptr ? 0 : -1;
}
SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT (*exec_cb)(struct odbc_obj *obj, void *data), void *data)
{
int attempt;
SQLHSTMT stmt;
ao2_lock(obj);
for (attempt = 0; attempt < 2; attempt++) {
stmt = exec_cb(obj, data);
if (stmt) {
break;
} else if (obj->tx) {
ast_log(LOG_WARNING, "Failed to execute, but unable to reconnect, as we're transactional.\n");
break;
} else if (attempt == 0) {
ast_log(LOG_WARNING, "SQL Execute error! Verifying connection to %s [%s]...\n", obj->parent->name, obj->parent->dsn);
}
if (!ast_odbc_sanity_check(obj)) {
break;
}
}
ao2_unlock(obj);
return stmt;
}
SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
{
int res = 0, i, attempt;
SQLINTEGER nativeerror=0, numfields=0;
SQLSMALLINT diagbytes=0;
unsigned char state[10], diagnostic[256];
SQLHSTMT stmt;
ao2_lock(obj);
for (attempt = 0; attempt < 2; attempt++) {
/* This prepare callback may do more than just prepare -- it may also
* bind parameters, bind results, etc. The real key, here, is that
* when we disconnect, all handles become invalid for most databases.
* We must therefore redo everything when we establish a new
* connection. */
stmt = prepare_cb(obj, data);
if (stmt) {
res = SQLExecute(stmt);
if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
if (res == SQL_ERROR) {
SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
for (i = 0; i < numfields; i++) {
SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
if (i > 10) {
ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
break;
}
}
}
if (obj->tx) {
ast_log(LOG_WARNING, "SQL Execute error, but unable to reconnect, as we're transactional.\n");
break;
} else {
ast_log(LOG_WARNING, "SQL Execute error %d! Verifying connection to %s [%s]...\n", res, obj->parent->name, obj->parent->dsn);
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
stmt = NULL;
obj->up = 0;
/*
* While this isn't the best way to try to correct an error, this won't automatically
* fail when the statement handle invalidates.
*/
if (!ast_odbc_sanity_check(obj)) {
break;
}
continue;
}
} else {
obj->last_used = ast_tvnow();
}
break;
} else if (attempt == 0) {
ast_odbc_sanity_check(obj);
}
}
ao2_unlock(obj);
return stmt;
}
int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt)
{
int res = 0, i;
SQLINTEGER nativeerror=0, numfields=0;
SQLSMALLINT diagbytes=0;
unsigned char state[10], diagnostic[256];
ao2_lock(obj);
res = SQLExecute(stmt);
if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
if (res == SQL_ERROR) {
SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
for (i = 0; i < numfields; i++) {
SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
if (i > 10) {
ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
break;
}
}
}
} else {
obj->last_used = ast_tvnow();
}
ao2_unlock(obj);
return res;
}
SQLRETURN ast_odbc_ast_str_SQLGetData(struct ast_str **buf, int pmaxlen, SQLHSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLSMALLINT TargetType, SQLLEN *StrLen_or_Ind)
{
SQLRETURN res;
if (pmaxlen == 0) {
if (SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), 0, StrLen_or_Ind) == SQL_SUCCESS_WITH_INFO) {
ast_str_make_space(buf, *StrLen_or_Ind + 1);
}
} else if (pmaxlen > 0) {
ast_str_make_space(buf, pmaxlen);
}
res = SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), ast_str_size(*buf), StrLen_or_Ind);
ast_str_update(*buf);
return res;
}
int ast_odbc_sanity_check(struct odbc_obj *obj)
{
char *test_sql = "select 1";
SQLHSTMT stmt;
int res = 0;
if (!ast_strlen_zero(obj->parent->sanitysql))
test_sql = obj->parent->sanitysql;
if (obj->up) {
res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
obj->up = 0;
} else {
res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
obj->up = 0;
} else {
res = SQLExecute(stmt);
if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
obj->up = 0;
}
}
}
SQLFreeHandle (SQL_HANDLE_STMT, stmt);
}
if (!obj->up && !obj->tx) { /* Try to reconnect! */
ast_log(LOG_WARNING, "Connection is down attempting to reconnect...\n");
odbc_obj_disconnect(obj);
odbc_obj_connect(obj);
}
return obj->up;
}
static int load_odbc_config(void)
{
static char *cfg = "res_odbc.conf";
struct ast_config *config;
struct ast_variable *v;
char *cat;
const char *dsn, *username, *password, *sanitysql;
int enabled, pooling, limit, bse, conntimeout, forcecommit, isolation;
struct timeval ncache = { 0, 0 };
unsigned int idlecheck;
int preconnect = 0, res = 0;
struct ast_flags config_flags = { 0 };
struct odbc_class *new;
config = ast_config_load(cfg, config_flags);
if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
return -1;
}
for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
if (!strcasecmp(cat, "ENV")) {
for (v = ast_variable_browse(config, cat); v; v = v->next) {
setenv(v->name, v->value, 1);
ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
}
} else {
/* Reset all to defaults for each class of odbc connections */
dsn = username = password = sanitysql = NULL;
enabled = 1;
preconnect = idlecheck = 0;
pooling = 0;
limit = 0;
bse = 1;
conntimeout = 10;
forcecommit = 0;
isolation = SQL_TXN_READ_COMMITTED;
for (v = ast_variable_browse(config, cat); v; v = v->next) {
if (!strcasecmp(v->name, "pooling")) {
if (ast_true(v->value))
pooling = 1;
} else if (!strncasecmp(v->name, "share", 5)) {
/* "shareconnections" is a little clearer in meaning than "pooling" */
if (ast_false(v->value))
pooling = 1;
} else if (!strcasecmp(v->name, "limit")) {
sscanf(v->value, "%30d", &limit);
if (ast_true(v->value) && !limit) {
ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'. Setting limit to 1023 for ODBC class '%s'.\n", v->value, cat);
limit = 1023;
} else if (ast_false(v->value)) {
ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'. Disabling ODBC class '%s'.\n", v->value, cat);
enabled = 0;
break;
}
} else if (!strcasecmp(v->name, "idlecheck")) {
sscanf(v->value, "%30u", &idlecheck);
} else if (!strcasecmp(v->name, "enabled")) {
enabled = ast_true(v->value);
} else if (!strcasecmp(v->name, "pre-connect")) {
preconnect = ast_true(v->value);
} else if (!strcasecmp(v->name, "dsn")) {
dsn = v->value;
} else if (!strcasecmp(v->name, "username")) {
username = v->value;
} else if (!strcasecmp(v->name, "password")) {
password = v->value;
} else if (!strcasecmp(v->name, "sanitysql")) {
sanitysql = v->value;
} else if (!strcasecmp(v->name, "backslash_is_escape")) {
bse = ast_true(v->value);
} else if (!strcasecmp(v->name, "connect_timeout")) {
if (sscanf(v->value, "%d", &conntimeout) != 1 || conntimeout < 1) {
ast_log(LOG_WARNING, "connect_timeout must be a positive integer\n");
conntimeout = 10;
}
} else if (!strcasecmp(v->name, "negative_connection_cache")) {
double dncache;
if (sscanf(v->value, "%lf", &dncache) != 1 || dncache < 0) {
ast_log(LOG_WARNING, "negative_connection_cache must be a non-negative integer\n");
/* 5 minutes sounds like a reasonable default */
ncache.tv_sec = 300;
ncache.tv_usec = 0;
} else {
ncache.tv_sec = (int)dncache;
ncache.tv_usec = (dncache - ncache.tv_sec) * 1000000;
}
} else if (!strcasecmp(v->name, "forcecommit")) {
forcecommit = ast_true(v->value);
} else if (!strcasecmp(v->name, "isolation")) {
if ((isolation = text2isolation(v->value)) == 0) {
ast_log(LOG_ERROR, "Unrecognized value for 'isolation': '%s' in section '%s'\n", v->value, cat);
isolation = SQL_TXN_READ_COMMITTED;
}
}
}
if (enabled && !ast_strlen_zero(dsn)) {
new = ao2_alloc(sizeof(*new), odbc_class_destructor);
if (!new) {
res = -1;
break;
}
SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
ao2_ref(new, -1);
return res;
}
new->obj_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr);
if (pooling) {
new->haspool = pooling;
if (limit) {
new->limit = limit;
} else {
ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless. Changing limit from 0 to 5.\n");
new->limit = 5;
}
}
new->backslash_is_escape = bse ? 1 : 0;
new->forcecommit = forcecommit ? 1 : 0;
new->isolation = isolation;
new->idlecheck = idlecheck;
new->conntimeout = conntimeout;
new->negative_connection_cache = ncache;
if (cat)
ast_copy_string(new->name, cat, sizeof(new->name));
if (dsn)
ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
if (username && !(new->username = ast_strdup(username))) {
ao2_ref(new, -1);
break;
}
if (password && !(new->password = ast_strdup(password))) {
ao2_ref(new, -1);
break;
}
if (sanitysql && !(new->sanitysql = ast_strdup(sanitysql))) {
ao2_ref(new, -1);
break;
}
odbc_register_class(new, preconnect);
ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
ao2_ref(new, -1);
new = NULL;
}
}
}
ast_config_destroy(config);
return res;
}
static char *handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ao2_iterator aoi;
struct odbc_class *class;
struct odbc_obj *current;
int length = 0;
int which = 0;
char *ret = NULL;
switch (cmd) {
case CLI_INIT:
e->command = "odbc show";
e->usage =
"Usage: odbc show [class]\n"
" List settings of a particular ODBC class or,\n"
" if not specified, all classes.\n";
return NULL;
case CLI_GENERATE:
if (a->pos != 2)
return NULL;
length = strlen(a->word);
aoi = ao2_iterator_init(class_container, 0);
while ((class = ao2_iterator_next(&aoi))) {
if (!strncasecmp(a->word, class->name, length) && ++which > a->n) {
ret = ast_strdup(class->name);
}
ao2_ref(class, -1);
if (ret) {
break;
}
}
ao2_iterator_destroy(&aoi);
if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
ret = ast_strdup("all");
}
return ret;
}
ast_cli(a->fd, "\nODBC DSN Settings\n");
ast_cli(a->fd, "-----------------\n\n");
aoi = ao2_iterator_init(class_container, 0);
while ((class = ao2_iterator_next(&aoi))) {
if ((a->argc == 2) || (a->argc == 3 && !strcmp(a->argv[2], "all")) || (!strcmp(a->argv[2], class->name))) {
int count = 0;
char timestr[80];
struct ast_tm tm;
ast_localtime(&class->last_negative_connect, &tm, NULL);
ast_strftime(timestr, sizeof(timestr), "%Y-%m-%d %T", &tm);
ast_cli(a->fd, " Name: %s\n DSN: %s\n", class->name, class->dsn);
ast_cli(a->fd, " Last connection attempt: %s\n", timestr);
if (class->haspool) {
struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
ast_cli(a->fd, " Pooled: Yes\n Limit: %u\n Connections in use: %d\n", class->limit, class->count);
while ((current = ao2_iterator_next(&aoi2))) {
ao2_lock(current);
#ifdef DEBUG_THREADS
ast_cli(a->fd, " - Connection %d: %s (%s:%d %s)\n", ++count,
current->used ? "in use" :
current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected",
current->file, current->lineno, current->function);
#else
ast_cli(a->fd, " - Connection %d: %s\n", ++count,
current->used ? "in use" :
current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");