Fri Jul 3 20:35:31 2009

Asterisk developer's documentation


app_addon_sql_pgsql.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- A telephony toolkit for Linux.
00003  *
00004  * Connect to PostgreSQL
00005  * 
00006  * Copyright (C) 2008, Nick Gavrikov <nickgavirkov@gmail.com>
00007  * Copyright (C) 2002, Christos Ricudis <ricudis@itc.auth.gr>
00008  *
00009  * Based on modules MYSQL and PGSQL written by:
00010  *
00011  * Christos Ricudis <ricudis@itc.auth.gr>
00012  * Constantine Filin <cf@intermedia.net>
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License
00016  */
00017 /*** MODULEINFO
00018    <depend>pgsql</depend>
00019  ***/
00020 
00021 #include <asterisk.h>
00022 
00023 #include <stdlib.h>
00024 #include <unistd.h>
00025 #include <string.h>
00026 #include <stdlib.h>
00027 #include <sys/types.h>
00028 #include <stdio.h>
00029 #include <unistd.h>
00030 
00031 #include <pgsql/libpq-fe.h>
00032 
00033 #include <asterisk/file.h>
00034 #include <asterisk/logger.h>
00035 #include <asterisk/channel.h>
00036 #include <asterisk/pbx.h>
00037 #include <asterisk/module.h>
00038 #include <asterisk/linkedlists.h>
00039 #include <asterisk/chanvars.h>
00040 #include <asterisk/lock.h>
00041 
00042 #define EXTRA_LOG 0
00043 
00044 static char *app = "PGSQL";
00045 
00046 static char *synopsis = "Do several PgSQLy things";
00047 
00048 static char *descrip =
00049    "PGSQL():  Do several SQLy things\n"
00050    "Syntax:\n"
00051    "  PGSQL(Connect var option-string)\n"
00052    "    Connects to a database.  Option string contains standard PostgreSQL\n"
00053    "    parameters like host=, dbname=, user=.  Connection identifier returned\n"
00054    "    in ${var}.\n"
00055    "  PGSQL(Query var ${connection_identifier} query-string)\n"
00056    "    Executes standard SQL query contained in query-string using established\n"
00057    "    connection identified by ${connection_identifier}.  Result of query is\n"
00058    "    stored in ${var}.\n"
00059    "  PGSQL(Fetch statusvar ${result_identifier} var1 var2 ... varn)\n"
00060    "    Fetches a single row from a result set contained in ${result_identifier}.\n"
00061    "    Assigns returned fields to ${var1} ... ${varn}.  ${statusvar} is set TRUE\n"
00062    "    if additional rows exist in result set.\n"
00063    "  PGSQL(Clear ${result_identifier})\n"
00064    "    Frees memory and data structures associated with result set.                \n"
00065    "  PGSQL(Disconnect ${connection_identifier})                                             \n" "    Disconnects from named connection to PostgreSQL.                            \n";
00066 
00067 /* 
00068 Syntax of SQL commands :
00069 
00070    Connect var option-string
00071 
00072    Connects to a database using the option-string and stores the
00073    connection identifier in ${var}
00074 
00075 
00076    Query var ${connection_identifier} query-string
00077 
00078    Submits query-string to database backend and stores the result
00079    identifier in ${var}
00080 
00081 
00082    Fetch statusvar ${result_identifier} var1 var2 var3 ... varn
00083 
00084    Fetches a row from the query and stores end-of-table status in
00085    ${statusvar} and columns in ${var1} ... ${varn}
00086 
00087 
00088    Clear ${result_identifier}
00089 
00090    Clears data structures associated with ${result_identifier}
00091 
00092 
00093    Disconnect ${connection_identifier}
00094 
00095    Disconnects from named connection
00096 
00097 
00098 EXAMPLES OF USE :
00099 
00100 exten => s,2,PGSQL(Connect connid host=localhost user=asterisk dbname=credit)
00101 exten => s,3,PGSQL(Query resultid ${connid} SELECT username,credit FROM credit WHERE callerid=${CALLERIDNUM})
00102 exten => s,4,PGSQL(Fetch fetchid ${resultid} datavar1 datavar2)
00103 exten => s,5,GotoIf(${fetchid}?6:8)
00104 exten => s,6,Festival("User ${datavar1} currently has credit balance of ${datavar2} dollars.")
00105 exten => s,7,Goto(s,4)
00106 exten => s,8,PGSQL(Clear ${resultid})
00107 exten => s,9,PGSQL(Disconnect ${connid})
00108 */
00109 
00110 AST_MUTEX_DEFINE_STATIC(_pgsql_mutex);
00111 
00112 enum id_type {
00113    AST_PGSQL_ID_DUMMY = 0,
00114    AST_PGSQL_ID_CONNID,
00115    AST_PGSQL_ID_RESID,
00116    AST_PGSQL_ID_FETCHID
00117 };
00118 
00119 struct ast_PGSQL_id {
00120    enum id_type identifier_type; /* 0 = dummy, 1 = connid, 2 = resultid, 3 = fetchid */
00121    int identifier;
00122    void *data;
00123      AST_LIST_ENTRY(ast_PGSQL_id) entries;
00124 } *ast_PGSQL_id;
00125 
00126 AST_LIST_HEAD(PGSQLidshead, ast_PGSQL_id) PGSQLidshead;
00127 
00128     static void *find_identifier(const int identifier, const enum id_type identifier_type)
00129 {
00130    struct PGSQLidshead *headp;
00131    struct ast_PGSQL_id *i;
00132    void *res = NULL;
00133    int found = 0;
00134 
00135    headp = &PGSQLidshead;
00136 
00137    if (AST_LIST_LOCK(headp)) {
00138       ast_log(LOG_WARNING, "Unable to lock identifiers list\n");
00139    } else {
00140       AST_LIST_TRAVERSE(headp, i, entries) {
00141          if ((i->identifier == identifier) && (i->identifier_type == identifier_type)) {
00142             found = 1;
00143             res = i->data;
00144             break;
00145          }
00146       }
00147       if (!found) {
00148          ast_log(LOG_WARNING, "Identifier %d, identifier_type %d not found in identifier list\n", identifier, identifier_type);
00149       }
00150       AST_LIST_UNLOCK(headp);
00151    }
00152 
00153    return res;
00154 }
00155 
00156 static int add_identifier(const enum id_type identifier_type, void *data)
00157 {
00158    struct ast_PGSQL_id *i, *j;
00159    struct PGSQLidshead *headp;
00160    int maxidentifier = 0;
00161 
00162    headp = &PGSQLidshead;
00163    i = NULL;
00164    j = NULL;
00165 
00166    if (AST_LIST_LOCK(headp)) {
00167       ast_log(LOG_WARNING, "Unable to lock identifiers list\n");
00168       return -1;
00169    }
00170 
00171    if (!(i = ast_malloc(sizeof(*i)))) {
00172       AST_LIST_UNLOCK(headp);
00173       return -1;
00174    }
00175 
00176    AST_LIST_TRAVERSE(headp, j, entries) {
00177       if (j->identifier > maxidentifier)
00178          maxidentifier = j->identifier;
00179    }
00180    i->identifier = maxidentifier + 1;
00181    i->identifier_type = identifier_type;
00182    i->data = data;
00183    AST_LIST_INSERT_HEAD(headp, i, entries);
00184    AST_LIST_UNLOCK(headp);
00185 
00186    return i->identifier;
00187 }
00188 
00189 static int del_identifier(const int identifier, const enum id_type identifier_type)
00190 {
00191    struct ast_PGSQL_id *i;
00192    struct PGSQLidshead *headp;
00193    int found = 0;
00194 
00195    headp = &PGSQLidshead;
00196 
00197    if (AST_LIST_LOCK(headp)) {
00198       ast_log(LOG_WARNING, "Unable to lock identifiers list\n");
00199    } else {
00200       AST_LIST_TRAVERSE(headp, i, entries) {
00201          if ((i->identifier == identifier) && (i->identifier_type == identifier_type)) {
00202             AST_LIST_REMOVE(headp, i, entries);
00203             free(i);
00204             found = 1;
00205             break;
00206          }
00207       }
00208       AST_LIST_UNLOCK(headp);
00209    }
00210 
00211    if (!found) {
00212       ast_log(LOG_WARNING, "Could not find identifier %d, identifier_type %d in list to delete\n", identifier, identifier_type);
00213       return -1;
00214    } else {
00215       return 0;
00216    }
00217 }
00218 
00219 /* PGSQL operations */
00220 static int aPGSQL_connect(struct ast_channel *chan, void *data)
00221 {
00222    char s[100] = "";
00223    char *optionstring;
00224    char *var;
00225    int res = 0;
00226    PGconn *PGSQLconn;
00227    int id;
00228    char *stringp = NULL;
00229 
00230    if (!(stringp = ast_strdupa(data)))
00231       return -1;
00232 
00233    strsep(&stringp, " ");     /* eat the first token, we already know it :P  */
00234    var = strsep(&stringp, " ");
00235    optionstring = strsep(&stringp, "\n");
00236 
00237    PGSQLconn = PQconnectdb(optionstring);
00238    if (PQstatus(PGSQLconn) == CONNECTION_BAD) {
00239       ast_log(LOG_WARNING, "Connection to database using '%s' failed. postgress reports : %s\n", optionstring, PQerrorMessage(PGSQLconn));
00240       res = -1;
00241    } else {
00242       ast_log(LOG_WARNING, "Adding identifier\n");
00243       id = add_identifier(AST_PGSQL_ID_CONNID, PGSQLconn);
00244       snprintf(s, sizeof(s), "%d", id);
00245       pbx_builtin_setvar_helper(chan, var, s);
00246    }
00247 
00248    return res;
00249 }
00250 
00251 static int aPGSQL_query(struct ast_channel *chan, void *data)
00252 {
00253    char *s2, *s3;
00254    char s[100] = "";
00255    char *querystring;
00256    char *var;
00257    int res = 0, nres;
00258    PGconn *PGSQLconn;
00259    PGresult *PGSQLres;
00260    int id, id1;
00261    char *stringp = NULL;
00262 
00263    if (!(stringp = ast_strdupa(data)))
00264       return -1;
00265 
00266    strsep(&stringp, " ");     /* eat the first token, we already know it :P  */
00267    s2 = strsep(&stringp, " ");
00268    while (1) {             /* ugly trick to make branches with break; */
00269       var = s2;
00270       s3 = strsep(&stringp, " ");
00271       id = atoi(s3);
00272       querystring = strsep(&stringp, "\n");
00273       if (!(PGSQLconn = find_identifier(id, AST_PGSQL_ID_CONNID))) {
00274          ast_log(LOG_WARNING, "Invalid connection identifier %d passed in aPGSQL_query\n", id);
00275          res = -1;
00276          break;
00277       }
00278       if (!(PGSQLres = PQexec(PGSQLconn, querystring))) {
00279          ast_log(LOG_WARNING, "aPGSQL_query: Connection Error (connection identifier = %d, error message : %s)\n", id, PQerrorMessage(PGSQLconn));
00280          res = -1;
00281          break;
00282       }
00283       if (PQresultStatus(PGSQLres) == PGRES_BAD_RESPONSE || PQresultStatus(PGSQLres) == PGRES_NONFATAL_ERROR || PQresultStatus(PGSQLres) == PGRES_FATAL_ERROR) {
00284          ast_log(LOG_WARNING, "aPGSQL_query: Query Error (connection identifier : %d, error message : %s)\n", id, PQcmdStatus(PGSQLres));
00285          res = -1;
00286          break;
00287       }
00288       nres = PQnfields(PGSQLres);
00289       id1 = add_identifier(AST_PGSQL_ID_RESID, PGSQLres);
00290       snprintf(s, sizeof(s), "%d", id1);
00291       pbx_builtin_setvar_helper(chan, var, s);
00292       break;
00293    }
00294 
00295    return res;
00296 }
00297 
00298 
00299 static int aPGSQL_fetch(struct ast_channel *chan, void *data)
00300 {
00301    char *s2, *s3, *s4, *fetchid_var;
00302    const char *s5 = NULL;
00303    char s[100];
00304    char *var;
00305    int res = 0;
00306    PGresult *PGSQLres;
00307    int id, id1, i, j, fnd;
00308    int *identp = NULL;
00309    int nres;
00310    struct ast_var_t *variables;
00311    struct varshead *headp;
00312    char *stringp = NULL;
00313 
00314    headp = &chan->varshead;
00315 
00316    if (!(stringp = ast_strdupa(data)))
00317       return -1;
00318 
00319    strsep(&stringp, " ");     /* eat the first token, we already know it :P  */
00320    fetchid_var = strsep(&stringp, " ");
00321    while (1) {             /* ugly trick to make branches with break; */
00322       var = fetchid_var;      /* fetchid */
00323       fnd = 0;
00324 
00325       AST_LIST_TRAVERSE(headp, variables, entries) {
00326          if (!(strncasecmp(ast_var_name(variables), fetchid_var, strlen(fetchid_var)))) {
00327             s5 = ast_var_value(variables);
00328             fnd = 1;
00329             break;
00330          }
00331       }
00332 
00333       if (!fnd) {
00334          s5 = "0";
00335          pbx_builtin_setvar_helper(chan, fetchid_var, s5);
00336       }
00337 
00338       s2 = strsep(&stringp, " ");
00339       id = atoi(s2);       /* resultid */
00340       if (!(PGSQLres = find_identifier(id, AST_PGSQL_ID_RESID))) {
00341          ast_log(LOG_WARNING, "ast_PGSQL_fetch : Invalid result identifier %d passed in aPGSQL_fetch\n", id);
00342          res = -1;
00343          break;
00344       }
00345       id = atoi(s5);       /*fetchid */
00346       if (!(identp = find_identifier(id, AST_PGSQL_ID_FETCHID))) {
00347          i = 0;            /* fetching the very first row */
00348       } else {
00349          i = *identp;
00350          free(identp);
00351          del_identifier(id, AST_PGSQL_ID_FETCHID); /* will re-add it a bit later */
00352       }
00353 
00354       if (i < PQntuples(PGSQLres)) {
00355          nres = PQnfields(PGSQLres);
00356          ast_log(LOG_WARNING, "ast_PGSQL_fetch : nres = %d i = %d ;\n", nres, i);
00357          for (j = 0; j < nres; j++) {
00358             if (!(s3 = strsep(&stringp, " "))) {
00359                ast_log(LOG_WARNING, "ast_PGSQL_fetch : More tuples (%d) than variables (%d)\n", nres, j);
00360                break;
00361             }
00362             if (!(s4 = PQgetvalue(PGSQLres, i, j))) {
00363                ast_log(LOG_WARNING, "ast_PGSQL_fetch : PQgetvalue(res, %d, %d) returned NULL in ast_PGSQL_fetch\n", i, j);
00364                break;
00365             }
00366             ast_log(LOG_WARNING, "ast_PGSQL_fetch : ===setting variable '%s' to '%s'\n", s3, s4);
00367             pbx_builtin_setvar_helper(chan, s3, s4);
00368          }
00369          if (!(identp = ast_malloc(sizeof(int))))
00370             return -1;
00371          *identp = ++i;    /* advance to the next row */
00372          id1 = add_identifier(AST_PGSQL_ID_FETCHID, identp);
00373       } else {
00374          ast_log(LOG_WARNING, "ast_PGSQL_fetch : EOF\n");
00375          id1 = 0;       /* no more rows */
00376       }
00377       snprintf(s, sizeof(s), "%d", id1);
00378       ast_log(LOG_WARNING, "ast_PGSQL_fetch : Setting var '%s' to value '%s'\n", fetchid_var, s);
00379       pbx_builtin_setvar_helper(chan, fetchid_var, s);
00380       break;
00381    }
00382 
00383    return res;
00384 }
00385 
00386 static int aPGSQL_reset(struct ast_channel *chan, void *data)
00387 {
00388    char *s;
00389    PGconn *PGSQLconn;
00390    int id;
00391    char *stringp = NULL;
00392 
00393    if (!(stringp = ast_strdupa(data)))
00394       return -1;
00395 
00396    strsep(&stringp, " ");     /* eat the first token, we already know it :P  */
00397    s = strsep(&stringp, " ");
00398    id = atoi(s);
00399    if (!(PGSQLconn = find_identifier(id, AST_PGSQL_ID_CONNID))) {
00400       ast_log(LOG_WARNING, "aPGSQL_reset : Invalid connection identifier %d passed in aPGSQL_reset\n", id);
00401    } else {
00402       PQreset(PGSQLconn);
00403    }
00404 
00405    return 0;
00406 }
00407 
00408 static int aPGSQL_clear(struct ast_channel *chan, void *data)
00409 {
00410    char *s;
00411    PGresult *PGSQLres;
00412    int id;
00413    char *stringp = NULL;
00414 
00415    if (!(stringp = ast_strdupa(data)))
00416       return -1;
00417 
00418    strsep(&stringp, " ");     /* eat the first token, we already know it :P  */
00419    s = strsep(&stringp, " ");
00420    id = atoi(s);
00421    if (!(PGSQLres = find_identifier(id, AST_PGSQL_ID_RESID))) {
00422       ast_log(LOG_WARNING, "aPGSQL_clear : Invalid result identifier %d passed in aPGSQL_clear\n", id);
00423    } else {
00424       PQclear(PGSQLres);
00425       del_identifier(id, AST_PGSQL_ID_RESID);
00426    }
00427 
00428    return 0;
00429 }
00430 
00431 static int aPGSQL_disconnect(struct ast_channel *chan, void *data)
00432 {
00433    char *s;
00434    PGconn *PGSQLconn;
00435    int id;
00436    char *stringp = NULL;
00437 
00438    if (!(stringp = ast_strdupa(data)))
00439       return -1;
00440 
00441    strsep(&stringp, " ");     /* eat the first token, we already know it :P  */
00442    s = strsep(&stringp, " ");
00443    id = atoi(s);
00444    if (!(PGSQLconn = find_identifier(id, AST_PGSQL_ID_CONNID))) {
00445       ast_log(LOG_WARNING, "aPGSQL_disconnect : Invalid connection identifier %d passed in aPGSQL_disconnect\n", id);
00446    } else {
00447       PQfinish(PGSQLconn);
00448       del_identifier(id, AST_PGSQL_ID_CONNID);
00449    }
00450 
00451    return 0;
00452 }
00453 
00454 
00455 static int PGSQL_exec(struct ast_channel *chan, void *data)
00456 {
00457    struct ast_module_user *u;
00458    int result;
00459    char sresult[12];       // "-2147483646"
00460 
00461 #if EXTRA_LOG
00462    fprintf(stderr, "PGSQL_exec: data=%s\n", (char *) data);
00463 #endif
00464 
00465    if (!data) {
00466       ast_log(LOG_WARNING, "APP_PGSQL requires an argument (see manual)\n");
00467       return -1;
00468    }
00469 
00470    u = ast_module_user_add(chan);
00471    result = 0;
00472 
00473    ast_mutex_lock(&_pgsql_mutex);
00474 
00475    if (!(strncasecmp("connect", data, strlen("connect")))) {
00476       result = (aPGSQL_connect(chan, data));
00477    } else if (!(strncasecmp("query", data, strlen("query")))) {
00478       result = (aPGSQL_query(chan, data));
00479    } else if (!(strncasecmp("fetch", data, strlen("fetch")))) {
00480       result = (aPGSQL_fetch(chan, data));
00481    } else if (!(strncasecmp("reset", data, strlen("reset")))) {
00482       result = (aPGSQL_reset(chan, data));
00483    } else if (!(strncasecmp("clear", data, strlen("clear")))) {
00484       result = (aPGSQL_clear(chan, data));
00485       /*
00486          } else if (!(strncasecmp("debug", data, strlen("debug")))) {
00487          result = (aPGSQL_debug(chan, data));
00488        */
00489    } else if (!(strncasecmp("disconnect", data, strlen("disconnect")))) {
00490       result = (aPGSQL_disconnect(chan, data));
00491    } else {
00492       ast_log(LOG_WARNING, "Unknown APP_PGSQL argument : %s\n", (char *) data);
00493       result = -1;
00494    }
00495 
00496    ast_mutex_unlock(&_pgsql_mutex);
00497 
00498    ast_module_user_remove(u);
00499    snprintf(sresult, sizeof(sresult), "%d", result);
00500    pbx_builtin_setvar_helper(chan, "PGSQL_STATUS", sresult);
00501    return 0;
00502 }
00503 
00504 static int unload_module(void)
00505 {
00506    ast_module_user_hangup_all();
00507    return ast_unregister_application(app);
00508 }
00509 
00510 static int load_module(void)
00511 {
00512    struct PGSQLidshead *headp = &PGSQLidshead;
00513    AST_LIST_HEAD_INIT(headp);
00514    return ast_register_application(app, PGSQL_exec, synopsis, descrip);
00515 }
00516 
00517 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Simple PostgreSQL Interface");

Generated on Fri Jul 3 20:35:31 2009 for Asterisk - the Open Source PBX by  doxygen 1.5.9