Merge slepp's sub-second expiration timer although hopefully it will never have to...
[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;
41 static int hostname_alloc = 0, dbname_alloc = 0, dbuser_alloc = 0, password_alloc = 0, dbsock_alloc = 0, dbport_alloc = 0;
42 static int connected = 0;
43
44 static ast_mutex_t pgsql_lock = AST_MUTEX_INITIALIZER;
45
46 PGconn          *conn;
47 PGresult        *result;
48
49 static int pgsql_log(struct ast_cdr *cdr)
50 {
51         struct tm tm;
52         struct timeval tv;
53         char sqlcmd[2048], timestr[128];
54         time_t t;
55         char *pgerror;
56
57         ast_mutex_lock(&pgsql_lock);
58
59         memset(sqlcmd,0,2048);
60
61         gettimeofday(&tv,NULL);
62         t = tv.tv_sec;
63         localtime_r(&t,&tm);
64         strftime(timestr,128,DATE_FORMAT,&tm);
65
66         if ((!connected) && pghostname && pgdbuser && pgpassword && pgdbname) {
67                 conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
68                 if (PQstatus(conn) != CONNECTION_BAD) {
69                         connected = 1;
70                 } else {
71                         pgerror = PQerrorMessage(conn);
72                         ast_log(LOG_ERROR, "cdr_pgsql: Unable to connect to database server %s.  Calls will not be logged!\n", pghostname);
73                         ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
74                 }
75         }
76
77         if (connected) {
78                 char *clid=NULL, *dcontext=NULL, *channel=NULL, *dstchannel=NULL, *lastapp=NULL, *lastdata=NULL;
79                 char *uniqueid=NULL, *userfield=NULL;
80
81                 /* Maximum space needed would be if all characters needed to be escaped, plus a trailing NULL */
82                 if ((clid = alloca(strlen(cdr->clid) * 2 + 1)) != NULL)
83                         PQescapeString(clid, cdr->clid, strlen(cdr->clid));
84                 if ((dcontext = alloca(strlen(cdr->dcontext) * 2 + 1)) != NULL)
85                         PQescapeString(dcontext, cdr->dcontext, strlen(cdr->dcontext));
86                 if ((channel = alloca(strlen(cdr->channel) * 2 + 1)) != NULL)
87                         PQescapeString(channel, cdr->channel, strlen(cdr->channel));
88                 if ((dstchannel = alloca(strlen(cdr->dstchannel) * 2 + 1)) != NULL)
89                         PQescapeString(dstchannel, cdr->dstchannel, strlen(cdr->dstchannel));
90                 if ((lastapp = alloca(strlen(cdr->lastapp) * 2 + 1)) != NULL)
91                         PQescapeString(lastapp, cdr->lastapp, strlen(cdr->lastapp));
92                 if ((lastdata = alloca(strlen(cdr->lastdata) * 2 + 1)) != NULL)
93                         PQescapeString(lastdata, cdr->lastdata, strlen(cdr->lastdata));
94                 if ((uniqueid = alloca(strlen(cdr->uniqueid) * 2 + 1)) != NULL)
95                         PQescapeString(uniqueid, cdr->uniqueid, strlen(cdr->uniqueid));
96                 if ((userfield = alloca(strlen(cdr->userfield) * 2 + 1)) != NULL)
97                         PQescapeString(userfield, cdr->userfield, strlen(cdr->userfield));
98
99                 /* Check for all alloca failures above at once */
100                 if ((!clid) || (!dcontext) || (!channel) || (!dstchannel) || (!lastapp) || (!lastdata) || (!uniqueid) || (!userfield)) {
101                         ast_log(LOG_ERROR, "cdr_pgsql:  Out of memory error (insert fails)\n");
102                         ast_mutex_unlock(&pgsql_lock);
103                         return -1;
104                 }
105
106                 ast_log(LOG_DEBUG,"cdr_pgsql: inserting a CDR record.\n");
107
108                 sprintf(sqlcmd,"INSERT INTO cdr (calldate,clid,src,dst,dcontext,channel,dstchannel,lastapp,lastdata,duration,billsec,disposition,amaflags,accountcode,uniqueid,userfield) VALUES ('%s','%s','%s','%s','%s', '%s','%s','%s','%s',%i,%i,'%s',%i,'%s','%s','%s')",timestr,clid,cdr->src, cdr->dst, dcontext,channel, dstchannel, lastapp, lastdata,cdr->duration,cdr->billsec,ast_cdr_disp2str(cdr->disposition),cdr->amaflags, cdr->accountcode, uniqueid, userfield);
109                 ast_log(LOG_DEBUG,"cdr_pgsql: SQL command executed:  %s\n",sqlcmd);
110         
111                 /* Test to be sure we're still connected... */
112                 /* If we're connected, and connection is working, good. */
113                 /* Otherwise, attempt reconnect.  If it fails... sorry... */
114                 if (PQstatus(conn) == CONNECTION_OK) {
115                         connected = 1;
116                 } else {
117                         ast_log(LOG_ERROR, "cdr_pgsql: Connection was lost... attempting to reconnect.\n");
118                         PQreset(conn);
119                         if (PQstatus(conn) == CONNECTION_OK) {
120                                 ast_log(LOG_ERROR, "cdr_pgsql: Connection reestablished.\n");
121                                 connected = 1;
122                         } else {
123                                 pgerror = PQerrorMessage(conn);
124                                 ast_log(LOG_ERROR, "cdr_pgsql: Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
125                                 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
126                                 connected = 0;
127                                 ast_mutex_unlock(&pgsql_lock);
128                                 return -1;
129                         }
130                 }
131                 result = PQexec(conn, sqlcmd);
132                 if ( PQresultStatus(result) != PGRES_COMMAND_OK) {
133                         pgerror = PQresultErrorMessage(result);
134                         ast_log(LOG_ERROR,"cdr_pgsql: Failed to insert call detail record into database!\n");
135                         ast_log(LOG_ERROR,"cdr_pgsql: Reason: %s\n", pgerror);
136                         ast_mutex_unlock(&pgsql_lock);
137                         return -1;
138                 }
139         }
140         ast_mutex_unlock(&pgsql_lock);
141         return 0;
142 }
143
144 char *description(void)
145 {
146         return desc;
147 }
148
149 static int my_unload_module(void)
150
151         PQfinish(conn);
152         connected = 0;
153         if (pghostname && hostname_alloc) {
154                 free(pghostname);
155                 pghostname = NULL;
156                 hostname_alloc = 0;
157         }
158         if (pgdbname && dbname_alloc) {
159                 free(pgdbname);
160                 pgdbname = NULL;
161                 dbname_alloc = 0;
162         }
163         if (pgdbuser && dbuser_alloc) {
164                 free(pgdbuser);
165                 pgdbuser = NULL;
166                 dbuser_alloc = 0;
167         }
168         if (pgdbsock && dbsock_alloc) {
169                 free(pgdbsock);
170                 pgdbsock = NULL;
171                 dbsock_alloc = 0;
172         }
173         if (pgpassword && password_alloc) {
174                 free(pgpassword);
175                 pgpassword = NULL;
176                 password_alloc = 0;
177         }
178         if (pgdbport && dbport_alloc) {
179                 free(pgdbport);
180                 pgdbport = NULL;
181                 dbport_alloc = 0;
182         }
183         ast_cdr_unregister(name);
184         return 0;
185 }
186
187 static int my_load_module(void)
188 {
189         int res;
190         struct ast_config *cfg;
191         struct ast_variable *var;
192         char *pgerror;
193         char *tmp;
194
195         cfg = ast_load(config);
196         if (!cfg) {
197                 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
198                 return 0;
199         }
200         
201         var = ast_variable_browse(cfg, "global");
202         if (!var) {
203                 /* nothing configured */
204                 return 0;
205         }
206
207         tmp = ast_variable_retrieve(cfg,"global","hostname");
208         if (tmp) {
209                 pghostname = malloc(strlen(tmp) + 1);
210                 if (pghostname != NULL) {
211                         hostname_alloc = 1;
212                         strcpy(pghostname,tmp);
213                 } else {
214                         ast_log(LOG_ERROR,"Out of memory error.\n");
215                         return -1;
216                 }
217         } else {
218                 ast_log(LOG_WARNING,"PostgreSQL server hostname not specified.  Assuming localhost\n");
219                 pghostname = "localhost";
220         }
221
222         tmp = ast_variable_retrieve(cfg,"global","dbname");
223         if (tmp) {
224                 pgdbname = malloc(strlen(tmp) + 1);
225                 if (pgdbname != NULL) {
226                         dbname_alloc = 1;
227                         strcpy(pgdbname,tmp);
228                 } else {
229                         ast_log(LOG_ERROR,"Out of memory error.\n");
230                         return -1;
231                 }
232         } else {
233                 ast_log(LOG_WARNING,"PostgreSQL database not specified.  Assuming asterisk\n");
234                 pgdbname = "asteriskcdrdb";
235         }
236
237         tmp = ast_variable_retrieve(cfg,"global","user");
238         if (tmp) {
239                 pgdbuser = malloc(strlen(tmp) + 1);
240                 if (pgdbuser != NULL) {
241                         dbuser_alloc = 1;
242                         strcpy(pgdbuser,tmp);
243                 } else {
244                         ast_log(LOG_ERROR,"Out of memory error.\n");
245                         return -1;
246                 }
247         } else {
248                 ast_log(LOG_WARNING,"PostgreSQL database user not specified.  Assuming root\n");
249                 pgdbuser = "root";
250         }
251
252         tmp = ast_variable_retrieve(cfg,"global","password");
253         if (tmp) {
254                 pgpassword = malloc(strlen(tmp) + 1);
255                 if (pgpassword != NULL) {
256                         password_alloc = 1;
257                         strcpy(pgpassword,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 password not specified.  Assuming blank\n");
264                 pgpassword = "";
265         }
266
267         tmp = ast_variable_retrieve(cfg,"global","port");
268         if (tmp) {
269                 pgdbport = malloc(strlen(tmp) + 1);
270                 if (pgdbport != NULL) {
271                         dbport_alloc = 1;
272                         strcpy(pgdbport,tmp);
273                 } else {
274                         ast_log(LOG_ERROR,"Out of memory error.\n");
275                         return -1;
276                 }
277         } else {
278                 ast_log(LOG_WARNING,"PostgreSQL database port not specified.  Using default 5432.\n");
279                 pgdbport = "5432";
280         }
281
282         ast_destroy(cfg);
283
284         ast_log(LOG_DEBUG,"cdr_pgsql: got hostname of %s\n",pghostname);
285         ast_log(LOG_DEBUG,"cdr_pgsql: got port of %s\n",pgdbport);
286         if (pgdbsock)
287                 ast_log(LOG_DEBUG,"cdr_pgsql: got sock file of %s\n",pgdbsock);
288         ast_log(LOG_DEBUG,"cdr_pgsql: got user of %s\n",pgdbuser);
289         ast_log(LOG_DEBUG,"cdr_pgsql: got dbname of %s\n",pgdbname);
290         ast_log(LOG_DEBUG,"cdr_pgsql: got password of %s\n",pgpassword);
291
292         conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
293         if (PQstatus(conn) != CONNECTION_BAD) {
294                 ast_log(LOG_DEBUG,"Successfully connected to PostgreSQL database.\n");
295                 connected = 1;
296         } else {
297                 pgerror = PQerrorMessage(conn);
298                 ast_log(LOG_ERROR, "cdr_pgsql: Unable to connect to database server %s.  Calls will not be logged!\n", pghostname);
299                 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
300                 connected = 0;
301         }
302
303         res = ast_cdr_register(name, desc, pgsql_log);
304         if (res) {
305                 ast_log(LOG_ERROR, "Unable to register PGSQL CDR handling\n");
306         }
307         return res;
308 }
309
310 int load_module(void)
311 {
312         return my_load_module();
313 }
314
315 int unload_module(void)
316 {
317         return my_unload_module();
318 }
319
320 int reload(void)
321 {
322         my_unload_module();
323         return my_load_module();
324 }
325
326 int usecount(void)
327 {
328         return connected;
329 }
330
331 char *key()
332 {
333         return ASTERISK_GPL_KEY;
334 }