Beispiel #1
0
static PyObject *
_dbm_dbm_keys_impl(dbmobject *self)
/*[clinic end generated code: output=434549f7c121b33c input=d210ba778cd9c68a]*/
{
    PyObject *v, *item;
    datum key;
    int err;

    check_dbmobject_open(self);
    v = PyList_New(0);
    if (v == NULL)
        return NULL;
    for (key = dbm_firstkey(self->di_dbm); key.dptr;
         key = dbm_nextkey(self->di_dbm)) {
        item = PyBytes_FromStringAndSize(key.dptr, key.dsize);
        if (item == NULL) {
            Py_DECREF(v);
            return NULL;
        }
        err = PyList_Append(v, item);
        Py_DECREF(item);
        if (err != 0) {
            Py_DECREF(v);
            return NULL;
        }
    }
    return v;
}
Beispiel #2
0
static PyObject *
dbm_keys(register dbmobject *dp, PyObject *unused)
{
	register PyObject *v, *item;
	datum key;
	int err;

        check_dbmobject_open(dp);
	v = PyList_New(0);
	if (v == NULL)
		return NULL;
	for (key = dbm_firstkey(dp->di_dbm); key.dptr;
	     key = dbm_nextkey(dp->di_dbm)) {
		item = PyString_FromStringAndSize(key.dptr, key.dsize);
		if (item == NULL) {
			Py_DECREF(v);
			return NULL;
		}
		err = PyList_Append(v, item);
		Py_DECREF(item);
		if (err != 0) {
			Py_DECREF(v);
			return NULL;
		}
	}
	return v;
}
Beispiel #3
0
int main(int argc, char *argv[]) {
  int i;
  DBM *db;
  datum daKey, daVal;

  /* Open the database (create) */
  db = dbm_open("ndbmTest", O_RDWR, 0660);
  if(db == NULL) {
    printf("ERROR: Could not open the DB file.  Error number: %d.\n", errno);
    exit(1);
  } else {
    printf("DB handle created.\n");
    printf("DB file opened.\n");
  }

  /* At this point you can add and remove things from the DB just as in mkNDBM. */
 
  /* Traverse the entire DB and lookup each key. */
  printf("All the records in the DB:\n");
  for(i=1,daKey=dbm_firstkey(db); daKey.dptr!=NULL; daKey=dbm_nextkey(db),i++) {
    daVal = dbm_fetch(db, daKey);
    if(daVal.dptr == NULL) {
      printf("ERROR: Could not look up %s\n", (char *)daKey.dptr);
    } else {
      printf("  Record(%d): '%s' ==> '%s'\n", i, (char *)daKey.dptr, (char *)daVal.dptr);
    } /* end if/else */
  } /* end for */
  printf("Found %d records\n", i-1);

  /* Close the DB (flush everything to the file) */
  dbm_close(db);
  printf("DB closed... Bye!\n");

  return 0;
} /* end func main */
Beispiel #4
0
/* Check for the existence of the replay dbm file, and create it if it does
 * not exist.  Returns the number of db entries or -1 on error.
*/
static int
replay_db_cache_init(fko_srv_options_t *opts)
{
#ifdef NO_DIGEST_CACHE
    return(-1);
#else

#ifdef HAVE_LIBGDBM
    GDBM_FILE   rpdb;
#elif HAVE_LIBNDBM
    DBM        *rpdb;
    datum       db_ent;
#endif

    datum       db_key, db_next_key;
    int         db_count = 0;

#ifdef HAVE_LIBGDBM
    rpdb = gdbm_open(
        opts->config[CONF_DIGEST_DB_FILE], 512, GDBM_WRCREAT, S_IRUSR|S_IWUSR, 0
    );
#elif HAVE_LIBNDBM
    rpdb = dbm_open(
        opts->config[CONF_DIGEST_DB_FILE], O_RDWR|O_CREAT, S_IRUSR|S_IWUSR
    );
#endif

    if(!rpdb)
    {
        log_msg(LOG_ERR,
            "Unable to open digest cache file: '%s': %s",
            opts->config[CONF_DIGEST_DB_FILE],
            MY_DBM_STRERROR(errno)
        );

        return(-1);
    }

#ifdef HAVE_LIBGDBM
    db_key = gdbm_firstkey(rpdb);

    while (db_key.dptr != NULL)
    {
        db_count++;
        db_next_key = gdbm_nextkey(rpdb, db_key);
        free(db_key.dptr);
        db_key = db_next_key;
    }
#elif HAVE_LIBNDBM
    for (db_key = dbm_firstkey(rpdb); db_ent.dptr != NULL; db_key = dbm_nextkey(rpdb))
        db_count++;
#endif

    MY_DBM_CLOSE(rpdb);

    return(db_count);
#endif /* NO_DIGEST_CACHE */
}
Beispiel #5
0
void runSuccess() {
    char buf[] = "file";
    //@ assert \valid(buf+(0..\block_length(buf)-1));
    //@ assert \exists integer x; buf[x] == '\0';

    DBM* db = dbm_open(buf, O_RDWR, S_IRUSR);
    if (db == NULL) {return;}

    dbm_firstkey(db);
}
Beispiel #6
0
Datum
ldbm_firstkey( LDBM ldbm, LDBMCursor **dbcp )
{
	Datum d;

	LDBM_RLOCK;
	d = dbm_firstkey( ldbm );
	LDBM_RUNLOCK;

	return d;
}
Beispiel #7
0
value caml_dbm_firstkey(value vdb)            /* ML */
{
  datum key = dbm_firstkey(extract_dbm(vdb));

  if (key.dptr) {
    value res = alloc_string(key.dsize);
    memmove (String_val (res), key.dptr, key.dsize);
    return res;
  }
  else raise_not_found();
}
Beispiel #8
0
static apr_status_t vt_ndbm_firstkey(apr_dbm_t *dbm, apr_datum_t *pkey)
{
    datum rd;

    rd = dbm_firstkey(dbm->file);

    pkey->dptr = rd.dptr;
    pkey->dsize = rd.dsize;

    /* store any error info into DBM, and return a status code. */
    return set_error(dbm, APR_SUCCESS);
}
Beispiel #9
0
static int
_ndbm_firstkey (mu_dbm_file_t db, struct mu_dbm_datum *ret)
{
  DBM *dbm = db->db_descr;
  datum keydat;

  errno = 0;
  keydat = dbm_firstkey (dbm);
  if (keydat.dptr == NULL)
    return MU_ERR_NOENT;
  return _ndbm_conv_datum (db, ret, keydat);
}
Beispiel #10
0
void dbm_list(DBM *dbmgroup) {
  datum key,resp;

  for (key = dbm_firstkey(dbmgroup); key.dptr !=  NULL;  key = dbm_nextkey(dbmgroup)) {
    resp = dbm_fetch(dbmgroup,key);
    printf("Group: %s\n",key.dptr);
    if (resp.dptr) {
      printf(" Users: %s\n",resp.dptr);
    } else {
      printf(" Empty\n");
    }
  }
}
Beispiel #11
0
int main (int argc, char *argv[]) 
{
    FILE *std_fp;
    DBM  *db;
    datum dtKey, dtRec;
    char rec[MAX_STRING_LEN];
    char key[MAX_STRING_LEN];
    char *pch1, *pch2;
    int  ndx;

    if (argc != 3) 
	usage(argv[0]);

    if (!(std_fp = fopen(argv[2], "w"))) {
	fprintf(stderr,"%s: Could not open file %s for writing.\n",
		argv[0],argv[2]);
	perror("fopen");
	exit(1);
    }

    if (!(db = dbm_open (argv[1], O_RDONLY, 0))) {
	fprintf(stderr,"%s: Could not open database file %s.\n", 
		argv[0], argv[1]);
        exit(1);
    }

    for (dtKey = dbm_firstkey(db); dtKey.dptr; dtKey = dbm_nextkey(db)) {
	dtRec = dbm_fetch (db, dtKey);

	pch1 = key;
	for (ndx = 0; ndx < dtKey.dsize; ndx++)
	    *pch1++ = dtKey.dptr[ndx];
	*pch1 = '\0';

	pch2 = rec;
	for (ndx = 0; ndx < dtRec.dsize; ndx++)
	    *pch2++ = dtRec.dptr[ndx];
	*pch2 = '\0';

	printf ("Storing data <%s> with key <%s>\n",
		rec, key);
	if (strchr (rec, ' '))
	    fprintf (std_fp,"%s: %s\n", key, rec);
	else
	    fprintf (std_fp,"%s:%s\n", key, rec);
    }

    dbm_close(db);
    exit(0);
}
Beispiel #12
0
void testValues() {
    f = 2;
    datum result;
    char buf[] = "file";
    //@ assert \valid(buf+(0..\block_length(buf)-1));
    //@ assert \exists integer x; buf[x] == '\0';

    DBM* db = dbm_open(buf, O_RDWR, S_IRUSR);
    if (db == NULL) {return;}
    
    result = dbm_firstkey(db);
    //@ assert result.dptr == \null || \valid((char*)result.dptr);
    
    //@ assert f == 2;
    //@ assert vacuous: \false;
}
Beispiel #13
0
/* This function searches for a catalog entry, where the catalog
   text contains the provided search text. If the search text points
   to a null character then all entries are considered to match */
cdc_entry search_cdc_entry(const char *cd_catalog_ptr, int *first_call_ptr)
{
    static int local_first_call = 1;
    cdc_entry entry_to_return;
    datum local_data_datum;
    static datum local_key_datum;	/* notice this must be static */

    memset(&entry_to_return, '\0', sizeof(entry_to_return));

    /* check database initialized and parameters valid */
    if (!cdc_dbm_ptr || !cdt_dbm_ptr) return (entry_to_return);
    if (!cd_catalog_ptr || !first_call_ptr) return (entry_to_return);
    if (strlen(cd_catalog_ptr) >= CAT_CAT_LEN) return (entry_to_return);

    /* protect against never passing *first_call_ptr true */
    if (local_first_call) {
	local_first_call = 0;
	*first_call_ptr = 1;
    }
    if (*first_call_ptr) {
	*first_call_ptr = 0;
	local_key_datum = dbm_firstkey(cdc_dbm_ptr);
    } else {
	local_key_datum = dbm_nextkey(cdc_dbm_ptr);
    }

    do {
	if (local_key_datum.dptr != NULL) {
	    /* an entry was found */
	    local_data_datum = dbm_fetch(cdc_dbm_ptr, local_key_datum);
	    if (local_data_datum.dptr) {
		memcpy(&entry_to_return, (char *) local_data_datum.dptr, local_data_datum.dsize);

		/* check if search string occures in the entry */
		if (!strstr(entry_to_return.catalog, cd_catalog_ptr)) {
		    memset(&entry_to_return, '\0', sizeof(entry_to_return));
		    local_key_datum = dbm_nextkey(cdc_dbm_ptr);
		}
	    }
	}
    } while (local_key_datum.dptr &&
	     local_data_datum.dptr &&
	     (entry_to_return.catalog[0] == '\0'));
    /* Finished finding entries, either there are no more or one matched */

    return (entry_to_return);
} /* search_cdc_entry */
Beispiel #14
0
static void
dumprgb (char *filename)
{
#ifdef NDBM
    DBM *rgb_dbm;
#else
    int rgb_dbm;
#endif
    datum key;

    rgb_dbm = dbm_open (filename, O_RDONLY, 0);
    if (!rgb_dbm) {
	fprintf (stderr, "%s:  unable to open rgb database \"%s\"\n",
		 ProgramName, filename);
	exit (1);
    }

#ifndef NDBM
#define dbm_nextkey(db) (nextkey(key))	/* need variable called key */
#endif

    for (key = dbm_firstkey(rgb_dbm); key.dptr != NULL;
	 key = dbm_nextkey(rgb_dbm)) {
	datum value;

	value = dbm_fetch(rgb_dbm, key);
	if (value.dptr) {
	    RGB rgb;
	    unsigned short r, g, b;
	    memcpy( (char *)&rgb, value.dptr, sizeof rgb);
#define N(x) (((x) >> 8) & 0xff)
	    r = N(rgb.red);
	    g = N(rgb.green);
	    b = N(rgb.blue);
#undef N
	    printf ("%3u %3u %3u\t\t", r, g, b);
	    fwrite (key.dptr, 1, key.dsize, stdout);
	    putchar ('\n');
	} else {
	    fprintf (stderr, "%s:  no value found for key \"", ProgramName);
	    fwrite (key.dptr, 1, key.dsize, stderr);
	    fprintf (stderr, "\"\n");
	}
    }

    dbm_close (rgb_dbm);
}
Beispiel #15
0
/*
 * This provides private-symbol filtration for the enumeration functions.
 */
static void
ypfilter(DBM *fdb, datum *inkey, datum *outkey, datum *val, uint_t *status,
							bool_t update)
{
	datum k;

	if (inkey) {

		if (isypsym(inkey)) {
			*status = (unsigned)YP_BADARGS;
			return;
		}

		k = dbm_do_nextkey(fdb, *inkey);
	} else {
		k = dbm_firstkey(fdb);
	}

	while (k.dptr && isypsym(&k)) {
		k = dbm_nextkey(fdb);
	}

	if (k.dptr == NULL) {
		*status = YP_NOMORE;
		return;
	}

	*outkey = k;

	/*
	 * In N2L mode we must call a version of dbm_fetch() that either does
	 * or does not check for entry updates. In non N2L mode both of these
	 * will end up doing a normal dbm_fetch().
	 */
	if (update)
		*val = shim_dbm_fetch(fdb, k);
	else
		*val = shim_dbm_fetch_noupdate(fdb, k);

	if (val->dptr != NULL) {
		*status = YP_TRUE;
	} else {
		*status = (unsigned)YP_BADDB;
	}
}
Beispiel #16
0
static krb5_error_code
NDBM_seq(krb5_context context, HDB *db,
	 unsigned flags, hdb_entry_ex *entry, int first)

{
    struct ndbm_db *d = (struct ndbm_db *)db->hdb_db;
    datum key, value;
    krb5_data key_data, data;
    krb5_error_code ret = 0;

    if(first)
	key = dbm_firstkey(d->db);
    else
	key = dbm_nextkey(d->db);
    if(key.dptr == NULL)
	return HDB_ERR_NOENTRY;
    key_data.data = key.dptr;
    key_data.length = key.dsize;
    ret = db->hdb_lock(context, db, HDB_RLOCK);
    if(ret) return ret;
    value = dbm_fetch(d->db, key);
    db->hdb_unlock(context, db);
    data.data = value.dptr;
    data.length = value.dsize;
    memset(entry, 0, sizeof(*entry));
    if(hdb_value2entry(context, &data, &entry->entry))
	return NDBM_seq(context, db, flags, entry, 0);
    if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) {
	ret = hdb_unseal_keys (context, db, &entry->entry);
	if (ret)
	    hdb_free_entry (context, entry);
    }
    if (ret == 0 && entry->entry.principal == NULL) {
	entry->entry.principal = malloc (sizeof(*entry->entry.principal));
	if (entry->entry.principal == NULL) {
	    hdb_free_entry (context, entry);
	    ret = ENOMEM;
	    krb5_set_error_message(context, ret, "malloc: out of memory");
	} else {
	    hdb_key2principal (context, &key_data, entry->entry.principal);
	}
    }
    return ret;
}
Beispiel #17
0
static Py_ssize_t
dbm_length(dbmobject *dp)
{
        if (dp->di_dbm == NULL) {
                 PyErr_SetString(DbmError, "DBM object has already been closed"); 
                 return -1; 
        }
        if ( dp->di_size < 0 ) {
		datum key;
		int size;

		size = 0;
		for ( key=dbm_firstkey(dp->di_dbm); key.dptr;
		      key = dbm_nextkey(dp->di_dbm))
			size++;
		dp->di_size = size;
	}
	return dp->di_size;
}
Beispiel #18
0
int listusers(const char *path, listcb_t *cb)
{
    DBM *indb;
    datum dkey, nextkey, dvalue;

    indb = dbm_open(path, O_RDONLY, S_IRUSR | S_IWUSR);

    if (!indb) {
	fprintf(stderr, "can't open %s\n", path);
	return 1;
    }

    dkey = dbm_firstkey(indb);

    while (dkey.dptr != NULL) {
	char *authid = dkey.dptr;
	char *realm  = dkey.dptr+strlen(authid)+1;
	char *tmp    = realm + strlen(realm)+1;
	char mech[1024];
	int len = dkey.dsize - (tmp - ((char *)dkey.dptr));

	if (len >= (int) sizeof mech) {
	    fprintf(stderr, "malformed database entry\n");
	    break;
	}
	memcpy(mech, tmp, len);
	mech[dkey.dsize - (tmp - ((char *)dkey.dptr))] = '\0';

	dvalue = dbm_fetch(indb, dkey);

	if (*authid && dvalue.dptr) {
	    /* don't check return values */
	    cb(authid,realm,mech,dvalue.dptr,dvalue.dsize);
	}

	nextkey=dbm_nextkey(indb);
	dkey=nextkey;
    }

    dbm_close(indb);
    return 0;
}
Beispiel #19
0
static VALUE
fdbm_key(VALUE obj, VALUE valstr)
{
    datum key, val;
    struct dbmdata *dbmp;
    DBM *dbm;

    ExportStringValue(valstr);
    val.dptr = RSTRING_PTR(valstr);
    val.dsize = RSTRING_LEN(valstr);

    GetDBM2(obj, dbmp, dbm);
    for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
	val = dbm_fetch(dbm, key);
	if (val.dsize == RSTRING_LEN(valstr) &&
	    memcmp(val.dptr, RSTRING_PTR(valstr), val.dsize) == 0) {
	    return rb_tainted_str_new(key.dptr, key.dsize);
	}
    }
    return Qnil;
}
Beispiel #20
0
extern void c_dbm_firstkey (DBM *db, datum *key) {
  *key = dbm_firstkey(db);
}
Beispiel #21
0
static int
cmdproc(struct cmd_syndesc *as, void * arock)
{
    DBM *kdb;
    datum key, data;
    kalog_elt rdata;
    afs_int32 cnt = 0;
    struct cmd_item *ti;

    if (as->parms[0].items) {
	dbmfile = as->parms[0].items->data;
    }
    kdb = dbm_open(dbmfile, O_RDONLY, KALOG_DB_MODE);
    if (!kdb) {
	perror(dbmfile);
	exit(1);
    }
    if (!(ti = as->parms[1].items)) {
	printf("Printing all entries found in %s\n", dbmfile);
	for (key = dbm_firstkey(kdb); key.dptr;
	     key = afs_dbm_nextkey(kdb, key), cnt++) {
            if (as->parms[2].items) {
		data = dbm_fetch(kdb, key);
		if (!data.dptr) {
		    fprintf(stderr, "%s: no entry exists\n", (char *)key.dptr);
		    continue;
		}
		if (data.dsize != sizeof(kalog_elt)) {
		    fprintf(stderr, "%s: data came out corrupt\n", 
			(char *)key.dptr);
		    continue;
		}
		memcpy(&rdata, data.dptr, sizeof(kalog_elt));
		if (! as->parms[3].items) {
		    char *hostName;
		    hostName = hostutil_GetNameByINet(rdata.host);
		    printf("%s: last operation from host %s at %s",
			   (char *)key.dptr, hostName,
			   ctime(&rdata.last_use));
		} else {
		    char *hostIP;
		    char hoststr[16];
		    hostIP = afs_inet_ntoa_r(rdata.host, hoststr);
		    printf("%s: last operation from host %s at %s",
			   (char *)key.dptr, hostIP,
			   ctime(&rdata.last_use));
		}
            } else {
		printf("\t%s\n", (char *)key.dptr);
            }
	}
	printf("%d entries were found\n", cnt);
    } else {
	for (; ti; ti = ti->next) {
	    key.dsize = strlen(ti->data) + 1;
	    key.dptr = ti->data;
	    data = dbm_fetch(kdb, key);
	    if (!data.dptr) {
		fprintf(stderr, "%s: no entry exists\n", ti->data);
		continue;
	    }
	    if (data.dsize != sizeof(kalog_elt)) {
		fprintf(stderr, "%s: data came out corrupt\n", ti->data);
		continue;
	    }
	    memcpy(&rdata, data.dptr, sizeof(kalog_elt));
	    printf("%s: last operation from host %x at %s", ti->data,
		   rdata.host, ctime(&rdata.last_use));
	}
    }
    dbm_close(kdb);
    return 0;
}
Beispiel #22
0
int main(void)
{
   struct test_data items_to_store[ITEMS_USED];
   struct test_data items_retrieved;
   
   char key_to_use[20];
   int i, result;
   
   datum key_datum;
   datum data_datum;
   DBM *dbm_ptr;
 
   dbm_ptr = dbm_open(TEST_DB_FILE, O_RDWR | O_CREAT, 0666);
   if(!dbm_ptr)  {
       fprintf(stderr, "Failed to open database\n");
       exit(EXIT_FAILURE);
   }
   
   memset(items_to_store, '\0', sizeof(items_to_store));
   strcpy(items_to_store[0].misc_chars, "First!");
   items_to_store[0].any_integer = 47;
   strcpy(items_to_store[0].more_chars, "foo");
   
   strcpy(items_to_store[1].misc_chars, "bar");
   items_to_store[1].any_integer = 13;
   strcpy(items_to_store[1].more_chars, "unlucky?");

   strcpy(items_to_store[2].misc_chars, "Third");
   items_to_store[2].any_integer = 3;
   strcpy(items_to_store[2].more_chars, "baz");
   
   for(i = 0; i < ITEMS_USED; i++)  {
       sprintf(key_to_use, "%c%c%d", items_to_store[i].misc_chars[0],
       items_to_store[i].more_chars[0], items_to_store[i].any_integer);

       key_datum.dptr = (void *)key_to_use;
       key_datum.dsize = strlen(key_to_use);
       data_datum.dptr = (void *)&items_to_store[i];
       data_datum.dsize = sizeof(struct test_data);

       result = dbm_store(dbm_ptr, key_datum, data_datum, DBM_REPLACE);
       if(result != 0)  { 
           fprintf(stderr, "dbm_store failed on key %s\n", key_to_use);
           exit(2);
      }
   }
   /* let's delete some data */
   sprintf(key_to_use, "bu%d", 13);
   key_datum.dptr = key_to_use;
   key_datum.dsize = strlen(key_to_use);

   if(dbm_delete(dbm_ptr, key_datum) == 0) 
       printf("Data with key %s deleted\n", key_to_use);
   else
      printf("nothing deleted for key %s", key_to_use);

   for(key_datum =dbm_firstkey(dbm_ptr); key_datum.dptr; 
                  key_datum = dbm_nextkey(dbm_ptr))  {
       data_datum = dbm_fetch(dbm_ptr, key_datum);
       if(data_datum.dptr)  {
           printf("Data retrieved\n");
           memcpy(&items_retrieved, data_datum.dptr, data_datum.dsize);
           printf("Retrieved items - %s %d %s\n", items_retrieved.misc_chars,
              items_retrieved.any_integer, items_retrieved.more_chars);
       }
       else 
           printf("No data found for key %s\n", key_to_use);
   }    
   
   dbm_close(dbm_ptr);
   exit(EXIT_SUCCESS);
}
Beispiel #23
0
/*
 * Looks up an user name in a database and checks the password
 *
 * return values:
 *	 1  = User not found
 *	 0  = OK
 * 	-1  = Password incorrect
 *	-2  = System error
 */
static int user_lookup(const char *user, const char *pass)
{
    DBM *dbm;
    datum key, data;

    /* Open the DB file. */
    dbm = dbm_open(database, O_RDONLY, 0644);
    if (dbm == NULL) {
	_pam_log(LOG_ERR, "user_lookup: could not open database `%s'",
		 database);
	return -2;
    }

    if (ctrl &PAM_DUMP_ARG) {
	_pam_log(LOG_INFO, "Database dump:");
	for (key = dbm_firstkey(dbm);  key.dptr != NULL;
	     key = dbm_nextkey(dbm)) {
	    data = dbm_fetch(dbm, key);
	    _pam_log(LOG_INFO, "key[len=%d] = `%s', data[len=%d] = `%s'",
		     key.dsize, key.dptr, data.dsize, data.dptr);
	}
    } 
    /* do some more init work */

    memset(&key, 0, sizeof(key));
    memset(&data, 0, sizeof(data));
    key.dptr = x_strdup(user);
    key.dsize = strlen(user);
    user = NULL;

    if (key.dptr) {
	data = dbm_fetch(dbm, key);
	memset(key.dptr, 0, key.dsize);
	free(key.dptr);
    }

    if (ctrl & PAM_DEBUG_ARG) {
	_pam_log(LOG_INFO, "password in database is [%p]`%s', len is %d",
		 data.dptr, (char *) data.dptr, data.dsize);
    }

    if (data.dptr != NULL) {
	int compare = 0;
	
	if (strlen(pass) != data.dsize) {
	    compare = 1;
	} else if (ctrl & PAM_ICASE_ARG) {
	    compare = strncasecmp(data.dptr, pass, data.dsize);
	} else {
	    compare = strncmp(data.dptr, pass, data.dsize);
	}
	dbm_close(dbm);
	if (compare == 0)
	    return 0; /* match */
	else
	    return -1; /* wrong */
    } else {
	if (ctrl & PAM_DEBUG_ARG) {    
	    _pam_log(LOG_INFO, "error returned by dbm_fetch: %s",
		     strerror(errno));
	}
	dbm_close(dbm);
	/* probably we should check dbm_error() here */
	return 1; /* not found */
    }

    /* NOT REACHED */
    return -2;
}
Beispiel #24
0
/*
 * FUNCTION:	update_map_from_dit()
 *
 * DESCRIPTION:	Core code called to update an entire map.
 *		Information is recovered from LDAP and used to build a duplicate
 *		copy of the live maps. When this is complete the maps are
 *		locked and then overwritten by the new copy.
 *
 * INPUTS:	map_ctrl containing lots of information about the map and a
 *		pointer to it's lock which will be required.
 *		Flag indicating if progress logging is required.
 *
 * OUTPUTS:	SUCCESS = Map updated
 *		FAILURE = Map not updated
 */
suc_code
update_map_from_dit(map_ctrl *map, bool_t log_flag) {
	__nis_table_mapping_t	*t;
	__nis_rule_value_t	*rv;
	__nis_ldap_search_t	*ls;
	__nis_object_dn_t	*objectDN = NULL;
	datum			*datval, *datkey;
	int			nr = 0, i, j, nv, numDNs;
	int			statP = SUCCESS, flag;
	char			*objname, **dn;
	/* Name of temporary entries DBM file */
	char			*temp_entries;
	/* Name of temporary TTL DBM file */
	char			*temp_ttl;
	/* Temporary DBM handles */
	DBM			*temp_entries_db;
	DBM			*temp_ttl_db;
	map_ctrl		temp_map;
	datum			key;
	char			*myself = "update_map_from_dit";
	bool_t			secure_flag;
	int			entry_count = 1;
	int			next_print = PRINT_FREQ;
	int			search_flag = SUCCESS;

	int			m;

	/* list of maps whose keys will be transliterated to lowercase */
	char			*xlate_to_lcase_maps[] = {
		"hosts.byname",
		"ipnodes.byname",
		NULL
	};
	bool_t			xlate_to_lcase = FALSE;

	if (!map || !map->map_name || !map->domain) {
		return (FAILURE);
	}

	__nisdb_get_tsd()->escapeFlag = '\0';

	/*
	 * netgroup.byxxx maps are a special case. They are regenerated from
	 * the netgroup map, not the DIT, so handle special case.
	 */
	if ((0 == strcmp(map->map_name, NETGROUP_BYHOST)) ||
		0 == (strcmp(map->map_name,  NETGROUP_BYUSER))) {
		return (update_netgroup_byxxx(map));
	}

	/* Get the mapping information for the map */
	if ((t = mappingFromMap(map->map_name, map->domain, &statP)) == 0) {
		if (statP == MAP_NO_MAPPING_EXISTS)
			logmsg(MSG_NOTIMECHECK, LOG_WARNING,
			"%s: No mapping information available for %s,%s",
				myself, map->map_name, map->domain);
		return (FAILURE);
	}

	/* Allocate and set up names */
	if (SUCCESS != alloc_temp_names(map->map_path,
				&temp_entries, &temp_ttl)) {
		logmsg(MSG_NOTIMECHECK, LOG_ERR,
			"%s: Unable to create map names for %s",
			myself, map->map_path);
		return (FAILURE);
	}

	/* Create temp entry and TTL file */
	if ((temp_entries_db = dbm_open(temp_entries, O_RDWR | O_CREAT, 0644))
						== NULL) {
		logmsg(MSG_NOTIMECHECK, LOG_ERR, "%s: Could not open %s",
						myself, temp_entries);
		sfree(temp_entries);
		sfree(temp_ttl);
		return (FAILURE);
	}

	if ((temp_ttl_db = dbm_open(temp_ttl, O_RDWR | O_CREAT, 0644))
						== NULL) {
		logmsg(MSG_NOTIMECHECK, LOG_ERR, "%s: Could not open %s",
						myself, temp_ttl);
		dbm_close(temp_entries_db);
		delete_map(temp_entries);
		sfree(temp_entries);
		sfree(temp_ttl);
		return (FAILURE);
	}

	/* Initialize domainContext tsd */
	__nisdb_get_tsd()->domainContext = 0;
	for (i = 0; i < ypDomains.numDomains; i++) {
		if (0 == ypDomains.domainLabels[i])
			continue;
		if (0 == strcasecmp(map->domain, ypDomains.domainLabels[i])) {
			__nisdb_get_tsd()->domainContext = ypDomains.domains[i];
			break;
		}
	}

	if (!(objname = getFullMapName(map->map_name, map->domain))) {
		if (temp_entries_db)
			dbm_close(temp_entries_db);
		if (temp_ttl_db)
			dbm_close(temp_ttl_db);
		delete_map(temp_entries);
		sfree(temp_entries);
		delete_map(temp_ttl);
		sfree(temp_ttl);
		return (FAILURE);
	}

	/*
	 * set xlate_to_lcase to TRUE if map_name is found in
	 * xlate_to_lcase_maps[]
	 */
	m = 0;
	while (xlate_to_lcase_maps[m] != NULL) {
		if (strncmp(map->map_name, xlate_to_lcase_maps[m],
			strlen(xlate_to_lcase_maps[m])) == 0) {
			xlate_to_lcase = TRUE;
			break;
		}
		++m;
	}

	/* Try each mapping for the map */
	for (flag = 0; t != 0 && search_flag != FAILURE; t = t->next) {

		/* Check if the mapping is the correct one */
		if (strcmp(objname, t->objName) != 0) {
			continue;
		}

		/* Check if rulesFromLDAP are provided */
		if (t->numRulesFromLDAP == 0) {
			logmsg(MSG_NOTIMECHECK, LOG_ERR,
				"%s: No rulesFromLDAP available for %s (%s)",
				myself, t->dbId, map->map_name);
			continue;
		}

		/* Set flag to indicate update is enabled */
		flag = 1;
		/* Create ldap request for enumeration */
		for (objectDN = t->objectDN;
				objectDN && objectDN->read.base;
				objectDN = objectDN->next) {
			if ((ls = createLdapRequest(t, 0, 0, 1, NULL,
						objectDN)) == 0) {
				logmsg(MSG_NOTIMECHECK, LOG_ERR,
					"%s: Failed to create "
					"ldapSearch request for "
					"%s (%s) for base %s",
					myself, t->dbId,
					map->map_name,
					objectDN->read.base);
				statP = FAILURE;
				search_flag = FAILURE;
				break;
			}

			if (log_flag) {
				printf("Waiting for LDAP search results.\n");
			}

			/* Query LDAP */
			nr = (ls->isDN)?0:-1;
			rv = ldapSearch(ls, &nr, 0, &statP);
			freeLdapSearch(ls);
			if (rv == 0) {
				if (statP == LDAP_NO_SUCH_OBJECT) {
				/*
				 * No Entry exists in the ldap server. Not
				 * a problem. Maybe there are just no entries
				 * in this map.
				 */
					continue;
				}
				logmsg(MSG_NOTIMECHECK, LOG_ERR,
					"%s: ldapSearch error %d "
					"(%s) for %s (%s) for base %s",
					myself, statP, ldap_err2string(statP),
					t->dbId, map->map_name,
					objectDN->read.base);
				statP = FAILURE;
				search_flag = FAILURE;
				break;
			}

			if (log_flag) {
				printf("Processing search results.\n");
			}

			/* Obtain list of DNs for logging */
			if ((dn = findDNs(myself, rv, nr, 0, &numDNs)) == 0) {
				statP = FAILURE;
				search_flag = FAILURE;
				break;
			}

			/* For each entry in the result  do the following */
			for (i = 0; i < nr; i++) {
			/* Convert LDAP data to NIS equivalents */
				statP = buildNISRuleValue(t, &rv[i],
						map->domain);
				if (statP == MAP_INDEXLIST_ERROR)
					continue;
				if (statP != SUCCESS) {
					logmsg(MSG_NOTIMECHECK, LOG_WARNING,
					    "%s: Conversion error %d (LDAP to "
					    "name=value pairs) "
					    "for (dn: %s) for "
					    "%s (%s) for base %s",
					    myself, statP, NIL(dn[i]),
					    t->dbId, map->map_name,
					    objectDN->read.base);
					continue;
				}

				/* Obtain the datum for value */
				datval = ruleValueToDatum(t, &rv[i], &statP);
				if (datval == 0) {
					logmsg(MSG_NOTIMECHECK, LOG_WARNING,
						"%s: Conversion error %d "
						"(name=value pairs to NIS)"
						" for (dn: %s) for "
						"%s (%s) for base %s",
						myself, statP, NIL(dn[i]),
						t->dbId, map->map_name,
						objectDN->read.base);
					continue;
				}

				/* Obtain the datum for key */
				datkey = getKeyFromRuleValue(t, &rv[i],
				    &nv, &statP, xlate_to_lcase);
				if (datkey == 0) {
					logmsg(MSG_NOTIMECHECK, LOG_WARNING,
						"%s: Unable to obtain NIS "
						"key from LDAP data (dn:%s) "
						"for %s (%s) for base %s",
						myself, NIL(dn[i]), t->dbId,
						map->map_name,
						objectDN->read.base);
					sfree(datval->dptr);
					sfree(datval);
					continue;
				}

				/* Write to the temporary map */
				for (j = 0; j < nv; j++, entry_count ++) {
					if (datkey[j].dsize == 0)
						continue;
					errno = 0;
					/* DBM_INSERT to match */
					/* singleReadFromDIT */
					if (dbm_store(temp_entries_db,
						datkey[j],
						*datval,
						DBM_INSERT) < 0) {
						/*
						 * For some cases errno may
						 * still be 0 but dbm_error
						 * isn't informative at all.
						 */
						logmsg(MSG_NOTIMECHECK,
						    LOG_WARNING,
						    "%s: dbm store error "
						    "(errno=%d) "
						    "for (key=%s, value=%s) "
						    "for %s (%s) for base %s",
						    myself,
						    errno,
						    datkey[j].dptr,
						    datval->dptr, t->dbId,
						    map->map_name,
						    objectDN->read.base);
						/* clear the error */
						dbm_clearerr(temp_entries_db);
					}
					sfree(datkey[j].dptr);

					if (log_flag && (entry_count >=
							next_print)) {
						printf("%d entries processed\n",
							entry_count);
						next_print *= 2;
					}

				}
				sfree(datkey);
				sfree(datval->dptr);
				sfree(datval);
			}

			freeRuleValue(rv, nr);
			freeDNs(dn, numDNs);
		} /* End of for over objectDN */
	}
	sfree(objname);

	if (t != 0 || flag == 0 || search_flag == FAILURE) {
		if (temp_entries_db)
			dbm_close(temp_entries_db);
		if (temp_ttl_db)
			dbm_close(temp_ttl_db);
		delete_map(temp_entries);
		sfree(temp_entries);
		delete_map(temp_ttl);
		sfree(temp_ttl);
		return (statP);
	}
	/* Set up enough of map_ctrl to call update_entry_ttl */
	temp_map.map_name = map->map_name;
	temp_map.domain = map->domain;
	temp_map.ttl = temp_ttl_db;

	/* Generate new TTL file */
	key = dbm_firstkey(temp_entries_db);
	while (key.dptr != 0) {
		if (!is_special_key(&key))
			/*
			 * We don't want all the entries to time out at the
			 * same time so create random TTLs.
			 */
			if (FAILURE == update_entry_ttl(&temp_map, &key,
								TTL_RAND))
				logmsg(MSG_NOTIMECHECK, LOG_ERR,
					"%s: Could not update TTL for "
					"(key=%s) for map %s,%s",
					myself, NIL(key.dptr), map->map_name,
					map->domain);
		key = dbm_nextkey(temp_entries_db);
	}

	/* Update map TTL */
	if (SUCCESS != update_map_ttl(&temp_map)) {
		logmsg(MSG_NOTIMECHECK, LOG_ERR, "%s: Could not update map TTL "
			"for %s,%s", myself, map->map_name, map->domain);
	}

	/* Set up 'special' nis entries */
	add_special_entries(temp_entries_db, map, &secure_flag);

	/* Close temp DBM files */
	dbm_close(temp_entries_db);
	dbm_close(temp_ttl_db);

	/* Lock access to the map for copy */
	lock_map_ctrl(map);

	/* Move temp maps to real ones */
	rename_map(temp_entries, map->map_path, secure_flag);
	rename_map(temp_ttl, map->ttl_path, secure_flag);

	/* Free file names */
	sfree(temp_entries);
	sfree(temp_ttl);

	/* Unlock map */
	unlock_map_ctrl(map);

	return (SUCCESS);
}
Beispiel #25
0
/*
 * Looks up an user name in a database and checks the password
 *
 * return values:
 *	 1  = User not found
 *	 0  = OK
 *	-1  = Password incorrect
 *	-2  = System error
 */
static int
user_lookup (pam_handle_t *pamh, const char *database, const char *cryptmode,
	     const char *user, const char *pass, int ctrl)
{
    DBM *dbm;
    datum key, data;

    /* Open the DB file. */
    dbm = dbm_open(database, O_RDONLY, 0644);
    if (dbm == NULL) {
	pam_syslog(pamh, LOG_ERR,
		   "user_lookup: could not open database `%s': %m", database);
	return -2;
    }

    /* dump out the database contents for debugging */
    if (ctrl & PAM_DUMP_ARG) {
	pam_syslog(pamh, LOG_INFO, "Database dump:");
	for (key = dbm_firstkey(dbm);  key.dptr != NULL;
	     key = dbm_nextkey(dbm)) {
	    data = dbm_fetch(dbm, key);
	    pam_syslog(pamh, LOG_INFO,
		       "key[len=%d] = `%s', data[len=%d] = `%s'",
		       key.dsize, key.dptr, data.dsize, data.dptr);
	}
    }

    /* do some more init work */
    memset(&key, 0, sizeof(key));
    memset(&data, 0, sizeof(data));
    if (ctrl & PAM_KEY_ONLY_ARG) {
	if (asprintf(&key.dptr, "%s-%s", user, pass) < 0)
	    key.dptr = NULL;
	else
	    key.dsize = strlen(key.dptr);
    } else {
        key.dptr = strdup(user);
        key.dsize = strlen(user);
    }

    if (key.dptr) {
	data = dbm_fetch(dbm, key);
	memset(key.dptr, 0, key.dsize);
	free(key.dptr);
    }

    if (ctrl & PAM_DEBUG_ARG) {
	pam_syslog(pamh, LOG_INFO,
		   "password in database is [%p]`%.*s', len is %d",
		   data.dptr, data.dsize, (char *) data.dptr, data.dsize);
    }

    if (data.dptr != NULL) {
	int compare = 0;

	if (ctrl & PAM_KEY_ONLY_ARG)
	  {
	    dbm_close (dbm);
	    return 0; /* found it, data contents don't matter */
	}

	if (cryptmode && strncasecmp(cryptmode, "crypt", 5) == 0) {

	  /* crypt(3) password storage */

	  char *cryptpw = NULL;

	  if (data.dsize < 13) {
	    compare = -2;
	  } else if (ctrl & PAM_ICASE_ARG) {
	    compare = -2;
	  } else {
#ifdef HAVE_CRYPT_R
	    struct crypt_data *cdata = NULL;
	    cdata = malloc(sizeof(*cdata));
	    if (cdata != NULL) {
		cdata->initialized = 0;
		cryptpw = crypt_r(pass, data.dptr, cdata);
	    }
#else
	    cryptpw = crypt (pass, data.dptr);
#endif
	    if (cryptpw && strlen(cryptpw) == (size_t)data.dsize) {
	      compare = memcmp(data.dptr, cryptpw, data.dsize);
	    } else {
	      compare = -2;
	      if (ctrl & PAM_DEBUG_ARG) {
		if (cryptpw)
		  pam_syslog(pamh, LOG_INFO, "lengths of computed and stored hashes differ");
		else
		  pam_syslog(pamh, LOG_INFO, "crypt() returned NULL");
	      }
	    }
#ifdef HAVE_CRYPT_R
	    free(cdata);
#endif
	  }

	} else {

	  /* Unknown password encryption method -
	   * default to plaintext password storage
	   */

	  if (strlen(pass) != (size_t)data.dsize) {
	    compare = 1; /* wrong password len -> wrong password */
	  } else if (ctrl & PAM_ICASE_ARG) {
	    compare = strncasecmp(data.dptr, pass, data.dsize);
	  } else {
	    compare = strncmp(data.dptr, pass, data.dsize);
	  }

	  if (cryptmode && strncasecmp(cryptmode, "none", 4)
		&& (ctrl & PAM_DEBUG_ARG)) {
	    pam_syslog(pamh, LOG_INFO, "invalid value for crypt parameter: %s",
		       cryptmode);
	    pam_syslog(pamh, LOG_INFO, "defaulting to plaintext password mode");
	  }

	}

	dbm_close(dbm);
	if (compare == 0)
	    return 0; /* match */
	else
	    return -1; /* wrong */
    } else {
        int saw_user = 0;

	if (ctrl & PAM_DEBUG_ARG) {
	    pam_syslog(pamh, LOG_INFO, "error returned by dbm_fetch: %m");
	}

	/* probably we should check dbm_error() here */

        if ((ctrl & PAM_KEY_ONLY_ARG) == 0) {
	    dbm_close(dbm);
            return 1; /* not key_only, so no entry => no entry for the user */
        }

        /* now handle the key_only case */
        for (key = dbm_firstkey(dbm);
             key.dptr != NULL;
             key = dbm_nextkey(dbm)) {
            int compare;
            /* first compare the user portion (case sensitive) */
            compare = strncmp(key.dptr, user, strlen(user));
            if (compare == 0) {
                /* assume failure */
                compare = -1;
                /* if we have the divider where we expect it to be... */
                if (key.dptr[strlen(user)] == '-') {
		    saw_user = 1;
		    if ((size_t)key.dsize == strlen(user) + 1 + strlen(pass)) {
		        if (ctrl & PAM_ICASE_ARG) {
			    /* compare the password portion (case insensitive)*/
                            compare = strncasecmp(key.dptr + strlen(user) + 1,
                                                  pass,
                                                  strlen(pass));
		        } else {
                            /* compare the password portion (case sensitive) */
                            compare = strncmp(key.dptr + strlen(user) + 1,
                                              pass,
                                              strlen(pass));
		        }
		    }
                }
                if (compare == 0) {
                    dbm_close(dbm);
                    return 0; /* match */
                }
            }
        }
        dbm_close(dbm);
	if (saw_user)
	    return -1; /* saw the user, but password mismatch */
	else
	    return 1; /* not found */
    }

    /* NOT REACHED */
    return -2;
}
Beispiel #26
0
int
main(int argc, char **argv)
{
        typedef enum {
                YOW, FETCH, STORE, DELETE, SCAN, REGEXP
        } commands;
        char opt;
        int flags;
        int giveusage = 0;
        int verbose = 0;
        commands what = YOW;
        char *comarg[3];
        int st_flag = DBM_INSERT;
        int argn;
        DBM *db;
        datum key;
        datum content;

        flags = O_RDWR;
        argn = 0;

        while ((opt = getopt(argc, argv, "acdfFm:rstvx")) != ':') {
                switch (opt) {
                case 'a':
                        what = SCAN;
                        break;
                case 'c':
                        flags |= O_CREAT;
                        break;
                case 'd':
                        what = DELETE;
                        break;
                case 'f':
                        what = FETCH;
                        break;
                case 'F':
                        what = REGEXP;
                        break;
                case 'm':
                        flags &= ~(000007);
                        if (strcmp(optarg, "r") == 0)
                                flags |= O_RDONLY;
                        else if (strcmp(optarg, "w") == 0)
                                flags |= O_WRONLY;
                        else if (strcmp(optarg, "rw") == 0)
                                flags |= O_RDWR;
                        else {
                                fprintf(stderr, "Invalid mode: \"%s\"\n", optarg);
                                giveusage = 1;
                        }
                        break;
                case 'r':
                        st_flag = DBM_REPLACE;
                        break;
                case 's':
                        what = STORE;
                        break;
                case 't':
                        flags |= O_TRUNC;
                        break;
                case 'v':
                        verbose = 1;
                        break;
                case 'x':
                        flags |= O_EXCL;
                        break;
                case '!':
                        giveusage = 1;
                        break;
                case '?':
                        if (argn < 3)
                                comarg[argn++] = optarg;
                        else {
                                fprintf(stderr, "Too many arguments.\n");
                                giveusage = 1;
                        }
                        break;
                }
        }

        if (giveusage || what == YOW || argn < 1) {
                fprintf(stderr, "Usage: %s database [-m r|w|rw] [-crtx] -a|-d|-f|-F|-s [key [content]]\n", argv[0]);
                exit(-1);
        }

        if ((db = dbm_open(comarg[0], flags, 0777)) == NULL) {
                fprintf(stderr, "Error opening database \"%s\"\n", comarg[0]);
                exit(-1);
        }

        if (argn > 1)
                key = read_datum(comarg[1]);
        if (argn > 2)
                content = read_datum(comarg[2]);

        switch (what) {

        case SCAN:
                key = dbm_firstkey(db);
                if (dbm_error(db)) {
                        fprintf(stderr, "Error when fetching first key\n");
                        goto db_exit;
                }
                while (key.dptr != NULL) {
                        content = dbm_fetch(db, key);
                        if (dbm_error(db)) {
                                fprintf(stderr, "Error when fetching ");
                                print_datum(key);
                                printf("\n");
                                goto db_exit;
                        }
                        print_datum(key);
                        printf(": ");
                        print_datum(content);
                        printf("\n");
                        if (dbm_error(db)) {
                                fprintf(stderr, "Error when fetching next key\n");
                                goto db_exit;
                        }
                        key = dbm_nextkey(db);
                }
                break;

        case REGEXP:
                if (argn < 2) {
                        fprintf(stderr, "Missing regular expression.\n");
                        goto db_exit;
                }
                if (re_comp(comarg[1])) {
                        fprintf(stderr, "Invalid regular expression\n");
                        goto db_exit;
                }
                key = dbm_firstkey(db);
                if (dbm_error(db)) {
                        fprintf(stderr, "Error when fetching first key\n");
                        goto db_exit;
                }
                while (key.dptr != NULL) {
                        if (re_exec(key2s(key))) {
                                content = dbm_fetch(db, key);
                                if (dbm_error(db)) {
                                        fprintf(stderr, "Error when fetching ");
                                        print_datum(key);
                                        printf("\n");
                                        goto db_exit;
                                }
                                print_datum(key);
                                printf(": ");
                                print_datum(content);
                                printf("\n");
                                if (dbm_error(db)) {
                                        fprintf(stderr, "Error when fetching next key\n");
                                        goto db_exit;
                                }
                        }
                        key = dbm_nextkey(db);
                }
                break;

        case FETCH:
                if (argn < 2) {
                        fprintf(stderr, "Missing fetch key.\n");
                        goto db_exit;
                }
                content = dbm_fetch(db, key);
                if (dbm_error(db)) {
                        fprintf(stderr, "Error when fetching ");
                        print_datum(key);
                        printf("\n");
                        goto db_exit;
                }
                if (content.dptr == NULL) {
                        fprintf(stderr, "Cannot find ");
                        print_datum(key);
                        printf("\n");
                        goto db_exit;
                }
                print_datum(key);
                printf(": ");
                print_datum(content);
                printf("\n");
                break;

        case DELETE:
                if (argn < 2) {
                        fprintf(stderr, "Missing delete key.\n");
                        goto db_exit;
                }
                if (dbm_delete(db, key) || dbm_error(db)) {
                        fprintf(stderr, "Error when deleting ");
                        print_datum(key);
                        printf("\n");
                        goto db_exit;
                }
                if (verbose) {
                        print_datum(key);
                        printf(": DELETED\n");
                }
                break;

        case STORE:
                if (argn < 3) {
                        fprintf(stderr, "Missing key and/or content.\n");
                        goto db_exit;
                }
                if (dbm_store(db, key, content, st_flag) || dbm_error(db)) {
                        fprintf(stderr, "Error when storing ");
                        print_datum(key);
                        printf("\n");
                        goto db_exit;
                }
                if (verbose) {
                        print_datum(key);
                        printf(": ");
                        print_datum(content);
                        printf(" STORED\n");
                }
                break;
        }

db_exit:
        dbm_clearerr(db);
        dbm_close(db);
        if (dbm_error(db)) {
                fprintf(stderr, "Error closing database \"%s\"\n", comarg[0]);
                exit(-1);
        }
}
Beispiel #27
0
void
ypoldfirst(SVCXPRT *transp)
{
	bool dbmop_ok = TRUE;
	struct yprequest req;
	struct ypresponse resp;
	char *fun = "ypoldfirst";
	DBM *fdb;

	memset((void *) &req, 0, sizeof (req));
	memset((void *) &resp, 0, sizeof (resp));

	if (!svc_getargs(transp,
				(xdrproc_t)_xdr_yprequest,
				(caddr_t)&req)) {
		svcerr_decode(transp);
		return;
	}

	if (req.yp_reqtype != YPFIRST_REQTYPE) {
		resp.ypfirst_resp_status = (unsigned)YP_BADARGS;
		dbmop_ok = FALSE;
	}

	if (dbmop_ok &&
		((fdb = ypset_current_map(req.ypfirst_req_map,
						req.ypfirst_req_domain,
						&resp.ypfirst_resp_status))
						!= NULL) &&
						yp_map_access(transp,
						&resp.ypfirst_resp_status,
						fdb)) {

		resp.ypfirst_resp_keydat = dbm_firstkey(fdb);

		if (resp.ypfirst_resp_keyptr != NULL) {
			resp.ypfirst_resp_valdat =
				dbm_fetch(fdb, resp.ypfirst_resp_keydat);

			if (resp.ypfirst_resp_valptr != NULL) {
				resp.ypfirst_resp_status = YP_TRUE;
			} else {
				resp.ypfirst_resp_status = (unsigned)YP_BADDB;
			}
		} else {
			resp.ypfirst_resp_status = (unsigned)YP_NOKEY;
		}
	}

	resp.yp_resptype = YPFIRST_RESPTYPE;

	if (!svc_sendreply(transp,
				(xdrproc_t)_xdr_ypresponse,
				(caddr_t)&resp)) {
		RESPOND_ERR;
	}

	if (!svc_freeargs(transp,
				(xdrproc_t)_xdr_yprequest,
				(caddr_t)&req)) {
		FREE_ERR;
	}
}
Beispiel #28
0
void runFailure() {
    dbm_firstkey(NULL);
}
Beispiel #29
0
int main(int n, char **argv) {

	const char	*fname = NULL;
	DBM  	*pdb;
	datum	k,d;
	int 	ch;
	int 	i;

	progname = argv[0];



	while ((ch = getopt(n, argv, "i:l:wf:v")) != -1)
		switch (ch) {
			case 'i': 	if (!isdigit((int) *optarg)) usage();
					lotstup = atoi(optarg);
					break;
			case 'l':	if (!isdigit((int) *optarg)) usage();
					wraplen = atoi(optarg);
					break;
			case 'w':	needwrap = 1;
					break;
			case 'f':	fname = optarg;
					break;
			case 'v':	printf("%s: $Id: rlm_dbm_cat.c,v 1.8 2004/02/26 19:04:28 aland Exp $\n",progname);
					exit(0);
					break;
			default : usage(); exit(1); break;

		}
	n -= (optind - 1);
	argv += (optind -1);

	if ( fname == NULL) fname = "sandy_db";

	if ( ( pdb = dbm_open(fname, O_RDONLY, 0777) ) == NULL ) {
		perror("Couldn't open database");
		exit(1);
	}
	if ( n > 1 ) {
		for ( i = 1 ; i < n ; i++ ) {
			printf(" Check: %s\n",argv[i]);
			k.dptr  = argv[i];
			k.dsize = strlen(argv[i]) + 1;
			if ( (d = dbm_fetch(pdb,k)).dptr == NULL ) {
				printf("Not found\n");
			} else dump_record(k, d);
		}
	} else {
		for ( k = dbm_firstkey(pdb) ; k.dptr != NULL ; k = dbm_nextkey(pdb) )
			if ( (d = dbm_fetch(pdb,k)).dptr == NULL ) {
				perror("Couldn't fetch user record");
				exit(1);
			} else dump_record(k, d);
	}
	dbm_close(pdb);
	fflush(stdout);

	return 0;

}
int main() {
    struct test_data items_to_store[ITEMS_USED];
    struct test_data item_retrieved;
    char key_to_use[20];
    int i, result;
    // a datum is dbm's wrapper around binary data. It consists of a void*
    // to our data and a size_t giving the data size
    datum key_datum;
    datum data_datum;
    // a DBM struct is a wrapper around two files, one used to track indices
    // and another used to store the binary data.
    DBM *dbm_p;

    dbm_p = dbm_open(TEST_DB_FILE, O_RDWR | O_CREAT, 0666);
    if (!dbm_p) {
        fprintf(stderr, "Failed to open database\n");
        exit(EXIT_FAILURE);
    }

    // set all data to zero first, then set some data
    //    note that we *need* all zeros in some cases, e.g. if we use
    //    char arrays as keys. If they are only used for values it's less
    //    important.
    memset(items_to_store, '\0', sizeof(items_to_store));
    // Ff47
    strcpy(items_to_store[0].misc_chars, "First!");
    items_to_store[0].any_integer = 47;
    strcpy(items_to_store[0].more_chars, "foo");
    // bu13
    strcpy(items_to_store[1].misc_chars, "bar");
    items_to_store[1].any_integer = 13;
    strcpy(items_to_store[1].more_chars, "unlucky?");
    // Tb3
    strcpy(items_to_store[2].misc_chars, "Third");
    items_to_store[2].any_integer = 3;
    strcpy(items_to_store[2].more_chars, "baz");

    for (i = 0; i < ITEMS_USED; i++) {
        // make the key string
        sprintf(key_to_use, "%c%c%d",
                items_to_store[i].misc_chars[0],
                items_to_store[i].more_chars[0],
                items_to_store[i].any_integer);
        // make the key. Check that you understand why we *must* use
        // strlen() here and not sizeof()
        key_datum.dptr = (void *) key_to_use;
        key_datum.dsize = strlen(key_to_use);
        // make the data
        data_datum.dptr = (void *) &items_to_store[i];
        data_datum.dsize = sizeof(struct test_data);

        // write the data. Note that we have a choice of what to do
        // if we see a known key; here it doesn't matter.
        result = dbm_store(dbm_p, key_datum, data_datum, DBM_REPLACE);
        if (result != 0) {
            fprintf(stderr, "Failed to write to database\n");
            exit(2);
        }
    }

    // now try retrieving the second entry
    sprintf(key_to_use, "bu%d", 13);
    key_datum.dptr = (void *) key_to_use;
    key_datum.dsize = strlen(key_to_use);
    data_datum = dbm_fetch(dbm_p, key_datum);
    // if we don't find a key, we get a datum with NULL dptr
    if (data_datum.dptr) {
        printf("Data retrieved\n");
        memcpy(&item_retrieved, data_datum.dptr, data_datum.dsize);
        printf("Retrieved item - %s %d %s\n",
                item_retrieved.misc_chars,
                item_retrieved.any_integer,
                item_retrieved.more_chars);
    } else {
        printf("No data found for key %s\n", key_to_use);
    }

    printf("\n\nNow we'll try deleting and then cycling\n\n");

    // delete the entry we just looked at
    if (dbm_delete(dbm_p, key_datum) == 0) {
        printf("Data with key %s deleted\n", key_to_use);
    } else {
        printf("Nothing deleted for key %s\n", key_to_use);
    }

    // now use dbm_firstkey and dbm_nextkey to iterate over keys.
    //   ... the order in which they appear is not defined
    for (key_datum = dbm_firstkey(dbm_p);
         key_datum.dptr;                    // the end condition is a NULL dptr
         key_datum = dbm_nextkey(dbm_p)) {
        // get the data. The data_datum shouldn't be null in this situation,
        // but it could happen due to race conditions and such, so we should
        // still guard against it.
        data_datum = dbm_fetch(dbm_p, key_datum);
        if (data_datum.dptr) {
        printf("Data retrieved for key %s\n", (char *)key_datum.dptr);
        memcpy(&item_retrieved, data_datum.dptr, data_datum.dsize);
        printf("Retrieved item - %s %d %s\n",
                item_retrieved.misc_chars,
                item_retrieved.any_integer,
                item_retrieved.more_chars);

        } else {
            // the authors oopsed here, don't use `key_to_use`
            printf("No data found for key %s\n", (char *) key_datum.dptr);
        }
    }
    
    // don't forget to close the database!
    dbm_close(dbm_p);
    exit(EXIT_SUCCESS);
}