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