int c_syb_make (int m_size) { int count; error_message = (char *) malloc (sizeof (char) * (m_size + ERROR_MESSAGE_SIZE)); clear_error (); max_size = m_size; if (dbinit () == FAIL) { return error_number; /* exit(ERREXIT); */ } dberrhandle ((EHANDLEFUNC)err_handler); dbmsghandle ((MHANDLEFUNC)msg_handler); if (login == NULL) { login = safe_alloc (dblogin()); DBSETLCHARSET (login, "utf8"); } for (count = 0; count < MAX_DESCRIPTOR; count++) { descriptor[count] = NULL; } return error_number; }
void sql_server_operator::start_up() { //初始化 dbinit(); //连接数据库 loginrec = dblogin(); DBSETLUSER(loginrec, user_name.c_str()); DBSETLPWD(loginrec, password.c_str()); dbprocess = dbopen(loginrec, server_host.c_str()); if(dbprocess == FAIL) { throw std::runtime_error("sqlserver val_ptr new failed"); } if(dbuse(dbprocess, dbname.c_str()) == FAIL) { throw std::runtime_error("sqlserver val_ptr new failed"); } pthread_create(&tid, NULL, _thread_t<sql_server_operator, &sql_server_operator::_Run>, this); pthread_detach(tid); }
/************************************************************************* * * Function: sql_create_socket * * Purpose: Establish connection to the db * *************************************************************************/ static int sql_init_socket(SQLSOCK *sqlsocket, SQL_CONFIG *config) { LOGINREC *login; rlm_sql_freetds_sock *freetds_sock; if (!sqlsocket->conn) { sqlsocket->conn = (rlm_sql_freetds_sock *)rad_malloc(sizeof(struct rlm_sql_freetds_sock)); if (!sqlsocket->conn) { return -1; } } if (dbinit() == FAIL) { radlog(L_ERR, "rlm_sql_freetds: Unable to init FreeTDS"); return -1; } dbsetversion(DBVERSION_80); dberrhandle(err_handler); // Timeout so that FreeTDS doesn't wait for ever. dbsetlogintime((unsigned long)config->query_timeout); dbsettime((unsigned long)config->query_timeout); freetds_sock = sqlsocket->conn; memset(freetds_sock, 0, sizeof(*freetds_sock)); DEBUG("rlm_sql_freetds (%s): Starting connect to FreeTDS/MSSQL server", config->xlat_name); if (!(login = dblogin())) { radlog(L_ERR, "rlm_sql_freetds (%s): Unable to allocate login record", config->xlat_name); return -1; } DBSETLUSER(login, config->sql_login); DBSETLPWD(login, config->sql_password); if ((freetds_sock->dbproc = dbopen(login, config->sql_server)) == FAIL) { radlog(L_ERR, "rlm_sql_freetds (%s): Unable to connect to FreeTDS/MSSQL server %s@%s", config->xlat_name, config->sql_login, config->sql_server); dbloginfree(login); return -1; } dbloginfree(login); if ((dbuse(freetds_sock->dbproc, config->sql_db)) == FAIL) { radlog(L_ERR, "rlm_sql_freetds (%s): Unable to select database on FreeTDS/MSSQL server %s@%s:%s", config->xlat_name, config->sql_login, config->sql_server, config->sql_db); return -1; } /* I know this may look strange, but it sets a pointer to the freetds_sock struct so that it can be used within the query_timeout_handler function to be able to timeout properly */ dbsetinterrupt(freetds_sock->dbproc, query_timeout_handler, query_timeout_handler); dbsetuserdata(freetds_sock->dbproc, (BYTE *)freetds_sock); return 0; }
int ast_db_put(const char *family, const char *keys, char *value) { char fullkey[256]; DBT key, data; int res, fullkeylen; ast_mutex_lock(&dblock); if (dbinit()) { ast_mutex_unlock(&dblock); return -1; } fullkeylen = snprintf(fullkey, sizeof(fullkey), "/%s/%s", family, keys); memset(&key, 0, sizeof(key)); memset(&data, 0, sizeof(data)); key.data = fullkey; key.size = fullkeylen + 1; data.data = value; data.size = strlen(value) + 1; res = astdb->put(astdb, &key, &data, 0); astdb->sync(astdb, 0); ast_mutex_unlock(&dblock); if (res) ast_log(LOG_WARNING, "Unable to put value '%s' for key '%s' in family '%s'\n", value, keys, family); return res; }
int ast_db_del(const char *family, const char *keys) { char fullkey[256]; DBT key; int res, fullkeylen; ast_mutex_lock(&dblock); if (dbinit()) { ast_mutex_unlock(&dblock); return -1; } fullkeylen = snprintf(fullkey, sizeof(fullkey), "/%s/%s", family, keys); memset(&key, 0, sizeof(key)); key.data = fullkey; key.size = fullkeylen + 1; res = astdb->del(astdb, &key, 0); astdb->sync(astdb, 0); ast_mutex_unlock(&dblock); if (res) ast_log(LOG_DEBUG, "Unable to find key '%s' in family '%s'\n", keys, family); return res; }
int save_pid_to_db(int id,char* pd) { char szUsername[32] = "sa"; char szPassword[32]= "1qazxsw2*"; char szDBName[32] = "ids_db"; char szServer[32] = "10.2.10.201"; char sqlquery[1024]={0}; snprintf(sqlquery,1024,"update ids_policy_event set pid='%s' where id='%d'",pd,id); dbinit(); LOGINREC *loginrec = dblogin(); DBSETLUSER(loginrec, szUsername); DBSETLPWD(loginrec, szPassword); DBPROCESS *dbprocess = dbopen(loginrec, szServer); if(dbprocess == FAIL) { LOG_INFO(" Conect MS SQL SERVER fail "); return -1; } if(dbuse(dbprocess, szDBName) == FAIL) { LOG_INFO(" Open database name fail"); return -1; } dbcmd(dbprocess,sqlquery); if(dbsqlexec(dbprocess) == FAIL) { LOG_INFO("task.cpp dbsqlexec error!!!"); } dbclose(dbprocess); return 0; }
BOOL DBConnect(char *szServer, char *szUser, char *szPswd) { // Initialize DB-Library if ( dbinit() == FAIL ) return FALSE; // Install user-supplied error-handling and message-handling dberrhandle((EHANDLEFUNC)err_handler); dbmsghandle((MHANDLEFUNC)msg_handler); // Allocate and init LOGINREC structure used to open a connection to SQL Server login = dblogin(); DBSETLUSER(login, szUser); // "sa" DBSETLPWD(login, szPswd); // "" DBSETLAPP(login, "cags_import_bcp"); // Enable bulk copy for this connection BCP_SETL(login, TRUE); // Get a connection to the database. if ((dbproc = dbopen(login, szServer)) == (DBPROCESS *) NULL) // "cgserver" { errfile << ERROR_PREFIX << "can't connect to server" << endl; return FALSE; } // Make cags the current database if ( dbuse(dbproc, "cags") == FAIL ) { errfile << ERROR_PREFIX << "can't make cags current database." << endl; return FALSE; } return TRUE; }
/* * First add a set of points to the gen_pts struct. * * Then these points are added into the gen table in the * database. The operation is timed. * We then convert the gen_pts to penta_pts and add these * points to the penta table in the DB. This is also timed. * * The second part is to query the two tables and time how * long it takes to complete each query */ int main(int argc, char **argv) { MYSQL dbase; int r, i; /* connect to DB */ if (dbinit(&dbase, "localhost", "ashwink", "", "2d") < 0) { printf("Error connecting to database\n"); return -1; } #ifdef TABLE_INIT /* table init */ r = table_init(&dbase); if (r < 0) { printf("table_init failed\n"); return -1; } /* time the adding of points */ if (time_fills(&dbase) < 0) { return -1; } #endif /* time the queries */ if (time_query(&dbase, MIN_P, MAX_P) < 0) { return -1; } return 0; }
RETCODE db_connect(const char * user,const char * passwd, const char* serv_name,const char * db_name,DBPROCESS **db_proc) { LOGINREC *login; DBPROCESS *dbproc; RETCODE erc=-1; if(dbinit()==FAIL) { fprintf(stderr,"%s:%d: dbinit() failed\n", __func__, __LINE__); return erc; } if((login=dblogin())==NULL) { fprintf(stderr, "%s:%d: unable to allocate login structure\n", __func__, __LINE__); return erc; } DBSETLUSER(login,user); DBSETLPWD(login,passwd); if((dbproc=dbopen(login,serv_name))==NULL) { fprintf(stderr, "%s:%d: unable to connect to %s as %s\n", __func__, __LINE__,serv_name, user); return erc; } if(db_name && ((erc=dbuse(dbproc,db_name))==FAIL)) { fprintf(stderr, "%s:%d: unable to use to database %s\n", __func__, __LINE__, db_name); return erc; } *db_proc=dbproc; return erc; }
bool COleDBConnectionProp::ConnectMSOracle(ATL::CDataSource* pDataSource,CSession* pSession) { ASSERT(pDataSource); m_strDatabaseName = g_sDBName; m_strLoginName = g_sDBUser; m_strPassword = g_sDBPassword; m_strServerName = g_sDBDNS; CComBSTR bstrServer(m_strServerName); CComBSTR bstrUser(m_strLoginName); CComBSTR bstrPassword(m_strPassword); CComBSTR bstrDatabase(m_strDatabaseName); if (pSession && pSession->m_spOpenRowset != NULL) pSession->m_spOpenRowset.Release(); CDBPropSet dbinit(DBPROPSET_DBINIT); dbinit.AddProperty(DBPROP_AUTH_PASSWORD, bstrPassword); dbinit.AddProperty(DBPROP_AUTH_PERSIST_SENSITIVE_AUTHINFO, false); dbinit.AddProperty(DBPROP_AUTH_USERID, bstrUser); dbinit.AddProperty(DBPROP_INIT_DATASOURCE, bstrDatabase); dbinit.AddProperty(DBPROP_INIT_LCID, (long)1049); dbinit.AddProperty(DBPROP_INIT_PROMPT, (short)4); if(FAILED(pDataSource->Open(_T("MSDAORA"), &dbinit))) { CString strMsg = "Cannot connect to data source"; strMsg += "\nDatabase\t= " + m_strDatabaseName; strMsg += "\nLogin\t= " + m_strLoginName; strMsg += "\nPassword\t= " + m_strPassword; AfxMessageBox(strMsg); if(pDataSource) { pDataSource->Close(); } goto ErrorExit; } else { if (pSession && pSession->Open(*pDataSource) != S_OK) { AfxMessageBox(_T("Couldn't create session on data source")); goto ErrorExit; } } return true; ErrorExit: CloseConnection(); return false; }
static int sanity_check(void) { if (!loaded) { cw_log(LOG_ERROR, "NICE RACE CONDITION WE HAVE HERE! PUTTING THE CART BEFORE THE HORSE EH? >=0\n"); dbinit(); } return 0; }
void QTDSDriver::init() { d = new QTDSDriverPrivate(); d->initialized = (dbinit() == SUCCEED); // the following two code-lines will fail compilation on some FreeTDS versions // just comment them out if you have FreeTDS (you won't get any errors and warnings then) dberrhandle((QERRHANDLE)qTdsErrHandler); dbmsghandle((QMSGHANDLE)qTdsMsgHandler); }
static char *handle_cli_database_showkey(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { char suffix[256]; DBT key, data; char *keys, *values; int res; int pass; int counter = 0; switch (cmd) { case CLI_INIT: e->command = "database showkey"; e->usage = "Usage: database showkey <keytree>\n" " Shows Asterisk database contents, restricted to a given key.\n"; return NULL; case CLI_GENERATE: return NULL; } if (a->argc == 3) { /* Key only */ snprintf(suffix, sizeof(suffix), "/%s", a->argv[2]); } else { return CLI_SHOWUSAGE; } ast_mutex_lock(&dblock); if (dbinit()) { ast_mutex_unlock(&dblock); ast_cli(a->fd, "Database unavailable\n"); return CLI_SUCCESS; } memset(&key, 0, sizeof(key)); memset(&data, 0, sizeof(data)); pass = 0; while (!(res = astdb->seq(astdb, &key, &data, pass++ ? R_NEXT : R_FIRST))) { if (key.size) { keys = key.data; keys[key.size - 1] = '\0'; } else { keys = "<bad key>"; } if (data.size) { values = data.data; values[data.size - 1]='\0'; } else { values = "<bad value>"; } if (subkeymatch(keys, suffix)) { ast_cli(a->fd, "%-50s: %-25s\n", keys, values); counter++; } } ast_mutex_unlock(&dblock); ast_cli(a->fd, "%d results found.\n", counter); return CLI_SUCCESS; }
void Connector::init_db_connectors() { if (dbinit() == FAIL){ conn_status = false; s_error_message.append("Could not initialize db library. "); error_code = 1; } else { conn_status = true; } }
int astdb_init(void) { dbinit(); ast_cli_register_multiple(cli_database, ARRAY_LEN(cli_database)); ast_manager_register("DBGet", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_dbget, "Get DB Entry"); ast_manager_register("DBPut", EVENT_FLAG_SYSTEM, manager_dbput, "Put DB Entry"); ast_manager_register("DBDel", EVENT_FLAG_SYSTEM, manager_dbdel, "Delete DB Entry"); ast_manager_register("DBDelTree", EVENT_FLAG_SYSTEM, manager_dbdeltree, "Delete DB Tree"); return 0; }
int main(int argc, char *argv[]) { LOGINREC *login; DBPROCESS *dbproc; int ret_code; int num_cols; int num_res; set_malloc_options(); read_login_info(argc, argv); printf("Starting %s\n", argv[0]); dbinit(); dberrhandle(syb_err_handler); dbmsghandle(syb_msg_handler); printf("About to logon\n"); login = dblogin(); DBSETLPWD(login, PASSWORD); DBSETLUSER(login, USER); DBSETLAPP(login, "t0012"); dbproc = dbopen(login, SERVER); if (strlen(DATABASE)) { dbuse(dbproc, DATABASE); } dbloginfree(login); printf("After logon\n"); /* select */ sql_cmd(dbproc); dbsqlexec(dbproc); num_res = 0; while ((ret_code = dbresults(dbproc)) == SUCCEED) { num_cols = dbnumcols(dbproc); printf("Result %d has %d columns\n", num_res, num_cols); if (!(num_res % 2) && num_cols) set_failed(); while(dbnextrow(dbproc) != NO_MORE_ROWS) {}; num_res++; } if (ret_code == FAIL) set_failed(); dbclose(dbproc); dbexit(); printf("%s %s\n", __FILE__, (failed ? "failed!" : "OK")); return failed ? 1 : 0; }
int main(int argc, char **argv) { LOGINREC *login; read_login_info(argc, argv); fprintf(stdout, "Starting %s\n", argv[0]); dbinit(); dberrhandle(syb_err_handler); dbmsghandle(syb_msg_handler); fprintf(stdout, "About to logon\n"); login = dblogin(); DBSETLPWD(login, PASSWORD); DBSETLUSER(login, USER); DBSETLAPP(login, "thread"); fprintf(stdout, "About to open \"%s\"\n", SERVER); dbproc = dbopen(login, SERVER); if (!dbproc) { fprintf(stderr, "Unable to connect to %s\n", SERVER); return 1; } dbloginfree(login); if (strlen(DATABASE)) dbuse(dbproc, DATABASE); test("VARCHAR(10)", 1); test("CHAR(10)", 1); test("TEXT", 1); test("NVARCHAR(10)", 0); #ifndef DBNTWIN32 if (dbtds(dbproc) >= DBTDS_7_0) test("NTEXT", 0); #endif test("VARCHAR(MAX)", 0); #ifndef DBNTWIN32 if (dbtds(dbproc) >= DBTDS_7_0) test("NVARCHAR(MAX)", 0); #endif dbexit(); return failed ? 1 : 0; }
int main(int argc, char **argv) { LOGINREC *login; DBPROCESS *dbproc; read_login_info(argc, argv); printf("Starting %s\n", argv[0]); dbinit(); printf("About to logon\n"); login = dblogin(); DBSETLPWD(login, PASSWORD); DBSETLUSER(login, USER); DBSETLAPP(login, "t0011"); printf("About to open\n"); dbproc = dbopen(login, SERVER); if (strlen(DATABASE)) dbuse(dbproc, DATABASE); dbloginfree(login); printf("Dropping table\n"); sql_cmd(dbproc); dbsqlexec(dbproc); while (dbresults(dbproc) != NO_MORE_RESULTS) { /* nop */ } printf("creating table\n"); sql_cmd(dbproc); dbsqlexec(dbproc); while (dbresults(dbproc) != NO_MORE_RESULTS) { /* nop */ } printf("insert\n"); insert_row(dbproc); insert_row(dbproc); insert_row(dbproc); failed = select_rows(dbproc, STRINGBIND); dbexit(); printf("%s %s\n", __FILE__, (failed ? "failed!" : "OK")); return failed ? 1 : 0; }
int astdb_init(void) { dbinit(); ast_cli_register(&cli_database_show); ast_cli_register(&cli_database_showkey); ast_cli_register(&cli_database_get); ast_cli_register(&cli_database_put); ast_cli_register(&cli_database_del); ast_cli_register(&cli_database_deltree); ast_manager_register("DBGet", EVENT_FLAG_SYSTEM, manager_dbget, "Get DB Entry"); ast_manager_register("DBPut", EVENT_FLAG_SYSTEM, manager_dbput, "Put DB Entry"); return 0; }
static void dbd_freetds_init(apr_pool_t *pool) { int rv = regcomp(&dbd_freetds_find_arg, "%(\\{[^}]*\\})?([0-9]*)[A-Za-z]", REG_EXTENDED); if (rv != 0) { char errmsg[256]; regerror(rv, &dbd_freetds_find_arg, errmsg, 256); fprintf(stderr, "regcomp failed: %s\n", errmsg); } dbinit(); dberrhandle(freetds_err_handler); apr_pool_cleanup_register(pool, NULL, freetds_term, apr_pool_cleanup_null); }
int main(int argc, char *argv[]) { client_init(); if(!dbinit()) { std::cout <<"DB Error!\n"; } else { std::cout <<"DB Connect!\n"; std::cout <<"PID"<<PID<<"\n"; std::cout<< current_user.userno<<"\n"; } return ui_start(argc,argv); }
static VALUE rb_tinytds_connect(VALUE self, VALUE opts) { /* Parsing options hash to local vars. */ VALUE user, pass, dataserver, database, app, version, ltimeout, timeout, charset; user = rb_hash_aref(opts, sym_username); pass = rb_hash_aref(opts, sym_password); dataserver = rb_hash_aref(opts, sym_dataserver); database = rb_hash_aref(opts, sym_database); app = rb_hash_aref(opts, sym_appname); version = rb_hash_aref(opts, sym_tds_version); ltimeout = rb_hash_aref(opts, sym_login_timeout); timeout = rb_hash_aref(opts, sym_timeout); charset = rb_hash_aref(opts, sym_encoding); /* Dealing with options. */ if (dbinit() == FAIL) { rb_raise(cTinyTdsError, "failed dbinit() function"); return self; } dberrhandle(tinytds_err_handler); dbmsghandle(tinytds_msg_handler); GET_CLIENT_WRAPPER(self); cwrap->login = dblogin(); if (!NIL_P(user)) dbsetluser(cwrap->login, StringValuePtr(user)); if (!NIL_P(pass)) dbsetlpwd(cwrap->login, StringValuePtr(pass)); if (!NIL_P(app)) dbsetlapp(cwrap->login, StringValuePtr(app)); if (!NIL_P(version)) dbsetlversion(cwrap->login, NUM2INT(version)); if (!NIL_P(ltimeout)) dbsetlogintime(NUM2INT(ltimeout)); if (!NIL_P(timeout)) dbsettime(NUM2INT(timeout)); if (!NIL_P(charset)) DBSETLCHARSET(cwrap->login, StringValuePtr(charset)); cwrap->client = dbopen(cwrap->login, StringValuePtr(dataserver)); if (cwrap->client) { cwrap->closed = 0; cwrap->charset = charset; dbsetuserdata(cwrap->client, (BYTE*)cwrap->userdata); cwrap->userdata->closed = 0; if (!NIL_P(database)) dbuse(cwrap->client, StringValuePtr(database)); #ifdef HAVE_RUBY_ENCODING_H VALUE transposed_encoding = rb_funcall(cTinyTdsClient, intern_transpose_iconv_encoding, 1, charset); cwrap->encoding = rb_enc_find(StringValuePtr(transposed_encoding)); #endif } return self; }
void supla_datalogger::log(void) { gettimeofday(&now, NULL); if (now.tv_sec - temperature_tv.tv_sec >= TEMPLOG_INTERVAL) { temperature_tv = now; if (dbinit()) log_temperature(); } if (db != NULL) { delete db; db = NULL; } }
static int database_show(int fd, int argc, char *argv[]) { char prefix[256]; DBT key, data; char *keys, *values; int res; int pass; if (argc == 4) { /* Family and key tree */ snprintf(prefix, sizeof(prefix), "/%s/%s", argv[2], argv[3]); } else if (argc == 3) { /* Family only */ snprintf(prefix, sizeof(prefix), "/%s", argv[2]); } else if (argc == 2) { /* Neither */ prefix[0] = '\0'; } else { return RESULT_SHOWUSAGE; } ast_mutex_lock(&dblock); if (dbinit()) { ast_mutex_unlock(&dblock); ast_cli(fd, "Database unavailable\n"); return RESULT_SUCCESS; } memset(&key, 0, sizeof(key)); memset(&data, 0, sizeof(data)); pass = 0; while (!(res = astdb->seq(astdb, &key, &data, pass++ ? R_NEXT : R_FIRST))) { if (key.size) { keys = key.data; keys[key.size - 1] = '\0'; } else { keys = "<bad key>"; } if (data.size) { values = data.data; values[data.size - 1]='\0'; } else { values = "<bad value>"; } if (keymatch(keys, prefix)) { ast_cli(fd, "%-50s: %-25s\n", keys, values); } } ast_mutex_unlock(&dblock); return RESULT_SUCCESS; }
int main(int argc, char **argv) { read_login_info(argc, argv); dbinit(); test(DECIMALBIND); test(NUMERICBIND); dbexit(); printf("Succeed\n"); return 0; }
int main(void) { /* initialize db library */ if (dbinit() == FAIL) return 0; /* set message and error handler routines */ dberrhandle((EHANDLEFUNC)err_handler); dbmsghandle((MHANDLEFUNC)msg_handler); /* create login, user and pw are stored in sybdbex.h */ login = dblogin(); DBSETLUSER(login, USER); DBSETLPWD(login, PASSWORD); DBSETLAPP(login, "store_beispiel"); /* login to server */ dbproc = dbopen(login, "syb150"); dbuse(dbproc, "ma11s61406"); while(1) { get_berufe(); printf("beruf?\n"); gets(answer); if(strcmp(answer, "")==0) continue; while(1) { get_mitarbeiter(answer); printf("mitnr?\n"); gets(answer); if(strcmp(answer, "")==0) break; get_all(answer); break; } } /* dbexit(STDEXIT); */ dbexit(); exit(STDEXIT); }
int cwdb_init(void) { int res = 0; cw_db_load_config(); res = dbinit(); if (res == 0) { cw_cli_register(&cli_database_show); cw_cli_register(&cli_database_get); cw_cli_register(&cli_database_put); cw_cli_register(&cli_database_del); cw_cli_register(&cli_database_deltree); } return res; }
int ast_db_deltree(const char *family, const char *keytree) { char prefix[256]; DBT key, data; char *keys; int res; int pass; int counter = 0; if (family) { if (keytree) { snprintf(prefix, sizeof(prefix), "/%s/%s", family, keytree); } else { snprintf(prefix, sizeof(prefix), "/%s", family); } } else if (keytree) { return -1; } else { prefix[0] = '\0'; } ast_mutex_lock(&dblock); if (dbinit()) { ast_mutex_unlock(&dblock); return -1; } memset(&key, 0, sizeof(key)); memset(&data, 0, sizeof(data)); pass = 0; while (!(res = astdb->seq(astdb, &key, &data, pass++ ? R_NEXT : R_FIRST))) { if (key.size) { keys = key.data; keys[key.size - 1] = '\0'; } else { keys = "<bad key>"; } if (keymatch(keys, prefix)) { astdb->del(astdb, &key, 0); counter++; } } astdb->sync(astdb, 0); ast_mutex_unlock(&dblock); return counter; }
/*! * \internal * \brief Invoke a callback function on all keys, using given data and filter. * * \param cb Callback function to invoke (itself returns number of keys it affected). * \param data Value to pass to cb's data param. * \param filter Value to pass to cb's filter param. * \param sync If non-zero, call db_sync() when done. * \return Number of keys affected by the callback, or -1 if database is unavailable. */ static int process_db_keys(process_keys_cb cb, void *data, const char *filter, int sync) { DBT key = { 0, }, value = { 0, }, last_key = { 0, }; int counter = 0; int res, last = 0; char last_key_s[MAX_DB_FIELD]; ast_mutex_lock(&dblock); if (dbinit()) { ast_mutex_unlock(&dblock); return -1; } /* Somehow, the database can become corrupted such that astdb->seq will continue looping through * the database indefinitely. The pointer to last_key.data ends up getting re-used by the BDB lib * so this specifically queries for the last entry, makes a copy of the key, and then uses it as * a sentinel to avoid repeatedly looping over the list. */ if (astdb->seq(astdb, &last_key, &value, R_LAST)) { /* Empty database */ ast_mutex_unlock(&dblock); return 0; } memcpy(last_key_s, last_key.data, MIN(last_key.size - 1, sizeof(last_key_s))); last_key_s[last_key.size - 1] = '\0'; for (res = astdb->seq(astdb, &key, &value, R_FIRST); !res; res = astdb->seq(astdb, &key, &value, R_NEXT)) { /* The callback might delete the key, so we have to check it before calling */ last = !strcmp(dbt_data2str_full(&key, "<bad key>"), last_key_s); counter += cb(&key, &value, filter, data); if (last) { break; } } if (sync) { db_sync(); } ast_mutex_unlock(&dblock); return counter; }
/*! * \internal * \brief Get key value specified by family/key. * * Gets the value associated with the specified \a family and \a keys, and * stores it, either into the fixed sized buffer specified by \a buffer * and \a bufferlen, or as a heap allocated string if \a bufferlen is -1. * * \note If \a bufferlen is -1, \a buffer points to heap allocated memory * and must be freed by calling ast_free(). * * \retval -1 An error occurred * \retval 0 Success */ static int db_get_common(const char *family, const char *keys, char **buffer, int bufferlen) { char fullkey[MAX_DB_FIELD] = ""; DBT key, data; int res, fullkeylen; ast_mutex_lock(&dblock); if (dbinit()) { ast_mutex_unlock(&dblock); return -1; } fullkeylen = snprintf(fullkey, sizeof(fullkey), "/%s/%s", family, keys); memset(&key, 0, sizeof(key)); memset(&data, 0, sizeof(data)); key.data = fullkey; key.size = fullkeylen + 1; res = astdb->get(astdb, &key, &data, 0); /* Be sure to NULL terminate our data either way */ if (res) { ast_debug(1, "Unable to find key '%s' in family '%s'\n", keys, family); } else { if (data.size) { ((char *)data.data)[data.size - 1] = '\0'; if (bufferlen == -1) { *buffer = ast_strdup(data.data); } else { /* Make sure that we don't write too much to the dst pointer or we don't * read too much from the source pointer */ ast_copy_string(*buffer, data.data, bufferlen > data.size ? data.size : bufferlen); } } else { ast_log(LOG_NOTICE, "Strange, empty value for /%s/%s\n", family, keys); } } /* Data is not fully isolated for concurrency, so the lock must be extended * to after the copy to the output buffer. */ ast_mutex_unlock(&dblock); return res; }