// this is a simple test to check the implementation, not the algorithm void t01_test_random(){ INIT_LOCAL(); onion_random_init(); unsigned char rand_generated[256]; onion_random_generate(rand_generated,256); //set of which numbers were generated char char_set[256]; memset(char_set,0,256); unsigned unique_numbers_generated=0; unsigned i; for( i=0; i<256; ++i ) { if( char_set[ rand_generated[i] ] == 0) { char_set[ rand_generated[i] ] = 1; unique_numbers_generated++; } } FAIL_IF_NOT( unique_numbers_generated > 256/2 ); onion_random_free(); END_LOCAL(); }
/** * @short Creates a redis backend for sessions * @ingroup sessions */ onion_sessions* onion_sessions_redis_new(const char* server_ip, int port) { onion_random_init(); onion_sessions *ret = onion_low_malloc(sizeof(onion_sessions)); ret->data = onion_low_malloc(sizeof(onion_session_redis)); ret->free=onion_sessions_redis_free; ret->get=onion_sessions_redis_get; ret->save=onion_sessions_redis_save; onion_session_redis *p = ret->data; p->context = redisConnect(server_ip, port); if(p->context != NULL && p->context->err) { ONION_ERROR("Can't connect to redis. Error (%s)", p->context->errstr); redisFree(p->context); return NULL; } #ifdef HAVE_PTHREADS pthread_mutex_init(&p->mutex, NULL); #endif return ret; }
onion_sessions *onion_sessions_mem_new(){ onion_random_init(); onion_sessions *ret=onion_low_malloc(sizeof(onion_sessions)); ret->data=onion_dict_new(); ret->get=onion_sessions_mem_get; ret->save=onion_sessions_mem_save; ret->free=onion_sessions_mem_free; return ret; }
/** * @short Creates a sqlite backend for sessions * @ingroup sessions * * @see onion_set_session_backend */ onion_sessions* onion_sessions_sqlite3_new(const char *database_filename) { onion_random_init(); int rc; sqlite3 *db; sqlite3_stmt *save; sqlite3_stmt *get; rc = sqlite3_open(database_filename, &db); if( rc ){ ONION_ERROR("Can't open database: %s", sqlite3_errmsg(db)); sqlite3_close(db); return NULL; } // I blindly try to create tables. If they exist, error, if not, create sqlite3_exec(db, "CREATE TABLE sessions (id TEXT PRIMARY KEY, data TEXT)", 0,0,0); const char *GET_SQL="SELECT data FROM sessions WHERE id=?"; rc=sqlite3_prepare_v2(db, GET_SQL, strlen(GET_SQL), &get, NULL); if( rc != SQLITE_OK ){ ONION_ERROR("Cant prepare statement to get (%d)", rc); sqlite3_close(db); return NULL; } const char *SAVE_SQL="INSERT OR REPLACE INTO sessions (id, data) VALUES (?, ?);"; rc=sqlite3_prepare_v2(db, SAVE_SQL, strlen(SAVE_SQL), &save, NULL); if( rc != SQLITE_OK ){ ONION_ERROR("Cant prepare statement to save (%d)", rc); sqlite3_close(db); return NULL; } onion_sessions *ret=onion_low_malloc(sizeof(onion_sessions)); ret->data=onion_low_malloc(sizeof(onion_session_sqlite3)); ret->free=onion_sessions_sqlite3_free; ret->get=onion_sessions_sqlite3_get; ret->save=onion_sessions_sqlite3_save; onion_session_sqlite3 *p=ret->data; p->db=db; p->save=save; p->get=get; #ifdef HAVE_PTHREADS pthread_mutex_init(&p->mutex, NULL); #endif return ret; }