예제 #1
0
int mail_cache_db_del(struct mail_cache_db * cache_db,
    const void * key, size_t key_len)
{
#if DBVERS >= 1
  int r;
  DBT db_key;
  DB * dbp;
  
  dbp = cache_db->internal_database;
  
  memset(&db_key, 0, sizeof(db_key));
  db_key.data = (void *) key;
  db_key.size = key_len;
  
#if DBVERS > 1  
  r = dbp->del(dbp, NULL, &db_key, 0);
#elif DBVERS == 1
  r = dbp->del(dbp, &db_key, 0);
#else
  r = -1;
#endif
  if (r != 0)
    return -1;
  
  return 0;
#else
  return -1;
#endif
}
예제 #2
0
파일: db3.c 프로젝트: xrg/RPM
static int db3cdel(dbiIndex dbi, DBC * dbcursor, DBT * key, DBT * data,
		unsigned int flags)
{
    DB * db = dbi->dbi_db;
    int rc;

    assert(db != NULL);
    if (dbcursor == NULL) {
	rc = db->del(db, dbi->dbi_txnid, key, flags);
	rc = cvtdberr(dbi, "db->del", rc, _debug);
    } else {
	int _printit;

	/* XXX TODO: insure that cursor is positioned with duplicates */
	rc = dbcursor->c_get(dbcursor, key, data, DB_SET);
	/* XXX DB_NOTFOUND can be returned */
	_printit = (rc == DB_NOTFOUND ? 0 : _debug);
	rc = cvtdberr(dbi, "dbcursor->c_get", rc, _printit);

	if (rc == 0) {
	    rc = dbcursor->c_del(dbcursor, flags);
	    rc = cvtdberr(dbi, "dbcursor->c_del", rc, _debug);
	}
    }

    return rc;
}
예제 #3
0
int vdadisk_write (const char *db_name, LogicalSector *sector) {
	DB *base;
	DBT key, data;
	int ret;

	if ((ret = db_create(&base, NULL, 0)) != 0)
		return ret;
	/* Associate DB with a file (create a btree)*/
	//if ((ret = base->open(base, NULL,concat( getGlobalHeap(), 2, db_name, ".db"), NULL, DB_BTREE, DB_CREATE, 0)) != 0) {
	if ((ret = base->open(base, NULL, db_name, NULL, DB_BTREE, DB_CREATE, 0)) != 0) {
		if(isDebugEnabled()) error( "[BDB] Fallo al abrir la base" );
		//base->err(base, ret, "DB open failed\n");
		base->close(base,0);
		return ret;
	}
	loadDBT (&key, &data, sector);
	ret = base->put(base, NULL, &key, &data, DB_NOOVERWRITE);
	if (ret == DB_KEYEXIST) {
		//base->err(base, ret, "La clave %d ya existe!\n");*
		//_itoa_s(sector->sectorId, aux, 10, 10);
		if(isDebugEnabled()) debug(concat( getGlobalHeap() , 2 , "[BDB] Ya existe el sector ", itoa_buf(sector->sectorId)));
		if ((ret = base->del(base, NULL, &key, 0)) == 0 ){  /* Si existe lo borro y lo vuelvo a escribir */
			if(isDebugEnabled()) debug(concat( getGlobalHeap() , 2 , "[BDB] Reescribiendo el sector ", itoa_buf(sector->sectorId)));
			ret = base->put(base, NULL, &key, &data, DB_NOOVERWRITE);
		}
	}
	base->close(base,0);
	return ret;
}
예제 #4
0
파일: db.c 프로젝트: rforge/rberkeley
/* {{{ rberkeley_db_del */
SEXP rberkeley_db_del(SEXP _dbp, SEXP _txnid, SEXP _key, SEXP _flags)
{
  DB *dbp;
  DBT key;
  DB_TXN *txnid;
  u_int32_t flags;
  int ret;

  memset(&key, 0, sizeof(key));
  key.data = (unsigned char *)RAW(_key);
  key.size = length(_key);

  dbp = R_ExternalPtrAddr(_dbp);
  if(R_ExternalPtrTag(_dbp) != RBerkeley_DB || dbp == NULL)
    error("invalid 'db' handle");

  if(!isNull(_txnid)) {
    txnid = R_ExternalPtrAddr(_txnid);
  } else {
    txnid = NULL;
  }

  flags = (u_int32_t)INTEGER(_flags)[0];

  ret = dbp->del(dbp, txnid, &key, flags);
  
  return ScalarInteger(ret);
}
예제 #5
0
int mail_cache_db_clean_up(struct mail_cache_db * cache_db,
    chash * exist)
{
  DB * dbp;
  int r;
  DBT db_key;
  DBT db_data;
  
  dbp = cache_db->internal_database;
  
  r = dbp->seq(dbp, &db_key, &db_data, R_FIRST);
  if (r == -1)
    return -1;
  
  while (r == 0) {
    chashdatum hash_key;
    chashdatum hash_data;
    
    hash_key.data = db_key.data;
    hash_key.len = db_key.size;

    r = chash_get(exist, &hash_key, &hash_data);
    if (r < 0) {
      r = dbp->del(dbp, &db_key, 0);
      if (r != 0)
        return -1;
    }
    
    r = dbp->seq(dbp, &db_key, &db_data, R_NEXT);
    if (r < 0)
      return -1;
  }
  
  return 0;
}
예제 #6
0
int uriindex_delete (char uri[], char subname[]) {

        DB *dbp = NULL;

        DBT key;
        int ret;
	int forreturn = 1;

        if (!uriindex_open(&dbp,subname, DB_CREATE)) {
		fprintf(stderr,"can't open uriindex\n");
		return 0;
	}


        //resetter minne
        memset(&key, 0, sizeof(DBT));

	//legger inn datane i bdb strukturen
        key.data = uri;
        key.size = strlen(uri);

        if ((ret = dbp->del(dbp, NULL, &key, 0)) == 0) {
		forreturn = 1;
        }
        else {
                dbp->err(dbp, ret, "DBcursor->get");
                forreturn = 0;
        }

	uriindex_close(&dbp);

	return forreturn;

}
예제 #7
0
    void CollectionMap::kill_ns(const StringData& ns) {
        init();
        if (!allocated()) { // that's ok, may dropping something that doesn't exist
            return;
        }
        if (!Lock::isWriteLocked(ns)) {
            throw RetryWithWriteLock();
        }

        // Must copy ns before we delete the collection, otherwise ns will be pointing to freed
        // memory.
        BSONObj nsobj = BSON("ns" << ns);

        CollectionStringMap::const_iterator it = _collections.find(ns);
        if (it != _collections.end()) {
            // Might not be in the _collections map if the ns exists but is closed.
            // Note this ns in the rollback, since we are about to modify its entry.
            CollectionMapRollback &rollback = cc().txn().collectionMapRollback();
            rollback.noteNs(ns);
            shared_ptr<Collection> cl = it->second;
            const int r = _collections.erase(ns);
            verify(r == 1);
            cl->close();
        }

        storage::Key sKey(nsobj, NULL);
        DBT ndbt = sKey.dbt();
        DB *db = _metadb->db();
        int r = db->del(db, cc().txn().db_txn(), &ndbt, 0);
        if (r != 0) {
            storage::handle_ydb_error_fatal(r);
        }
    }
예제 #8
0
    void NamespaceIndex::kill_ns(const StringData& ns) {
        init();
        if (!allocated()) { // that's ok, may dropping something that doesn't exist
            return;
        }
        if (!Lock::isWriteLocked(ns)) {
            throw RetryWithWriteLock();
        }

        NamespaceDetailsMap::const_iterator it = _namespaces.find(ns);
        if (it != _namespaces.end()) {
            // Might not be in the _namespaces map if the ns exists but is closed.
            // Note this ns in the rollback, since we are about to modify its entry.
            NamespaceIndexRollback &rollback = cc().txn().nsIndexRollback();
            rollback.noteNs(ns);
            shared_ptr<NamespaceDetails> d = it->second;
            const int r = _namespaces.erase(ns);
            verify(r == 1);
            d->close();
        }

        BSONObj nsobj = BSON("ns" << ns);
        storage::Key sKey(nsobj, NULL);
        DBT ndbt = sKey.dbt();
        DB *db = _nsdb->db();
        int r = db->del(db, cc().txn().db_txn(), &ndbt, 0);
        if (r != 0) {
            storage::handle_ydb_error_fatal(r);
        }
    }
예제 #9
0
// Delete a record from the database
static void del(bdb_drv_t *bdb_drv, ErlIOVec *ev) {
  ErlDrvBinary* data = ev->binv[1];
  char *bytes = data->orig_bytes;
  char *key_bytes = bytes+1;
  
  DB *db = bdb_drv->db;
  DBT key;
  int status;
  
  bzero(&key, sizeof(DBT));
    
  key.data = key_bytes;
  key.size = KEY_SIZE;
  
  status = db->del(db, NULL, &key, 0);
  db->sync(db, 0);
  
  if(status == 0) {
  	// Delete went OK, return atom 'ok'
    ErlDrvTermData spec[] = {ERL_DRV_ATOM, driver_mk_atom("ok")};
    
    driver_output_term(bdb_drv->port, spec, sizeof(spec) / sizeof(spec[0]));
    
  } else {
  	// There was an error
    char *error_reason;

    switch(status) {
    case DB_NOTFOUND:
      error_reason = "not_found";
      break;
    case DB_LOCK_DEADLOCK:
      error_reason = "deadlock";
      break;
    case DB_SECONDARY_BAD:
      error_reason = "bad_secondary_index";
      break;
    case EINVAL:
      error_reason = "bad_flag";
      break;
    case EACCES:
      error_reason = "readonly";
      break;
    case DB_RUNRECOVERY:
      error_reason = "run_recovery";
      break;
    default:
      error_reason = "unknown";
    }
    
    // Return tuple {error, Reason}
    ErlDrvTermData spec[] = {ERL_DRV_ATOM, driver_mk_atom("error"),
			     ERL_DRV_ATOM, driver_mk_atom(error_reason),
			     ERL_DRV_TUPLE, 2};

    driver_output_term(bdb_drv->port, spec, sizeof(spec) / sizeof(spec[0]));
  }
}
예제 #10
0
int pctlmfdb_rcv(struct pctldb_st *pctldb, struct timespec *ts,
		 struct memfile_st *mf, int *dberror){

  int status = 0;
  int dberror_del;
  DBT key, data;
  DB* mfdbp = pctldb->mfdbp;

  memset(&key, 0 , sizeof(DBT));
  memset(&data, 0 , sizeof(DBT));

  key.data = ts;
  key.ulen = sizeof(struct timespec);
  key.flags = DB_DBT_USERMEM;
  data.data = mf->p;
  data.ulen = get_memfile_allocated_size(mf);
  data.flags = DB_DBT_USERMEM;
  *dberror = mfdbp->get(mfdbp, NULL, &key, &data, 0);
  if(*dberror == DB_BUFFER_SMALL){
    status = realloc_memfile(mf, data.size);
    if(status == 0){
      data.data = mf->p;
      data.ulen = get_memfile_allocated_size(mf);
      *dberror = mfdbp->get(mfdbp, NULL, &key, &data, 0);
    }else
      *dberror = errno;
  }

  if(*dberror == 0)
    mf->size = data.size;
  else{
    status = -1;
    mf->size = 0; /* Only for convenience in the substraction below */
  }

  dberror_del = mfdbp->del(mfdbp, NULL, &key, 0);

  if(dberror_del == 0){
    if(pctldb->mf_total_size > mf->size)
      pctldb->mf_total_size -= mf->size;
    else
      pctldb->mf_total_size = 0;
  }else{
    if(*dberror == 0){
      status = -1;
      *dberror = dberror_del;
    }
  }

  return(status);
}
예제 #11
0
int del (void **db, void *key, int key_len, void *value, int value_len) {
    int ret;
    DB *dbp = *db;
    DBT db_key;

    memset(&db_key, 0, sizeof(db_key));
    db_key.data = key;
    db_key.size = key_len;

    if (ret = dbp->del(dbp, NULL, key, 0)) {
        dbp->err(dbp, ret, "DB->del");
        exit(1);
    }
}
예제 #12
0
int Db::del(DbTxn *txnid, Dbt *key, u_int32_t flags)
{
	DB *db = unwrap(this);
	int err;

	if ((err = db->del(db, unwrap(txnid), key, flags)) != 0) {
		// DB_NOTFOUND is a "normal" return, so should not be
		// thrown as an error
		//
		if (err != DB_NOTFOUND) {
			DB_ERROR("Db::del", err, error_policy());
			return (err);
		}
	}
	return (err);
}
예제 #13
0
파일: state.c 프로젝트: kbarber/cfng
void
DeletePersistentClass(char *name)
{
    int errno;
    DBT key,value;
    DB *dbp;
    struct CfState state;
    time_t now = time(NULL),expires;
    char filename[CF_BUFSIZE];

    snprintf(filename,CF_BUFSIZE,"%s/%s",g_vlockdir,CF_STATEDB_FILE);

    if ((errno = db_create(&dbp,NULL,0)) != 0) {
        snprintf(g_output, CF_BUFSIZE,
                "Couldn't open average database %s\n", filename);
        CfLog(cferror,g_output,"db_open");
        return;
    }

#ifdef CF_OLD_DB
    if ((errno = dbp->open(dbp,filename,NULL,DB_BTREE,
                    DB_CREATE,0644)) != 0)
#else
    if ((errno = dbp->open(dbp,NULL,filename,NULL,DB_BTREE,
                    DB_CREATE,0644)) != 0)
#endif
    {
    snprintf(g_output,CF_BUFSIZE,"Couldn't open average database %s\n",filename);
    CfLog(cferror,g_output,"db_open");
    return;
    }

    chmod(filename,0644);

    memset(&key,0,sizeof(key));
    memset(&value,0,sizeof(value));

    key.data = name;
    key.size = strlen(name)+1;

    if ((errno = dbp->del(dbp,NULL,&key,0)) != 0) {
        CfLog(cferror,"","db_store");
    }

    Debug("Deleted persistent state %s if found\n",name);
    dbp->close(dbp,0);
}
예제 #14
0
파일: vsdb.c 프로젝트: lembacon/VSDataStore
vsdb_ret_t vsdb_set(vsdb_t vsdb, const char *key, size_t key_length,
                                 const void *value, size_t value_size)
{
  DB *db;
  DBT kt, dt;
  int ret;

  if ((db = getdb(vsdb)) == NULL)
    goto failed;
  if (key == NULL)
    goto failed;
  if (key_length == SIZE_T_MAX)
    key_length = strlen(key);
  if (key_length == 0)
    goto failed;

  kt.data = (void *)key;
  kt.size = key_length;

  if (value != NULL) {
    dt.data = (void *)value;
    dt.size = value_size;

    lockdb(vsdb);
    ret = db->put(db, &kt, &dt, 0);
    unlockdb(vsdb);

    if (ret != 0) {
      goto failed;
    }
  }
  else {
    lockdb(vsdb);
    ret = db->del(db, &kt, 0);
    unlockdb(vsdb);

    if (ret != 0) {
      goto failed;
    }
  }

  return vsdb_okay;

failed:
  return vsdb_failed;
}
예제 #15
0
 int PerconaFTEngine::Del(Context& ctx, const KeyObject& key)
 {
     DB* db = GetFTDB(ctx, key.GetNameSpace(), ctx.flags.create_if_notexist);
     if (NULL == db)
     {
         return ERR_ENTRY_NOT_EXIST;
     }
     PerconaFTLocalContext& local_ctx = g_local_ctx.GetValue();
     Slice ks = local_ctx.GetSlice(key);
     DBT key_slice = to_dbt(ks);
     DB_TXN* txn = local_ctx.transc.Get();
     int r = 0;
     //CHECK_EXPR(r = m_env->txn_begin(m_env, NULL, &txn, 0));
     CHECK_EXPR(r = db->del(db, txn, &key_slice, 0));
     local_ctx.transc.Release(true);
     return ENGINE_NERR(r);
 }
예제 #16
0
/**
 * e_dbhash_remove:
 * @edbh: an #EDbHash
 * @key: a database key
 *
 * Removes the database object corresponding to @key.
 **/
void
e_dbhash_remove (EDbHash *edbh,
                 const gchar *key)
{
	DB *db;
	DBT dkey;

	g_return_if_fail (edbh != NULL);
	g_return_if_fail (edbh->priv != NULL);
	g_return_if_fail (key != NULL);

	db = edbh->priv->db;

	/* Key dbt */
	string_to_dbt (key, &dkey);

	/* Remove from database */
	db->del (db, NULL, &dkey, 0);
}
static void del (u_int32_t key_size, void* praw_key, bdb_drv_t *pdrv) {

    DB* pdb = pdrv->pcfg->pdb;

    DBT key;

    int ret, count;

    memset(&key, 0, sizeof(DBT));

    key.data   = praw_key,
    key.size   = key_size,

    count = 0;

    while (1) {

        ret = pdb->del(pdb, NULL, &key, 0);

        if        ((ret == 0) || (ret == DB_NOTFOUND)) {
            return_ok(pdrv);
            break;
        } else if (ret == DB_LOCK_DEADLOCK) {
            if (count < 5) {
                count = count + 1;
                usleep(1000);
            } else {
                return_error_tuple(pdrv, db_strerror(ret));
                break;
            }

        } else {
            return_error_tuple(pdrv, db_strerror(ret));
            break;
        }

    }

    return;

}
예제 #18
0
int bdb_id2entry_delete(
	BackendDB *be,
	DB_TXN *tid,
	Entry *e )
{
	struct bdb_info *bdb = (struct bdb_info *) be->be_private;
	DB *db = bdb->bi_id2entry->bdi_db;
	DBT key;
	int rc;

	bdb_cache_delete_entry(&bdb->bi_cache, e);

	DBTzero( &key );
	key.data = (char *) &e->e_id;
	key.size = sizeof(ID);

	/* delete from database */
	rc = db->del( db, tid, &key, 0 );

	return rc;
}
예제 #19
0
파일: cc_db.c 프로젝트: PADL/pam_ccreds
int pam_cc_db_delete(void *_db, const char *keyname, size_t keylength)
{
	DB *db = (DB *)_db;
	DBT key;
	int rc;

	memset(&key, 0, sizeof(key));
	key.data = (char *)keyname;
	key.size = keylength;

#if USE_FLOCK
	rc = _pam_cc_db_lock(db, LOCK_EX);
	if (rc != PAM_SUCCESS) {
		return rc;
	}
#endif

	rc = db->del(db,
#if DB_VERSION_MAJOR >= 2
		NULL,
#endif
		&key, 0);
	if (rc == 0) {
		rc = _pam_cc_db_sync(db);
	} else {
#if DB_VERSION_MAJOR >= 2
		if (rc != DB_NOTFOUND)
			errno = rc;
#endif
		return (rc == DB_NOTFOUND) ? PAM_AUTHINFO_UNAVAIL : PAM_SERVICE_ERR;
	}

#if USE_FLOCK
	_pam_cc_db_lock(db, LOCK_UN);
#endif

	return rc;
}
예제 #20
0
int
bdb_dn2id_delete(
	BackendDB	*be,
	DB_TXN *txn,
	char	*pdn,
	Entry	*e )
{
	struct bdb_info *bdb = (struct bdb_info *) be->be_private;
	int rc;
	DBT		key;
	DB *db = bdb->bi_id2parent->bdi_db;
	idNode *n;

	DBTzero(&key);
	key.size = sizeof(e->e_id);
	key.data = &e->e_id;

	rc = db->del( db, txn, &key, 0);

	ldap_pvt_thread_rdwr_wlock(&bdb->bi_tree_rdwr);
	n = avl_delete(&bdb->bi_tree, &e->e_id, node_find_cmp);
	if (n) {
		if (n->i_parent) {
			ldap_pvt_thread_rdwr_wlock(&n->i_parent->i_kids_rdwr);
			avl_delete(&n->i_parent->i_kids, &n->i_rdn->nrdn, node_frdn_cmp);
			ldap_pvt_thread_rdwr_wunlock(&n->i_parent->i_kids_rdwr);
		}
		free(n->i_rdn);
		ldap_pvt_thread_rdwr_destroy(&n->i_kids_rdwr);
		free(n);
	}
	if (e->e_id == 1)
		bdb->bi_troot = NULL;
	ldap_pvt_thread_rdwr_wunlock(&bdb->bi_tree_rdwr);

	return rc;
}
예제 #21
0
/*
 * Delete a row from table
 *
 * To delete ALL rows:
 *   do Not specify any keys, or values, and _n <=0
 *
 */
int bdb_delete(db_con_t* _h, db_key_t* _k, db_op_t* _op, db_val_t* _v, int _n)
{
    tbl_cache_p _tbc = NULL;
    table_p _tp = NULL;
    char kbuf[MAX_ROW_SIZE];
    int i, j, ret, klen;
    int *lkey=NULL;
    DBT key;
    DB *db;
    DBC *dbcp;
    str s;

    i = j = ret = 0;
    klen=MAX_ROW_SIZE;

    if (_op)
        return ( _bdb_delete_cursor(_h, _k, _op, _v, _n) );

    if ((!_h) || !CON_TABLE(_h))
        return -1;

    s.s = (char*)CON_TABLE(_h);
    s.len = strlen(CON_TABLE(_h));

    _tbc = bdblib_get_table(BDB_CON_CONNECTION(_h), &s);
    if(!_tbc)
    {   LM_WARN("table does not exist!\n");
        return -3;
    }

    _tp = _tbc->dtp;
    if(!_tp)
    {   LM_WARN("table not loaded!\n");
        return -4;
    }

#ifdef BDB_EXTRA_DEBUG
    LM_DBG("DELETE in %.*s\n", _tp->name.len, _tp->name.s );
#endif

    db = _tp->db;
    memset(&key, 0, sizeof(DBT));
    memset(kbuf, 0, klen);

    if(!_k || !_v || _n<=0)
    {
        /* Acquire a cursor for the database. */
        if ((ret = db->cursor(db, NULL, &dbcp, DB_WRITECURSOR) ) != 0)
        {   LM_ERR("Error creating cursor\n");
            goto error;
        }

        while ((ret = dbcp->c_get(dbcp, &key, NULL, DB_NEXT)) == 0)
        {
            if(!strncasecmp((char*)key.data,"METADATA",8))
                continue;
#ifdef BDB_EXTRA_DEBUG
            LM_DBG("KEY: [%.*s]\n"
                   , (int)   key.size
                   , (char *)key.data);
#endif
            ret = dbcp->c_del(dbcp, 0);
        }

        dbcp->c_close(dbcp);
        return 0;
    }

    lkey = bdb_get_colmap(_tp, _k, _n);
    if(!lkey)  return -5;

    /* make the key */
    if ( (ret = bdblib_valtochar(_tp, lkey, kbuf, &klen, _v, _n, BDB_KEY)) != 0 )
    {   LM_ERR("Error in bdblib_makekey\n");
        ret = -6;
        goto error;
    }

    key.data = kbuf;
    key.ulen = MAX_ROW_SIZE;
    key.flags = DB_DBT_USERMEM;
    key.size = klen;

    if ((ret = db->del(db, NULL, &key, 0)) == 0)
    {
        bdblib_log(JLOG_DELETE, _tp, kbuf, klen);

#ifdef BDB_EXTRA_DEBUG
        LM_DBG("DELETED ROW \n KEY: %s \n", (char *)key.data);
#endif
    }
    else
    {   /*Berkeley DB error handler*/
        switch(ret) {

        case DB_NOTFOUND:
            ret = 0;
            break;

        /*The following are all critical/fatal */
        case DB_LOCK_DEADLOCK:
        /* The operation was selected to resolve a deadlock. */
        case DB_SECONDARY_BAD:
        /* A secondary index references a nonexistent primary key. */
        case DB_RUNRECOVERY:
        default:
            LM_CRIT("DB->del error: %s.\n"
                    , db_strerror(ret));
            bdblib_recover(_tp, ret);
            goto error;
        }
    }

    ret = 0;

error:
    if(lkey)
        pkg_free(lkey);

    return ret;

}
예제 #22
0
/*
 * Updates a row in table
 * Limitation: only knows how to update a single row
 *
 * _con: structure representing database connection
 * _k: key names
 * _op: operators
 * _v: values of the keys that must match
 * _uk: update keys; cols that need to be updated
 * _uv: update values; col values that need to be commited
 * _un: number of rows to update
 */
int bdb_update(db_con_t* _con, db_key_t* _k, db_op_t* _op, db_val_t* _v,
               db_key_t* _uk, db_val_t* _uv, int _n, int _un)
{
    str s;
    char *c, *t;
    int ret, i, qcol, len, sum;
    int *lkey=NULL;
    tbl_cache_p _tbc = NULL;
    table_p _tp = NULL;
    char kbuf[MAX_ROW_SIZE];
    char qbuf[MAX_ROW_SIZE];
    char ubuf[MAX_ROW_SIZE];
    DBT key, qdata, udata;
    DB *db;

    sum = ret = i = qcol = len = 0;

    if (!_con || !CON_TABLE(_con) || !_uk || !_uv || _un <= 0)
        return -1;

    s.s = (char*)CON_TABLE(_con);
    s.len = strlen(CON_TABLE(_con));

    _tbc = bdblib_get_table(BDB_CON_CONNECTION(_con), &s);
    if(!_tbc)
    {   LM_ERR("table does not exist\n");
        return -1;
    }

    _tp = _tbc->dtp;
    if(!_tp)
    {   LM_ERR("table not loaded\n");
        return -1;
    }

    db = _tp->db;
    if(!db)
    {   LM_ERR("DB null ptr\n");
        return -1;
    }

#ifdef BDB_EXTRA_DEBUG
    LM_DBG("UPDATE in %.*s\n", _tp->name.len, _tp->name.s);
    if (_op) LM_DBG("DONT-CARE : _op: operators for refining query \n");
#endif

    memset(&key, 0, sizeof(DBT));
    memset(kbuf, 0, MAX_ROW_SIZE);
    memset(&qdata, 0, sizeof(DBT));
    memset(qbuf, 0, MAX_ROW_SIZE);

    qdata.data = qbuf;
    qdata.ulen = MAX_ROW_SIZE;
    qdata.flags = DB_DBT_USERMEM;

    if(_k)
    {   lkey = bdb_get_colmap(_tbc->dtp, _k, _n);
        if(!lkey) return -4;
    }
    else
    {
        LM_ERR("Null keys in update _k=0 \n");
        return -1;
    }

    len = MAX_ROW_SIZE;

    if ( (ret = bdblib_valtochar(_tp, lkey, kbuf, &len, _v, _n, BDB_KEY)) != 0 )
    {   LM_ERR("Error in query key \n");
        goto cleanup;
    }

    if(lkey) pkg_free(lkey);

    key.data = kbuf;
    key.ulen = MAX_ROW_SIZE;
    key.flags = DB_DBT_USERMEM;
    key.size = len;

    /*stage 1: QUERY Berkely DB*/
    if ((ret = db->get(db, NULL, &key, &qdata, 0)) == 0)
    {

#ifdef BDB_EXTRA_DEBUG
        LM_DBG("RESULT\nKEY:  [%.*s]\nDATA: [%.*s]\n"
               , (int)   key.size
               , (char *)key.data
               , (int)   qdata.size
               , (char *)qdata.data);
#endif

    }
    else
    {   goto db_error;
    }

    /* stage 2: UPDATE row with new values */

    /* map the provided keys to those in our schema */
    lkey = bdb_get_colmap(_tbc->dtp, _uk, _un);
    if(!lkey) return -4;

    /* build a new row for update data (udata) */
    memset(&udata, 0, sizeof(DBT));
    memset(ubuf, 0, MAX_ROW_SIZE);

    /* loop over each column of the qbuf and copy it to our new ubuf unless
       its a field that needs to update
    */
    c = strtok(qbuf, DELIM);
    t = ubuf;
    while( c!=NULL)
    {   char* delim = DELIM;
        int k;

        len = strlen(c);
        sum+=len;

        if(sum > MAX_ROW_SIZE)
        {   LM_ERR("value too long for string \n");
            ret = -3;
            goto cleanup;
        }

        for(i=0; i<_un; i++)
        {
            k = lkey[i];
            if (qcol == k)
            {   /* update this col */
                int j = MAX_ROW_SIZE - sum;
                if( bdb_val2str( &_uv[i], t, &j) )
                {   LM_ERR("value too long for string \n");
                    ret = -3;
                    goto cleanup;
                }

                goto next;
            }

        }

        /* copy original column to the new column */
        strncpy(t, c, len);

next:
        t+=len;

        /* append DELIM */
        sum += DELIM_LEN;
        if(sum > MAX_ROW_SIZE)
        {   LM_ERR("value too long for string \n");
            ret = -3;
            goto cleanup;
        }

        strncpy(t, delim, DELIM_LEN);
        t += DELIM_LEN;

        c = strtok(NULL, DELIM);
        qcol++;
    }

    ubuf[sum]  = '0';
    udata.data = ubuf;
    udata.ulen  = MAX_ROW_SIZE;
    udata.flags = DB_DBT_USERMEM;
    udata.size  = sum;

#ifdef BDB_EXTRA_DEBUG
    LM_DBG("MODIFIED Data\nKEY:  [%.*s]\nDATA: [%.*s]\n"
           , (int)   key.size
           , (char *)key.data
           , (int)   udata.size
           , (char *)udata.data);
#endif
    /* stage 3: DELETE old row using key*/
    if ((ret = db->del(db, NULL, &key, 0)) == 0)
    {
#ifdef BDB_EXTRA_DEBUG
        LM_DBG("DELETED ROW\nKEY: %s \n", (char *)key.data);
#endif
    }
    else
    {   goto db_error;
    }

    /* stage 4: INSERT new row with key*/
    if ((ret = db->put(db, NULL, &key, &udata, 0)) == 0)
    {
        bdblib_log(JLOG_UPDATE, _tp, ubuf, sum);
#ifdef BDB_EXTRA_DEBUG
        LM_DBG("INSERT \nKEY:  [%.*s]\nDATA: [%.*s]\n"
               , (int)   key.size
               , (char *)key.data
               , (int)   udata.size
               , (char *)udata.data);
#endif
    }
    else
    {   goto db_error;
    }

#ifdef BDB_EXTRA_DEBUG
    LM_DBG("UPDATE COMPLETE \n");
#endif


cleanup:
    if(lkey)
        pkg_free(lkey);

    return ret;


db_error:

    /*Berkeley DB error handler*/
    switch(ret)
    {

    case DB_NOTFOUND:

#ifdef BDB_EXTRA_DEBUG
        LM_DBG("NO RESULT \n");
#endif
        return -1;

    /* The following are all critical/fatal */
    case DB_LOCK_DEADLOCK:
    /* The operation was selected to resolve a deadlock. */
    case DB_SECONDARY_BAD:
    /* A secondary index references a nonexistent primary key.*/
    case DB_RUNRECOVERY:
    default:
        LM_CRIT("DB->get error: %s.\n", db_strerror(ret));
        bdblib_recover(_tp,ret);
    }

    if(lkey)
        pkg_free(lkey);

    return ret;
}
예제 #23
0
파일: b_del.c 프로젝트: mcandre/db
int
b_del(int argc, char *argv[])
{
	extern char *optarg;
	extern int optind, __db_getopt_reset;
	DB *dbp;
	DBC *dbc;
	DBT key, data;
	DBTYPE type;
#if DB_VERSION_MAJOR > 5 || (DB_VERSION_MAJOR == 5 && DB_VERSION_MINOR >= 2)
	DB_HEAP_RID rid;
#endif
	db_recno_t recno;
	u_int32_t cachesize;
	int ch, i, count, ret, use_cursor;
	char *ts, buf[32];

	type = DB_BTREE;
	cachesize = MEGABYTE;
	count = 100000;
	use_cursor = 0;
	ts = "Btree";
	__db_getopt_reset = 1;
	while ((ch = getopt(argc, argv, "C:c:t:w")) != EOF)
		switch (ch) {
		case 'C':
			cachesize = (u_int32_t)atoi(optarg);
			break;
		case 'c':
			count = atoi(optarg);
			break;
		case 't':
			switch (optarg[0]) {
			case 'B': case 'b':
				ts = "Btree";
				type = DB_BTREE;
				break;
			case 'H': case 'h':
				if (optarg[1] == 'E' || optarg[1] == 'e') {
#if DB_VERSION_MAJOR > 5 || (DB_VERSION_MAJOR == 5 && DB_VERSION_MINOR >= 2)
					if (b_util_have_heap())
						return (0);
					ts = "Heap";
					type = DB_HEAP;
#else
					fprintf(stderr,
				"b_curwalk: Heap is not supported! \n");
					return (EXIT_SUCCESS);
#endif
				} else {
					if (b_util_have_hash())
						return (0);
					ts = "Hash";
					type = DB_HASH;
				}
				break;
			case 'Q': case 'q':
				if (b_util_have_queue())
					return (0);
				ts = "Queue";
				type = DB_QUEUE;
				break;
			case 'R': case 'r':
				ts = "Recno";
				type = DB_RECNO;
				break;
			default:
				return (b_del_usage());
			}
			break;
		case 'w':
			use_cursor = 1;
			break;
		case '?':
		default:
			return (b_del_usage());
		}
	argc -= optind;
	argv += optind;
	if (argc != 0)
		return (b_del_usage());

	/* Create the database. */
	DB_BENCH_ASSERT(db_create(&dbp, NULL, 0) == 0);
	DB_BENCH_ASSERT(dbp->set_cachesize(dbp, 0, cachesize, 0) == 0);
	dbp->set_errfile(dbp, stderr);

#if DB_VERSION_MAJOR > 5 || (DB_VERSION_MAJOR == 5 && DB_VERSION_MINOR >= 2)
	/* Need a cursor if using Heap. */
	if (type == DB_HEAP && !use_cursor) {
		printf("Heap databases require the -w flag.\n");
		return (-1);
	}
#endif

	/* Set record length for Queue. */
	if (type == DB_QUEUE)
		DB_BENCH_ASSERT(dbp->set_re_len(dbp, 20) == 0);

#if DB_VERSION_MAJOR > 4 || (DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 1)
	DB_BENCH_ASSERT(
	    dbp->open(dbp, NULL, TESTFILE, NULL, type, DB_CREATE, 0666) == 0);
#else
	DB_BENCH_ASSERT(
	    dbp->open(dbp, TESTFILE, NULL, type, DB_CREATE, 0666) == 0);
#endif

	/* Initialize the data. */
	memset(&key, 0, sizeof(key));
	memset(&data, 0, sizeof(data));
	data.data = "01234567890123456789";
	data.size = 20;

	/* Store a key/data pair. */
	switch (type) {
	case DB_BTREE:
	case DB_HASH:
		key.data = buf;
		key.size = 10;
		break;
#if DB_VERSION_MAJOR > 5 || (DB_VERSION_MAJOR == 5 && DB_VERSION_MINOR >= 2)
	case DB_HEAP:
		key.data = &rid;
		key.size = sizeof(rid);
		break;
#endif
	case DB_QUEUE:
	case DB_RECNO:
		key.data = &recno;
		key.size = sizeof(recno);
		break;
	case DB_UNKNOWN:
		b_util_abort();
		break;
	}

	/* Insert count in-order key/data pairs. */
	if (type == DB_BTREE || type == DB_HASH)
		for (i = 0; i < count; ++i) {
			(void)snprintf(buf, sizeof(buf), "%010d", i);
			DB_BENCH_ASSERT(
			    dbp->put(dbp, NULL, &key, &data, 0) == 0);
		}
#if DB_VERSION_MAJOR > 5 || (DB_VERSION_MAJOR == 5 && DB_VERSION_MINOR >= 2)
	else if (type == DB_HEAP)
		for (i = 0; i < count; i++)
			DB_BENCH_ASSERT(
			    dbp->put(dbp, NULL, &key, &data, DB_APPEND) == 0);
#endif
	else
		for (i = 0, recno = 1; i < count; ++i, ++recno)
			DB_BENCH_ASSERT(
			    dbp->put(dbp, NULL, &key, &data, 0) == 0);

	/* Delete the records. */
	TIMER_START;
	if (use_cursor) {
		DB_BENCH_ASSERT(dbp->cursor(dbp, NULL, &dbc, 0) == 0);
		while ((ret = dbc->c_get(dbc, &key, &data, DB_NEXT)) == 0)
			DB_BENCH_ASSERT(dbc->c_del(dbc, 0) == 0);
		DB_BENCH_ASSERT (ret == DB_NOTFOUND);
	} else
		if (type == DB_BTREE || type == DB_HASH)
			for (i = 0; i < count; ++i) {
				(void)snprintf(buf, sizeof(buf), "%010d", i);
				DB_BENCH_ASSERT(
				    dbp->del(dbp, NULL, &key, 0) == 0);
			}
		else
			for (i = 0, recno = 1; i < count; ++i, ++recno)
				DB_BENCH_ASSERT(
				    dbp->del(dbp, NULL, &key, 0) == 0);

	TIMER_STOP;

	printf(
    "# %d %s database in-order delete of 10/20 byte key/data pairs using %s\n",
	    count, ts, use_cursor ? "a cursor" : "the key");
	TIMER_DISPLAY(count);

	DB_BENCH_ASSERT(dbp->close(dbp, 0) == 0);

	return (0);
}
예제 #24
0
static int remove_collection_entry(char* storage_space, char* collname)
{
    char collections_db[PATH_MAX];
    DB * dbp;
    DBT key, data;
    int ret = 0;
    TROVE_coll_id coll_id;

    sprintf(collections_db, "%s/collections.db", storage_space);

    ret = access(collections_db, F_OK);
    if(ret == -1 && errno == ENOENT)
    {
        fprintf(stderr, "Error: could not find %s.\n", collections_db);
        fprintf(stderr, "Error: src directory is not a known format.\n");
        return ret;
    }
    else if(ret == -1)
    {
        fprintf(stderr, "access(%s): %s\n", collections_db, strerror(errno));
        return -1;
    }

    ret = db_create(&dbp, NULL, 0);
    if(ret != 0)
    {
        fprintf(stderr, "Error: db_create: %s.\n", db_strerror(ret));
        return -1;
    }

    ret = dbp->open(dbp,
#ifdef HAVE_TXNID_PARAMETER_TO_DB_OPEN
                    NULL,
#endif
                    collections_db,
                    NULL,
                    DB_UNKNOWN,
                    0,
                    0);
    if(ret != 0)
    {
        fprintf(stderr, "Error: dbp->open: %s.\n", db_strerror(ret));
        return(-1);
    }

    memset(&key, 0, sizeof(key));
    memset(&data, 0, sizeof(data));

    key.data = collname;
    key.size = strlen(collname) + 1;
    data.data = &coll_id;
    data.ulen = sizeof(coll_id);
    data.flags = DB_DBT_USERMEM;

    ret = dbp->get(dbp, NULL, &key, &data, 0);
    if (ret != 0)
    {
        fprintf(stderr, "Error: dbp->get: %s\n", db_strerror(ret));
        return -1;
    }

    ret = dbp->del(dbp, NULL, &key, 0);
    if (ret != 0)
    {
        fprintf(stderr, "Error: dbp->del: %s\n", db_strerror(ret));
        return -1;
    }

    ret = dbp->sync(dbp, 0);
    if (ret != 0)
    {
        fprintf(stderr, "Error: dbp->sync: %s\n", db_strerror(ret));
        return -1;
    }

    dbp->close(dbp, 0);
    return 0;
}
예제 #25
0
파일: bucket.c 프로젝트: jgarzik/tabled
bool bucket_del(struct client *cli, const char *user, const char *bucket)
{
	char *hdr, timestr[64];
	enum errcode err = InternalError;
	int rc;
	struct db_bucket_ent ent;
	DB_ENV *dbenv = tdbrep.tdb.env;
	DB_TXN *txn = NULL;
	DB *buckets = tdbrep.tdb.buckets;
	DB *acls = tdbrep.tdb.acls;
	DB *objs = tdbrep.tdb.objs;
	DBC *cur = NULL;
	DBT key, val;
	char structbuf[sizeof(struct db_acl_key) + 32];
	struct db_acl_key *acl_key = (struct db_acl_key *) &structbuf;
	struct db_obj_key *obj_key = (struct db_obj_key *) &structbuf;

	if (!user)
		return cli_err(cli, AccessDenied);

	/* open transaction */
	rc = dbenv->txn_begin(dbenv, NULL, &txn, 0);
	if (rc) {
		dbenv->err(dbenv, rc, "DB_ENV->txn_begin");
		goto err_none;
	}

	/* search for (bucket, *) in object database, to see if
	 * any objects associated with this bucket exist
	 */
	rc = objs->cursor(objs, txn, &cur, 0);
	if (rc) {
		objs->err(objs, rc, "objs->cursor");
		goto err_out;
	}

	memset(&structbuf, 0, sizeof(structbuf));
	strncpy(obj_key->bucket, bucket, sizeof(obj_key->bucket));
	obj_key->key[0] = 0;

	memset(&key, 0, sizeof(key));
	memset(&val, 0, sizeof(val));

	key.data = obj_key;
	key.size = sizeof(*obj_key) + strlen(obj_key->key) + 1;

	val.flags = DB_DBT_MALLOC;

	rc = cur->get(cur, &key, &val, DB_SET_RANGE);

	if (rc == 0) {
		struct db_obj_key *newkey = key.data;

		if (!strcmp(newkey->bucket, bucket)) {
			free(newkey);
			cur->close(cur);
			err = BucketNotEmpty;
			goto err_out;
		}

		free(newkey);
	} else if (rc != DB_NOTFOUND)
		objs->err(objs, rc, "bucket_del empty check");

	rc = cur->close(cur);
	if (rc) {
		objs->err(objs, rc, "objs->cursor_close");
		goto err_out;
	}

	memset(&key, 0, sizeof(key));
	key.data = (char *) bucket;
	key.size = strlen(bucket) + 1;

	memset(&val, 0, sizeof(val));
	val.data = &ent;
	val.ulen = sizeof(struct db_bucket_ent);
	val.flags = DB_DBT_USERMEM;

	/* verify the bucket exists */
	rc = buckets->get(buckets, txn, &key, &val, 0);
	if (rc) {
		if (rc == DB_NOTFOUND)
			err = NoSuchBucket;
		else
			buckets->err(buckets, rc, "buckets->get");
		goto err_out;
	}

	/* verify that it is the owner who wishes to delete bucket */
	if (strncmp(user, ent.owner, sizeof(ent.owner))) {
		err = AccessDenied;
		goto err_out;
	}

	/* delete bucket */
	rc = buckets->del(buckets, txn, &key, 0);
	if (rc) {
		buckets->err(buckets, rc, "bucket del");
		goto err_out;
	}

	/* delete bucket ACLs */
	memset(&structbuf, 0, sizeof(structbuf));
	strncpy(acl_key->bucket, bucket, sizeof(acl_key->bucket));
	acl_key->key[0] = 0;

	memset(&key, 0, sizeof(key));
	key.data = acl_key;
	key.size = sizeof(*acl_key) + strlen(acl_key->key) + 1;

	rc = acls->del(acls, txn, &key, 0);
	if (rc && rc != DB_NOTFOUND) {
		acls->err(acls, rc, "acl del");
		goto err_out;
	}

	/* commit */
	rc = txn->commit(txn, 0);
	if (rc) {
		dbenv->err(dbenv, rc, "DB_ENV->txn_commit");
		return cli_err(cli, InternalError);
	}

	if (asprintf(&hdr,
"HTTP/%d.%d 204 x\r\n"
"Content-Length: 0\r\n"
"Date: %s\r\n"
"Server: " PACKAGE_STRING "\r\n"
"\r\n",
		     cli->req.major,
		     cli->req.minor,
		     hutil_time2str(timestr, sizeof(timestr), time(NULL))) < 0)
		return cli_err(cli, InternalError);

	rc = atcp_writeq(&cli->wst, hdr, strlen(hdr), atcp_cb_free, hdr);
	if (rc) {
		free(hdr);
		return true;
	}

	return atcp_write_start(&cli->wst);

err_out:
	rc = txn->abort(txn);
	if (rc)
		dbenv->err(dbenv, rc, "DB_ENV->txn_abort");
err_none:
	return cli_err(cli, err);
}
예제 #26
0
파일: c_example.c 프로젝트: h0st/m3sec
int main() 
{
  DB *dbp;
  DBT key, data;
  int ret, t_ret;

  if ((ret = db_create(&dbp, NULL, 0)) != 0) 
  {
    cerr << "db_create:" << db_strerror(ret) << endl;
    exit (1);
  }

  if ((ret = dbp->open(dbp, NULL, kDatabaseName, "",
                       DB_BTREE, DB_CREATE, 0664)) != 0) 
  {
    dbp->err(dbp, ret, "%s", kDatabaseName);
    goto err;
  }

  memset(&key, 0, sizeof(key));
  memset(&data, 0, sizeof(data));
  key.data = (char*)"fruit";
  key.size = sizeof("fruit");
  data.data = (char*)"apple";
  data.size = sizeof("apple");

  if ((ret = dbp->put(dbp, NULL, &key, &data, 0)) == 0)
    cout << "db: " << (char*)key.data << ": key stored.\n";
  else 
  {
    dbp->err(dbp, ret, "DB->put");
    goto err;
  }

  if ((ret = dbp->get(dbp, NULL, &key, &data, 0)) == 0)
    cout << "db: " << (char*)key.data
         << ": key retrieved: data was " << (char *)data.data << endl;
  else 
  {
    dbp->err(dbp, ret, "DB->get");
    goto err;
  }

  if ((ret = dbp->del(dbp, NULL, &key, 0)) == 0)
    cout << "db: " << (char*)key.data << " key was deleted.\n";
  else 
  {
    dbp->err(dbp, ret, "DB->del");
    goto err;
  }

  if ((ret = dbp->get(dbp, NULL, &key, &data, 0)) == 0)
    cout << "db: " << (char*)key.data << ": key retrieved: data was "
         << (char *)data.data << endl;
  else
    dbp->err(dbp, ret, "DB->get");

err:
  if ((t_ret = dbp->close(dbp, 0)) != 0 && ret == 0)
    ret = t_ret;

  return ret;
}
예제 #27
0
int
dbupdate(char *dbname, char *ip)
{
	HASHINFO	hashinfo;
	DBT		dbk, dbd;
	DB		*db;
	struct gdata	gd;
	time_t		now;
	int		r;
	struct in_addr	ia;

	now = time(NULL);
	memset(&hashinfo, 0, sizeof(hashinfo));
	db = dbopen(dbname, O_EXLOCK|O_RDWR, 0600, DB_HASH, &hashinfo);
	if (db == NULL) {
		logmsg(LOG_ERR, "Can not open db %s: %s", dbname,
		    strerror(errno));
		return (-1);
	}
	if (inet_pton(AF_INET, ip, &ia) != 1) {
		logmsg(LOG_NOTICE, "Invalid IP address %s", ip);
		goto bad;
	}
	memset(&dbk, 0, sizeof(dbk));
	dbk.size = strlen(ip);
	dbk.data = ip;
	memset(&dbd, 0, sizeof(dbd));

	/* add or update whitelist entry */
	r = db->get(db, &dbk, &dbd, 0);
	if (r == -1) {
		logmsg(LOG_NOTICE, "db->get failed (%m)");
		goto bad;
	}

	if (r) {
		/* new entry */
		memset(&gd, 0, sizeof(gd));
		gd.first = now;
		gd.bcount = 1;
		gd.pass = now;
		gd.expire = now + whiteexp;
		memset(&dbk, 0, sizeof(dbk));
		dbk.size = strlen(ip);
		dbk.data = ip;
		memset(&dbd, 0, sizeof(dbd));
		dbd.size = sizeof(gd);
		dbd.data = &gd;
		r = db->put(db, &dbk, &dbd, 0);
		if (r) {
			logmsg(LOG_NOTICE, "db->put failed (%m)");
			goto bad;
		}
	} else {
		if (dbd.size != sizeof(gd)) {
			/* whatever this is, it doesn't belong */
			db->del(db, &dbk, 0);
			goto bad;
		}
		memcpy(&gd, dbd.data, sizeof(gd));
		gd.pcount++;
		gd.expire = now + whiteexp;
		memset(&dbk, 0, sizeof(dbk));
		dbk.size = strlen(ip);
		dbk.data = ip;
		memset(&dbd, 0, sizeof(dbd));
		dbd.size = sizeof(gd);
		dbd.data = &gd;
		r = db->put(db, &dbk, &dbd, 0);
		if (r) {
			logmsg(LOG_NOTICE, "db->put failed (%m)");
			goto bad;
		}
	}
	db->close(db);
	db = NULL;
	if (syncsend)
		sync_white(now, now + whiteexp, ip);
	return (0);
 bad:
	db->close(db);
	db = NULL;
	return (-1);
}
예제 #28
0
int _sasldb_putdata(const sasl_utils_t *utils,
		    sasl_conn_t *context,
		    const char *authid,
		    const char *realm,
		    const char *propName,
		    const char *data_in, size_t data_len)
{
  int result = SASL_OK;
  char *key;
  size_t key_len;
  DBT dbkey;
  DB *mbdb = NULL;

  if (!utils) return SASL_BADPARAM;

  if (!authid || !realm || !propName) {
      utils->seterror(context, 0,
		      "Bad parameter in db_berkeley.c: _sasldb_putdata");
      return SASL_BADPARAM;
  }
  
  if (!db_ok) {
      utils->seterror(context, 0,
		      "Database not checked");   
      return SASL_FAIL;
  }

  result = _sasldb_alloc_key(utils, authid, realm, propName,
			     &key, &key_len);
  if (result != SASL_OK) {
       utils->seterror(context, 0,
		      "Could not allocate key in _sasldb_putdata");     
       return result;
  }

  /* open the db */
  result=berkeleydb_open(utils, context, 1, &mbdb);
  if (result!=SASL_OK) goto cleanup;

  /* create the db key */
  memset(&dbkey, 0, sizeof(dbkey));
  dbkey.data = key;
  dbkey.size = key_len;

  if (data_in) {   /* putting secret */
    DBT data;

    memset(&data, 0, sizeof(data));    

    data.data = (char *)data_in;
    if(!data_len) data_len = strlen(data_in);
    data.size = data_len;

    result = mbdb->put(mbdb, NULL, &dbkey, &data, 0);

    if (result != 0)
    {
      utils->log(NULL, SASL_LOG_ERR,
		 "error updating sasldb: %s", db_strerror(result));
      utils->seterror(context, SASL_NOLOG,
		      "Couldn't update db");
      result = SASL_FAIL;
      goto cleanup;
    }
  } else {        /* removing secret */
    result=mbdb->del(mbdb, NULL, &dbkey, 0);

    if (result != 0)
    {
      utils->log(NULL, SASL_LOG_ERR,
		 "error deleting entry from sasldb: %s", db_strerror(result));
      utils->seterror(context, SASL_NOLOG,
		      "Couldn't update db");
      if (result == DB_NOTFOUND)
	  result = SASL_NOUSER;
      else	  
	  result = SASL_FAIL;
      goto cleanup;
    }
  }

 cleanup:

  if (mbdb != NULL) berkeleydb_close(utils, mbdb);

  utils->free(key);

  return result;
}
예제 #29
0
파일: dn2id.c 프로젝트: cptaffe/openldap
int
bdb_dn2id_delete(
	Operation *op,
	DB_TXN *txn,
	EntryInfo	*eip,
	Entry		*e )
{
	struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
	DB *db = bdb->bi_dn2id->bdi_db;
	char		*buf;
	DBT		key;
	struct berval	pdn, ptr;
	int		rc;

	Debug( LDAP_DEBUG_TRACE, "=> bdb_dn2id_delete 0x%lx: \"%s\"\n",
		e->e_id, e->e_ndn, 0 );

	DBTzero( &key );
	key.size = e->e_nname.bv_len + 2;
	buf = op->o_tmpalloc( key.size, op->o_tmpmemctx );
	key.data = buf;
	key.flags = DB_DBT_USERMEM;
	buf[0] = DN_BASE_PREFIX;
	ptr.bv_val = buf+1;
	ptr.bv_len = e->e_nname.bv_len;
	AC_MEMCPY( ptr.bv_val, e->e_nname.bv_val, e->e_nname.bv_len );
	ptr.bv_val[ptr.bv_len] = '\0';

	/* delete it */
	rc = db->del( db, txn, &key, 0 );
	if( rc != 0 ) {
		Debug( LDAP_DEBUG_ANY, "=> bdb_dn2id_delete 0x%lx: delete failed: %s %d\n",
			e->e_id, db_strerror(rc), rc );
		goto done;
	}

#ifndef BDB_MULTIPLE_SUFFIXES
	if( !be_issuffix( op->o_bd, &ptr ))
#endif
	{
		buf[0] = DN_SUBTREE_PREFIX;
		rc = bdb_idl_delete_key( op->o_bd, db, txn, &key, e->e_id );
		if( rc != 0 ) {
			Debug( LDAP_DEBUG_ANY,
			"=> bdb_dn2id_delete 0x%lx: subtree (%s) delete failed: %d\n",
			e->e_id, ptr.bv_val, rc );
			goto done;
		}

#ifdef BDB_MULTIPLE_SUFFIXES
	if( !be_issuffix( op->o_bd, &ptr ))
#endif
	{
		dnParent( &ptr, &pdn );

		key.size = pdn.bv_len + 2;
		key.ulen = key.size;
		pdn.bv_val[-1] = DN_ONE_PREFIX;
		key.data = pdn.bv_val - 1;
		ptr = pdn;

		rc = bdb_idl_delete_key( op->o_bd, db, txn, &key, e->e_id );

		if( rc != 0 ) {
			Debug( LDAP_DEBUG_ANY,
				"=> bdb_dn2id_delete 0x%lx: parent (%s) delete failed: %d\n",
				e->e_id, ptr.bv_val, rc );
			goto done;
		}
	}

#ifndef BDB_MULTIPLE_SUFFIXES
	while( !be_issuffix( op->o_bd, &ptr ))
#else
	for (;;)
#endif
	{
		ptr.bv_val[-1] = DN_SUBTREE_PREFIX;

		rc = bdb_idl_delete_key( op->o_bd, db, txn, &key, e->e_id );
		if( rc != 0 ) {
			Debug( LDAP_DEBUG_ANY,
				"=> bdb_dn2id_delete 0x%lx: subtree (%s) delete failed: %d\n",
				e->e_id, ptr.bv_val, rc );
			goto done;
		}
#ifdef BDB_MULTIPLE_SUFFIXES
		if( be_issuffix( op->o_bd, &ptr )) break;
#endif
		dnParent( &ptr, &pdn );

		key.size = pdn.bv_len + 2;
		key.ulen = key.size;
		key.data = pdn.bv_val - 1;
		ptr = pdn;
	}
	}

done:
	op->o_tmpfree( buf, op->o_tmpmemctx );
	Debug( LDAP_DEBUG_TRACE, "<= bdb_dn2id_delete 0x%lx: %d\n", e->e_id, rc, 0 );
	return rc;
}
예제 #30
0
파일: ip.c 프로젝트: kbarber/cfng
void CheckFriendConnections(int hours)
{
    DBT key,value;
    DB *dbp;
    DBC *dbcp;
    DB_ENV *dbenv = NULL;
    int ret, secs = 3600*hours, criterion;
    struct stat statbuf;
    time_t now = time(NULL),splaytime = 0;
    char name[CF_BUFSIZE];
    static struct LastSeen entry;
    double average = 0;

    if (GetMacroValue(g_contextid,"SplayTime")) {
        splaytime = atoi(GetMacroValue(g_contextid,"SplayTime"));
        if (splaytime < 0) {
            splaytime = 0;
        }
    }

    Verbose("CheckFriendConnections(%d)\n",hours);
    snprintf(name,CF_BUFSIZE-1,"%s/%s",g_vlockdir,CF_LASTDB_FILE);

    if ((errno = db_create(&dbp,dbenv,0)) != 0) {
        snprintf(g_output, CF_BUFSIZE*2,
                "Couldn't open last-seen database %s\n", name);
        CfLog(cferror,g_output,"db_open");
        return;
    }

#ifdef CF_OLD_DB
    if ((errno = dbp->open(dbp,name,NULL,DB_BTREE,DB_CREATE,0644)) != 0)
#else
    if ((errno = dbp->open(dbp,NULL,name,NULL,DB_BTREE,DB_CREATE,0644)) != 0)
#endif
   {
    snprintf(g_output, CF_BUFSIZE*2, 
            "Couldn't open last-seen database %s\n", name);
    CfLog(cferror,g_output,"db_open");
    dbp->close(dbp,0);
    return;
   }

    /* Acquire a cursor for the database. */

    if ((ret = dbp->cursor(dbp, NULL, &dbcp, 0)) != 0) {
        CfLog(cferror,"Error reading from last-seen database","");
        dbp->err(dbp, ret, "DB->cursor");
        return;
    }

    /* Initialize the key/data return pair. */

    memset(&key, 0, sizeof(key));
    memset(&value, 0, sizeof(value));
    memset(&entry, 0, sizeof(entry));

    /* Walk through the database and print out the key/data pairs. */

    while (dbcp->c_get(dbcp, &key, &value, DB_NEXT) == 0) {
        time_t then;

        bcopy(value.data,&then,sizeof(then));

        if (value.data != NULL) {
            bcopy(value.data,&entry,sizeof(entry));
            then = entry.lastseen;
            average = entry.expect_lastseen;
        } else {
            continue;
        }

        if (secs == 0) {
            criterion = now > then + splaytime + (int)(average+0.5);
        } else {
            criterion = now > then + splaytime + secs;
        }

        if ((int)average > CF_WEEK) {
            criterion = false;
        }

        /* anomalous couplings do not count*/
        if (average < 1800) {
            criterion = false;
        }

        snprintf(g_output, CF_BUFSIZE, 
                "Host %s last at %s\ti.e. not seen for %.2fhours\n\t"
                "(Expected <delta_t> = %.2f secs (= %.2f hours))",
                (char *)key.data,ctime(&then),
                (now-then) / 3600.0,average,
                average / 3600.0);

        if (criterion) {
            CfLog(cferror,g_output,"");

            if (now > CF_WEEK + then + splaytime + 2*3600) {

                snprintf(g_output, CF_BUFSIZE*2,
                        "INFO: Giving up on %s, last seen more than "
                        "a week ago at %s.", key.data, ctime(&then));

                CfLog(cferror,g_output,"");

            if ((errno = dbp->del(dbp,NULL,&key,0)) != 0) {
                CfLog(cferror,"","db_store");
                }
            }
        } else {
            CfLog(cfinform,g_output,"");
        }
    }

    dbcp->c_close(dbcp);
    dbp->close(dbp,0);
}