Ejemplo n.º 1
0
static rlm_rcode_t add_defaults(rlm_counter_t *inst)
{
	datum key_datum;
	datum time_datum;
	static char const *default1 = "DEFAULT1";
	static char const *default2 = "DEFAULT2";

	DEBUG2("rlm_counter: add_defaults: Start");

	memcpy(&key_datum.dptr, &default1, sizeof(key_datum.dptr));
	key_datum.dsize = strlen(key_datum.dptr);
	time_datum.dptr = (char *) &inst->reset_time;
	time_datum.dsize = sizeof(time_t);

	if (gdbm_store(inst->gdbm, key_datum, time_datum, GDBM_REPLACE) < 0) {
		ERROR("rlm_counter: Failed storing data to %s: %s", inst->filename, gdbm_strerror(gdbm_errno));
		return RLM_MODULE_FAIL;
	}
	DEBUG2("rlm_counter: DEFAULT1 set to %u", (unsigned int) inst->reset_time);

	memcpy(&key_datum.dptr, &default2, sizeof(key_datum.dptr));
	key_datum.dsize = strlen(key_datum.dptr);
	key_datum.dsize = strlen(default2);
	time_datum.dptr = (char *) &inst->last_reset;
	time_datum.dsize = sizeof(time_t);

	if (gdbm_store(inst->gdbm, key_datum, time_datum, GDBM_REPLACE) < 0) {
		ERROR("rlm_counter: Failed storing data to %s: %s", inst->filename, gdbm_strerror(gdbm_errno));
		return RLM_MODULE_FAIL;
	}
	DEBUG2("rlm_counter: DEFAULT2 set to %u", (unsigned int) inst->last_reset);
	DEBUG2("rlm_counter: add_defaults: End");

	return RLM_MODULE_OK;
}
Ejemplo n.º 2
0
int
main(int argc, char *argv[])
{
  int c;
  GDBM_FILE dbf;
  int flags = 0;

  while ((c = getopt (argc, argv, "hlv")) != -1)
    switch (c)
      {
      case 'h':
	usage (argv[0]);
	exit (0);

      case 'l':
	flags = GDBM_NOLOCK;
	break;

      case 'v':
	version ();
	exit (0);
	
      default:
	usage (argv[0]);
	exit (1);
      }

  if (argc != 3)
    {
      usage (argv[0]);
      exit (1);
    }

  dbf = gdbm_open (argv[1], 0, GDBM_READER | flags, 0600, NULL);
  if (dbf == NULL)
    {
      fprintf (stderr, "%s: couldn't open database, %s\n", argv[0],
	       gdbm_strerror (gdbm_errno));
      exit (1);
    }

  if (gdbm_export (dbf, argv[2], GDBM_WRCREAT | flags, 0600) == -1)
    {
      fprintf (stderr, "%s: export failed, %s\n",
	       argv[0], gdbm_strerror (gdbm_errno));
      gdbm_close (dbf);
      exit (1);
    }
  gdbm_close (dbf);
  exit (0);
}
Ejemplo n.º 3
0
/** Pomocna funkce, vytiskne obsah databaze na stdout.
 *
 */
void DirectoryDatabase::PrintContent() {
    datum keyd;
    datum nextkeyd;
    datum datad;
    FileInfoGdbmRecord record;
    
    keyd = gdbm_firstkey(db_file);
    while (keyd.dptr) {
        datad = gdbm_fetch(db_file, keyd);
        if (datad.dptr == 0) {
#ifdef DD_DEBUG
            cout << getpid() << " - soubor nebyl v databazi nalezen. ";
            cout << "gdbm_errno = " << gdbm_errno << " ... " << gdbm_strerror(gdbm_errno) << endl;
#endif
        }
        
        nextkeyd = gdbm_nextkey(db_file, keyd);
        memcpy(&record, datad.dptr, datad.dsize);
        free(datad.dptr); // nutne uvolnit misto na ktere ukazuje datad.dptr --> gdbm to samo neudela!!!
#ifdef DD_DEBUG
        cout << record.name << " user = "******" user_rights = " << record.user_rights << endl;
#endif
        free(keyd.dptr);
        keyd = nextkeyd;
    }
}
Ejemplo n.º 4
0
/*
 * call-seq:
 *      GDBM.new(filename, mode = 0666, flags = nil)
 *
 * Creates a new GDBM instance by opening a gdbm file named _filename_.
 * If the file does not exist, a new file with file mode _mode_ will be
 * created. _flags_ may be one of the following:
 * * *READER*  - open as a reader
 * * *WRITER*  - open as a writer
 * * *WRCREAT* - open as a writer; if the database does not exist, create a new one
 * * *NEWDB*   - open as a writer; overwrite any existing databases
 *
 * The values *WRITER*, *WRCREAT* and *NEWDB* may be combined with the following
 * values by bitwise or:
 * * *SYNC*    - cause all database operations to be synchronized to the disk
 * * *NOLOCK*  - do not lock the database file
 *
 * If no _flags_ are specified, the GDBM object will try to open the database
 * file as a writer and will create it if it does not already exist
 * (cf. flag <tt>WRCREAT</tt>). If this fails (for instance, if another process
 * has already opened the database as a reader), it will try to open the
 * database file as a reader (cf. flag <tt>READER</tt>).
 */
static VALUE
fgdbm_initialize(int argc, VALUE *argv, VALUE obj)
{
    VALUE file, vmode, vflags;
    GDBM_FILE dbm;
    struct dbmdata *dbmp;
    int mode, flags = 0;

    if (rb_scan_args(argc, argv, "12", &file, &vmode, &vflags) == 1) {
        mode = 0666;            /* default value */
    }
    else if (NIL_P(vmode)) {
        mode = -1;              /* return nil if DB does not exist */
    }
    else {
        mode = NUM2INT(vmode);
    }

    if (!NIL_P(vflags))
        flags = NUM2INT(vflags);

    SafeStringValue(file);

    if (flags & RUBY_GDBM_RW_BIT) {
        flags &= ~RUBY_GDBM_RW_BIT;
        dbm = gdbm_open(RSTRING_PTR(file), MY_BLOCK_SIZE, 
                        flags, mode, MY_FATAL_FUNC);
    }
    else {
        dbm = 0;
        if (mode >= 0)
            dbm = gdbm_open(RSTRING_PTR(file), MY_BLOCK_SIZE, 
                            GDBM_WRCREAT|flags, mode, MY_FATAL_FUNC);
        if (!dbm)
            dbm = gdbm_open(RSTRING_PTR(file), MY_BLOCK_SIZE, 
                            GDBM_WRITER|flags, 0, MY_FATAL_FUNC);
        if (!dbm)
            dbm = gdbm_open(RSTRING_PTR(file), MY_BLOCK_SIZE, 
                            GDBM_READER|flags, 0, MY_FATAL_FUNC);
    }

    if (!dbm) {
        if (mode == -1) return Qnil;

        if (gdbm_errno == GDBM_FILE_OPEN_ERROR ||
            gdbm_errno == GDBM_CANT_BE_READER ||
            gdbm_errno == GDBM_CANT_BE_WRITER)
            rb_sys_fail(RSTRING_PTR(file));
        else
            rb_raise(rb_eGDBMError, "%s", gdbm_strerror(gdbm_errno));
    }

    dbmp = ALLOC(struct dbmdata);
    free_dbm(DATA_PTR(obj));
    DATA_PTR(obj) = dbmp;
    dbmp->di_dbm = dbm;
    dbmp->di_size = -1;

    return obj;
}
Ejemplo n.º 5
0
/**
 * open the gdbm database
 *
 * @param pe error buffer
 * @param parameters db-specific parameter.  In this case,
 *                   the path to use
 * @returns DB_E_SUCCESS on success, DB_E_* otherwise.
 */
int db_gdbm_open(char **pe, char *parameters) {
    char db_path[PATH_MAX + 1];
    int result = DB_E_SUCCESS;

    snprintf(db_path,sizeof(db_path),"%s/%s",parameters,"songs.gdb");

    //    reload = reload ? GDBM_NEWDB : GDBM_WRCREAT;
    _gdbm_lock();
    _gdbm_songs = gdbm_open(db_path, 0, GDBM_WRCREAT | GDBM_SYNC | GDBM_NOLOCK,
                           0600,NULL);

    if(!_gdbm_songs) {
        /* let's try creating it! */
        _gdbm_songs = gdbm_open(db_path,0,GDBM_NEWDB | GDBM_SYNC | GDBM_NOLOCK,
                                0600,NULL);
    }

    if(!_gdbm_songs) {
        DPRINTF(E_FATAL,L_DB,"Could not open songs database (%s): %s\n",
                db_path,strerror(errno));
        db_get_error(pe,DB_E_DB_ERROR,gdbm_strerror(gdbm_errno));
        result = DB_E_DB_ERROR;
    }
    _gdbm_unlock();
    return result;
}
Ejemplo n.º 6
0
Archivo: err.c Proyecto: 4honor/QConf
void
gdbm_perror (const char *fmt, ...)
{
  va_list ap;
  va_start (ap, fmt);
  prerror (fmt, ap, gdbm_strerror (gdbm_errno));
  va_end (ap);
}
Ejemplo n.º 7
0
static void _hcache_validate_init(struct hcache *cache) {
  char *vfname;
  if (cache->validated) return;
  vfname = mystrcat(cache->path,".validate");
  cache->validated = gdbm_open(vfname,0, GDBM_NEWDB, 0666,NULL);
  if (!cache->validated)
    fatal(gdbm_errno,"gdbmopen(%s): %s", vfname, gdbm_strerror(gdbm_errno));
  free(vfname);
}
Ejemplo n.º 8
0
/** Maze z databaze informace o souboru.
 *
 * Presahne-li pocet smazanych polozek MAX_DELETED_ITEMS, reorganizuje
 * databazi.
 *
 * Navratove hodnoty:
 *
 *      -  1      vse OK.
 *      - -1      chyba pri vytvareni klice k souboru
 *      - -2      chyba pri zamykani/odemykani databaze
 *      - -3      chyba pri praci s databazi
 *
 */
int DirectoryDatabase::DeleteFileInfo(string &name) {
    string      key;
    datum       keyd, datad;
    int         ret;

    ret = File2Key(name.c_str(), key);
    if (ret != 1) return -1;
    
    keyd.dptr   = (char *) key.c_str();
    keyd.dsize  = key.size();

// --- zacatek KRITICKE SEKCE ---
    if (LockDatabase() != 1) return -2; 

    // otevreme databazi pro zapis
    db_file = gdbm_open((char *)db_name.c_str(), GDBM_BLOCK_SIZE, GDBM_WRITER, S_IRUSR | S_IWUSR, 0);
    if (db_file == 0) { 
#ifdef DD_DEBUG
        cout << getpid() << "DD::DFI open gdbm_errno = " << gdbm_errno << " ... " << gdbm_strerror(gdbm_errno) << endl;
#endif
        UnlockDatabase(); 
        return -3; 
    }
    

    if (gdbm_delete(db_file, keyd) != 0) {
#ifdef DD_DEBUG
        cout << getpid() << " - Informace o souboru " << name << " nelze z databaze odstranit." << endl;
#endif
        gdbm_close(db_file);
        UnlockDatabase();
        return -3;
    } else {
        
        num_of_deleted_items++; 
        if (num_of_deleted_items >= MAX_DELETED_ITEMS) {
            // gdbm samo nezmensi velikost souboru databaze, je potreba ho
            // donutit pomoci gdbm_reorganize(), ktere by se nemelo volat moc
            // casto
            if (gdbm_reorganize(db_file) != 0) {
#ifdef DD_DEBUG
                cout << getpid() << " - Nejspis se nepovedla reorganizace databaze ..." << endl;
#endif
            }
        
        }
        
    }//else
    
    gdbm_close(db_file);
    if (UnlockDatabase() != 1) return -2;
// --- konec KRITICKE SEKCE ---

    return 1;
}
Ejemplo n.º 9
0
int main(int argc, char *argv[])
{
  GDBM_FILE gdbm_file;
  datum key_data, data_data;

  if(argc != 4) {
    usage(argv[0]);
  }

  if((strlen(argv[1]) != 17)
     || (argv[1][2] != ':')
     || (argv[1][5] != ':')
     || (argv[1][8] != ':')
     || (argv[1][11] != ':')
     || (argv[1][14] != ':')) {
    printf("Wrong MAC Address format. Example: 08:00:09:B4:AA:81\n");
    exit(-1);
  }

  gdbm_file = gdbm_open (argv[3], 0, GDBM_WRCREAT, 00664, NULL);
  
  if(gdbm_file == NULL) {
    printf("Database open failed: %s\n", gdbm_strerror(gdbm_errno));
    exit(-1);    
  }

  key_data.dptr = argv[1];
  key_data.dsize = strlen(key_data.dptr)+1;
  data_data.dptr = argv[2];
  data_data.dsize = strlen(data_data.dptr)+1;

  if(gdbm_store(gdbm_file, key_data, data_data, GDBM_REPLACE) != 0)
    printf("Error while adding data: %s\n", gdbm_strerror(gdbm_errno));

  gdbm_close(gdbm_file);

  return(0);
}
Ejemplo n.º 10
0
int
main(int argc, char **argv)
{
	GDBM_FILE dbf;
	datum key, next, value;
	int i;

	while ((i = getopt(argc, argv, "py")) != -1) {
		switch (i) {
		case 'p':
			pflag = 1;
			break;
		case 'y':
			yflag = 1;
			break;
		default:
			fprintf(stderr, "Usage: %s [-p] [-y] file [...]\n",
				strchr(argv[0], '/') ?
				strrchr(argv[0], '/') + 1 : argv[0]);
			return 1;
			break;
		}
	}
	for (i = optind; i < argc; i++) {
		dbf = gdbm_open(argv[i], 0, GDBM_READER, 0600, NULL);
		if (dbf == NULL) {
			fprintf(stderr, "Error opening `%s': %s\n", argv[i],
				gdbm_errno ? gdbm_strerror(gdbm_errno) :
				strerror(errno));
			return 1;
		}
		dump_start(argc - optind, argv[i]);
		key = gdbm_firstkey(dbf);
		while (key.dptr != NULL) {
			value = gdbm_fetch(dbf, key);
			if (value.dptr != NULL) {
				dump_entry(key, value);
				free(value.dptr);
			}
			next = gdbm_nextkey(dbf, key);
			free(key.dptr);
			key = next;
		}
		dump_end();
		gdbm_close(dbf);
	}
	return 0;
}
Ejemplo n.º 11
0
static PyObject *
_gdbm_gdbm_reorganize_impl(dbmobject *self)
/*[clinic end generated code: output=38d9624df92e961d input=f6bea85bcfd40dd2]*/
{
    check_dbmobject_open(self);
    errno = 0;
    if (gdbm_reorganize(self->di_dbm) < 0) {
        if (errno != 0)
            PyErr_SetFromErrno(DbmError);
        else
            PyErr_SetString(DbmError, gdbm_strerror(gdbm_errno));
        return NULL;
    }
    Py_INCREF(Py_None);
    return Py_None;
}
Ejemplo n.º 12
0
void hcache_put(struct hcache *cache, struct stat *st,char *hash) {
  datum key, datum;
  //ckpt();
  _hcache_validate_done(cache);
  key = _hcache_genkey(cache,st);
  //ckptm(">>");
  //printhex(stderr,key.dptr,key.dsize,0);
  //ckptm("\n");

  datum.dptr = hash;
  datum.dsize = cache->hlen;
  //ckpt();
  //ckptm("hash=%s, len=%d\n",hash,cache->hlen);
  if (gdbm_store(cache->dbf,key,datum,GDBM_REPLACE) == -1)
    fatal(gdbm_errno,"gdbm_store %s", gdbm_strerror(gdbm_errno));
  //ckpt();
  free(key.dptr);
  //ckpt();
}
Ejemplo n.º 13
0
static apr_status_t set_error(apr_dbm_t *dbm, apr_status_t dbm_said)
{
    apr_status_t rv = APR_SUCCESS;

    /* ### ignore whatever the DBM said (dbm_said); ask it explicitly */

    if ((dbm->errcode = gdbm_errno) == GDBM_NO_ERROR) {
        dbm->errmsg = NULL;
    }
    else {
        dbm->errmsg = gdbm_strerror(gdbm_errno);
        rv = APR_EGENERAL;        /* ### need something better */
    }

    /* captured it. clear it now. */
    gdbm_errno = GDBM_NO_ERROR;

    return rv;
}
Ejemplo n.º 14
0
void hcache_validate(struct hcache *cache, struct stat *st) {
  datum key, datum;
  //ckpt(0);
  _hcache_validate_init(cache);
  if (!cache->dbf) return;
  //ckpt(0);
  key = _hcache_genkey(cache,st);
  //ckpt(0);
  datum = gdbm_fetch(cache->dbf, key);
  //ckpt(0);
  if (datum.dptr == NULL) {
    free(key.dptr);
    return;
  }
  if (gdbm_store(cache->validated, key, datum, GDBM_INSERT) == -1)
    fatal(gdbm_errno,"gdbm_store %s", gdbm_strerror(gdbm_errno));
  //ckpt(0);
  free(datum.dptr);
  free(key.dptr);
}
Ejemplo n.º 15
0
static PyObject *
newdbmobject(char *file, int flags, int mode)
{
    dbmobject *dp;

    dp = PyObject_New(dbmobject, &Dbmtype);
    if (dp == NULL)
        return NULL;
    dp->di_size = -1;
    errno = 0;
    if ((dp->di_dbm = gdbm_open(file, 0, flags, mode, NULL)) == 0) {
        if (errno != 0)
            PyErr_SetFromErrno(DbmError);
        else
            PyErr_SetString(DbmError, gdbm_strerror(gdbm_errno));
        Py_DECREF(dp);
        return NULL;
    }
    return (PyObject *)dp;
}
Ejemplo n.º 16
0
static int
dbm_ass_sub(dbmobject *dp, PyObject *v, PyObject *w)
{
    datum krec, drec;

    if (!PyArg_Parse(v, "s#", &krec.dptr, &krec.dsize) ) {
        PyErr_SetString(PyExc_TypeError,
                        "gdbm mappings have string indices only");
        return -1;
    }
    if (dp->di_dbm == NULL) {
        PyErr_SetString(DbmError,
                        "GDBM object has already been closed"); 
        return -1; 
    }
    dp->di_size = -1;
    if (w == NULL) {
        if (gdbm_delete(dp->di_dbm, krec) < 0) {
            PyErr_SetString(PyExc_KeyError,
                            PyString_AS_STRING((PyStringObject *)v));
            return -1;
        }
    }
    else {
        if (!PyArg_Parse(w, "s#", &drec.dptr, &drec.dsize)) {
            PyErr_SetString(PyExc_TypeError,
                            "gdbm mappings have string elements only");
            return -1;
        }
        errno = 0;
        if (gdbm_store(dp->di_dbm, krec, drec, GDBM_REPLACE) < 0) {
            if (errno != 0)
                PyErr_SetFromErrno(DbmError);
            else
                PyErr_SetString(DbmError,
                                gdbm_strerror(gdbm_errno));
            return -1;
        }
    }
    return 0;
}
Ejemplo n.º 17
0
/*
 *	Write accounting information to this modules database.
 */
static rlm_rcode_t CC_HINT(nonnull) mod_accounting(void *instance, REQUEST *request)
{
	rlm_counter_t *inst = instance;
	datum key_datum;
	datum count_datum;
	VALUE_PAIR *key_vp, *count_vp, *proto_vp, *uniqueid_vp;
	rad_counter counter;
	rlm_rcode_t rcode;
	int ret;
	int acctstatustype = 0;
	time_t diff;

	if ((key_vp = pairfind(request->packet->vps, PW_ACCT_STATUS_TYPE, 0, TAG_ANY)) != NULL)
		acctstatustype = key_vp->vp_integer;
	else {
		DEBUG("rlm_counter: Could not find account status type in packet");
		return RLM_MODULE_NOOP;
	}
	if (acctstatustype != PW_STATUS_STOP) {
		DEBUG("rlm_counter: We only run on Accounting-Stop packets");
		return RLM_MODULE_NOOP;
	}
	uniqueid_vp = pairfind(request->packet->vps, PW_ACCT_UNIQUE_SESSION_ID, 0, TAG_ANY);
	if (uniqueid_vp != NULL)
		DEBUG("rlm_counter: Packet Unique ID = '%s'",uniqueid_vp->vp_strvalue);

	/*
	 *	Before doing anything else, see if we have to reset
	 *	the counters.
	 */
	if (inst->reset_time && (inst->reset_time <= request->timestamp)) {
		DEBUG("rlm_counter: Time to reset the database");
		inst->last_reset = inst->reset_time;
		find_next_reset(inst,request->timestamp);
		pthread_mutex_lock(&inst->mutex);
		rcode = reset_db(inst);
		pthread_mutex_unlock(&inst->mutex);
		if (rcode != RLM_MODULE_OK)
			return rcode;
	}
	/*
	 * Check if we need to watch out for a specific service-type. If yes then check it
	 */
	if (inst->service_type != NULL) {
		if ((proto_vp = pairfind(request->packet->vps, PW_SERVICE_TYPE, 0, TAG_ANY)) == NULL) {
			DEBUG("rlm_counter: Could not find Service-Type attribute in the request. Returning NOOP");
			return RLM_MODULE_NOOP;
		}
		if ((unsigned)proto_vp->vp_integer != inst->service_val) {
			DEBUG("rlm_counter: This Service-Type is not allowed. Returning NOOP");
			return RLM_MODULE_NOOP;
		}
	}
	/*
	 * Check if request->timestamp - {Acct-Delay-Time} < last_reset
	 * If yes reject the packet since it is very old
	 */
	key_vp = pairfind(request->packet->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY);
	if (key_vp != NULL) {
		if ((key_vp->vp_integer != 0) && (request->timestamp - (time_t) key_vp->vp_integer) < inst->last_reset) {
			DEBUG("rlm_counter: This packet is too old. Returning NOOP");
			return RLM_MODULE_NOOP;
		}
	}



	/*
	 *	Look for the key.  User-Name is special.  It means
	 *	The REAL username, after stripping.
	 */
	key_vp = (inst->key_attr->attr == PW_USER_NAME) ? request->username :
					pair_find_by_da(request->packet->vps, inst->key_attr, TAG_ANY);
	if (!key_vp) {
		DEBUG("rlm_counter: Could not find the key-attribute in the request. Returning NOOP");
		return RLM_MODULE_NOOP;
	}

	/*
	 *	Look for the attribute to use as a counter.
	 */
	count_vp = pair_find_by_da(request->packet->vps, inst->count_attr, TAG_ANY);
	if (!count_vp) {
		DEBUG("rlm_counter: Could not find the count_attribute in the request");
		return RLM_MODULE_NOOP;
	}

	ASSIGN(key_datum.dptr, key_vp->vp_strvalue);
	key_datum.dsize = key_vp->length;

	DEBUG("rlm_counter: Searching the database for key '%s'",key_vp->vp_strvalue);
	pthread_mutex_lock(&inst->mutex);
	count_datum = gdbm_fetch(inst->gdbm, key_datum);
	if (!count_datum.dptr) {
		DEBUG("rlm_counter: Could not find the requested key in the database");
		counter.user_counter = 0;
		if (uniqueid_vp != NULL)
			strlcpy(counter.uniqueid,uniqueid_vp->vp_strvalue, sizeof(counter.uniqueid));
		else
			memset((char *)counter.uniqueid,0,UNIQUEID_MAX_LEN);
	} else {
		DEBUG("rlm_counter: Key found");
		memcpy(&counter, count_datum.dptr, sizeof(rad_counter));
		free(count_datum.dptr);
		DEBUG("rlm_counter: Counter Unique ID = '%s'",counter.uniqueid);
		if (uniqueid_vp != NULL) {
			if (strncmp(uniqueid_vp->vp_strvalue,counter.uniqueid, UNIQUEID_MAX_LEN - 1) == 0) {
				DEBUG("rlm_counter: Unique IDs for user match. Droping the request");
				pthread_mutex_unlock(&inst->mutex);
				return RLM_MODULE_NOOP;
			}
			strlcpy(counter.uniqueid,uniqueid_vp->vp_strvalue, sizeof(counter.uniqueid));
		}
		DEBUG("rlm_counter: User=%s, Counter=%d.",request->username->vp_strvalue,counter.user_counter);
	}

	if (inst->count_attr->attr == PW_ACCT_SESSION_TIME) {
		/*
		 *	If session time < diff then the user got in after the
		 *	last reset. So add his session time, otherwise add the
		 *	diff.
		 *
		 *	That way if he logged in at 23:00 and we reset the
		 *	daily counter at 24:00 and he logged out at 01:00
		 *	then we will only count one hour (the one in the new
		 *	day). That is the right thing
		 */
		diff = request->timestamp - inst->last_reset;
		counter.user_counter += ((time_t) count_vp->vp_integer < diff) ? count_vp->vp_integer : diff;

	} else if (count_vp->da->type == PW_TYPE_INTEGER) {
		/*
		 *	Integers get counted, without worrying about
		 *	reset dates.
		 */
		counter.user_counter += count_vp->vp_integer;

	} else {
		/*
		 *	The attribute is NOT an integer, just count once
		 *	more that we've seen it.
		 */
		counter.user_counter++;
	}

	DEBUG("rlm_counter: User=%s, New Counter=%d.",request->username->vp_strvalue,counter.user_counter);
	count_datum.dptr = (char *) &counter;
	count_datum.dsize = sizeof(rad_counter);

	DEBUG("rlm_counter: Storing new value in database");
	ret = gdbm_store(inst->gdbm, key_datum, count_datum, GDBM_REPLACE);
	pthread_mutex_unlock(&inst->mutex);
	if (ret < 0) {
		ERROR("rlm_counter: Failed storing data to %s: %s", inst->filename, gdbm_strerror(gdbm_errno));
		return RLM_MODULE_FAIL;
	}
	DEBUG("rlm_counter: New value stored successfully");

	return RLM_MODULE_OK;
}
Ejemplo n.º 18
0
/** Uklada do databaze informace o souboru.
 * 
 * K vytvoreni klice pouziva File2Key.
 *
 * Navratove hodnoty:
 *
 *      -  1      vse OK.
 *      - -1      chyba pri vytvareni klice k souboru
 *      - -2      chyba pri zamykani/odemykani databaze
 *      - -3      chyba pri praci s databazi
 */
int DirectoryDatabase::PutFileInfo(FileInfo &file) {
    string              key;
    datum               keyd, datad;
    FileInfoGdbmRecord  file_record; //data, ktera budou ulozena do databaze
    int                 store_err;
    int                 open_err;
    int                 ret;
    
    ret = File2Key(file.name.c_str(), key);
    if (ret != 1) return -1;
    
    keyd.dptr   = (char *)key.c_str();
    keyd.dsize  = key.size();
    
    file_record = (FileInfoGdbmRecord) file; //pretypujeme FileInfo na nas zaznam
    datad.dptr  = (char *)&file_record;
    datad.dsize = sizeof(struct FileInfoGdbmRecord);

    
#ifdef DD_DEBUG
    cout << getpid() << " - DD::PutFileInfo ... storing " << file_record.name << " juzra: " << file_record.user_name
         << " with i-node# " << key << " user_rights = " << file_record.user_rights << " in da dejtabejz" << endl;
#endif
    
// --- zacatek KRITICKE SEKCE ---
    if (LockDatabase() != 1) return -2;

    // otevreme databazi pro zapis
    db_file = gdbm_open((char *)db_name.c_str(), GDBM_BLOCK_SIZE, GDBM_WRITER, S_IRUSR | S_IWUSR, 0);
    if (db_file == 0) { //nastala chyba
#ifdef DD_DEBUG
        cout << getpid() << "DD::PFI open gdbm_errno = " << gdbm_errno << " ... " << gdbm_strerror(gdbm_errno) << endl;
#endif
        UnlockDatabase(); 
        return -3; 
    }
    
    //ulozime data
    int err = gdbm_store(db_file, keyd, datad, GDBM_REPLACE);
    if (err != 0) { 
#ifdef DD_DEBUG
        cout << getpid() << "DD::PFI store gdbm_errno = " << gdbm_errno << " ... " << gdbm_strerror(gdbm_errno) << endl;
#endif
        gdbm_close(db_file); //musime, viz komentar niz
        UnlockDatabase(); 
        return -3; 
    }
    
    //databazi zase musime zavrit!!! aby ostatni procesy mohly cist a
    //zapisovat !!!
    gdbm_close(db_file);
    ret = UnlockDatabase();
    if (ret != 1){ 
        return -2;
    }
// --- konec KRITICKE SEKCE ---
    
#ifdef DD_DEBUG
    cout << getpid() << " - DD::PutFileInfo ... stored" << endl;
#endif
    
    return 1;
}
Ejemplo n.º 19
0
int main(int argc, char **argv)
{
    GDBM_FILE db;
    char *dbfile = "sift.db";
    int dbflags = 0;
    char *index_dir = 0;
    char *exec = 0;
    int dump = 0;

    struct option long_options[] = {
        {"index",required_argument, 0,  'i'},
        {"clean",no_argument,       &dbflags, GDBM_NEWDB},
        {"db",   required_argument, 0,  'b'},
        {"exec", required_argument, 0,  'e'},
        {"dump", no_argument,       &dump, 1},
        {"help", no_argument,       0,  'h'},
        {"verbose",no_argument,     &verbose, 1},
        {0,      0,                 0,   0}
    };

    while(1) {
        int option_index = 0;
        int c = getopt_long(argc, argv, "", long_options, &option_index);
        if(c == -1)
            break;

        switch (c) {
        case 'i':
            index_dir = optarg;
            break;
        case 'b':
            dbfile = optarg;
            break;
        case 'e':
            exec = optarg;
            break;
        case 'h':
            print_usage(stderr);
            return 0;
        case 0: // Flags
            break;
        default:
            return 1;
        }
    }

    if(index_dir) {
        db = gdbm_open(dbfile, 1024, GDBM_WRCREAT|dbflags, 0644, 0);
        if(!db) {
            fprintf(stderr, "Can't open '%s': %s\n", dbfile, gdbm_strerror(gdbm_errno));
            return 1;
        }

        fprintf(stderr, "Indexing '%s'\n", index_dir);
        update_index(index_dir, db);
        gdbm_close(db);
    }

    // Subsequent operations require no write access
    db = gdbm_open(dbfile, 1024, GDBM_READER, 0, 0);
    if(!db) {
        fprintf(stderr, "Can't open '%s': %s\n", dbfile, gdbm_strerror(gdbm_errno));
        return 1;
    }

    if(dump) {
        // This functionality doesn't seem to be available easily
        // using gdbmtool or similar thus I added it here
        datum key = gdbm_firstkey(db);

        while(key.dptr) {
            datum nextkey = gdbm_nextkey(db, key);
            puts(key.dptr);
            free(key.dptr);
            key = nextkey;
        }

        gdbm_close(db);
        return 0;
    }

    // At least space for argv[0] and terminating NUL
    char **exec_files = malloc(2*sizeof(char*));
    int num_exec_files = 1;
    exec_files[0] = exec;

    for(int i = optind; i < argc; i++) {
        struct match *matches;
        int num_matches = 0;

        fprintf(stderr, "Matching '%s'...\n", argv[i]);
        match_file(argv[i], db, &matches, &num_matches);

        num_exec_files += num_matches;
        exec_files = realloc(exec_files, (num_exec_files+1)*sizeof(char*));
        match_sort(matches, num_matches);

        for(int j = 0; j < num_matches; j++) {
            exec_files[num_exec_files - num_matches + j] = matches[j].file;
	    if(!isatty(STDOUT_FILENO))
		puts(matches[j].file);
	}

        free(matches);
    }

    if(exec) {
        if(verbose) {
            for(int i = 0; i < num_exec_files; i++)
                fprintf(stderr, "%s ", exec_files[i]);
            putc('\n', stderr);
        }

        gdbm_close(db);

        // terminate array with NUL
        exec_files[num_exec_files] = 0;

        execvp(exec, exec_files);
    }

    for(int i = 0; i < num_exec_files; i++)
        free(exec_files[i]);
    free(exec_files);

    gdbm_close(db);
    return 0;
}
Ejemplo n.º 20
0
/*
*	execute the 'index' function
*/
int		sblib_func_exec(int index, int param_count, slib_par_t *params, var_t *retval)
{
	int		success = 0;

	switch ( index )	{
	case	0:	// handle <- GDBM_OPEN(file[, block_size, flags, mode])
		{
			char	*file;
			int		bsize, flags, mode;

			success = mod_parstr_ptr(0, params, param_count, &file);
			success = mod_opt_parint(1, params, param_count, &bsize, 0);
			success = mod_opt_parint(2, params, param_count, &flags, GDBM_WRCREAT);
			success = mod_opt_parint(3, params, param_count, &mode, 0666);
		
			if	( success )	{
				int		handle;

				handle = get_free_handle();
				if	( handle >= 0 )	{
					table[handle].dbf = gdbm_open(file, bsize, flags, mode, NULL);
					success = (table[handle].dbf != NULL);
					if	( success )	
						v_setint(retval, handle);
					else
						v_setstr(retval, gdbm_strerror(gdbm_errno));
					}
				else	{
					success = 0;
					v_setstr(retval, "GDBM_OPEN: NO FREE HANDLES");
					}
				}
			else
				v_setstr(retval, "GDBM_OPEN: argument error");
		}
		break;

	case	1:	// handle <- GDBM_STORE(handle, key, data [, flags])
		{
			int		handle, flags;
			char	*key, *data;

			success = mod_parint    (0, params, param_count, &handle);
			success = mod_parstr_ptr(1, params, param_count, &key);
			success = mod_parstr_ptr(2, params, param_count, &data);
			success = mod_opt_parint(3, params, param_count, &flags, GDBM_REPLACE);
			if	( success )	{
				if	( is_valid_handle(handle) )	{
					datum	dt_key, dt_data;
					int		r;

					dt_key.dptr   = key;
					dt_key.dsize  = strlen(key) + 1;
					dt_data.dptr  = data;
					dt_data.dsize = strlen(data) + 1;
					
					r = gdbm_store(table[handle].dbf, dt_key, dt_data, flags);
					v_setint(retval, r);
					success = 1;
					}
				else	{
					success = 0;
					v_setstr(retval, "GDBM_STORE: INVALID HANDLE");
					}
				}
			else
				v_setstr(retval, "GDBM_STORE: argument error");
		}
		break;

	case	2:	// data <- GDBM_FETCH(handle, key)
		{
			int		handle;
			char	*key;

			success = mod_parint    (0, params, param_count, &handle);
			success = mod_parstr_ptr(1, params, param_count, &key);
			if	( success )	{
				if	( is_valid_handle(handle) )	{
					datum	dt_key, dt_data;

					dt_key.dptr   = key;
					dt_key.dsize  = strlen(key) + 1;
					
					dt_data = gdbm_fetch(table[handle].dbf, dt_key);
					v_setstr(retval, (char *) dt_data.dptr);
					success = 1;
					}
				else	{
					success = 0;
					v_setstr(retval, "GDBM_FETCH: INVALID HANDLE");
					}
				}
			else
				v_setstr(retval, "GDBM_FETCH: argument error");
		}
		break;

	case	3:	// status <- GDBM_DELETE(handle, key)
		{
			int		handle;
			char	*key;

			success = mod_parint    (0, params, param_count, &handle);
			success = mod_parstr_ptr(1, params, param_count, &key);
			if	( success )	{
				if	( is_valid_handle(handle) )	{
					datum	dt_key;
					int		r;

					dt_key.dptr   = key;
					dt_key.dsize  = strlen(key) + 1;
					
					r = gdbm_delete(table[handle].dbf, dt_key);
					v_setint(retval, r);
					success = 1;
					}
				else	{
					success = 0;
					v_setstr(retval, "GDBM_DELETE: INVALID HANDLE");
					}
				}
			else
				v_setstr(retval, "GDBM_DELETE: argument error");
		}
		break;

	case	4:	// key <- GDBM_FIRSTKEY(handle)
		{
			int		handle;

			success = mod_parint    (0, params, param_count, &handle);
			if	( success )	{
				if	( is_valid_handle(handle) )	{
					datum	dt_key;

					dt_key = gdbm_firstkey(table[handle].dbf);
					v_setstr(retval, (char *) dt_key.dptr);
					success = 1;
					}
				else	{
					success = 0;
					v_setstr(retval, "GDBM_FIRSTKEY: INVALID HANDLE");
					}
				}
			else
				v_setstr(retval, "GDBM_FIRSTKEY: argument error");
		}
		break;

	case	5:	// key <- GDBM_NEXTKEY(handle, key)
		{
			int		handle;
			char	*key;

			success = mod_parint    (0, params, param_count, &handle);
			success = mod_parstr_ptr(1, params, param_count, &key);
			if	( success )	{
				if	( is_valid_handle(handle) )	{
					datum	dt_key;

					dt_key.dptr   = key;
					dt_key.dsize  = strlen(key) + 1;

					dt_key = gdbm_nextkey(table[handle].dbf, dt_key);
					v_setstr(retval, (char *) dt_key.dptr);
					success = 1;
					}
				else	{
					success = 0;
					v_setstr(retval, "GDBM_NEXTKEY: INVALID HANDLE");
					}
				}
			else
				v_setstr(retval, "GDBM_NEXTKEY: argument error");
		}
		break;

	case	6:	// status <- GDBM_REORGANIZE(handle)
		{
			int		handle;

			success = mod_parint    (0, params, param_count, &handle);
			if	( success )	{
				if	( is_valid_handle(handle) )	{
					int		r;

					r = gdbm_reorganize(table[handle].dbf);
					v_setint(retval, r);
					success = 1;
					}
				else	{
					success = 0;
					v_setstr(retval, "GDBM_REORGANIZE: INVALID HANDLE");
					}
				}
			else
				v_setstr(retval, "GDBM_REORGANIZE: argument error");
		}
		break;

	case	7:	// status <- GDBM_EXISTS(handle, key)
		{
			int		handle;
			char	*key;

			success = mod_parint    (0, params, param_count, &handle);
			success = mod_parstr_ptr(1, params, param_count, &key);
			if	( success )	{
				if	( is_valid_handle(handle) )	{
					datum	dt_key;
					int		r;

					dt_key.dptr   = key;
					dt_key.dsize  = strlen(key) + 1;

					r = gdbm_exists(table[handle].dbf, dt_key);
					v_setint(retval, r);
					success = 1;
					}
				else	{
					success = 0;
					v_setstr(retval, "GDBM_EXISTS: INVALID HANDLE");
					}
				}
			else
				v_setstr(retval, "GDBM_EXISTS: argument error");
		}
		break;

	case	8:	// str <- GDBM_STRERROR()
		v_setstr(retval, gdbm_strerror(gdbm_errno));
		break;

	case	9:	// status <- GDBM_SETOPT(handle, option, value, size)
		{
			int		handle, option, value, size;

			success = mod_parint    (0, params, param_count, &handle);
			success = mod_parint    (1, params, param_count, &option);
			success = mod_parint    (2, params, param_count, &value);
			success = mod_parint    (3, params, param_count, &size);
			if	( success )	{
				if	( is_valid_handle(handle) )	{
					int		r;

					r = gdbm_setopt(table[handle].dbf, option, &value, size);
					v_setint(retval, r);
					success = 1;
					}
				else	{
					success = 0;
					v_setstr(retval, "GDBM_SETOPT: INVALID HANDLE");
					}
				}
			else
				v_setstr(retval, "GDBM_SETOPT: argument error");
		}
		break;

	case	10:	// status <- GDBM_FDESC(handle)
		{
			int		handle;

			success = mod_parint    (0, params, param_count, &handle);
			if	( success )	{
				if	( is_valid_handle(handle) )	{
					int		r;

					r = gdbm_fdesc(table[handle].dbf);
					v_setint(retval, r);
					success = 1;
					}
				else	{
					success = 0;
					v_setstr(retval, "GDBM_FDESC: INVALID HANDLE");
					}
				}
			else
				v_setstr(retval, "GDBM_FDESC: argument error");
		}
		break;

	default:
		v_setstr(retval, "GDBM: function does not exist!");
		}

	return success;
}
Ejemplo n.º 21
0
int
gdbm_store (GDBM_FILE dbf, datum key, datum content, int flags)
{
  int  new_hash_val;		/* The new hash value. */
  int  elem_loc;		/* The location in hash bucket. */
  off_t file_adr;		/* The address of new space in the file.  */
  off_t file_pos;		/* The position after a lseek. */
  off_t free_adr;		/* For keeping track of a freed section. */
  int  free_size;
  int   new_size;		/* Used in allocating space. */
  char *temp;			/* Used in _gdbm_findkey call. */
  int rc;

  /* First check to make sure this guy is a writer. */
  if (dbf->read_write == GDBM_READER)
    {
      gdbm_errno = GDBM_READER_CANT_STORE;
      return -1;
    }

  /* Check for illegal data values.  A NULL dptr field is illegal because
     NULL dptr returned by a lookup procedure indicates an error. */
  if ((key.dptr == NULL) || (content.dptr == NULL))
    {
      gdbm_errno = GDBM_ILLEGAL_DATA;
      return -1;
    }

  /* Initialize the gdbm_errno variable. */
  gdbm_errno = GDBM_NO_ERROR;

  /* Look for the key in the file.
     A side effect loads the correct bucket and calculates the hash value. */
  elem_loc = _gdbm_findkey (dbf, key, &temp, &new_hash_val);

  /* Initialize these. */
  file_adr = 0;
  new_size = key.dsize + content.dsize;

  /* Did we find the item? */
  if (elem_loc != -1)
    {
      if (flags == GDBM_REPLACE)
	{
	  /* Just replace the data. */
	  free_adr = dbf->bucket->h_table[elem_loc].data_pointer;
	  free_size = dbf->bucket->h_table[elem_loc].key_size
	              + dbf->bucket->h_table[elem_loc].data_size;
	  if (free_size != new_size)
	    {
	      _gdbm_free (dbf, free_adr, free_size);
	    }
	  else
	    {
	      /* Just reuse the same address! */
	      file_adr = free_adr;
	    }
	}
      else
	{
	  gdbm_errno = GDBM_CANNOT_REPLACE;
	  return 1;
	}
    }


  /* Get the file address for the new space.
     (Current bucket's free space is first place to look.) */
  if (file_adr == 0)
    file_adr = _gdbm_alloc (dbf, new_size);

  /* If this is a new entry in the bucket, we need to do special things. */
  if (elem_loc == -1)
    {
      if (dbf->bucket->count == dbf->header->bucket_elems)
	{
	  /* Split the current bucket. */
	  _gdbm_split_bucket (dbf, new_hash_val);
	}
      
      /* Find space to insert into bucket and set elem_loc to that place. */
      elem_loc = new_hash_val % dbf->header->bucket_elems;
      while (dbf->bucket->h_table[elem_loc].hash_value != -1)
	elem_loc = (elem_loc + 1) % dbf->header->bucket_elems;

      /* We now have another element in the bucket.  Add the new information.*/
      dbf->bucket->count++;
      dbf->bucket->h_table[elem_loc].hash_value = new_hash_val;
      memcpy (dbf->bucket->h_table[elem_loc].key_start, key.dptr,
	     (SMALL < key.dsize ? SMALL : key.dsize));
    }


  /* Update current bucket data pointer and sizes. */
  dbf->bucket->h_table[elem_loc].data_pointer = file_adr;
  dbf->bucket->h_table[elem_loc].key_size = key.dsize;
  dbf->bucket->h_table[elem_loc].data_size = content.dsize;

  /* Write the data to the file. */
  file_pos = __lseek (dbf, file_adr, SEEK_SET);
  if (file_pos != file_adr)
    _gdbm_fatal (dbf, _("lseek error"));
  rc = _gdbm_full_write (dbf, key.dptr, key.dsize);
  if (rc)
    _gdbm_fatal (dbf, gdbm_strerror (rc));
  rc = _gdbm_full_write (dbf, content.dptr, content.dsize);
  if (rc)
    _gdbm_fatal (dbf, gdbm_strerror (rc));

  /* Current bucket has changed. */
  dbf->cache_entry->ca_changed = TRUE;
  dbf->bucket_changed = TRUE;

  /* Write everything that is needed to the disk. */
  _gdbm_end_update (dbf);
  return 0;
  
}
Ejemplo n.º 22
0
/*
 *	Cache the reply items and the Auth-Type
 */
static int caching_postauth(void *instance, REQUEST *request)
{
	rlm_caching_t *data = (rlm_caching_t *)instance;
	char key[MAX_STRING_LEN];
	datum key_datum;
	datum data_datum;
	VALUE_PAIR *reply_vp;
	VALUE_PAIR *auth_type;
	rlm_caching_data cache_data;
	int count = 0;
	int ret = 0;
	int size = 0;
	int rcode = 0;

	if (pairfind(request->packet->vps, PW_CACHE_NO_CACHING, 0) != NULL){
		DEBUG("rlm_caching: Cache-No-Caching is set. Returning NOOP");
		return RLM_MODULE_NOOP;
	}
	if ((auth_type = pairfind(request->config_items, PW_AUTH_TYPE, 0)) != NULL){
		DEBUG("rlm_caching: Found Auth-Type, value: '%s'",auth_type->vp_strvalue);
		if (strcmp(auth_type->vp_strvalue,"Reject") == 0 && data->cache_rejects == 0){
			DEBUG("rlm_caching: No caching of Rejects. Returning NOOP");
			return RLM_MODULE_NOOP;
		}
		if (strlen(auth_type->vp_strvalue) > MAX_AUTH_TYPE - 1){
			DEBUG("rlm_caching: Auth-Type value too large");
			return RLM_MODULE_NOOP;
		}
	}
	else{
		DEBUG("rlm_caching: No Auth-Type found. Returning NOOP");
		return RLM_MODULE_NOOP;
	}

	reply_vp = request->reply->vps;

	if (reply_vp == NULL) {
		DEBUG("rlm_caching: The Request does not contain any reply attributes");
		return RLM_MODULE_NOOP;
	}
	if (!radius_xlat(key,sizeof(key), data->key, request, NULL)){
		radlog(L_ERR, "rlm_caching: xlat on key '%s' failed.",data->key);
		return RLM_MODULE_FAIL;
	}

	memset(&cache_data,0,sizeof(rlm_caching_data));

	cache_data.creation = time(NULL);
	strcpy(cache_data.auth_type,auth_type->vp_strvalue);

	size = MAX_RECORD_LEN;

	while(reply_vp) {
		if (size <= 1){
			DEBUG("rlm_caching: Not enough space.");
			return RLM_MODULE_NOOP;
		}
		ret = vp_prints(cache_data.data + count,size,reply_vp);
		if (ret == 0) {
			DEBUG("rlm_caching: Record is too large, will not store it.");
			return RLM_MODULE_NOOP;
		}
		count += (ret + 1);
		size -= (ret + 1);
		DEBUG("rlm_caching: VP=%s,VALUE=%s,length=%d,cache record length=%d, space left=%d",
			reply_vp->name,reply_vp->vp_strvalue,ret,count,size);
		reply_vp = reply_vp->next;
	}
	cache_data.len = count;

	DEBUG("rlm_caching: Storing cache for Key='%s'",key);
	data_datum.dptr = (rlm_caching_data *) &cache_data;
	data_datum.dsize = sizeof(rlm_caching_data);

	key_datum.dptr = (char *) key;
	key_datum.dsize = strlen(key);

	pthread_mutex_lock(&data->mutex);
	rcode = gdbm_store(data->gdbm, key_datum, data_datum, GDBM_REPLACE);
	pthread_mutex_unlock(&data->mutex);
	if (rcode < 0) {
		radlog(L_ERR, "rlm_caching: Failed storing data to %s: %s",
				data->filename, gdbm_strerror(gdbm_errno));
		return RLM_MODULE_FAIL;
	}
	DEBUG("rlm_caching: New value stored successfully.");

	return RLM_MODULE_OK;
}
Ejemplo n.º 23
0
int
main (int argc, char **argv)
{
  const char *progname = canonical_progname (argv[0]);
  const char *dbname;
  int line = 0;
  char buf[1024];
  datum key;
  datum data;
  int replace = 0;
  int flags = 0;
  int mode = GDBM_WRCREAT;
  int block_size = 0;
  GDBM_FILE dbf;
  int delim = '\t';
  int data_z = 0;
  size_t mapped_size_max = 0;
  
  while (--argc)
    {
      char *arg = *++argv;

      if (strcmp (arg, "-h") == 0)
	{
	  printf ("usage: %s [-replace] [-clear] [-blocksize=N] [-null] [-nolock] [-nommap] [-maxmap=N] [-sync] [-delim=CHR] DBFILE\n", progname);
	  exit (0);
	}
      else if (strcmp (arg, "-replace") == 0)
	replace |= GDBM_REPLACE;
      else if (strcmp (arg, "-clear") == 0)
	mode = GDBM_NEWDB;
      else if (strcmp (arg, "-null") == 0)
	data_z = 1;
      else if (strcmp (arg, "-nolock") == 0)
	flags |= GDBM_NOLOCK;
      else if (strcmp (arg, "-nommap") == 0)
	flags |= GDBM_NOMMAP;
      else if (strcmp (arg, "-sync") == 0)
	flags |= GDBM_SYNC;
      else if (strncmp (arg, "-blocksize=", 11) == 0)
	block_size = atoi (arg + 11);
      else if (strncmp (arg, "-maxmap=", 8) == 0)
	{
	  char *p;

	  errno = 0;
	  mapped_size_max = strtoul (arg + 8, &p, 10);
	  
	  if (errno)
	    {
	      fprintf (stderr, "%s: ", progname);
	      perror ("maxmap");
	      exit (1);
	    }

	  if (*p)
	    {
	      fprintf (stderr, "%s: bad maxmap\n", progname);
	      exit (1);
	    }
	}
      else if (strncmp (arg, "-delim=", 7) == 0)
	delim = arg[7];
      else if (strcmp (arg, "--") == 0)
	{
	  --argc;
	  ++argv;
	  break;
	}
      else if (arg[0] == '-')
	{
	  fprintf (stderr, "%s: unknown option %s\n", progname, arg);
	  exit (1);
	}
      else
	break;
    }

  if (argc != 1)
    {
      fprintf (stderr, "%s: wrong arguments\n", progname);
      exit (1);
    }
  dbname = *argv;
  
  dbf = gdbm_open (dbname, block_size, mode|flags, 00664, NULL);
  if (!dbf)
    {
      fprintf (stderr, "gdbm_open failed: %s\n", gdbm_strerror (gdbm_errno));
      exit (1);
    }

  if (mapped_size_max)
    {
      if (gdbm_setopt (dbf, GDBM_SETMAXMAPSIZE, &mapped_size_max,
		       sizeof (mapped_size_max)))
	{
	  fprintf (stderr, "gdbm_setopt failed: %s\n",
		   gdbm_strerror (gdbm_errno));
	  exit (1);
	}
    }  
  
  while (fgets (buf, sizeof buf, stdin))
    {
      size_t i, j;
      size_t len = strlen (buf);

      if (buf[len - 1] != '\n')
	{
	  fprintf (stderr, "%s: %d: line too long\n",
		   progname, line);
	  continue;
	}

      buf[--len] = 0;
      
      line++;

      for (i = j = 0; i < len; i++)
	{
	  if (buf[i] == '\\')
	    i++;
	  else if (buf[i] == delim)
	    break;
	  else
	    buf[j++] = buf[i];
	}

      if (buf[i] != delim)
	{
	  fprintf (stderr, "%s: %d: malformed line\n",
		   progname, line);
	  continue;
	}

      key.dptr = buf;
      key.dsize = j + data_z;
      data.dptr = buf + j + 1;
      data.dsize = strlen (buf + j + 1) + data_z;
      if (gdbm_store (dbf, key, data, replace) != 0)
	{
	  fprintf (stderr, "%s: %d: item not inserted\n",
		   progname, line);
	  exit (1);
	}
    }
  gdbm_close (dbf);
  exit (0);
}
Ejemplo n.º 24
0
static char const *
_gdbm_strerror (mu_dbm_file_t db)
{
  return gdbm_strerror (db->db_errno.n);
}
Ejemplo n.º 25
0
/** Ziska z databaze informace o zadanem souboru.
 * 
 * Navratove hodnoty:
 *
 *      -  1      vse OK.
 *      - -1      chyba pri vytvareni klice k souboru
 *      - -3      chyba pri praci s databazi
 *
 */
int DirectoryDatabase::GetFileInfo(string name, FileInfo &info) {
    string      key;
    datum       keyd, datad;
    int         ret;
    
    
    ret = File2Key(name.c_str(), key);
    if (ret != 1) return -1;
    
    keyd.dptr   = (char *) key.c_str();
    keyd.dsize  = key.size();
    
// --- zacatek KRITICKE SEKCE ---
    if (LockDatabase() != 1) return -2;

    // otevreme databazi pro cteni
    db_file = gdbm_open((char *)db_name.c_str(), GDBM_BLOCK_SIZE, GDBM_READER, S_IRUSR | S_IWUSR, 0);
    if (db_file == 0) { //nastala chyba
#ifdef DD_DEBUG
        cout << getpid() << "DD::GFI open gdbm_errno = " << gdbm_errno << " ... " << gdbm_strerror(gdbm_errno) << endl;
#endif
        UnlockDatabase(); 
        return -3; 
    }

    datad = gdbm_fetch(db_file, keyd);
    if (datad.dptr == 0) {
#ifdef DD_DEBUG
        cout << getpid() << " - soubor " << name << " nebyl v databazi nalezen. ";
        cout << "gdbm_errno = " << gdbm_errno << " ... " << gdbm_strerror(gdbm_errno) << endl;
#endif
        gdbm_close(db_file);
        UnlockDatabase(); 
        return -3;
    }

    //databazi zase musime zavrit!!! aby ostatni procesy mohly cist a
    //zapisovat !!!
    gdbm_close(db_file);
    
    ret = UnlockDatabase();
    if (ret != 1){ 
        return -2;
    }
// --- konec KRITICKE SEKCE ---
    
    FileInfoGdbmRecord record;
    memcpy(&record, datad.dptr, datad.dsize);
    //cout << "get file info: free(datad.dptr)" << endl;
    free(datad.dptr); // nutne uvolnit misto na ktere ukazuje datad.dptr --> gdbm to samo neudela!!!

#ifdef DD_DEBUG
    cout << getpid() << " - GetFileInfo: ke klici " << key << "jsme dostali informace o " << record.name << endl;
#endif
    
    FileInfo result;
    result = record;
   
    info = result;
    
    return 1;
}
Ejemplo n.º 26
0
M2_string system_dbmstrerror(void) {
     return M2_tostring(gdbm_strerror(gdbm_errno));
     }
Ejemplo n.º 27
0
int
main (int argc, char **argv)
{
  GDBM_FILE dbf = NULL;
  int rc, opt;
  char *dbname, *filename;
  FILE *fp;
  unsigned long err_line, n;
  char *end;
  int oflags = GDBM_NEWDB|GDBM_NOMMAP;
  int cache_size = 0;
  int block_size = 0;
  
#ifdef HAVE_SETLOCALE
  setlocale (LC_ALL, "");
#endif
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  set_progname (argv[0]);

  for (opt = parseopt_first (argc, argv, optab);
       opt != EOF;
       opt = parseopt_next ())
    {
    switch (opt)
      {
      case 'b':
	block_size = get_int (optarg);
	break;
	
      case 'c':
	cache_size = get_int (optarg);
	break;

      case 'm':
	{
	  errno = 0;
	  n = strtoul (optarg, &end, 8);
	  if (*end == 0 && errno == 0)
	    {
	      mode = n & 0777;
	      meta_mask |= GDBM_META_MASK_MODE;
	    }
	  else
	    {
	      error ("%s", _("invalid octal number"));
	      exit (EXIT_USAGE);
	    }
	}
	break;

      case 'u':
	{
	  size_t len;
	  struct passwd *pw;
	  
	  len = strcspn (optarg, ".:");
	  if (optarg[len])
	    optarg[len++] = 0;
	  pw = getpwnam (optarg);
	  if (pw)
	    owner_uid = pw->pw_uid;
	  else
	    {
	      errno = 0;
	      n = strtoul (optarg, &end, 10);
	      if (*end == 0 && errno == 0)
		owner_uid = n;
	      else
		{
		  error (_("invalid user name: %s"), optarg);
		  exit (EXIT_USAGE);
		}
	    }
	  
	  if (optarg[len])
	    {
	      char *grname = optarg + len;
	      struct group *gr = getgrnam (grname);
	      if (gr)
		owner_gid = gr->gr_gid;
	      else
		{
		  errno = 0;
		  n = strtoul (grname, &end, 10);
		  if (*end == 0 && errno == 0)
		    owner_gid = n;
		  else
		    {
		      error (_("invalid group name: %s"), grname);
		      exit (EXIT_USAGE);
		    }
		}
	    }
	  else
	    {
	      if (!pw)
		{
		  pw = getpwuid (owner_uid);
		  if (!pw)
		    {
		      error (_("no such UID: %lu"), (unsigned long)owner_uid);
		      exit (EXIT_USAGE);
		    }
		}
	      owner_gid = pw->pw_gid;
	    }
	  meta_mask |= GDBM_META_MASK_OWNER;
	}
	break;
	  
      case 'r':
	replace = 1;
	break;

      case 'n':
	no_meta_option = 1;
	break;

      case 'M':
	oflags &= ~GDBM_NOMMAP;
	break;
	
      default:
	error (_("unknown option"));
	exit (EXIT_USAGE);
      }
    }

  argc -= optind;
  argv += optind;
  
  if (argc == 0)
    {
      parseopt_print_help ();
      exit (EXIT_OK);
    }

  if (argc > 2)
    {
      error (_("too many arguments; try `%s -h' for more info"), progname);
      exit (EXIT_USAGE);
    }
  
  filename = argv[0];
  if (argc == 2)
    dbname = argv[1];
  else
    dbname = NULL;

  if (strcmp (filename, "-") == 0)
    {
      filename = "<stdin>";
      fp = stdin;
    }
  else
    {
      fp = fopen (filename, "r");
      if (!fp)
	{
	  sys_perror (errno, _("cannot open %s"), filename);
	  exit (EXIT_FATAL);
	}
    }
  
  if (dbname)
    {
      dbf = gdbm_open (dbname, block_size, oflags, 0600, NULL);
      if (!dbf)
	{
	  gdbm_perror (_("gdbm_open failed"));
	  exit (EXIT_FATAL);
	}

      if (cache_size &&
	  gdbm_setopt (dbf, GDBM_SETCACHESIZE, &cache_size, sizeof (int)) == -1)
	error (_("gdbm_setopt failed: %s"), gdbm_strerror (gdbm_errno));
    }
  
  rc = gdbm_load_from_file (&dbf, fp, replace,
			    no_meta_option ?
			      (GDBM_META_MASK_MODE | GDBM_META_MASK_OWNER) :
			      meta_mask,
			    &err_line);
  if (rc)
    {
      switch (gdbm_errno)
	{
	case GDBM_ERR_FILE_OWNER:
	case GDBM_ERR_FILE_MODE:
	  error (_("error restoring metadata: %s (%s)"),
		 gdbm_strerror (gdbm_errno), strerror (errno));
	  rc = EXIT_MILD;
	  break;
	  
	default:
	  if (err_line)
	    gdbm_perror ("%s:%lu", filename, err_line);
	  else
	    gdbm_perror (_("cannot load from %s"), filename);
	  rc = EXIT_FATAL;
	}
    }

  if (dbf)
    {
      if (!no_meta_option && set_meta_info (dbf))
	{
	  error (_("error restoring metadata: %s (%s)"),
		 gdbm_strerror (gdbm_errno), strerror (errno));
	  rc = EXIT_MILD;
	}
      
      if (!dbname)
	{
	  if (gdbm_setopt (dbf, GDBM_GETDBNAME, &dbname, sizeof (dbname)))
	    gdbm_perror (_("gdbm_setopt failed"));
	  else
	    {
	      printf ("%s: created %s\n", progname, dbname);
	      free (dbname);
	    }
	}
      gdbm_close (dbf);
    }
  exit (rc);
}