don't use '%i' at all, since we have no current use cases that need non base-10 parsi...
[asterisk/asterisk.git] / cdr / cdr_pgsql.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * PostgreSQL CDR logger 
5  *
6  * Matthew D. Hardeman <mhardemn@papersoft.com> 
7  * Adapted from the MySQL CDR logger originally by James Sharp 
8  *
9  * Modified September 2003
10  * Matthew D. Hardeman <mhardemn@papersoft.com>
11  *
12  * This program is free software, distributed under the terms of
13  * the GNU General Public License.
14  *
15  */
16
17 #include <sys/types.h>
18 #include "asterisk/config.h"
19 #include "asterisk/options.h"
20 #include "asterisk/channel.h"
21 #include "asterisk/cdr.h"
22 #include "asterisk/module.h"
23 #include "asterisk/logger.h"
24 #include "asterisk.h"
25
26 #include <stdio.h>
27 #include <string.h>
28
29 #include <stdlib.h>
30 #include <unistd.h>
31 #include <time.h>
32
33 #include <libpq-fe.h>
34
35 #define DATE_FORMAT "%Y-%m-%d %T"
36
37 static char *desc = "PostgreSQL CDR Backend";
38 static char *name = "pgsql";
39 static char *config = "cdr_pgsql.conf";
40 static char *pghostname = NULL, *pgdbname = NULL, *pgdbuser = NULL, *pgpassword = NULL, *pgdbsock = NULL, *pgdbport = NULL, *table = NULL;
41 static int hostname_alloc = 0, dbname_alloc = 0, dbuser_alloc = 0, password_alloc = 0, dbsock_alloc = 0, dbport_alloc = 0, table_alloc = 0;
42 static int connected = 0;
43
44 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
45
46 PGconn          *conn;
47 PGresult        *result;
48
49 static int pgsql_log(struct ast_cdr *cdr)
50 {
51         struct tm tm;
52         char sqlcmd[2048] = "", timestr[128];
53         char *pgerror;
54
55         ast_mutex_lock(&pgsql_lock);
56
57         localtime_r(&cdr->start.tv_sec,&tm);
58         strftime(timestr, sizeof(timestr), DATE_FORMAT, &tm);
59
60         if ((!connected) && pghostname && pgdbuser && pgpassword && pgdbname) {
61                 conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
62                 if (PQstatus(conn) != CONNECTION_BAD) {
63                         connected = 1;
64                 } else {
65                         pgerror = PQerrorMessage(conn);
66                         ast_log(LOG_ERROR, "cdr_pgsql: Unable to connect to database server %s.  Calls will not be logged!\n", pghostname);
67                         ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
68                 }
69         }
70
71         if (connected) {
72                 char *clid=NULL, *dcontext=NULL, *channel=NULL, *dstchannel=NULL, *lastapp=NULL, *lastdata=NULL;
73                 char *uniqueid=NULL, *userfield=NULL;
74
75                 /* Maximum space needed would be if all characters needed to be escaped, plus a trailing NULL */
76                 if ((clid = alloca(strlen(cdr->clid) * 2 + 1)) != NULL)
77                         PQescapeString(clid, cdr->clid, strlen(cdr->clid));
78                 if ((dcontext = alloca(strlen(cdr->dcontext) * 2 + 1)) != NULL)
79                         PQescapeString(dcontext, cdr->dcontext, strlen(cdr->dcontext));
80                 if ((channel = alloca(strlen(cdr->channel) * 2 + 1)) != NULL)
81                         PQescapeString(channel, cdr->channel, strlen(cdr->channel));
82                 if ((dstchannel = alloca(strlen(cdr->dstchannel) * 2 + 1)) != NULL)
83                         PQescapeString(dstchannel, cdr->dstchannel, strlen(cdr->dstchannel));
84                 if ((lastapp = alloca(strlen(cdr->lastapp) * 2 + 1)) != NULL)
85                         PQescapeString(lastapp, cdr->lastapp, strlen(cdr->lastapp));
86                 if ((lastdata = alloca(strlen(cdr->lastdata) * 2 + 1)) != NULL)
87                         PQescapeString(lastdata, cdr->lastdata, strlen(cdr->lastdata));
88                 if ((uniqueid = alloca(strlen(cdr->uniqueid) * 2 + 1)) != NULL)
89                         PQescapeString(uniqueid, cdr->uniqueid, strlen(cdr->uniqueid));
90                 if ((userfield = alloca(strlen(cdr->userfield) * 2 + 1)) != NULL)
91                         PQescapeString(userfield, cdr->userfield, strlen(cdr->userfield));
92
93                 /* Check for all alloca failures above at once */
94                 if ((!clid) || (!dcontext) || (!channel) || (!dstchannel) || (!lastapp) || (!lastdata) || (!uniqueid) || (!userfield)) {
95                         ast_log(LOG_ERROR, "cdr_pgsql:  Out of memory error (insert fails)\n");
96                         ast_mutex_unlock(&pgsql_lock);
97                         return -1;
98                 }
99
100                 ast_log(LOG_DEBUG,"cdr_pgsql: inserting a CDR record.\n");
101
102                 snprintf(sqlcmd,sizeof(sqlcmd),"INSERT INTO %s (calldate,clid,src,dst,dcontext,channel,dstchannel,"
103                                  "lastapp,lastdata,duration,billsec,disposition,amaflags,accountcode,uniqueid,userfield) VALUES"
104                                  " ('%s','%s','%s','%s','%s', '%s','%s','%s','%s',%d,%d,'%s',%d,'%s','%s','%s')",
105                                  table,timestr,clid,cdr->src, cdr->dst, dcontext,channel, dstchannel, lastapp, lastdata,
106                                  cdr->duration,cdr->billsec,ast_cdr_disp2str(cdr->disposition),cdr->amaflags, cdr->accountcode, uniqueid, userfield);
107                 
108                 ast_log(LOG_DEBUG,"cdr_pgsql: SQL command executed:  %s\n",sqlcmd);
109                 
110                 /* Test to be sure we're still connected... */
111                 /* If we're connected, and connection is working, good. */
112                 /* Otherwise, attempt reconnect.  If it fails... sorry... */
113                 if (PQstatus(conn) == CONNECTION_OK) {
114                         connected = 1;
115                 } else {
116                         ast_log(LOG_ERROR, "cdr_pgsql: Connection was lost... attempting to reconnect.\n");
117                         PQreset(conn);
118                         if (PQstatus(conn) == CONNECTION_OK) {
119                                 ast_log(LOG_ERROR, "cdr_pgsql: Connection reestablished.\n");
120                                 connected = 1;
121                         } else {
122                                 pgerror = PQerrorMessage(conn);
123                                 ast_log(LOG_ERROR, "cdr_pgsql: Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
124                                 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
125                                 connected = 0;
126                                 ast_mutex_unlock(&pgsql_lock);
127                                 return -1;
128                         }
129                 }
130                 result = PQexec(conn, sqlcmd);
131                 if ( PQresultStatus(result) != PGRES_COMMAND_OK) {
132                         pgerror = PQresultErrorMessage(result);
133                         ast_log(LOG_ERROR,"cdr_pgsql: Failed to insert call detail record into database!\n");
134                         ast_log(LOG_ERROR,"cdr_pgsql: Reason: %s\n", pgerror);
135                         ast_log(LOG_ERROR,"cdr_pgsql: Connection may have been lost... attempting to reconnect.\n");
136                         PQreset(conn);
137                         if (PQstatus(conn) == CONNECTION_OK) {
138                                 ast_log(LOG_ERROR, "cdr_pgsql: Connection reestablished.\n");
139                                 connected = 1;
140                                 result = PQexec(conn, sqlcmd);
141                                 if ( PQresultStatus(result) != PGRES_COMMAND_OK)
142                                 {
143                                         pgerror = PQresultErrorMessage(result);
144                                         ast_log(LOG_ERROR,"cdr_pgsql: HARD ERROR!  Attempted reconnection failed.  DROPPING CALL RECORD!\n");
145                                         ast_log(LOG_ERROR,"cdr_pgsql: Reason: %s\n", pgerror);
146                                 }
147                         }
148                         ast_mutex_unlock(&pgsql_lock);
149                         return -1;
150                 }
151         }
152         ast_mutex_unlock(&pgsql_lock);
153         return 0;
154 }
155
156 char *description(void)
157 {
158         return desc;
159 }
160
161 static int my_unload_module(void)
162
163         if (conn)
164                 PQfinish(conn);
165         conn = NULL;
166         connected = 0;
167         if (pghostname && hostname_alloc) {
168                 free(pghostname);
169                 pghostname = NULL;
170                 hostname_alloc = 0;
171         }
172         if (pgdbname && dbname_alloc) {
173                 free(pgdbname);
174                 pgdbname = NULL;
175                 dbname_alloc = 0;
176         }
177         if (pgdbuser && dbuser_alloc) {
178                 free(pgdbuser);
179                 pgdbuser = NULL;
180                 dbuser_alloc = 0;
181         }
182         if (pgdbsock && dbsock_alloc) {
183                 free(pgdbsock);
184                 pgdbsock = NULL;
185                 dbsock_alloc = 0;
186         }
187         if (pgpassword && password_alloc) {
188                 free(pgpassword);
189                 pgpassword = NULL;
190                 password_alloc = 0;
191         }
192         if (pgdbport && dbport_alloc) {
193                 free(pgdbport);
194                 pgdbport = NULL;
195                 dbport_alloc = 0;
196         }
197         if (table && table_alloc) {
198                 free(table);
199                 table = NULL;
200                 table_alloc = 0;
201         }
202         ast_cdr_unregister(name);
203         return 0;
204 }
205
206 static int process_my_load_module(struct ast_config *cfg)
207 {
208         int res;
209         struct ast_variable *var;
210         char *pgerror;
211         char *tmp;
212
213         var = ast_variable_browse(cfg, "global");
214         if (!var) {
215                 /* nothing configured */
216                 return 0;
217         }
218
219         tmp = ast_variable_retrieve(cfg,"global","hostname");
220         if (tmp) {
221                 pghostname = malloc(strlen(tmp) + 1);
222                 if (pghostname != NULL) {
223                         memset(pghostname, 0, strlen(tmp) + 1);
224                         hostname_alloc = 1;
225                         strncpy(pghostname, tmp, strlen(tmp));
226                 } else {
227                         ast_log(LOG_ERROR,"Out of memory error.\n");
228                         return -1;
229                 }
230         } else {
231                 ast_log(LOG_WARNING,"PostgreSQL server hostname not specified.  Assuming localhost\n");
232                 pghostname = "localhost";
233         }
234
235         tmp = ast_variable_retrieve(cfg,"global","dbname");
236         if (tmp) {
237                 pgdbname = malloc(strlen(tmp) + 1);
238                 if (pgdbname != NULL) {
239                         memset(pgdbname, 0, strlen(tmp) + 1);
240                         dbname_alloc = 1;
241                         strncpy(pgdbname, tmp, strlen(tmp));
242                 } else {
243                         ast_log(LOG_ERROR,"Out of memory error.\n");
244                         return -1;
245                 }
246         } else {
247                 ast_log(LOG_WARNING,"PostgreSQL database not specified.  Assuming asterisk\n");
248                 pgdbname = "asteriskcdrdb";
249         }
250
251         tmp = ast_variable_retrieve(cfg,"global","user");
252         if (tmp) {
253                 pgdbuser = malloc(strlen(tmp) + 1);
254                 if (pgdbuser != NULL) {
255                         memset(pgdbuser, 0, strlen(tmp) + 1);
256                         dbuser_alloc = 1;
257                         strncpy(pgdbuser, tmp, strlen(tmp));
258                 } else {
259                         ast_log(LOG_ERROR,"Out of memory error.\n");
260                         return -1;
261                 }
262         } else {
263                 ast_log(LOG_WARNING,"PostgreSQL database user not specified.  Assuming root\n");
264                 pgdbuser = "root";
265         }
266
267         tmp = ast_variable_retrieve(cfg,"global","password");
268         if (tmp) {
269                 pgpassword = malloc(strlen(tmp) + 1);
270                 if (pgpassword != NULL) {
271                         memset(pgpassword, 0, strlen(tmp) + 1);
272                         password_alloc = 1;
273                         strncpy(pgpassword, tmp, strlen(tmp));
274                 } else {
275                         ast_log(LOG_ERROR,"Out of memory error.\n");
276                         return -1;
277                 }
278         } else {
279                 ast_log(LOG_WARNING,"PostgreSQL database password not specified.  Assuming blank\n");
280                 pgpassword = "";
281         }
282
283         tmp = ast_variable_retrieve(cfg,"global","port");
284         if (tmp) {
285                 pgdbport = malloc(strlen(tmp) + 1);
286                 if (pgdbport != NULL) {
287                         memset(pgdbport, 0, strlen(tmp) + 1);
288                         dbport_alloc = 1;
289                         strncpy(pgdbport, tmp, strlen(tmp));
290                 } else {
291                         ast_log(LOG_ERROR,"Out of memory error.\n");
292                         return -1;
293                 }
294         } else {
295                 ast_log(LOG_WARNING,"PostgreSQL database port not specified.  Using default 5432.\n");
296                 pgdbport = "5432";
297         }
298         /* Loading stuff for table name */
299         tmp = ast_variable_retrieve(cfg,"global","table");
300         if (tmp) {
301                 table = malloc(strlen(tmp) + 1);
302                 if (table != NULL) {
303                         memset(table, 0, strlen(tmp) + 1);
304                         table_alloc = 1;
305                         strncpy(table, tmp, strlen(tmp));
306                 } else {
307                         ast_log(LOG_ERROR,"Out of memory error.\n");
308                         return -1;
309                 }
310         } else {
311                 ast_log(LOG_WARNING,"CDR table not specified.  Assuming cdr\n");
312                 table = "cdr";
313         }
314
315         ast_log(LOG_DEBUG,"cdr_pgsql: got hostname of %s\n",pghostname);
316         ast_log(LOG_DEBUG,"cdr_pgsql: got port of %s\n",pgdbport);
317         if (pgdbsock)
318                 ast_log(LOG_DEBUG,"cdr_pgsql: got sock file of %s\n",pgdbsock);
319         ast_log(LOG_DEBUG,"cdr_pgsql: got user of %s\n",pgdbuser);
320         ast_log(LOG_DEBUG,"cdr_pgsql: got dbname of %s\n",pgdbname);
321         ast_log(LOG_DEBUG,"cdr_pgsql: got password of %s\n",pgpassword);
322         ast_log(LOG_DEBUG,"cdr_pgsql: got sql table name of %s\n",table);
323         
324         conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
325         if (PQstatus(conn) != CONNECTION_BAD) {
326                 ast_log(LOG_DEBUG,"Successfully connected to PostgreSQL database.\n");
327                 connected = 1;
328         } else {
329                 pgerror = PQerrorMessage(conn);
330                 ast_log(LOG_ERROR, "cdr_pgsql: Unable to connect to database server %s.  CALLS WILL NOT BE LOGGED!!\n", pghostname);
331                 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
332                 connected = 0;
333         }
334
335         res = ast_cdr_register(name, desc, pgsql_log);
336         if (res) {
337                 ast_log(LOG_ERROR, "Unable to register PGSQL CDR handling\n");
338         }
339         return res;
340 }
341
342 static int my_load_module(void)
343 {
344         struct ast_config *cfg;
345         int res;
346         cfg = ast_config_load(config);
347         if (!cfg) {
348                 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
349                 return 0;
350         }
351         res = process_my_load_module(cfg);
352         ast_config_destroy(cfg);
353         return res;
354 }
355
356 int load_module(void)
357 {
358         return my_load_module();
359 }
360
361 int unload_module(void)
362 {
363         return my_unload_module();
364 }
365
366 int reload(void)
367 {
368         my_unload_module();
369         return my_load_module();
370 }
371
372 int usecount(void)
373 {
374         /* To be able to unload the module */
375         if ( ast_mutex_trylock(&pgsql_lock) ) {
376                 return 1;
377         } else {
378                 ast_mutex_unlock(&pgsql_lock);
379                 return 0;
380         }
381 }
382
383 char *key()
384 {
385         return ASTERISK_GPL_KEY;
386 }