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