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