Fri Jul 3 20:35:31 2009

Asterisk developer's documentation


app_addon_sql_mysql.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- A telephony toolkit for Linux.
00003  *
00004  * Connect to MySQL
00005  * 
00006  * Copyright (C) 2004, Constantine Filin and Christos Ricudis
00007  *
00008  * Christos Ricudis <ricudis@itc.auth.gr>
00009  * Constantine Filin <cf@intermedia.net>
00010  *
00011  * This program is free software, distributed under the terms of
00012  * the GNU General Public License
00013  */
00014 /*** MODULEINFO
00015    <depend>mysqlclient</depend>
00016  ***/
00017 
00018 /*** MODULEINFO
00019    <depend>mysqlclient</depend>
00020  ***/
00021 
00022 #include <asterisk.h>
00023 
00024 #include <stdlib.h>
00025 #include <unistd.h>
00026 #include <string.h>
00027 #include <stdlib.h>
00028 #include <sys/types.h>
00029 #include <stdio.h>
00030 #include <unistd.h>
00031 
00032 #include <mysql/mysql.h>
00033 
00034 #include <asterisk/file.h>
00035 #include <asterisk/logger.h>
00036 #include <asterisk/channel.h>
00037 #include <asterisk/pbx.h>
00038 #include <asterisk/module.h>
00039 #include <asterisk/linkedlists.h>
00040 #include <asterisk/chanvars.h>
00041 #include <asterisk/lock.h>
00042 
00043 #define EXTRA_LOG 0
00044 
00045 static char *app = "MYSQL";
00046 
00047 static char *synopsis = "Do several mySQLy things";
00048 
00049 static char *descrip = 
00050 "MYSQL():  Do several mySQLy things\n"
00051 "Syntax:\n"
00052 "  MYSQL(Connect connid dhhost dbuser dbpass dbname)\n"
00053 "    Connects to a database.  Arguments contain standard MySQL parameters\n"
00054 "    passed to function mysql_real_connect.  Connection identifer returned\n"
00055 "    in ${var}\n"
00056 "  MYSQL(Query resultid ${connid} query-string)\n"
00057 "    Executes standard MySQL query contained in query-string using established\n"
00058 "    connection identified by ${connection_identifier}. Result of query is\n"
00059 "    is stored in ${var}.\n"
00060 "  MYSQL(Fetch fetchid ${resultid} var1 var2 ... varN)\n"
00061 "    Fetches a single row from a result set contained in ${result_identifier}.\n"
00062 "    Assigns returned fields to ${var1} ... ${varn}.  ${fetchid} is set TRUE\n"
00063 "    if additional rows exist in result set.\n"
00064 "  MYSQL(Clear ${resultid})\n"
00065 "    Frees memory and datastructures associated with result set.\n" 
00066 "  MYSQL(Disconnect ${connid})\n"
00067 "    Disconnects from named connection to MySQL.\n"
00068 "  On exit, always returns 0. Sets MYSQL_STATUS to 0 on success and -1 on error.\n";
00069 
00070 /* 
00071 EXAMPLES OF USE : 
00072 
00073 exten => s,2,MYSQL(Connect connid localhost asterisk mypass credit)
00074 exten => s,3,MYSQL(Query resultid ${connid} SELECT username\,credit FROM credit WHERE callerid=${CALLERIDNUM})
00075 exten => s,4,MYSQL(Fetch fetchid ${resultid} datavar1 datavar2)
00076 exten => s,5,GotoIf(${fetchid}?6:8)
00077 exten => s,6,Festival("User ${datavar1} currently has credit balance of ${datavar2} dollars.")  
00078 exten => s,7,Goto(s,4)
00079 exten => s,8,MYSQL(Clear ${resultid})
00080 exten => s,9,MYSQL(Disconnect ${connid})
00081 */
00082 
00083 AST_MUTEX_DEFINE_STATIC(_mysql_mutex);
00084 
00085 #define AST_MYSQL_ID_DUMMY   0
00086 #define AST_MYSQL_ID_CONNID  1
00087 #define AST_MYSQL_ID_RESID   2
00088 #define AST_MYSQL_ID_FETCHID 3
00089 
00090 struct ast_MYSQL_id {
00091    int identifier_type; /* 0=dummy, 1=connid, 2=resultid */
00092    int identifier;
00093    void *data;
00094    AST_LIST_ENTRY(ast_MYSQL_id) entries;
00095 } *ast_MYSQL_id;
00096 
00097 AST_LIST_HEAD(MYSQLidshead,ast_MYSQL_id) _mysql_ids_head;
00098 
00099 /* helpful procs */
00100 static void *find_identifier(int identifier,int identifier_type) {
00101    struct MYSQLidshead *headp;
00102    struct ast_MYSQL_id *i;
00103    void *res=NULL;
00104    int found=0;
00105    
00106    headp=&_mysql_ids_head;
00107    
00108    if (AST_LIST_LOCK(headp)) {
00109       ast_log(LOG_WARNING,"Unable to lock identifiers list\n");
00110    } else {
00111       AST_LIST_TRAVERSE(headp,i,entries) {
00112          if ((i->identifier==identifier) && (i->identifier_type==identifier_type)) {
00113             found=1;
00114             res=i->data;
00115             break;
00116          }
00117       }
00118       if (!found) {
00119          ast_log(LOG_WARNING,"Identifier %d, identifier_type %d not found in identifier list\n",identifier,identifier_type);
00120       }
00121       AST_LIST_UNLOCK(headp);
00122    }
00123    
00124    return res;
00125 }
00126 
00127 static int add_identifier(int identifier_type,void *data) {
00128    struct ast_MYSQL_id *i,*j;
00129    struct MYSQLidshead *headp;
00130    int maxidentifier=0;
00131    
00132    headp=&_mysql_ids_head;
00133    i=NULL;
00134    j=NULL;
00135    
00136    if (AST_LIST_LOCK(headp)) {
00137       ast_log(LOG_WARNING,"Unable to lock identifiers list\n");
00138       return(-1);
00139    } else {
00140       i=malloc(sizeof(struct ast_MYSQL_id));
00141       AST_LIST_TRAVERSE(headp,j,entries) {
00142          if (j->identifier>maxidentifier) {
00143             maxidentifier=j->identifier;
00144          }
00145       }
00146       i->identifier=maxidentifier+1;
00147       i->identifier_type=identifier_type;
00148       i->data=data;
00149       AST_LIST_INSERT_HEAD(headp,i,entries);
00150       AST_LIST_UNLOCK(headp);
00151    }
00152    return i->identifier;
00153 }
00154 
00155 static int del_identifier(int identifier,int identifier_type) {
00156    struct ast_MYSQL_id *i;
00157    struct MYSQLidshead *headp;
00158    int found=0;
00159    
00160         headp=&_mysql_ids_head;
00161         
00162         if (AST_LIST_LOCK(headp)) {
00163       ast_log(LOG_WARNING,"Unable to lock identifiers list\n");
00164    } else {
00165       AST_LIST_TRAVERSE(headp,i,entries) {
00166          if ((i->identifier==identifier) && 
00167              (i->identifier_type==identifier_type)) {
00168             AST_LIST_REMOVE(headp,i,entries);
00169             free(i);
00170             found=1;
00171             break;
00172          }
00173       }
00174       AST_LIST_UNLOCK(headp);
00175    }
00176                    
00177    if (found==0) {
00178       ast_log(LOG_WARNING,"Could not find identifier %d, identifier_type %d in list to delete\n",identifier,identifier_type);
00179       return(-1);
00180    } else {
00181       return(0);
00182    }
00183 }
00184 
00185 static int set_asterisk_int(struct ast_channel *chan, char *varname, int id) {
00186    if( id>=0 ) {
00187       char s[100] = "";
00188       snprintf(s, sizeof(s)-1, "%d", id);
00189 #if EXTRA_LOG
00190       ast_log(LOG_WARNING,"MYSQL: setting var '%s' to value '%s'\n",varname,s);
00191 #endif
00192       pbx_builtin_setvar_helper(chan,varname,s);
00193    }
00194    return id;
00195 }
00196 
00197 static int add_identifier_and_set_asterisk_int(struct ast_channel *chan, char *varname, int identifier_type, void *data) {
00198    return set_asterisk_int(chan,varname,add_identifier(identifier_type,data));
00199 }
00200 
00201 static int safe_scan_int( char** data, char* delim, int def ) {
00202    char* end;
00203    int res = def;
00204    char* s = strsep(data,delim);
00205    if( s ) {
00206       res = strtol(s,&end,10);
00207       if (*end) res = def;  /* not an integer */
00208    }
00209    return res;
00210 }
00211 
00212 /* MYSQL operations */
00213 static int aMYSQL_connect(struct ast_channel *chan, char *data) {
00214    
00215    MYSQL *mysql;
00216 
00217    char *connid_var;
00218    char *dbhost;
00219    char *dbuser;
00220    char *dbpass;
00221    char *dbname;
00222     
00223    strsep(&data," "); // eat the first token, we already know it :P 
00224 
00225    connid_var=strsep(&data," ");
00226    dbhost=strsep(&data," ");
00227    dbuser=strsep(&data," ");
00228    dbpass=strsep(&data," ");
00229    dbname=strsep(&data,"\n");
00230    
00231    if( connid_var && dbhost && dbuser && dbpass && dbname ) {
00232       mysql = mysql_init(NULL);
00233       if (mysql) {
00234          if (mysql_real_connect(mysql,dbhost,dbuser,dbpass,dbname,0,NULL,0)) {
00235             add_identifier_and_set_asterisk_int(chan,connid_var,AST_MYSQL_ID_CONNID,mysql);
00236             return 0;
00237          }
00238          else {
00239             ast_log(LOG_WARNING,"mysql_real_connect(mysql,%s,%s,dbpass,%s,...) failed\n",dbhost,dbuser,dbname);
00240          }
00241       }
00242       else {
00243          ast_log(LOG_WARNING,"myslq_init returned NULL\n");
00244       }
00245    }
00246    else {
00247       ast_log(LOG_WARNING,"MYSQL(connect is missing some arguments\n");
00248    }
00249 
00250    return -1;
00251 }
00252 
00253 static int aMYSQL_query(struct ast_channel *chan, char *data) {
00254    
00255    MYSQL       *mysql;
00256    MYSQL_RES   *mysqlres;
00257 
00258    char *resultid_var;
00259    int connid;
00260    char *querystring;
00261    int mysql_query_res;
00262 
00263    strsep(&data," "); // eat the first token, we already know it :P 
00264 
00265    resultid_var = strsep(&data," ");
00266    connid       = safe_scan_int(&data," ",-1);
00267    querystring  = strsep(&data,"\n");
00268 
00269    if (resultid_var && (connid>=0) && querystring) {
00270       if ((mysql=find_identifier(connid,AST_MYSQL_ID_CONNID))!=NULL) {
00271          mysql_query_res = mysql_query(mysql,querystring);
00272          if (mysql_query_res != 0) {
00273             ast_log(LOG_WARNING, "aMYSQL_query: mysql_query failed. Error: %s\n", mysql_error(mysql));
00274          }
00275          else {
00276             if ((mysqlres=mysql_use_result(mysql))!=NULL) {
00277                add_identifier_and_set_asterisk_int(chan,resultid_var,AST_MYSQL_ID_RESID,mysqlres);
00278                return 0;
00279             }
00280             else if (mysql_field_count(mysql)==0) {
00281                return 0;  // See http://dev.mysql.com/doc/mysql/en/mysql_field_count.html
00282             }
00283             else {
00284                ast_log(LOG_WARNING,"aMYSQL_query: mysql_store_result() failed on query %s\n",querystring);
00285             }
00286          }
00287       }
00288       else {
00289          ast_log(LOG_WARNING,"aMYSQL_query: Invalid connection identifier %d passed in aMYSQL_query\n",connid);
00290       }
00291    }
00292    else {
00293       ast_log(LOG_WARNING,"aMYSQL_query: missing some arguments\n");
00294    }
00295    
00296    return -1;
00297 }
00298 
00299 
00300 static int aMYSQL_fetch(struct ast_channel *chan, char *data) {
00301    
00302    MYSQL_RES *mysqlres;
00303    MYSQL_ROW mysqlrow;
00304 
00305    char *fetchid_var,*s5,*s6;
00306    int resultid,numFields,j;
00307    
00308    strsep(&data," "); // eat the first token, we already know it :P 
00309 
00310    fetchid_var = strsep(&data," ");
00311    resultid    = safe_scan_int(&data," ",-1);
00312 
00313    if (fetchid_var && (resultid>=0) ) {
00314       if ((mysqlres=find_identifier(resultid,AST_MYSQL_ID_RESID))!=NULL) {
00315          /* Grab the next row */
00316          if ((mysqlrow=mysql_fetch_row(mysqlres))!=NULL) {
00317             numFields=mysql_num_fields(mysqlres);
00318             for (j=0;j<numFields;j++) {
00319                s5=strsep(&data," ");
00320                if (s5==NULL) {
00321                   ast_log(LOG_WARNING,"ast_MYSQL_fetch: More fields (%d) than variables (%d)\n",numFields,j);
00322                   break;
00323                }
00324                s6=mysqlrow[j];
00325                pbx_builtin_setvar_helper(chan,s5, s6 ? s6 : "NULL");
00326             }
00327 #if EXTRA_LOG
00328             ast_log(LOG_WARNING,"ast_MYSQL_fetch: numFields=%d\n",numFields);
00329 #endif
00330             set_asterisk_int(chan,fetchid_var,1); // try more rows
00331          } else {
00332 #if EXTRA_LOG
00333             ast_log(LOG_WARNING,"ast_MYSQL_fetch : EOF\n");
00334 #endif
00335             set_asterisk_int(chan,fetchid_var,0); // no more rows
00336          }
00337          return 0;
00338       }
00339       else {
00340          ast_log(LOG_WARNING,"aMYSQL_fetch: Invalid result identifier %d passed\n",resultid);
00341       }
00342    }
00343    else {
00344       ast_log(LOG_WARNING,"aMYSQL_fetch: missing some arguments\n");
00345    }
00346 
00347    return -1;
00348 }
00349 
00350 static int aMYSQL_clear(struct ast_channel *chan, char *data) {
00351 
00352    MYSQL_RES *mysqlres;
00353 
00354    int id;
00355    strsep(&data," "); // eat the first token, we already know it :P 
00356    id = safe_scan_int(&data," \n",-1);
00357    if ((mysqlres=find_identifier(id,AST_MYSQL_ID_RESID))==NULL) {
00358       ast_log(LOG_WARNING,"Invalid result identifier %d passed in aMYSQL_clear\n",id);
00359    } else {
00360       mysql_free_result(mysqlres);
00361       del_identifier(id,AST_MYSQL_ID_RESID);
00362    }
00363 
00364    return 0;
00365 }
00366 
00367 static int aMYSQL_disconnect(struct ast_channel *chan, char *data) {
00368    
00369    MYSQL *mysql;
00370    int id;
00371    strsep(&data," "); // eat the first token, we already know it :P 
00372 
00373    id = safe_scan_int(&data," \n",-1);
00374    if ((mysql=find_identifier(id,AST_MYSQL_ID_CONNID))==NULL) {
00375       ast_log(LOG_WARNING,"Invalid connection identifier %d passed in aMYSQL_disconnect\n",id);
00376    } else {
00377       mysql_close(mysql);
00378       del_identifier(id,AST_MYSQL_ID_CONNID);
00379    } 
00380 
00381    return 0;
00382 }
00383 
00384 static int MYSQL_exec(struct ast_channel *chan, void *data)
00385 {
00386    struct ast_module_user *u;
00387    int result;
00388    char sresult[10];
00389 
00390 #if EXTRA_LOG
00391    fprintf(stderr,"MYSQL_exec: data=%s\n",(char*)data);
00392 #endif
00393 
00394    if (!data) {
00395       ast_log(LOG_WARNING, "APP_MYSQL requires an argument (see manual)\n");
00396       return -1;
00397    }
00398 
00399    u = ast_module_user_add(chan);
00400    result=0;
00401 
00402    ast_mutex_lock(&_mysql_mutex);
00403 
00404    if (strncasecmp("connect",data,strlen("connect"))==0) {
00405       result=aMYSQL_connect(chan,ast_strdupa(data));
00406    } else   if (strncasecmp("query",data,strlen("query"))==0) {
00407       result=aMYSQL_query(chan,ast_strdupa(data));
00408    } else   if (strncasecmp("fetch",data,strlen("fetch"))==0) {
00409       result=aMYSQL_fetch(chan,ast_strdupa(data));
00410    } else   if (strncasecmp("clear",data,strlen("clear"))==0) {
00411       result=aMYSQL_clear(chan,ast_strdupa(data));
00412    } else   if (strncasecmp("disconnect",data,strlen("disconnect"))==0) {
00413       result=aMYSQL_disconnect(chan,ast_strdupa(data));
00414    } else {
00415       ast_log(LOG_WARNING, "Unknown argument to MYSQL application : %s\n",(char *)data);
00416       result=-1;  
00417    }
00418       
00419    ast_mutex_unlock(&_mysql_mutex);
00420 
00421    ast_module_user_remove(u);
00422    snprintf(sresult, sizeof(sresult), "%d", result);
00423    pbx_builtin_setvar_helper(chan, "MYSQL_STATUS", sresult);
00424    return 0;
00425 }
00426 
00427 static int unload_module(void)
00428 {
00429    ast_module_user_hangup_all();
00430    return ast_unregister_application(app);
00431 }
00432 
00433 static int load_module(void)
00434 {
00435    struct MYSQLidshead *headp = &_mysql_ids_head;
00436    AST_LIST_HEAD_INIT(headp);
00437    return ast_register_application(app, MYSQL_exec, synopsis, descrip);
00438 }
00439 
00440 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Simple Mysql Interface");

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