Esempio n. 1
0
int
meta_back_bind( Operation *op, SlapReply *rs )
{
	metainfo_t	*mi = ( metainfo_t * )op->o_bd->be_private;
	metaconn_t	*mc = NULL;

	int		rc = LDAP_OTHER,
			i,
			gotit = 0,
			isroot = 0;

	SlapReply	*candidates;

	rs->sr_err = LDAP_SUCCESS;

	Debug( LDAP_DEBUG_ARGS, "%s meta_back_bind: dn=\"%s\".\n",
		op->o_log_prefix, op->o_req_dn.bv_val );

	/* the test on the bind method should be superfluous */
	switch ( be_rootdn_bind( op, rs ) ) {
	case LDAP_SUCCESS:
		if ( META_BACK_DEFER_ROOTDN_BIND( mi ) ) {
			/* frontend will return success */
			return rs->sr_err;
		}

		isroot = 1;
		/* fallthru */

	case SLAP_CB_CONTINUE:
		break;

	default:
		/* be_rootdn_bind() sent result */
		return rs->sr_err;
	}

	/* we need meta_back_getconn() not send result even on error,
	 * because we want to intercept the error and make it
	 * invalidCredentials */
	mc = meta_back_getconn( op, rs, NULL, LDAP_BACK_BIND_DONTSEND );
	if ( !mc ) {
		if ( LogTest( LDAP_DEBUG_ANY ) ) {
			char	buf[ SLAP_TEXT_BUFLEN ];

			snprintf( buf, sizeof( buf ),
				"meta_back_bind: no target "
				"for dn \"%s\" (%d%s%s).",
				op->o_req_dn.bv_val, rs->sr_err,
				rs->sr_text ? ". " : "",
				rs->sr_text ? rs->sr_text : "" );
			Debug( LDAP_DEBUG_ANY,
				"%s %s\n",
				op->o_log_prefix, buf );
		}

		/* FIXME: there might be cases where we don't want
		 * to map the error onto invalidCredentials */
		switch ( rs->sr_err ) {
		case LDAP_NO_SUCH_OBJECT:
		case LDAP_UNWILLING_TO_PERFORM:
			rs->sr_err = LDAP_INVALID_CREDENTIALS;
			rs->sr_text = NULL;
			break;
		}
		send_ldap_result( op, rs );
		return rs->sr_err;
	}

	candidates = meta_back_candidates_get( op );

	/*
	 * Each target is scanned ...
	 */
	mc->mc_authz_target = META_BOUND_NONE;
	for ( i = 0; i < mi->mi_ntargets; i++ ) {
		metatarget_t	*mt = mi->mi_targets[ i ];
		int		lerr;

		/*
		 * Skip non-candidates
		 */
		if ( !META_IS_CANDIDATE( &candidates[ i ] ) ) {
			continue;
		}

		if ( gotit == 0 ) {
			/* set rc to LDAP_SUCCESS only if at least
			 * one candidate has been tried */
			rc = LDAP_SUCCESS;
			gotit = 1;

		} else if ( !isroot ) {
			/*
			 * A bind operation is expected to have
			 * ONE CANDIDATE ONLY!
			 */
			Debug( LDAP_DEBUG_ANY,
				"### %s meta_back_bind: more than one"
				" candidate selected...\n",
				op->o_log_prefix );
		}

		if ( isroot ) {
			if ( mt->mt_idassert_authmethod == LDAP_AUTH_NONE
				|| BER_BVISNULL( &mt->mt_idassert_authcDN ) )
			{
				metasingleconn_t	*msc = &mc->mc_conns[ i ];

				/* skip the target if no pseudorootdn is provided */
				if ( !BER_BVISNULL( &msc->msc_bound_ndn ) ) {
					ch_free( msc->msc_bound_ndn.bv_val );
					BER_BVZERO( &msc->msc_bound_ndn );
				}

				if ( !BER_BVISNULL( &msc->msc_cred ) ) {
					/* destroy sensitive data */
					memset( msc->msc_cred.bv_val, 0,
						msc->msc_cred.bv_len );
					ch_free( msc->msc_cred.bv_val );
					BER_BVZERO( &msc->msc_cred );
				}

				continue;
			}


			(void)meta_back_proxy_authz_bind( mc, i, op, rs, LDAP_BACK_DONTSEND, 1 );
			lerr = rs->sr_err;

		} else {
			lerr = meta_back_single_bind( op, rs, mc, i );
		}

		if ( lerr != LDAP_SUCCESS ) {
			rc = rs->sr_err = lerr;

			/* FIXME: in some cases (e.g. unavailable)
			 * do not assume it's not candidate; rather
			 * mark this as an error to be eventually
			 * reported to client */
			META_CANDIDATE_CLEAR( &candidates[ i ] );
			break;
		}
	}

	/* must re-insert if local DN changed as result of bind */
	if ( rc == LDAP_SUCCESS ) {
		if ( isroot ) {
			mc->mc_authz_target = META_BOUND_ALL;
		}

		if ( !LDAP_BACK_PCONN_ISPRIV( mc )
			&& !dn_match( &op->o_req_ndn, &mc->mc_local_ndn ) )
		{
			int		lerr;

			/* wait for all other ops to release the connection */
			ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
			assert( mc->mc_refcnt == 1 );
#if META_BACK_PRINT_CONNTREE > 0
			meta_back_print_conntree( mi, ">>> meta_back_bind" );
#endif /* META_BACK_PRINT_CONNTREE */

			/* delete all cached connections with the current connection */
			if ( LDAP_BACK_SINGLECONN( mi ) ) {
				metaconn_t	*tmpmc;

				while ( ( tmpmc = avl_delete( &mi->mi_conninfo.lai_tree, (caddr_t)mc, meta_back_conn_cmp ) ) != NULL )
				{
					assert( !LDAP_BACK_PCONN_ISPRIV( mc ) );
					Debug( LDAP_DEBUG_TRACE,
						"=>meta_back_bind: destroying conn %lu (refcnt=%u)\n",
						mc->mc_conn->c_connid, mc->mc_refcnt );

					if ( tmpmc->mc_refcnt != 0 ) {
						/* taint it */
						LDAP_BACK_CONN_TAINTED_SET( tmpmc );

					} else {
						/*
						 * Needs a test because the handler may be corrupted,
						 * and calling ldap_unbind on a corrupted header results
						 * in a segmentation fault
						 */
						meta_back_conn_free( tmpmc );
					}
				}
			}

			ber_bvreplace( &mc->mc_local_ndn, &op->o_req_ndn );
			lerr = avl_insert( &mi->mi_conninfo.lai_tree, (caddr_t)mc,
				meta_back_conndn_cmp, meta_back_conndn_dup );
#if META_BACK_PRINT_CONNTREE > 0
			meta_back_print_conntree( mi, "<<< meta_back_bind" );
#endif /* META_BACK_PRINT_CONNTREE */
			if ( lerr == 0 ) {
#if 0
				/* NOTE: a connection cannot be privileged
				 * and be in the avl tree at the same time
				 */
				if ( isroot ) {
					LDAP_BACK_CONN_ISPRIV_SET( mc );
					LDAP_BACK_PCONN_SET( mc, op );
				}
#endif
				LDAP_BACK_CONN_CACHED_SET( mc );

			} else {
				LDAP_BACK_CONN_CACHED_CLEAR( mc );
			}
			ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
		}
	}

	if ( mc != NULL ) {
		meta_back_release_conn( mi, mc );
	}

	/*
	 * rc is LDAP_SUCCESS if at least one bind succeeded,
	 * err is the last error that occurred during a bind;
	 * if at least (and at most?) one bind succeeds, fine.
	 */
	if ( rc != LDAP_SUCCESS ) {

		/*
		 * deal with bind failure ...
		 */

		/*
		 * no target was found within the naming context,
		 * so bind must fail with invalid credentials
		 */
		if ( rs->sr_err == LDAP_SUCCESS && gotit == 0 ) {
			rs->sr_err = LDAP_INVALID_CREDENTIALS;
		} else {
			rs->sr_err = slap_map_api2result( rs );
		}
		send_ldap_result( op, rs );
		return rs->sr_err;

	}

	return LDAP_SUCCESS;
}
Esempio n. 2
0
static void process_source_stat (stats_source_t *src_stats, stats_event_t *event)
{
    if (event->name)
    {
        stats_node_t *node = _find_node (src_stats->stats_tree, event->name);
        if (node == NULL)
        {
            /* adding node */
            if (event->action != STATS_EVENT_REMOVE && event->value)
            {
                DEBUG3 ("new node on %s \"%s\" (%s)", src_stats->source, event->name, event->value);
                node = (stats_node_t *)calloc (1,sizeof(stats_node_t));
                node->name = (char *)strdup (event->name);
                node->value = (char *)strdup (event->value);
                node->flags = event->flags;
                if (src_stats->flags & STATS_HIDDEN)
                    node->flags |= STATS_HIDDEN;
                stats_listener_send (node->flags, "EVENT %s %s %s\n", src_stats->source, event->name, event->value);
                avl_insert (src_stats->stats_tree, (void *)node);
            }
            return;
        }
        if (event->action == STATS_EVENT_REMOVE)
        {
            DEBUG2 ("delete node %s from %s", event->name, src_stats->source);
            stats_listener_send (node->flags, "DELETE %s %s\n", src_stats->source, event->name);
            avl_delete (src_stats->stats_tree, (void *)node, _free_stats);
            return;
        }
        modify_node_event (node, event);
        stats_listener_send (node->flags, "EVENT %s %s %s\n", src_stats->source, node->name, node->value);
        return;
    }
    if (event->action == STATS_EVENT_REMOVE && event->name == NULL)
    {
        avl_tree_unlock (src_stats->stats_tree);
        avl_tree_wlock (_stats.source_tree);
        avl_tree_wlock (src_stats->stats_tree);
        avl_delete (_stats.source_tree, (void *)src_stats, _free_source_stats);
        avl_tree_unlock (_stats.source_tree);
        return;
    }
    /* change source flags status */
    if (event->action & STATS_EVENT_HIDDEN)
    {
        avl_node *node = avl_get_first (src_stats->stats_tree);
        int visible = 0;

        if ((event->flags&STATS_HIDDEN) == (src_stats->flags&STATS_HIDDEN))
            return;
        if (src_stats->flags & STATS_HIDDEN)
        {
            stats_node_t *ct = _find_node (src_stats->stats_tree, "server_type");
            const char *type = "audio/mpeg";
            if (ct)
                type = ct->value;
            src_stats->flags &= ~STATS_HIDDEN;
            stats_listener_send (src_stats->flags, "NEW %s %s\n", type, src_stats->source);
            visible = 1;
        }
        else
        {
            stats_listener_send (src_stats->flags, "DELETE %s\n", src_stats->source);
            src_stats->flags |= STATS_HIDDEN;
        }
        while (node)
        {
            stats_node_t *stats = (stats_node_t*)node->key;
            if (visible)
            {
                stats->flags &= ~STATS_HIDDEN;
                stats_listener_send (stats->flags, "EVENT %s %s %s\n", src_stats->source, stats->name, stats->value);
            }
            else
                stats->flags |= STATS_HIDDEN;
            node = avl_get_next (node);
        }
    }
}
Esempio n. 3
0
int
bdb_idl_fetch_key(
	BackendDB	*be,
	DB			*db,
	DB_TXN		*tid,
	DBT			*key,
	ID			*ids )
{
	struct bdb_info *bdb = (struct bdb_info *) be->be_private;
	int rc;
	DBT data;
	DBC *cursor;
	ID *i;
	void *ptr;
	size_t len;
	int rc2;
	int flags = bdb->bi_db_opflags | DB_MULTIPLE;
#ifdef SLAP_IDL_CACHE
	bdb_idl_cache_entry_t idl_tmp;
#endif

	/* If using BerkeleyDB 4.0, the buf must be large enough to
	 * grab the entire IDL in one get(), otherwise BDB will leak
	 * resources on subsequent get's.  We can safely call get()
	 * twice - once for the data, and once to get the DB_NOTFOUND
	 * result meaning there's no more data. See ITS#2040 for details.
	 * This bug is fixed in BDB 4.1 so a smaller buffer will work if
	 * stack space is too limited.
	 *
	 * configure now requires Berkeley DB 4.1.
	 */
#if (DB_VERSION_MAJOR == 4) && (DB_VERSION_MINOR == 0)
#	define BDB_ENOUGH 5
#else
#	define BDB_ENOUGH 1
#endif
	ID buf[BDB_IDL_DB_SIZE*BDB_ENOUGH];

	char keybuf[16];

#ifdef NEW_LOGGING
	LDAP_LOG( INDEX, ARGS,
		"bdb_idl_fetch_key: %s\n", 
		bdb_show_key( key, keybuf ), 0, 0 );
#else
	Debug( LDAP_DEBUG_ARGS,
		"bdb_idl_fetch_key: %s\n", 
		bdb_show_key( key, keybuf ), 0, 0 );
#endif

	assert( ids != NULL );

#ifdef SLAP_IDL_CACHE
	if ( bdb->bi_idl_cache_max_size ) {
		bdb_idl_cache_entry_t *matched_idl_entry;
		DBT2bv( key, &idl_tmp.kstr );
		idl_tmp.db = db;
		ldap_pvt_thread_mutex_lock( &bdb->bi_idl_tree_mutex );
		matched_idl_entry = avl_find( bdb->bi_idl_tree, &idl_tmp,
		                              bdb_idl_entry_cmp );
		if ( matched_idl_entry != NULL ) {
			BDB_IDL_CPY( ids, matched_idl_entry->idl );
			IDL_LRU_DELETE( bdb, matched_idl_entry );
			IDL_LRU_ADD( bdb, matched_idl_entry );
			ldap_pvt_thread_mutex_unlock( &bdb->bi_idl_tree_mutex );
			return LDAP_SUCCESS;
		}
		ldap_pvt_thread_mutex_unlock( &bdb->bi_idl_tree_mutex );
	}
#endif

	DBTzero( &data );

	data.data = buf;
	data.ulen = sizeof(buf);
	data.flags = DB_DBT_USERMEM;

	if ( tid ) flags |= DB_RMW;

	rc = db->cursor( db, tid, &cursor, bdb->bi_db_opflags );
	if( rc != 0 ) {
#ifdef NEW_LOGGING
		LDAP_LOG( INDEX, ERR, 
			"bdb_idl_fetch_key: cursor failed: %s (%d)\n", 
			db_strerror(rc), rc, 0 );
#else
		Debug( LDAP_DEBUG_ANY, "=> bdb_idl_fetch_key: "
			"cursor failed: %s (%d)\n", db_strerror(rc), rc, 0 );
#endif
		return rc;
	}

	rc = cursor->c_get( cursor, key, &data, flags | DB_SET );
	if (rc == 0) {
		i = ids;
		while (rc == 0) {
			u_int8_t *j;

			DB_MULTIPLE_INIT( ptr, &data );
			while (ptr) {
				DB_MULTIPLE_NEXT(ptr, &data, j, len);
				if (j) {
					++i;
					AC_MEMCPY( i, j, sizeof(ID) );
				}
			}
			rc = cursor->c_get( cursor, key, &data, flags | DB_NEXT_DUP );
		}
		if ( rc == DB_NOTFOUND ) rc = 0;
		ids[0] = i - ids;
		/* On disk, a range is denoted by 0 in the first element */
		if (ids[1] == 0) {
			if (ids[0] != BDB_IDL_RANGE_SIZE) {
#ifdef NEW_LOGGING
				LDAP_LOG( INDEX, ERR, 
					"=> bdb_idl_fetch_key: range size mismatch: "
					"expected %ld, got %ld\n", 
					BDB_IDL_RANGE_SIZE, ids[0], 0 );
#else
				Debug( LDAP_DEBUG_ANY, "=> bdb_idl_fetch_key: "
					"range size mismatch: expected %d, got %ld\n",
					BDB_IDL_RANGE_SIZE, ids[0], 0 );
#endif
				cursor->c_close( cursor );
				return -1;
			}
			BDB_IDL_RANGE( ids, ids[2], ids[3] );
		}
		data.size = BDB_IDL_SIZEOF(ids);
	}

	rc2 = cursor->c_close( cursor );
	if (rc2) {
#ifdef NEW_LOGGING
		LDAP_LOG( INDEX, ERR, 
			"bdb_idl_fetch_key: close failed: %s (%d)\n", 
			db_strerror(rc2), rc2, 0 );
#else
		Debug( LDAP_DEBUG_ANY, "=> bdb_idl_fetch_key: "
			"close failed: %s (%d)\n", db_strerror(rc2), rc2, 0 );
#endif
		return rc2;
	}

	if( rc == DB_NOTFOUND ) {
		return rc;

	} else if( rc != 0 ) {
#ifdef NEW_LOGGING
		LDAP_LOG( INDEX, ERR, 
			"bdb_idl_fetch_key: get failed: %s (%d)\n", 
			db_strerror(rc), rc, 0 );
#else
		Debug( LDAP_DEBUG_ANY, "=> bdb_idl_fetch_key: "
			"get failed: %s (%d)\n",
			db_strerror(rc), rc, 0 );
#endif
		return rc;

	} else if ( data.size == 0 || data.size % sizeof( ID ) ) {
		/* size not multiple of ID size */
#ifdef NEW_LOGGING
		LDAP_LOG( INDEX, ERR, 
			"bdb_idl_fetch_key: odd size: expected %ld multiple, got %ld\n", 
			(long) sizeof( ID ), (long) data.size, 0 );
#else
		Debug( LDAP_DEBUG_ANY, "=> bdb_idl_fetch_key: "
			"odd size: expected %ld multiple, got %ld\n",
			(long) sizeof( ID ), (long) data.size, 0 );
#endif
		return -1;

	} else if ( data.size != BDB_IDL_SIZEOF(ids) ) {
		/* size mismatch */
#ifdef NEW_LOGGING
		LDAP_LOG( INDEX, ERR, 
			"bdb_idl_fetch_key: get size mismatch: expected %ld, got %ld\n", 
			(long) ((1 + ids[0]) * sizeof( ID )), (long) data.size, 0 );
#else
		Debug( LDAP_DEBUG_ANY, "=> bdb_idl_fetch_key: "
			"get size mismatch: expected %ld, got %ld\n",
			(long) ((1 + ids[0]) * sizeof( ID )), (long) data.size, 0 );
#endif
		return -1;
	}

#ifdef SLAP_IDL_CACHE
	if ( bdb->bi_idl_cache_max_size ) {
		bdb_idl_cache_entry_t *ee;
		ee = (bdb_idl_cache_entry_t *) ch_malloc(
			sizeof( bdb_idl_cache_entry_t ) );
		ee->db = db;
		ee->idl = (ID*) ch_malloc( BDB_IDL_SIZEOF ( ids ) );
		ee->idl_lru_prev = NULL;
		ee->idl_lru_next = NULL;
		BDB_IDL_CPY( ee->idl, ids );
		ber_dupbv( &ee->kstr, &idl_tmp.kstr );
		ldap_pvt_thread_mutex_lock( &bdb->bi_idl_tree_mutex );
		if ( avl_insert( &bdb->bi_idl_tree, (caddr_t) ee,
			bdb_idl_entry_cmp, avl_dup_error ))
		{
			ch_free( ee->kstr.bv_val );
			ch_free( ee->idl );
			ch_free( ee );
		} else {
			IDL_LRU_ADD( bdb, ee );
			if ( ++bdb->bi_idl_cache_size > bdb->bi_idl_cache_max_size ) {
				int i = 0;
				while ( bdb->bi_idl_lru_tail != NULL && i < 10 ) {
					ee = bdb->bi_idl_lru_tail;
					if ( avl_delete( &bdb->bi_idl_tree, (caddr_t) ee,
					            bdb_idl_entry_cmp ) == NULL ) {
#ifdef NEW_LOGGING
						LDAP_LOG( INDEX, ERR, 
							"bdb_idl_fetch_key: AVL delete failed\n", 
							0, 0, 0 );
#else
						Debug( LDAP_DEBUG_ANY, "=> bdb_idl_fetch_key: "
							"AVL delete failed\n",
							0, 0, 0 );
#endif
					}
					IDL_LRU_DELETE( bdb, ee );
					i++;
					--bdb->bi_idl_cache_size;
					ch_free( ee->kstr.bv_val );
					ch_free( ee->idl );
					ch_free( ee );
				}
			}
		}
		ldap_pvt_thread_mutex_unlock( &bdb->bi_idl_tree_mutex );
	}
#endif

	return rc;
}
Gestao inserir_compra_gestao(Gestao g, char*cl, char*pr, int mes, int tipo, int filial, int quant, double preco){
	int i, j, k, v;	
	char *cod;	
	Cliente procura        = NULL;
	Produto procura2       = NULL;
	ProdutoGestao procura3 = NULL;
	Produto p              = NULL;
	Cliente c              = NULL;	
	ProdutoGestao pg       = NULL;

	/*Atualizar ProdutoGestao************************************************/
	procura3       = (ProdutoGestao) malloc(sizeof(struct produtogestao));
	procura3->prod = pr; /*Não tem mal apenas igualar o apontador, pois esta variável será usada somente para efetuar uma procura e nunca para inserir a string para que se aponta, deste modo, seria redundante e menos eficiente alocar memória aqui.*/

	pg = (ProdutoGestao) avl_find (g->produtos[*pr-'A'], procura3);	

	pg->quantidade_anual    += quant;
	pg->faturacao_anual     += quant*preco;
	pg->faturacao[filial-1] += quant*preco;
	pg->vendas   [filial-1]++;	
	

	if (((char*)avl_find (pg->clientes[*cl-'A'], cl))==NULL) {
		pg->num_clientes++;
		
		cod = (char*) malloc ((sizeof(char))*(strlen(cl)+1));
		strcpy(cod,cl);
		
		avl_insert(pg->clientes[cod[0]-'A'], cod);
	}
	
	free(procura3);	
	/**********************************************************************/
	
	/*Inserir Cliente*/
	procura      = (Cliente) malloc(sizeof(struct cliente));
	procura->cli = cl; /*Não tem mal apenas igualar o apontador, pois esta variável será usada somente para efetuar uma procura e nunca para inserir a string para que se aponta, deste modo, seria redundante e menos eficiente alocar memória aqui.*/

	c = avl_find (g->clientes[(*cl)-'A'], procura);
	free(procura);

	/*Contador de Clientes que compraram em todas as filiais*/
	if ((c->comprador_todas_filiais)==0){
		for(i=0; i<N_FILIAIS; i++){
			if (i==filial-1) continue;
			for (v=0, j=0; j<N_MESES; j++){
				for (k=0; k<N_REGIMES; k++){
					v    += c->compras_mes[i][j][k];
				}
			}
			if (v==0) break;
		}
		if (i==N_FILIAIS) {
			g->num_compradores_todas_filiais++;
			c->comprador_todas_filiais = 1;
		}
	}
	/****************************************************/

	/*Contador de clientes compradores*/
	if (c->produtos_diferentes_comprados==0)
		g->num_clientes_compradores++;
	/*********************************/

	c->quantidade_mes[filial-1][mes-1][tipo]+=quant;
	c->compras_mes   [filial-1][mes-1][tipo]++;


	/*Inserir Produto*/
	procura2       = (Produto) malloc(sizeof(struct produto));
	procura2->prod = pr; /*Não tem mal apenas igualar o apontador, pois esta variável será usada somente para efetuar uma procura e nunca para inserir a string para que se aponta, deste modo, seria redundante e menos eficiente alocar memória aqui.*/


	p = avl_find (c->produtos[*pr-'A'], procura2);
	free(procura2);

	if (p==NULL) {
		p = init_produto_gestao(pr);
		p->faturacao        += quant*preco;
		p->quantidade_anual += quant;
		p->quantidade_mes[filial-1][mes-1][tipo]+=quant;
		p->compras_mes   [filial-1][mes-1][tipo]++;
		c->produtos_diferentes_comprados++;
		c->produtos_diferentes_comprados_mes[mes-1]++;
		avl_insert(c->produtos[*pr-'A'], p);
		
		return g;
	}

	p->faturacao        += quant*preco;
	p->quantidade_anual += quant;
	p->quantidade_mes[filial-1][mes-1][tipo]+=quant;
	p->compras_mes   [filial-1][mes-1][tipo]++;
	/*************/	

	return g;
}
Esempio n. 5
0
int
gsl_spmatrix_set(gsl_spmatrix *m, const size_t i, const size_t j,
                 const double x)
{
  if (!GSL_SPMATRIX_ISTRIPLET(m))
    {
      GSL_ERROR("matrix not in triplet representation", GSL_EINVAL);
    }
  else if (x == 0.0)
    {
      /* traverse binary tree to search for (i,j) element */
      void *ptr = tree_find(m, i, j);

      /*
       * just set the data element to 0; it would be easy to
       * delete the node from the tree with avl_delete(), but
       * we'd also have to delete it from the data arrays which
       * is less simple
       */
      if (ptr != NULL)
        *(double *) ptr = 0.0;

      return GSL_SUCCESS;
    }
  else
    {
      int s = GSL_SUCCESS;
      void *ptr;

      /* check if matrix needs to be realloced */
      if (m->nz >= m->nzmax)
        {
          s = gsl_spmatrix_realloc(2 * m->nzmax, m);
          if (s)
            return s;
        }

      /* store the triplet (i, j, x) */
      m->i[m->nz] = i;
      m->p[m->nz] = j;
      m->data[m->nz] = x;

      ptr = avl_insert(m->tree_data->tree, &m->data[m->nz]);
      if (ptr != NULL)
        {
          /* found duplicate entry (i,j), replace with new x */
          *((double *) ptr) = x;
        }
      else
        {
          /* no duplicate (i,j) found, update indices as needed */

          /* increase matrix dimensions if needed */
          m->size1 = GSL_MAX(m->size1, i + 1);
          m->size2 = GSL_MAX(m->size2, j + 1);

          ++(m->nz);
        }

      return s;
    }
} /* gsl_spmatrix_set() */
Esempio n. 6
0
int
main( int argc, char **argv )
{
	Avlnode	*tree = NULL;
	char	command[ 10 ];
	char	name[ 80 ];
	char	*p;

	printf( "> " );
	while ( fgets( command, sizeof( command ), stdin ) != NULL ) {
		switch( *command ) {
		case 'n':	/* new tree */
			( void ) avl_free( tree, free );
			tree = NULL;
			break;
		case 'p':	/* print */
			( void ) myprint( tree );
			break;
		case 't':	/* traverse with first, next */
#ifdef AVL_NONREENTRANT
			printf( "***\n" );
			for ( p = (char * ) avl_getfirst( tree );
			    p != NULL;
				p = (char *) avl_getnext())
				printf( "%s\n", p );
			printf( "***\n" );
#else
			printf( "*** reentrant interface not implemented ***" );
#endif
			break;
		case 'f':	/* find */
			printf( "data? " );
			if ( fgets( name, sizeof( name ), stdin ) == NULL )
				exit( EXIT_SUCCESS );
			name[ strlen( name ) - 1 ] = '\0';
			if ( (p = (char *) avl_find( tree, name, avl_strcmp ))
			    == NULL )
				printf( "Not found.\n\n" );
			else
				printf( "%s\n\n", p );
			break;
		case 'i':	/* insert */
			printf( "data? " );
			if ( fgets( name, sizeof( name ), stdin ) == NULL )
				exit( EXIT_SUCCESS );
			name[ strlen( name ) - 1 ] = '\0';
			if ( avl_insert( &tree, strdup( name ), avl_strcmp, 
			    avl_dup_error ) != 0 )
				printf( "\nNot inserted!\n" );
			break;
		case 'd':	/* delete */
			printf( "data? " );
			if ( fgets( name, sizeof( name ), stdin ) == NULL )
				exit( EXIT_SUCCESS );
			name[ strlen( name ) - 1 ] = '\0';
			if ( avl_delete( &tree, name, avl_strcmp ) == NULL )
				printf( "\nNot found!\n" );
			break;
		case 'q':	/* quit */
			exit( EXIT_SUCCESS );
			break;
		case '\n':
			break;
		default:
			printf("Commands: insert, delete, print, new, quit\n");
		}

		printf( "> " );
	}

	return( 0 );
}
Esempio n. 7
0
/* Create an entryinfo in the cache. Caller must release the locks later.
 */
static int
bdb_entryinfo_add_internal(
	struct bdb_info *bdb,
	EntryInfo *ei,
	EntryInfo **res )
{
	EntryInfo *ei2 = NULL;

	*res = NULL;

	ei2 = bdb_cache_entryinfo_new( &bdb->bi_cache );

	bdb_cache_entryinfo_lock( ei->bei_parent );
	ldap_pvt_thread_rdwr_wlock( &bdb->bi_cache.c_rwlock );

	ei2->bei_id = ei->bei_id;
	ei2->bei_parent = ei->bei_parent;
#ifdef BDB_HIER
	ei2->bei_rdn = ei->bei_rdn;
#endif
#ifdef SLAP_ZONE_ALLOC
	ei2->bei_bdb = bdb;
#endif

	/* Add to cache ID tree */
	if (avl_insert( &bdb->bi_cache.c_idtree, ei2, bdb_id_cmp,
		bdb_id_dup_err )) {
		EntryInfo *eix = ei2->bei_lrunext;
		bdb_cache_entryinfo_free( &bdb->bi_cache, ei2 );
		ei2 = eix;
#ifdef BDB_HIER
		/* It got freed above because its value was
		 * assigned to ei2.
		 */
		ei->bei_rdn.bv_val = NULL;
#endif
	} else {
		int rc;

		bdb->bi_cache.c_eiused++;
		ber_dupbv( &ei2->bei_nrdn, &ei->bei_nrdn );

		/* This is a new leaf node. But if parent had no kids, then it was
		 * a leaf and we would be decrementing that. So, only increment if
		 * the parent already has kids.
		 */
		if ( ei->bei_parent->bei_kids || !ei->bei_parent->bei_id )
			bdb->bi_cache.c_leaves++;
		rc = avl_insert( &ei->bei_parent->bei_kids, ei2, bdb_rdn_cmp,
			avl_dup_error );
#ifdef BDB_HIER
		/* it's possible for hdb_cache_find_parent to beat us to it */
		if ( !rc ) {
			ei->bei_parent->bei_ckids++;
		}
#endif
	}

	*res = ei2;
	return 0;
}
Esempio n. 8
0
void
range_tree_add(void *arg, uint64_t start, uint64_t size)
{
	range_tree_t *rt = arg;
	avl_index_t where;
	range_seg_t rsearch, *rs_before, *rs_after, *rs;
	uint64_t end = start + size;
	boolean_t merge_before, merge_after;

	VERIFY(size != 0);

	rsearch.rs_start = start;
	rsearch.rs_end = end;
	rs = avl_find(&rt->rt_root, &rsearch, &where);

	if (rs != NULL && rs->rs_start <= start && rs->rs_end >= end) {
		zfs_panic_recover("zfs: allocating allocated segment"
		    "(offset=%llu size=%llu)\n",
		    (longlong_t)start, (longlong_t)size);
		return;
	}

	/* Make sure we don't overlap with either of our neighbors */
	VERIFY3P(rs, ==, NULL);

	rs_before = avl_nearest(&rt->rt_root, where, AVL_BEFORE);
	rs_after = avl_nearest(&rt->rt_root, where, AVL_AFTER);

	merge_before = (rs_before != NULL && rs_before->rs_end == start);
	merge_after = (rs_after != NULL && rs_after->rs_start == end);

	if (merge_before && merge_after) {
		avl_remove(&rt->rt_root, rs_before);
		if (rt->rt_ops != NULL) {
			rt->rt_ops->rtop_remove(rt, rs_before, rt->rt_arg);
			rt->rt_ops->rtop_remove(rt, rs_after, rt->rt_arg);
		}

		range_tree_stat_decr(rt, rs_before);
		range_tree_stat_decr(rt, rs_after);

		rs_after->rs_start = rs_before->rs_start;
		kmem_cache_free(range_seg_cache, rs_before);
		rs = rs_after;
	} else if (merge_before) {
		if (rt->rt_ops != NULL)
			rt->rt_ops->rtop_remove(rt, rs_before, rt->rt_arg);

		range_tree_stat_decr(rt, rs_before);

		rs_before->rs_end = end;
		rs = rs_before;
	} else if (merge_after) {
		if (rt->rt_ops != NULL)
			rt->rt_ops->rtop_remove(rt, rs_after, rt->rt_arg);

		range_tree_stat_decr(rt, rs_after);

		rs_after->rs_start = start;
		rs = rs_after;
	} else {
		rs = kmem_cache_alloc(range_seg_cache, KM_SLEEP);
		rs->rs_start = start;
		rs->rs_end = end;
		avl_insert(&rt->rt_root, rs, where);
	}

	if (rt->rt_ops != NULL)
		rt->rt_ops->rtop_add(rt, rs, rt->rt_arg);

	range_tree_stat_incr(rt, rs);
	rt->rt_space += size;
}
Esempio n. 9
0
/*
 * Inits a session
 */
struct rewrite_session *
rewrite_session_init(
		struct rewrite_info *info,
		const void *cookie
)
{
	struct rewrite_session 	*session, tmp;
	int			rc;

	assert( info != NULL );
	assert( cookie != NULL );

#ifdef USE_REWRITE_LDAP_PVT_THREADS
	ldap_pvt_thread_rdwr_wlock( &info->li_cookies_mutex );
#endif /* USE_REWRITE_LDAP_PVT_THREADS */

	tmp.ls_cookie = ( void * )cookie;
	session = ( struct rewrite_session * )avl_find( info->li_cookies, 
			( caddr_t )&tmp, rewrite_cookie_cmp );
	if ( session ) {
		session->ls_count++;
#ifdef USE_REWRITE_LDAP_PVT_THREADS
		ldap_pvt_thread_rdwr_wunlock( &info->li_cookies_mutex );
#endif /* USE_REWRITE_LDAP_PVT_THREADS */
		return session;
	}
		
	session = calloc( sizeof( struct rewrite_session ), 1 );
	if ( session == NULL ) {
		return NULL;
	}
	session->ls_cookie = ( void * )cookie;
	session->ls_count = 1;
	
#ifdef USE_REWRITE_LDAP_PVT_THREADS
	if ( ldap_pvt_thread_mutex_init( &session->ls_mutex ) ) {
		free( session );
		return NULL;
	}
	if ( ldap_pvt_thread_rdwr_init( &session->ls_vars_mutex ) ) {
		ldap_pvt_thread_mutex_destroy( &session->ls_mutex );
		free( session );
		return NULL;
	}
#endif /* USE_REWRITE_LDAP_PVT_THREADS */

	rc = avl_insert( &info->li_cookies, ( caddr_t )session,
			rewrite_cookie_cmp, rewrite_cookie_dup );
	info->li_num_cookies++;

#ifdef USE_REWRITE_LDAP_PVT_THREADS
        ldap_pvt_thread_rdwr_wunlock( &info->li_cookies_mutex );
#endif /* USE_REWRITE_LDAP_PVT_THREADS */
	
	if ( rc != 0 ) {
#ifdef USE_REWRITE_LDAP_PVT_THREADS
		ldap_pvt_thread_rdwr_destroy( &session->ls_vars_mutex );
		ldap_pvt_thread_mutex_destroy( &session->ls_mutex );
#endif /* USE_REWRITE_LDAP_PVT_THREADS */

		free( session );
		return NULL;
	}
	
	return session;
}
Esempio n. 10
0
static int ndb_tool_next_id(
	Operation *op,
	NdbArgs *NA,
	struct berval *text,
	int hole )
{
	struct berval ndn = NA->e->e_nname;
	int rc;

	if (ndn.bv_len == 0) {
		NA->e->e_id = 0;
		return 0;
	}

	rc = ndb_entry_get_info( op, NA, 0, NULL );
	if ( rc ) {
		Attribute *a, tmp = {0};
		if ( !be_issuffix( op->o_bd, &ndn ) ) {
			struct dn_id *dptr;
			struct berval npdn;
			dnParent( &ndn, &npdn );
			NA->e->e_nname = npdn;
			NA->rdns->nr_num--;
			rc = ndb_tool_next_id( op, NA, text, 1 );
			NA->e->e_nname = ndn;
			NA->rdns->nr_num++;
			if ( rc ) {
				return rc;
			}
			/* If parent didn't exist, it was created just now
			 * and its ID is now in e->e_id.
			 */
			dptr = (struct dn_id *)ch_malloc( sizeof( struct dn_id ) + npdn.bv_len + 1);
			dptr->id = NA->e->e_id;
			dptr->dn.bv_val = (char *)(dptr+1);
			strcpy(dptr->dn.bv_val, npdn.bv_val );
			dptr->dn.bv_len = npdn.bv_len;
			if ( avl_insert( &myParents, dptr, ndb_dnid_cmp, avl_dup_error )) {
				ch_free( dptr );
			}
		}
		rc = ndb_next_id( op->o_bd, myNdb, &NA->e->e_id );
		if ( rc ) {
			snprintf( text->bv_val, text->bv_len,
				"next_id failed: %s (%d)",
				myNdb->getNdbError().message, myNdb->getNdbError().code );
			Debug( LDAP_DEBUG_ANY,
				"=> ndb_tool_next_id: %s\n", text->bv_val );
			return rc;
		}
		if ( hole ) {
			a = NA->e->e_attrs;
			NA->e->e_attrs = &tmp;
			tmp.a_desc = slap_schema.si_ad_objectClass;
			tmp.a_vals = glueval;
			tmp.a_nvals = tmp.a_vals;
			tmp.a_numvals = 1;
		}
		rc = ndb_entry_put_info( op->o_bd, NA, 0 );
		if ( hole ) {
			NA->e->e_attrs = a;
		}
		if ( rc ) {
			snprintf( text->bv_val, text->bv_len,
				"ndb_entry_put_info failed: %s (%d)",
				myNdb->getNdbError().message, myNdb->getNdbError().code );
		Debug( LDAP_DEBUG_ANY,
			"=> ndb_tool_next_id: %s\n", text->bv_val );
		} else if ( hole ) {
			if ( nholes == nhmax - 1 ) {
				if ( holes == hbuf ) {
					holes = (dn_id *)ch_malloc( nhmax * sizeof(dn_id) * 2 );
					AC_MEMCPY( holes, hbuf, sizeof(hbuf) );
				} else {
					holes = (dn_id *)ch_realloc( holes, nhmax * sizeof(dn_id) * 2 );
				}
				nhmax *= 2;
			}
			ber_dupbv( &holes[nholes].dn, &ndn );
			holes[nholes++].id = NA->e->e_id;
		}
	} else if ( !hole ) {
		unsigned i;

		for ( i=0; i<nholes; i++) {
			if ( holes[i].id == NA->e->e_id ) {
				unsigned j;
				free(holes[i].dn.bv_val);
				for (j=i;j<nholes;j++) holes[j] = holes[j+1];
				holes[j].id = 0;
				nholes--;
				rc = ndb_entry_put_info( op->o_bd, NA, 1 );
				break;
			} else if ( holes[i].id > NA->e->e_id ) {
				break;
			}
		}
	}
	return rc;
}
Esempio n. 11
0
File: rrdns.c Progetto: jow-/luci-ng
static int
rrdns_next_query(struct rrdns_context *rctx)
{
    const char *addr = NULL, *hex = "0123456789abcdef";
    struct rrdns_request *req;
    int i, alen, family;
    char *p, dname[73];

    union {
        unsigned char uchar[4];
        struct in6_addr in6;
        struct in_addr in;
    } a = { };

    union {
        unsigned char buf[512];
        HEADER hdr;
    } msg;

    if (rctx->addr_rem > 0 &&
            blob_pad_len(rctx->addr_cur) <= rctx->addr_rem &&
            blob_pad_len(rctx->addr_cur) >= sizeof(struct blob_attr)) {

        addr = blobmsg_get_string(rctx->addr_cur);
        rctx->addr_rem -= blob_pad_len(rctx->addr_cur);
        rctx->addr_cur = blob_next(rctx->addr_cur);
    }

    if (!addr)
        return 0;

    if (inet_pton(AF_INET6, addr, &a.in6)) {
        memset(dname, 0, sizeof(dname));

        for (i = 0, p = dname; i < 16; i++) {
            *p++ = hex[a.in6.s6_addr[15-i] % 16];
            *p++ = '.';
            *p++ = hex[a.in6.s6_addr[15-i] / 16];
            *p++ = '.';
        }

        p += snprintf(p, p - dname - 1, "ip6.arpa");

        family = AF_INET6;
        alen = p - dname;
    }
    else if (inet_pton(AF_INET, addr, &a.in)) {
        family = AF_INET;
        alen = snprintf(dname, sizeof(dname), "%u.%u.%u.%u.in-addr.arpa",
                        a.uchar[3], a.uchar[2], a.uchar[1], a.uchar[0]);
    }
    else {
        return -EINVAL;
    }

    alen = res_mkquery(QUERY, dname, C_IN, T_PTR, NULL, 0, NULL,
                       msg.buf, sizeof(msg.buf));

    if (alen < 0)
        return alen;

    if (avl_find(&rctx->request_addrs, &a.in6))
        return -ENOTUNIQ;

    if (send(rctx->socket.fd, msg.buf, alen, 0) != alen)
        return -errno;

    req = calloc(1, sizeof(*req));

    if (!req)
        return -ENOMEM;

    req->id = msg.hdr.id;
    req->by_id.key = &req->id;
    avl_insert(&rctx->request_ids, &req->by_id);

    req->family = family;
    req->addr.in6 = a.in6;
    req->by_addr.key = &req->addr.in6;
    avl_insert(&rctx->request_addrs, &req->by_addr);

    return 0;
}
Esempio n. 12
0
/* find/create handle and return it with the structure in a locked state */
static fh_node *open_fh (fbinfo *finfo)
{
    fh_node *fh, *result;

    if (finfo->mount == NULL)
        finfo->mount = "";
    fh = calloc (1, sizeof (fh_node));
    memcpy (&fh->finfo, finfo, sizeof (fbinfo));
    if (avl_get_by_key (fh_cache, fh, (void**)&result) == 0)
    {
        free (fh);
        thread_mutex_lock (&result->lock);
        avl_tree_unlock (fh_cache);
        if (finfo->flags & FS_FALLBACK)
        {
            if (result->finfo.type != finfo->type && finfo->type != FORMAT_TYPE_UNDEFINED)
            {
                WARN1 ("format mismatched for %s", finfo->mount);
                thread_mutex_unlock (&result->lock);
                return NULL;
            }
            result->expire = (time_t)-1;
        }
        return result;
    }

    // insert new one
    if (fh->finfo.mount[0])
    {
        char *fullpath= util_get_path_from_normalised_uri (fh->finfo.mount, fh->finfo.flags&FS_USE_ADMIN);
        char *contenttype = fserve_content_type (fullpath);
        format_type_t type = format_get_type (contenttype);

        if (fh->finfo.type == FORMAT_TYPE_UNDEFINED)
            fh->finfo.type = type;
        if (finfo->flags & FS_FALLBACK)
        {
            if (fh->finfo.type != type && type != FORMAT_TYPE_UNDEFINED && fh->finfo.type != FORMAT_TYPE_UNDEFINED)
            {
                avl_tree_unlock (fh_cache);
                free (contenttype);
                free (fullpath);
                free (fh);
                WARN1 ("format mismatched for %s", finfo->mount);
                return NULL;
            }
            fh->expire = (time_t)-1;
            INFO2 ("lookup of fallback file \"%s\" (%d)", finfo->mount, finfo->limit);
        }
        else
            INFO1 ("lookup of \"%s\"", finfo->mount);
        if (file_open (&fh->f, fullpath) < 0)
        {
            INFO1 ("Failed to open \"%s\"", fullpath);
            avl_tree_unlock (fh_cache);
            free (contenttype);
            free (fullpath);
            free (fh);
            return NULL;
        }
        free (fullpath);
        fh->format = calloc (1, sizeof (format_plugin_t));
        fh->format->type = fh->finfo.type;
        fh->format->contenttype = strdup (contenttype);
        free (contenttype);
        if (fh->finfo.type != FORMAT_TYPE_UNDEFINED)
        {
            fh->format->mount = strdup (fh->finfo.mount);
            if (format_get_plugin (fh->format) < 0)
            {
                avl_tree_unlock (fh_cache);
                file_close (&fh->f);
                free (fh->format);
                free (fh);
                return NULL;
            }
        }
        if (fh->finfo.limit)
            fh->out_bitrate = rate_setup (10000, 1000);
    }
    fh->clients = avl_tree_new (client_compare, NULL);
    thread_mutex_create (&fh->lock);
    thread_mutex_lock (&fh->lock);
    avl_insert (fh_cache, fh);
    avl_tree_unlock (fh_cache);

    fh->refcount = 0;
    fh->peak = 0;
    fh->finfo.mount = strdup (finfo->mount);
    fh->finfo.fallback = NULL;

    return fh;
}
Esempio n. 13
0
void fserve_recheck_mime_types (ice_config_t *config)
{
    mime_type *mapping;
    int i;
    avl_tree *old_mimetypes = NULL, *new_mimetypes = avl_tree_new(_compare_mappings, NULL);

    mime_type defaults[] = {
        { "m3u",            "audio/x-mpegurl" },
        { "pls",            "audio/x-scpls" },
        { "xspf",           "application/xspf+xml" },
        { "ogg",            "application/ogg" },
        { "xml",            "text/xml" },
        { "mp3",            "audio/mpeg" },
        { "aac",            "audio/aac" },
        { "aacp",           "audio/aacp" },
        { "css",            "text/css" },
        { "txt",            "text/plain" },
        { "html",           "text/html" },
        { "jpg",            "image/jpg" },
        { "png",            "image/png" },
        { "gif",            "image/gif" },
        { NULL, NULL }
    };

    for (i=0; defaults[i].ext; i++)
    {
        mapping = malloc (sizeof(mime_type));
        mapping->ext = strdup (defaults [i].ext);
        mapping->type = strdup (defaults [i].type);
        if (avl_insert (new_mimetypes, mapping) != 0)
            _delete_mapping (mapping);
    }
    do
    {
        char *type, *ext, *cur;
        FILE *mimefile = NULL;
        char line[4096];

        if (config->mimetypes_fn == NULL)
        {
            INFO0 ("no mime types file defined, using defaults");
            break;
        }
        mimefile = fopen (config->mimetypes_fn, "r");
        if (mimefile == NULL)
        {
            WARN1 ("Cannot open mime types file %s, using defaults", config->mimetypes_fn);
            break;
        }
        while (fgets(line, sizeof line, mimefile))
        {
            line[4095] = 0;

            if(*line == 0 || *line == '#')
                continue;

            type = line;
            cur = line;

            while(*cur != ' ' && *cur != '\t' && *cur)
                cur++;
            if(*cur == 0)
                continue;

            *cur++ = 0;

            while(1)
            {
                while(*cur == ' ' || *cur == '\t')
                    cur++;
                if(*cur == 0)
                    break;

                ext = cur;
                while(*cur != ' ' && *cur != '\t' && *cur != '\n' && *cur)
                    cur++;
                *cur++ = 0;
                if(*ext)
                {
                    void *tmp;
                    /* Add a new extension->type mapping */
                    mapping = malloc(sizeof(mime_type));
                    mapping->ext = strdup(ext);
                    mapping->type = strdup(type);
                    if (!avl_get_by_key (new_mimetypes, mapping, &tmp))
                        avl_delete (new_mimetypes, mapping, _delete_mapping);
                    if (avl_insert (new_mimetypes, mapping) != 0)
                        _delete_mapping (mapping);
                }
            }
        }
        fclose(mimefile);
    } while (0);

    thread_spin_lock (&pending_lock);
    old_mimetypes = mimetypes;
    mimetypes = new_mimetypes;
    thread_spin_unlock (&pending_lock);
    if (old_mimetypes)
        avl_tree_free (old_mimetypes, _delete_mapping);
}
Esempio n. 14
0
File: spmatrix.c Progetto: FMX/gsl
int
gsl_spmatrix_realloc(const size_t nzmax, gsl_spmatrix *m)
{
  int s = GSL_SUCCESS;
  void *ptr;

  if (nzmax < m->nz)
    {
      GSL_ERROR("new nzmax is less than current nz", GSL_EINVAL);
    }

  ptr = realloc(m->i, nzmax * sizeof(size_t));
  if (!ptr)
    {
      GSL_ERROR("failed to allocate space for row indices", GSL_ENOMEM);
    }

  m->i = (size_t *) ptr;

  if (GSL_SPMATRIX_ISTRIPLET(m))
    {
      ptr = realloc(m->p, nzmax * sizeof(size_t));
      if (!ptr)
        {
          GSL_ERROR("failed to allocate space for column indices", GSL_ENOMEM);
        }

      m->p = (size_t *) ptr;
    }

  ptr = realloc(m->data, nzmax * sizeof(double));
  if (!ptr)
    {
      GSL_ERROR("failed to allocate space for data", GSL_ENOMEM);
    }

  m->data = (double *) ptr;

  /* rebuild binary tree */
  if (GSL_SPMATRIX_ISTRIPLET(m))
    {
      size_t n;

      /* reset tree to empty state, but don't free root tree ptr */
      avl_empty(m->tree_data->tree, NULL);
      m->tree_data->n = 0;

      ptr = realloc(m->tree_data->node_array, nzmax * sizeof(struct avl_node));
      if (!ptr)
        {
          GSL_ERROR("failed to allocate space for AVL tree nodes", GSL_ENOMEM);
        }

      m->tree_data->node_array = ptr;

      /*
       * need to reinsert all tree elements since the m->data addresses
       * have changed
       */
      for (n = 0; n < m->nz; ++n)
        {
          ptr = avl_insert(m->tree_data->tree, &m->data[n]);
          if (ptr != NULL)
            {
              GSL_ERROR("detected duplicate entry", GSL_EINVAL);
            }
        }
    }

  /* update to new nzmax */
  m->nzmax = nzmax;

  return s;
} /* gsl_spmatrix_realloc() */
Esempio n. 15
0
File: conf.c Progetto: 95ulisse/tinc
void config_add(avl_tree_t *config_tree, config_t *cfg) {
	avl_insert(config_tree, cfg);
}
Esempio n. 16
0
int
rwm_map_config(
		struct ldapmap	*oc_map,
		struct ldapmap	*at_map,
		const char	*fname,
		int		lineno,
		int		argc,
		char		**argv )
{
	struct ldapmap		*map;
	struct ldapmapping	*mapping;
	char			*src, *dst;
	int			is_oc = 0;
	int			rc = 0;

	if ( argc < 3 || argc > 4 ) {
		Debug( LDAP_DEBUG_ANY,
	"%s: line %d: syntax is \"map {objectclass | attribute} [<local> | *] {<foreign> | *}\"\n",
			fname, lineno, 0 );
		return 1;
	}

	if ( strcasecmp( argv[1], "objectclass" ) == 0 ) {
		map = oc_map;
		is_oc = 1;

	} else if ( strcasecmp( argv[1], "attribute" ) == 0 ) {
		map = at_map;

	} else {
		Debug( LDAP_DEBUG_ANY, "%s: line %d: syntax is "
			"\"map {objectclass | attribute} [<local> | *] "
			"{<foreign> | *}\"\n",
			fname, lineno, 0 );
		return 1;
	}

	if ( !is_oc && map->map == NULL ) {
		/* only init if required */
		if ( rwm_map_init( map, &mapping ) != LDAP_SUCCESS ) {
			return 1;
		}
	}

	if ( strcmp( argv[2], "*" ) == 0 ) {
		if ( argc < 4 || strcmp( argv[3], "*" ) == 0 ) {
			map->drop_missing = ( argc < 4 );
			goto success_return;
		}
		src = dst = argv[3];

	} else if ( argc < 4 ) {
		src = "";
		dst = argv[2];

	} else {
		src = argv[2];
		dst = ( strcmp( argv[3], "*" ) == 0 ? src : argv[3] );
	}

	if ( ( map == at_map )
			&& ( strcasecmp( src, "objectclass" ) == 0
			|| strcasecmp( dst, "objectclass" ) == 0 ) )
	{
		Debug( LDAP_DEBUG_ANY,
			"%s: line %d: objectclass attribute cannot be mapped\n",
			fname, lineno, 0 );
		return 1;
	}

	mapping = (struct ldapmapping *)ch_calloc( 2,
		sizeof(struct ldapmapping) );
	if ( mapping == NULL ) {
		Debug( LDAP_DEBUG_ANY,
			"%s: line %d: out of memory\n",
			fname, lineno, 0 );
		return 1;
	}
	ber_str2bv( src, 0, 1, &mapping[0].m_src );
	ber_str2bv( dst, 0, 1, &mapping[0].m_dst );
	mapping[1].m_src = mapping[0].m_dst;
	mapping[1].m_dst = mapping[0].m_src;

	mapping[0].m_flags = RWMMAP_F_NONE;
	mapping[1].m_flags = RWMMAP_F_NONE;

	/*
	 * schema check
	 */
	if ( is_oc ) {
		if ( src[0] != '\0' ) {
			mapping[0].m_src_oc = oc_bvfind( &mapping[0].m_src );
			if ( mapping[0].m_src_oc == NULL ) {
				Debug( LDAP_DEBUG_ANY,
	"%s: line %d: warning, source objectClass '%s' "
	"should be defined in schema\n",
					fname, lineno, src );

				/*
				 * FIXME: this should become an err
				 */
				mapping[0].m_src_oc = ch_malloc( sizeof( ObjectClass ) );
				memset( mapping[0].m_src_oc, 0, sizeof( ObjectClass ) );
				mapping[0].m_src_oc->soc_cname = mapping[0].m_src;
				mapping[0].m_flags |= RWMMAP_F_FREE_SRC;
			}
			mapping[1].m_dst_oc = mapping[0].m_src_oc;
		}

		mapping[0].m_dst_oc = oc_bvfind( &mapping[0].m_dst );
		if ( mapping[0].m_dst_oc == NULL ) {
			Debug( LDAP_DEBUG_ANY,
	"%s: line %d: warning, destination objectClass '%s' "
	"is not defined in schema\n",
				fname, lineno, dst );

			mapping[0].m_dst_oc = oc_bvfind_undef( &mapping[0].m_dst );
			if ( mapping[0].m_dst_oc == NULL ) {
				Debug( LDAP_DEBUG_ANY, "%s: line %d: unable to mimic destination objectClass '%s'\n",
					fname, lineno, dst );
				goto error_return;
			}
		}
		mapping[1].m_src_oc = mapping[0].m_dst_oc;

		mapping[0].m_flags |= RWMMAP_F_IS_OC;
		mapping[1].m_flags |= RWMMAP_F_IS_OC;

	} else {
		int			rc;
		const char		*text = NULL;

		if ( src[0] != '\0' ) {
			rc = slap_bv2ad( &mapping[0].m_src,
					&mapping[0].m_src_ad, &text );
			if ( rc != LDAP_SUCCESS ) {
				Debug( LDAP_DEBUG_ANY,
	"%s: line %d: warning, source attributeType '%s' "
	"should be defined in schema\n",
					fname, lineno, src );

				/*
				 * we create a fake "proxied" ad 
				 * and add it here.
				 */

				rc = slap_bv2undef_ad( &mapping[0].m_src,
						&mapping[0].m_src_ad, &text,
						SLAP_AD_PROXIED );
				if ( rc != LDAP_SUCCESS ) {
					char prefix[1024];
					snprintf( prefix, sizeof(prefix),
	"%s: line %d: source attributeType '%s': %d",
						fname, lineno, src, rc );
					Debug( LDAP_DEBUG_ANY, "%s (%s)\n",
						prefix, text ? text : "null", 0 );
					goto error_return;
				}

			}
			mapping[1].m_dst_ad = mapping[0].m_src_ad;
		}

		rc = slap_bv2ad( &mapping[0].m_dst, &mapping[0].m_dst_ad, &text );
		if ( rc != LDAP_SUCCESS ) {
			Debug( LDAP_DEBUG_ANY,
	"%s: line %d: warning, destination attributeType '%s' "
	"is not defined in schema\n",
				fname, lineno, dst );

			rc = slap_bv2undef_ad( &mapping[0].m_dst,
					&mapping[0].m_dst_ad, &text,
					SLAP_AD_PROXIED );
			if ( rc != LDAP_SUCCESS ) {
				char prefix[1024];
				snprintf( prefix, sizeof(prefix), 
	"%s: line %d: destination attributeType '%s': %d",
					fname, lineno, dst, rc );
				Debug( LDAP_DEBUG_ANY, "%s (%s)\n",
					prefix, text ? text : "null", 0 );
				goto error_return;
			}
		}
		mapping[1].m_src_ad = mapping[0].m_dst_ad;
	}

	if ( ( src[0] != '\0' && avl_find( map->map, (caddr_t)mapping, rwm_mapping_cmp ) != NULL)
			|| avl_find( map->remap, (caddr_t)&mapping[1], rwm_mapping_cmp ) != NULL)
	{
		Debug( LDAP_DEBUG_ANY,
			"%s: line %d: duplicate mapping found.\n",
			fname, lineno, 0 );
		/* FIXME: free stuff */
		goto error_return;
	}

	if ( src[0] != '\0' ) {
		avl_insert( &map->map, (caddr_t)&mapping[0],
					rwm_mapping_cmp, rwm_mapping_dup );
	}
	avl_insert( &map->remap, (caddr_t)&mapping[1],
				rwm_mapping_cmp, rwm_mapping_dup );

success_return:;
	return rc;

error_return:;
	if ( mapping ) {
		rwm_mapping_free( mapping );
	}

	return 1;
}
Esempio n. 17
0
static void
trim_map_segment_add(trim_map_t *tm, uint64_t start, uint64_t end, uint64_t txg)
{
	avl_index_t where;
	trim_seg_t tsearch, *ts_before, *ts_after, *ts;
	boolean_t merge_before, merge_after;
	hrtime_t time;

	ASSERT(MUTEX_HELD(&tm->tm_lock));
	VERIFY(start < end);

	time = gethrtime();
	tsearch.ts_start = start;
	tsearch.ts_end = end;

	ts = avl_find(&tm->tm_queued_frees, &tsearch, &where);
	if (ts != NULL) {
		if (start < ts->ts_start)
			trim_map_segment_add(tm, start, ts->ts_start, txg);
		if (end > ts->ts_end)
			trim_map_segment_add(tm, ts->ts_end, end, txg);
		return;
	}

	ts_before = avl_nearest(&tm->tm_queued_frees, where, AVL_BEFORE);
	ts_after = avl_nearest(&tm->tm_queued_frees, where, AVL_AFTER);

	merge_before = (ts_before != NULL && ts_before->ts_end == start);
	merge_after = (ts_after != NULL && ts_after->ts_start == end);

	if (merge_before && merge_after) {
		TRIM_MAP_SINC(tm, ts_after->ts_start - ts_before->ts_end);
		TRIM_MAP_QDEC(tm);
		avl_remove(&tm->tm_queued_frees, ts_before);
		list_remove(&tm->tm_head, ts_before);
		ts_after->ts_start = ts_before->ts_start;
		ts_after->ts_txg = txg;
		ts_after->ts_time = time;
		kmem_free(ts_before, sizeof (*ts_before));
	} else if (merge_before) {
		TRIM_MAP_SINC(tm, end - ts_before->ts_end);
		ts_before->ts_end = end;
		ts_before->ts_txg = txg;
		ts_before->ts_time = time;
	} else if (merge_after) {
		TRIM_MAP_SINC(tm, ts_after->ts_start - start);
		ts_after->ts_start = start;
		ts_after->ts_txg = txg;
		ts_after->ts_time = time;
	} else {
		TRIM_MAP_SINC(tm, end - start);
		TRIM_MAP_QINC(tm);
		ts = kmem_alloc(sizeof (*ts), KM_SLEEP);
		ts->ts_start = start;
		ts->ts_end = end;
		ts->ts_txg = txg;
		ts->ts_time = time;
		avl_insert(&tm->tm_queued_frees, ts, where);
		list_insert_tail(&tm->tm_head, ts);
	}
}
Esempio n. 18
0
/*
 * Finish the initialization of a new segment descriptor allocated by
 * ld_map_seg_alloc(), and enter it into the segment list.
 *
 * entry:
 *	mf - Mapfile descriptor
 *	seg_type - One of DBG_SEG_NEW or DBG_SEG_NEW_IMPLICIT
 *	ins_head - If true, the new segment goes at the front of
 *		others of its type. If false, it goes at the end.
 *	sgp - Segment descriptor to enter.
 *	where - Insertion point, initialized by a previous (failed) call to
 *		ld_seg_lookup(). Ignored if the segment has a NULL sg_name.
 *
 * exit:
 *	On success, returns SEG_INS_OK. A non-fatal error is indicated with
 *	a return value of SEG_INS_SKIP, in which case the descriptor is
 *	not entered, but the user is expected to discard it and continue
 *	running. On failure, returns SEG_INS_FAIL.
 *
 * note:
 *	This routine will modify the contents of the descriptor referenced
 *	by sgp_tmpl before allocating the new descriptor. The caller must
 *	not expect it to be unmodified.
 */
ld_map_seg_ins_t
ld_map_seg_insert(Mapfile *mf, dbg_state_t dbg_state, Sg_desc *sgp,
    avl_index_t where)
{
	Ofl_desc	*ofl = mf->mf_ofl;
	size_t		idx;
	Sg_desc		*sgp2;		/* temp segment descriptor pointer */
	int		ins_head;
	Elf64_Xword	sg_ndx;

	/*
	 * If specific fields have not been supplied via
	 * map_equal(), make sure defaults are supplied.
	 */
	if (((sgp->sg_flags & FLG_SG_P_TYPE) == 0) &&
	    (sgp->sg_phdr.p_type == PT_NULL)) {
		/*
		 * Default to a loadable segment.
		 */
		sgp->sg_phdr.p_type = PT_LOAD;
		sgp->sg_flags |= FLG_SG_P_TYPE;
	}
	if (sgp->sg_phdr.p_type == PT_LOAD) {
		if ((sgp->sg_flags & FLG_SG_P_FLAGS) == 0) {
			/*
			 * Default to read/write and execute.
			 */
			sgp->sg_phdr.p_flags = PF_R + PF_W + PF_X;
			sgp->sg_flags |= FLG_SG_P_FLAGS;
		}
		if ((sgp->sg_flags & FLG_SG_P_ALIGN) == 0) {
			/*
			 * Default to segment alignment
			 */
			sgp->sg_phdr.p_align = ld_targ.t_m.m_segm_align;
			sgp->sg_flags |= FLG_SG_P_ALIGN;
		}
	}

	/*
	 * Determine where the new item should be inserted in
	 * the segment descriptor list.
	 */
	switch (sgp->sg_phdr.p_type) {
	case PT_LOAD:
		if (sgp->sg_flags & FLG_SG_EMPTY)
			sgp->sg_id = SGID_TEXT_EMPTY;
		else
			sgp->sg_id = SGID_TEXT;
		break;
	case PT_NULL:
		if (sgp->sg_flags & FLG_SG_EMPTY)
			sgp->sg_id = SGID_NULL_EMPTY;
		else
			sgp->sg_id = SGID_NULL;
		break;
	case PT_NOTE:
		sgp->sg_id = SGID_NOTE;
		break;
	default:
		mf_fatal(mf, (MSG_MAP_UNKSEGTYP),
		    EC_WORD(sgp->sg_phdr.p_type));
		return (SEG_INS_FAIL);
	}

	/*
	 * Add the descriptor to the segment list. In the v1 syntax,
	 * new sections are added at the head of their type, while in
	 * the newer syntax, they go at the end of their type.
	 */
	sg_ndx = 0;
	ins_head = (mf->mf_version == MFV_SYSV);
	for (APLIST_TRAVERSE(ofl->ofl_segs, idx, sgp2)) {
		if (ins_head) {	/* Insert before the others of its type */
			if (sgp->sg_id > sgp2->sg_id) {
				sg_ndx++;
				continue;
			}
		} else {	/* Insert after the others of its type */
			if (sgp->sg_id >= sgp2->sg_id) {
				sg_ndx++;
				continue;
			}
		}
		break;
	}
	if (aplist_insert(&ofl->ofl_segs, sgp, AL_CNT_SEGMENTS, idx) == NULL)
		return (SEG_INS_FAIL);
	if (sgp->sg_name != NULL)
		avl_insert(&ofl->ofl_segs_avl, sgp, where);

	//DBG_CALL(Dbg_map_seg(ofl, dbg_state, sg_ndx, sgp, mf->mf_lineno));
	return (SEG_INS_OK);
}
Esempio n. 19
0
int bdb_tool_idl_add(
	BackendDB *be,
	DB *db,
	DB_TXN *txn,
	DBT *key,
	ID id )
{
	struct bdb_info *bdb = (struct bdb_info *) be->be_private;
	bdb_tool_idl_cache *ic, itmp;
	bdb_tool_idl_cache_entry *ice;
	int rc;

	if ( !bdb->bi_idl_cache_max_size )
		return bdb_idl_insert_key( be, db, txn, key, id );

	DBT2bv( key, &itmp.kstr );

	ic = avl_find( (Avlnode *)db->app_private, &itmp, bdb_tool_idl_cmp );

	/* No entry yet, create one */
	if ( !ic ) {
		DBC *curs;
		DBT data;
		ID nid;
		int rc;

		ic = ch_malloc( sizeof( bdb_tool_idl_cache ) + itmp.kstr.bv_len );
		ic->kstr.bv_len = itmp.kstr.bv_len;
		ic->kstr.bv_val = (char *)(ic+1);
		AC_MEMCPY( ic->kstr.bv_val, itmp.kstr.bv_val, ic->kstr.bv_len );
		ic->head = ic->tail = NULL;
		ic->last = 0;
		ic->count = 0;
		avl_insert( (Avlnode **)&db->app_private, ic, bdb_tool_idl_cmp,
			avl_dup_error );

		/* load existing key count here */
		rc = db->cursor( db, NULL, &curs, 0 );
		if ( rc ) return rc;

		data.ulen = sizeof( ID );
		data.flags = DB_DBT_USERMEM;
		data.data = &nid;
		rc = curs->c_get( curs, key, &data, DB_SET );
		if ( rc == 0 ) {
			if ( nid == 0 ) {
				ic->count = BDB_IDL_DB_SIZE+1;
			} else {
				db_recno_t count;

				curs->c_count( curs, &count, 0 );
				ic->count = count;
				BDB_DISK2ID( &nid, &ic->first );
			}
		}
		curs->c_close( curs );
	}
	/* are we a range already? */
	if ( ic->count > BDB_IDL_DB_SIZE ) {
		ic->last = id;
		return 0;
	/* Are we at the limit, and converting to a range? */
	} else if ( ic->count == BDB_IDL_DB_SIZE ) {
		int n;
		for ( ice = ic->head, n=0; ice; ice = ice->next, n++ )
			/* counting */ ;
		if ( n ) {
			ldap_pvt_thread_mutex_lock( &bdb->bi_idl_tree_lrulock );
			ic->tail->next = bdb_tool_idl_free_list;
			bdb_tool_idl_free_list = ic->head;
			bdb->bi_idl_cache_size -= n;
			ldap_pvt_thread_mutex_unlock( &bdb->bi_idl_tree_lrulock );
		}
		ic->head = ic->tail = NULL;
		ic->last = id;
		ic->count++;
		return 0;
	}
	/* No free block, create that too */
	if ( !ic->tail || ( ic->count & (IDBLOCK-1)) == 0) {
		ice = NULL;
		ldap_pvt_thread_mutex_lock( &bdb->bi_idl_tree_lrulock );
		if ( bdb->bi_idl_cache_size >= bdb->bi_idl_cache_max_size ) {
			ldap_pvt_thread_mutex_unlock( &bdb->bi_idl_tree_lrulock );
			rc = bdb_tool_idl_flush_db( db, ic );
			if ( rc )
				return rc;
			avl_insert( (Avlnode **)&db->app_private, ic, bdb_tool_idl_cmp,
				avl_dup_error );
			ldap_pvt_thread_mutex_lock( &bdb->bi_idl_tree_lrulock );
		}
		bdb->bi_idl_cache_size++;
		if ( bdb_tool_idl_free_list ) {
			ice = bdb_tool_idl_free_list;
			bdb_tool_idl_free_list = ice->next;
		}
		ldap_pvt_thread_mutex_unlock( &bdb->bi_idl_tree_lrulock );
		if ( !ice ) {
			ice = ch_malloc( sizeof( bdb_tool_idl_cache_entry ));
		}
		memset( ice, 0, sizeof( *ice ));
		if ( !ic->head ) {
			ic->head = ice;
		} else {
			ic->tail->next = ice;
		}
		ic->tail = ice;
		if ( !ic->count )
			ic->first = id;
	}
	ice = ic->tail;
	ice->ids[ ic->count & (IDBLOCK-1) ] = id;
	ic->count++;

	return 0;
}
Esempio n. 20
0
/* Insert element a into the AVL tree t
 * returns 1 if the depth of the tree has grown
 * Warning: do not insert elements already present
 */
int avl_insert(avl_tree* t,avl* a)
{
   /* initialize */
   a->left=0;
   a->right=0;
   a->balance=0;
   /* insert into an empty tree */
   if(!t->root){
      t->root=a;
      return 1;
   }
   
   if(t->compar(t->root,a)>0){
      /* insert into the left subtree */
      if(t->root->left){
	 avl_tree left_subtree;
	 left_subtree.root=t->root->left;
	 left_subtree.compar=t->compar;
	 if(avl_insert(&left_subtree,a)){
	    switch(t->root->balance--){
	     case 1: return 0;
	     case 0:	return 1;
	    }
	    if(t->root->left->balance<0){
	       avl_swr(&(t->root));
	       t->root->balance=0;
	       t->root->right->balance=0;
	    }else{
	       avl_swl(&(t->root->left));
	       avl_swr(&(t->root));
	       avl_nasty(t->root);
	    }
	 }else t->root->left=left_subtree.root;
	 return 0;
      }else{
	 t->root->left=a;
	 if(t->root->balance--) return 0;
	 return 1;
      }
   }else{
      /* insert into the right subtree */
      if(t->root->right){
	 avl_tree right_subtree;
	 right_subtree.root=t->root->right;
	 right_subtree.compar=t->compar;
	 if(avl_insert(&right_subtree,a)){
	    switch(t->root->balance++){
	     case -1: return 0;
	     case 0: return 1;
	    }
	    if(t->root->right->balance>0){
	       avl_swl(&(t->root));
	       t->root->balance=0;
	       t->root->left->balance=0;
	    }else{
	       avl_swr(&(t->root->right));
	       avl_swl(&(t->root));
	       avl_nasty(t->root);
	    }
	 }else t->root->right=right_subtree.root;
	 return 0;
      }else{
	 t->root->right=a;
	 if(t->root->balance++) return 0;
	 return 1;
      }
   }
}
Esempio n. 21
0
/* Walk up the tree from a child node, looking for an ID that's already
 * been linked into the cache.
 */
int
hdb_cache_find_parent(
	Operation *op,
	DB_TXN	*txn,
	ID id,
	EntryInfo **res )
{
	struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
	EntryInfo ei, eip, *ei2 = NULL, *ein = NULL, *eir = NULL;
	int rc, add;

	ei.bei_id = id;
	ei.bei_kids = NULL;
	ei.bei_ckids = 0;

	for (;;) {
		rc = hdb_dn2id_parent( op, txn, &ei, &eip.bei_id );
		if ( rc ) break;

		/* Save the previous node, if any */
		ei2 = ein;

		/* Create a new node for the current ID */
		ein = bdb_cache_entryinfo_new( &bdb->bi_cache );
		ein->bei_id = ei.bei_id;
		ein->bei_kids = ei.bei_kids;
		ein->bei_nrdn = ei.bei_nrdn;
		ein->bei_rdn = ei.bei_rdn;
		ein->bei_ckids = ei.bei_ckids;
#ifdef SLAP_ZONE_ALLOC
		ein->bei_bdb = bdb;
#endif
		ei.bei_ckids = 0;
		add = 1;
		
		/* This node is not fully connected yet */
		ein->bei_state |= CACHE_ENTRY_NOT_LINKED;

		/* If this is the first time, save this node
		 * to be returned later.
		 */
		if ( eir == NULL ) {
			eir = ein;
			ein->bei_finders++;
		}

again:
		/* Insert this node into the ID tree */
		ldap_pvt_thread_rdwr_wlock( &bdb->bi_cache.c_rwlock );
		if ( avl_insert( &bdb->bi_cache.c_idtree, (caddr_t)ein,
			bdb_id_cmp, bdb_id_dup_err ) ) {
			EntryInfo *eix = ein->bei_lrunext;

			if ( bdb_cache_entryinfo_trylock( eix )) {
				ldap_pvt_thread_rdwr_wunlock( &bdb->bi_cache.c_rwlock );
				ldap_pvt_thread_yield();
				goto again;
			}
			ldap_pvt_thread_rdwr_wunlock( &bdb->bi_cache.c_rwlock );

			/* Someone else created this node just before us.
			 * Free our new copy and use the existing one.
			 */
			bdb_cache_entryinfo_free( &bdb->bi_cache, ein );

			/* if it was the node we were looking for, just return it */
			if ( eir == ein ) {
				*res = eix;
				rc = 0;
				break;
			}

			ein = ei2;
			ei2 = eix;
			add = 0;

			/* otherwise, link up what we have and return */
			goto gotparent;
		}

		/* If there was a previous node, link it to this one */
		if ( ei2 ) ei2->bei_parent = ein;

		/* Look for this node's parent */
par2:
		if ( eip.bei_id ) {
			ei2 = (EntryInfo *) avl_find( bdb->bi_cache.c_idtree,
					(caddr_t) &eip, bdb_id_cmp );
		} else {
			ei2 = &bdb->bi_cache.c_dntree;
		}
		if ( ei2 && bdb_cache_entryinfo_trylock( ei2 )) {
			ldap_pvt_thread_rdwr_wunlock( &bdb->bi_cache.c_rwlock );
			ldap_pvt_thread_yield();
			ldap_pvt_thread_rdwr_wlock( &bdb->bi_cache.c_rwlock );
			goto par2;
		}
		if ( add )
			bdb->bi_cache.c_eiused++;
		if ( ei2 && ( ei2->bei_kids || !ei2->bei_id ))
			bdb->bi_cache.c_leaves++;
		ldap_pvt_thread_rdwr_wunlock( &bdb->bi_cache.c_rwlock );

gotparent:
		/* Got the parent, link in and we're done. */
		if ( ei2 ) {
			bdb_cache_entryinfo_lock( eir );
			ein->bei_parent = ei2;

			if ( avl_insert( &ei2->bei_kids, (caddr_t)ein, bdb_rdn_cmp,
				avl_dup_error) == 0 )
				ei2->bei_ckids++;

			/* Reset all the state info */
			for (ein = eir; ein != ei2; ein=ein->bei_parent)
				ein->bei_state &= ~CACHE_ENTRY_NOT_LINKED;

			bdb_cache_entryinfo_unlock( ei2 );
			eir->bei_finders--;

			*res = eir;
			break;
		}
		ei.bei_kids = NULL;
		ei.bei_id = eip.bei_id;
		ei.bei_ckids = 1;
		avl_insert( &ei.bei_kids, (caddr_t)ein, bdb_rdn_cmp,
			avl_dup_error );
	}
	return rc;
}
Esempio n. 22
0
/*
 * XL-COM Connection Listener
 */
void* thr_listener(void* arg) {
	int listen_fd, client_fd;
	struct sockaddr_in client_addr, server_addr;
	socklen_t client_sz = sizeof(client_addr);
	struct epoll_event epoll_ev;
	int result;
	int* key_tmp;
	client_info_t* info_tmp;

	// Open socket to listen for new clients
	if ((listen_fd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
		printf("[xlcom_server] [L] cannot open socket.\n");
		return NULL;
	}

	// Initialize server address structure
	memset((char *)&server_addr, 0, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = INADDR_ANY;
	server_addr.sin_port = htons(LISTEN_PORT);

	// Bind socket to listen port
	while(bind(listen_fd, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1) {
		printf("[xlcom_server] [L] cannot bind port %d. trying again in %d seconds.\n", LISTEN_PORT, BIND_RETRY_DELAY);
		sleep(BIND_RETRY_DELAY);
	}

	// Listen on that port
	listen(listen_fd, LISTEN_QUEUE);
	printf("[xlcom_server] [L] Listening on port %d. Max pending connections %d.\n", LISTEN_PORT, LISTEN_QUEUE);

	while(1) {

		// Wait for new connection
		if ((client_fd = accept(listen_fd, (struct sockaddr *) &client_addr, &client_sz)) < 0) {
			perror("[xlcom_server] [L] could not accept connection.\n");
			close(listen_fd);
			return NULL;
		}
		printf("[xlcom_server] [L] Received new connection from %s on fd %d.\n", inet_ntoa(client_addr.sin_addr), client_fd);

		// Add new connection to epoll
		epoll_ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
		epoll_ev.data.fd = client_fd;
		if ((result = epoll_ctl(Epoll_fd, EPOLL_CTL_ADD, client_fd, &epoll_ev)) != 0) {
			printf("[xlcom_server] [L] Error adding new connection to epoll queue.\n");
			close(listen_fd);
			return NULL;
		}

		// Insert new connection into Active_connections
		// Key = Client socket FD
		key_tmp = malloc(sizeof(int));
		*key_tmp = client_fd;
		// Info = client_info_t structure
		info_tmp = client_info_create();
		client_info_set_fd(info_tmp, client_fd);
		client_info_set_address(info_tmp, inet_ntoa(client_addr.sin_addr));
		client_info_set_username(info_tmp, "Anonymous");
		// Insert it on active connections database
		avl_insert(Active_connections, key_tmp, info_tmp);
	}

}
Esempio n. 23
0
static void *_stats_thread(void *arg)
{
    stats_event_t *event;
    stats_event_t *copy;
    stats_node_t *node;
    stats_node_t *anode;
    stats_source_t *snode;
    stats_source_t *asnode;
    event_listener_t *listener;
    avl_node *avlnode;

    while (_stats_running) {
        thread_mutex_lock(&_global_event_mutex);
        if (_global_event_queue != NULL) {
            /* grab the next event from the queue */
            event = _global_event_queue;
            _global_event_queue = event->next;
            event->next = NULL;
            thread_mutex_unlock(&_global_event_mutex);

            thread_mutex_lock(&_stats_mutex);
            if (event->source == NULL) {
                /* we have a global event */
                if (event->value != NULL) {
                    /* adding/updating */
                    node = _find_node(_stats.global_tree, event->name);
                    if (node == NULL) {
                        /* add node */
                        anode = (stats_node_t *)malloc(sizeof(stats_node_t));
                        anode->name = (char *)strdup(event->name);
                        anode->value = (char *)strdup(event->value);

                        avl_insert(_stats.global_tree, (void *)anode);
                    } else {
                        /* update node */
                        free(node->value);
                        node->value = (char *)strdup(event->value);
                    }

                } else {
                    /* we're deleting */
                    node = _find_node(_stats.global_tree, event->name);
                    if (node != NULL)
                        avl_delete(_stats.global_tree, (void *)node, _free_stats);
                }
            } else {
                /* we have a source event */

                snode = _find_source(_stats.source_tree, event->source);
                if (snode != NULL) {
                    /* this is a source we already have a tree for */
                    if (event->value != NULL) {
                        /* we're add/updating */
                        node = _find_node(snode->stats_tree, event->name);
                        if (node == NULL) {
                            /* adding node */
                            anode = (stats_node_t *)malloc(sizeof(stats_node_t));
                            anode->name = (char *)strdup(event->name);
                            anode->value = (char *)strdup(event->value);

                            avl_insert(snode->stats_tree, (void *)anode);
                        } else {
                            /* updating node */
                            free(node->value);
                            node->value = (char *)strdup(event->value);
                        }
                    } else {
                        /* we're deleting */
                        node = _find_node(snode->stats_tree, event->name);
                        if (node != NULL) {
                            avl_delete(snode->stats_tree, (void *)node, _free_stats);

                                avlnode = avl_get_first(snode->stats_tree);
                            if (avlnode == NULL) {
                                avl_delete(_stats.source_tree, (void *)snode, _free_source_stats);
                            }
                        }
                    }
                } else {
                    /* this is a new source */
                    asnode = (stats_source_t *)malloc(sizeof(stats_source_t));
                    asnode->source = (char *)strdup(event->source);
                    asnode->stats_tree = avl_tree_new(_compare_stats, NULL);

                    anode = (stats_node_t *)malloc(sizeof(stats_node_t));
                    anode->name = (char *)strdup(event->name);
                    anode->value = (char *)strdup(event->value);
                    
                    avl_insert(asnode->stats_tree, (void *)anode);

                    avl_insert(_stats.source_tree, (void *)asnode);
                }
            }
            
            /* now we have an event that's been processed into the running stats */
            /* this event should get copied to event listeners' queues */
            listener = _event_listeners;
            while (listener) {
                copy = _copy_event(event);
                thread_mutex_lock(listener->mutex);
                _add_event_to_queue(copy, listener->queue);
                thread_mutex_unlock(listener->mutex);

                listener = listener->next;
            }
            thread_cond_broadcast(&_event_signal_cond);

            /* now we need to destroy the event */
            _free_event(event);

            thread_mutex_unlock(&_stats_mutex);
            continue;
        } else {
            thread_mutex_unlock(&_global_event_mutex);
        }

        thread_sleep(300000);
    }

    /* wake the other threads so they can shut down cleanly */
    thread_cond_broadcast(&_event_signal_cond);

    thread_exit(0);

    return NULL;
}
Esempio n. 24
0
/* ARGSUSED */
static int
zfsctl_snapdir_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, pathname_t *pnp,
    int flags, vnode_t *rdir, cred_t *cr, caller_context_t *ct,
    int *direntflags, pathname_t *realpnp)
{
	zfsctl_snapdir_t *sdp = dvp->v_data;
	objset_t *snap;
	char snapname[MAXNAMELEN];
	char real[MAXNAMELEN];
	char *mountpoint;
	zfs_snapentry_t *sep, search;
	struct mounta margs;
	vfs_t *vfsp;
	size_t mountpoint_len;
	avl_index_t where;
	zfsvfs_t *zfsvfs = dvp->v_vfsp->vfs_data;
	int err;

	/*
	 * No extended attributes allowed under .zfs
	 */
	if (flags & LOOKUP_XATTR)
		return (EINVAL);

	ASSERT(dvp->v_type == VDIR);

	/*
	 * If we get a recursive call, that means we got called
	 * from the domount() code while it was trying to look up the
	 * spec (which looks like a local path for zfs).  We need to
	 * add some flag to domount() to tell it not to do this lookup.
	 */
	if (MUTEX_HELD(&sdp->sd_lock))
		return (ENOENT);

	ZFS_ENTER(zfsvfs);

	if (gfs_lookup_dot(vpp, dvp, zfsvfs->z_ctldir, nm) == 0) {
		ZFS_EXIT(zfsvfs);
		return (0);
	}

	if (flags & FIGNORECASE) {
		boolean_t conflict = B_FALSE;

		err = dmu_snapshot_realname(zfsvfs->z_os, nm, real,
		    MAXNAMELEN, &conflict);
		if (err == 0) {
			nm = real;
		} else if (err != ENOTSUP) {
			ZFS_EXIT(zfsvfs);
			return (err);
		}
		if (realpnp)
			(void) strlcpy(realpnp->pn_buf, nm,
			    realpnp->pn_bufsize);
		if (conflict && direntflags)
			*direntflags = ED_CASE_CONFLICT;
	}

	mutex_enter(&sdp->sd_lock);
	search.se_name = (char *)nm;
	if ((sep = avl_find(&sdp->sd_snaps, &search, &where)) != NULL) {
		*vpp = sep->se_root;
		if (VN_HOLD(*vpp) == NULL) {
			*vpp = NULL;
			err = EAGAIN;
		} else {
			err = traverse(vpp);
			if (err) {
				VN_RELE(*vpp);
				*vpp = NULL;
			} else if (*vpp == sep->se_root) {
				/*
				 * The snapshot was unmounted behind our backs,
				 * try to remount it.
				 */
				goto domount;
			} else {
				/*
				 * VROOT was set during the traverse call.  We need
				 * to clear it since we're pretending to be part
				 * of our parent's vfs.
				 */
				(*vpp)->v_flag &= ~VROOT;
			}
		}
		mutex_exit(&sdp->sd_lock);
		ZFS_EXIT(zfsvfs);
		return (err);
	}

	/*
	 * The requested snapshot is not currently mounted, look it up.
	 */
	err = zfsctl_snapshot_zname(dvp, nm, MAXNAMELEN, snapname);
	if (err) {
		mutex_exit(&sdp->sd_lock);
		ZFS_EXIT(zfsvfs);
		/*
		 * handle "ls *" or "?" in a graceful manner,
		 * forcing EILSEQ to ENOENT.
		 * Since shell ultimately passes "*" or "?" as name to lookup
		 */
		return (err == EILSEQ ? ENOENT : err);
	}
	if (dmu_objset_hold(snapname, FTAG, &snap) != 0) {
		mutex_exit(&sdp->sd_lock);
		ZFS_EXIT(zfsvfs);
		return (ENOENT);
	}

	sep = kmem_alloc(sizeof (zfs_snapentry_t), KM_SLEEP);
	sep->se_name = kmem_alloc(strlen(nm) + 1, KM_SLEEP);
	(void) strcpy(sep->se_name, nm);
	*vpp = sep->se_root = zfsctl_snapshot_mknode(dvp, dmu_objset_id(snap));
	avl_insert(&sdp->sd_snaps, sep, where);

	dmu_objset_rele(snap, FTAG);
domount:
	mountpoint_len = strlen(refstr_value(dvp->v_vfsp->vfs_mntpt)) +
	    strlen("/.zfs/snapshot/") + strlen(nm) + 1;
	mountpoint = kmem_alloc(mountpoint_len, KM_SLEEP);
	(void) snprintf(mountpoint, mountpoint_len, "%s/.zfs/snapshot/%s",
	    refstr_value(dvp->v_vfsp->vfs_mntpt), nm);

	margs.spec = snapname;
	margs.dir = mountpoint;
	margs.flags = MS_SYSSPACE | MS_NOMNTTAB;
	margs.fstype = "zfs";
	margs.dataptr = NULL;
	margs.datalen = 0;
	margs.optptr = NULL;
	margs.optlen = 0;

	err = domount("zfs", &margs, *vpp, kcred, &vfsp);
	kmem_free(mountpoint, mountpoint_len);

	if (err == 0) {
		/*
		 * Return the mounted root rather than the covered mount point.
		 * Takes the GFS vnode at .zfs/snapshot/<snapname> and returns
		 * the ZFS vnode mounted on top of the GFS node.  This ZFS
		 * vnode is the root of the newly created vfsp.
		 */
		VFS_RELE(vfsp);
		err = traverse(vpp);
	}

	if (err == 0) {
		/*
		 * Fix up the root vnode mounted on .zfs/snapshot/<snapname>.
		 *
		 * This is where we lie about our v_vfsp in order to
		 * make .zfs/snapshot/<snapname> accessible over NFS
		 * without requiring manual mounts of <snapname>.
		 */
		ASSERT(VTOZ(*vpp)->z_zfsvfs != zfsvfs);
		VTOZ(*vpp)->z_zfsvfs->z_parent = zfsvfs;
		(*vpp)->v_vfsp = zfsvfs->z_vfs;
		(*vpp)->v_flag &= ~VROOT;
	}
	mutex_exit(&sdp->sd_lock);
	ZFS_EXIT(zfsvfs);

	/*
	 * If we had an error, drop our hold on the vnode and
	 * zfsctl_snapshot_inactive() will clean up.
	 */
	if (err) {
		VN_RELE(*vpp);
		*vpp = NULL;
	}
	return (err);
}
Esempio n. 25
0
void fserve_recheck_mime_types(ice_config_t *config)
{
    FILE *mimefile;
    char line[4096];
    char *type, *ext, *cur;
    mime_type *mapping;
    avl_tree *new_mimetypes;

    if (config->mimetypes_fn == NULL)
        return;
    mimefile = fopen (config->mimetypes_fn, "r");
    if (mimefile == NULL)
    {
        ICECAST_LOG_WARN("Cannot open mime types file %s", config->mimetypes_fn);
        return;
    }

    new_mimetypes = avl_tree_new(_compare_mappings, NULL);

    while(fgets(line, 4096, mimefile))
    {
        line[4095] = 0;

        if(*line == 0 || *line == '#')
            continue;

        type = line;

        cur = line;

        while(*cur != ' ' && *cur != '\t' && *cur)
            cur++;
        if(*cur == 0)
            continue;

        *cur++ = 0;

        while(1) {
            while(*cur == ' ' || *cur == '\t')
                cur++;
            if(*cur == 0)
                break;

            ext = cur;
            while(*cur != ' ' && *cur != '\t' && *cur != '\n' && *cur)
                cur++;
            *cur++ = 0;
            if(*ext)
            {
                void *tmp;
                /* Add a new extension->type mapping */
                mapping = malloc(sizeof(mime_type));
                mapping->ext = strdup(ext);
                mapping->type = strdup(type);
                if (!avl_get_by_key (new_mimetypes, mapping, &tmp))
                    avl_delete (new_mimetypes, mapping, _delete_mapping);
                avl_insert (new_mimetypes, mapping);
            }
        }
    }
    fclose(mimefile);

    thread_spin_lock (&pending_lock);
    if (mimetypes)
        avl_tree_free (mimetypes, _delete_mapping);
    mimetypes = new_mimetypes;
    thread_spin_unlock (&pending_lock);
}
Esempio n. 26
0
/* Read table definitions from the DB and populate ObjectClassInfo */
extern "C" int
ndb_oc_read( struct ndb_info *ni, const NdbDictionary::Dictionary *myDict )
{
	const NdbDictionary::Table *myTable;
	const NdbDictionary::Column *myCol;
	NdbOcInfo *oci, octmp;
	NdbAttrInfo *ai;
	ObjectClass *oc;
	NdbDictionary::Dictionary::List myList;
	struct berval bv;
	int i, j, rc, col;

	rc = myDict->listObjects( myList, NdbDictionary::Object::UserTable );
	/* Populate our objectClass structures */
	for ( i=0; i<myList.count; i++ ) {
		/* Ignore other DBs */
		if ( strcmp( myList.elements[i].database, ni->ni_dbname ))
			continue;
		/* Ignore internal tables */
		if ( !strncmp( myList.elements[i].name, "OL_", 3 ))
			continue;
		ber_str2bv( myList.elements[i].name, 0, 0, &octmp.no_name );
		oci = (NdbOcInfo *)avl_find( ni->ni_oc_tree, &octmp, ndb_name_cmp );
		if ( oci )
			continue;

		oc = oc_bvfind( &octmp.no_name );
		if ( !oc ) {
			/* undefined - shouldn't happen */
			continue;
		}
		myTable = myDict->getTable( myList.elements[i].name );
		oci = (NdbOcInfo *)ch_malloc( sizeof( NdbOcInfo )+oc->soc_cname.bv_len+1 );
		oci->no_table.bv_val = (char *)(oci+1);
		strcpy( oci->no_table.bv_val, oc->soc_cname.bv_val );
		oci->no_table.bv_len = oc->soc_cname.bv_len;
		oci->no_name = oci->no_table;
		oci->no_oc = oc;
		oci->no_flag = 0;
		oci->no_nsets = 0;
		oci->no_nattrs = 0;
		col = 0;
		/* Make space for all attrs, even tho sups will be dropped */
		if ( oci->no_oc->soc_required ) {
			for ( j=0; oci->no_oc->soc_required[j]; j++ );
			col = j;
		}
		if ( oci->no_oc->soc_allowed ) {
			for ( j=0; oci->no_oc->soc_allowed[j]; j++ );
			col += j;
		}
		oci->no_attrs = (struct ndb_attrinfo **)ch_malloc( col * sizeof(struct ndb_attrinfo *));
		avl_insert( &ni->ni_oc_tree, oci, ndb_name_cmp, avl_dup_error );

		col = myTable->getNoOfColumns();
		/* Skip 0 and 1, eid and vid */
		for ( j = 2; j<col; j++ ) {
			myCol = myTable->getColumn( j );
			ber_str2bv( myCol->getName(), 0, 0, &bv );
			ai = ndb_ai_get( ni, &bv );
			/* shouldn't happen */
			if ( !ai )
				continue;
			ai->na_oi = oci;
			ai->na_column = j;
			ai->na_len = myCol->getLength();
			if ( myCol->getType() == NdbDictionary::Column::Blob )
				ai->na_flag |= NDB_INFO_ATBLOB;
		}
	}
	/* Link to any attrsets */
	for ( i=0; i<myList.count; i++ ) {
		/* Ignore other DBs */
		if ( strcmp( myList.elements[i].database, ni->ni_dbname ))
			continue;
		/* Ignore internal tables */
		if ( !strncmp( myList.elements[i].name, "OL_", 3 ))
			continue;
		ber_str2bv( myList.elements[i].name, 0, 0, &octmp.no_name );
		oci = (NdbOcInfo *)avl_find( ni->ni_oc_tree, &octmp, ndb_name_cmp );
		/* shouldn't happen */
		if ( !oci )
			continue;
		col = 2;
		if ( oci->no_oc->soc_required ) {
			rc = ndb_ai_check( ni, oci, oci->no_oc->soc_required, NULL, &col, 0 );
		}
		if ( oci->no_oc->soc_allowed ) {
			rc = ndb_ai_check( ni, oci, oci->no_oc->soc_allowed, NULL, &col, 0 );
		}
		/* shrink down to just the needed size */
		oci->no_attrs = (struct ndb_attrinfo **)ch_realloc( oci->no_attrs,
			oci->no_nattrs * sizeof(struct ndb_attrinfo *));
	}
	return 0;
}
Esempio n. 27
0
int
imap_driver_init(struct module *module, struct event_base *base)
{
    struct imap_driver *driver = module->priv;
    struct imap_config *config;
    struct imap_handler *handler = handlers;
    struct module *ldap;
    struct sockaddr_in6 sin;
    int socklen = sizeof(sin);

    assert(driver && driver->config && base);
    config = driver->config;

    driver->base = base;
    driver->dnsbase = get_dnsbase();

    if (config->cert) {
        driver->ssl_ctx = new_ssl_ctx(config->cert, config->pkey);
        if (driver->ssl_ctx == NULL) {
            return 1;
        }
    } else {
        /* skip the STARTTLS handler */
        handler += 1;
    }

    for (; handler->command; handler++) {
        /* handle the private handler storage */
        if (avl_insert(&driver->commands, handler, imap_handler_cmp, avl_dup_error)) {
            return 1;
        }
    }

    if (evutil_parse_sockaddr_port(config->listen, (struct sockaddr *)&sin, &socklen)) {
        return 1;
    }

    /* we start in disabled state until the LDAP interface is ready */
    driver->listener = evconnlistener_new_bind(base, listen_cb, (void*)driver,
            LEV_OPT_REUSEABLE|LEV_OPT_DISABLED|LEV_OPT_CLOSE_ON_FREE,
            -1, (struct sockaddr *)&sin, socklen);
    /* could also be wise to set an error callback, but what errors do we face
     * on accept()? */

    if (!driver->listener) {
        skeeter_log(LOG_CRIT, "Could not create a listener!");
        return 1;
    }

    ldap = get_module("ldap");
    if (!ldap || !ldap->register_event) {
        skeeter_log(LOG_CRIT, "LDAP module not available!");
        return 1;
    }

    if (ldap->register_event(ldap, MODULE_ANY | MODULE_PERSIST, trigger_listener, driver->listener)) {
        skeeter_log(LOG_CRIT, "Regitration with LDAP module failed!");
        return 1;
    }

    driver->ldap = ldap;

    return 0;
}
Esempio n. 28
0
static int
ndb_oc_list( struct ndb_info *ni, const NdbDictionary::Dictionary *myDict,
	struct berval *oname, int implied, NdbOcs *out )
{
	const NdbDictionary::Table *myTable;
	NdbOcInfo *oci, octmp;
	ObjectClass *oc;
	int i, rc;

	/* shortcut top */
	if ( ber_bvstrcasecmp( oname, &slap_schema.si_oc_top->soc_cname )) {
		octmp.no_name = *oname;
		oci = (NdbOcInfo *)avl_find( ni->ni_oc_tree, &octmp, ndb_name_cmp );
		if ( oci ) {
			oc = oci->no_oc;
		} else {
			oc = oc_bvfind( oname );
			if ( !oc ) {
				/* undefined - shouldn't happen */
				return LDAP_INVALID_SYNTAX;
			}
		}
		if ( oc->soc_sups ) {
			int i;

			for ( i=0; oc->soc_sups[i]; i++ ) {
				rc = ndb_oc_list( ni, myDict, &oc->soc_sups[i]->soc_cname, 1, out );
				if ( rc ) return rc;
			}
		}
	} else {
		oc = slap_schema.si_oc_top;
	}
	/* Only insert once */
	for ( i=0; i<out->no_ntext; i++ )
		if ( out->no_text[i].bv_val == oc->soc_cname.bv_val )
			break;
	if ( i == out->no_ntext ) {
		for ( i=0; i<out->no_nitext; i++ )
			if ( out->no_itext[i].bv_val == oc->soc_cname.bv_val )
				break;
		if ( i == out->no_nitext ) {
			if ( implied )
				out->no_itext[out->no_nitext++] = oc->soc_cname;
			else
				out->no_text[out->no_ntext++] = oc->soc_cname;
		}
	}

	/* ignore top, etc... */
	if ( oc->soc_kind == LDAP_SCHEMA_ABSTRACT )
		return 0;

	if ( !oci ) {
		ldap_pvt_thread_rdwr_runlock( &ni->ni_oc_rwlock );
		oci = (NdbOcInfo *)ch_malloc( sizeof( NdbOcInfo )+oc->soc_cname.bv_len+1 );
		oci->no_table.bv_val = (char *)(oci+1);
		strcpy( oci->no_table.bv_val, oc->soc_cname.bv_val );
		oci->no_table.bv_len = oc->soc_cname.bv_len;
		oci->no_name = oci->no_table;
		oci->no_oc = oc;
		oci->no_flag = 0;
		oci->no_nsets = 0;
		oci->no_nattrs = 0;
		ldap_pvt_thread_rdwr_wlock( &ni->ni_oc_rwlock );
		if ( avl_insert( &ni->ni_oc_tree, oci, ndb_name_cmp, ndb_oc_dup_err )) {
			octmp.no_oc = oci->no_oc;
			ch_free( oci );
			oci = (NdbOcInfo *)octmp.no_oc;
		}
		/* see if the oc table already exists in the DB */
		myTable = myDict->getTable( oci->no_table.bv_val );
		rc = ndb_oc_create( ni, oci, myTable == NULL );
		ldap_pvt_thread_rdwr_wunlock( &ni->ni_oc_rwlock );
		ldap_pvt_thread_rdwr_rlock( &ni->ni_oc_rwlock );
		if ( rc ) return rc;
	}
	/* Only insert once */
	for ( i=0; i<out->no_ninfo; i++ )
		if ( out->no_info[i] == oci )
			break;
	if ( i == out->no_ninfo )
		out->no_info[out->no_ninfo++] = oci;
	return 0;
}
Esempio n. 29
0
void * load_rules(void * raw)
{
		unsigned int * tid = raw;
    int rulefd;
    char rulestr[LINELEN];
    uint64_t curval;
    uint64_t nbpwds;
    uint64_t i;
    struct s_rule_link * link;
    unsigned int nbloaded;

    unsigned int jobid;
    uint64_t pwtested;

    while(1)
    {
        /* select jobid */
        pthread_mutex_lock( &rj_mutex );
        for(jobid=0;jobid<nbfiles;jobid++)
            if( rulejob[jobid].done_by == -1 )
                break;
        if(jobid>=nbfiles)
        {
            pthread_mutex_unlock( &rj_mutex );
            break;
        }
        rulejob[jobid].done_by = *tid;
        pthread_mutex_unlock( &rj_mutex );

        rulefd = open(rulejob[jobid].filename, O_RDONLY);
        if(rulefd <0)
        {
            perror(rulejob[jobid].filename);
            continue;
        }


        nbloaded = 0;
        while(1)
        {
						curval = 0;
						pwtested = 0;
						nbpwds = 0;
            if(read(rulefd, &curval, sizeof(unsigned int)) != sizeof(unsigned int))
                break;
            if(curval>=(LINELEN-1))
            {
                fprintf(stderr, "rule length too large : %ld>=%d\n", curval, LINELEN-1);
                break;
            }
            if(read(rulefd, rulestr, curval) != curval)
            {
                fprintf(stderr, "could not read rule string of len %ld", curval);
                break;
            }
            rulestr[curval]=0;
            if(read(rulefd, &pwtested, sizeof(unsigned long)) != sizeof(unsigned long))
            {
                fprintf(stderr, "could not read nb pwd tested\n");
                break;
            }
            if(read(rulefd, &nbpwds, sizeof(unsigned int)) != sizeof(unsigned int))
            {
                fprintf(stderr, "could not read nbpwd\n");
                break;
            }
            if(nbpwds >= matchlimit)
            {
                nbloaded++;
                link = newlink(rulestr, pwtested);
                for(i=0;i<nbpwds;i++)
                {
										curval = 0;
                    if( read(rulefd, &curval, sizeof(unsigned int)) != sizeof(unsigned int) )
                    {
                        fprintf(stderr, "could not read password %ld/%ld\n", i, nbpwds);
                        break;
                    }
                    if(avl_insert(link->coverage, (void *) curval) == NULL)
                    {
                        if(errno == EEXIST)
                            continue;
                        perror("avl_insert");
                        exit(1);
                    }
                }
                link->next = rulejob[jobid].root;
                if(rulejob[jobid].tail == NULL)
                    rulejob[jobid].tail = link;
                rulejob[jobid].root = link;
            }
            else
            {
                lseek(rulefd, sizeof(unsigned int)*nbpwds, SEEK_CUR);
            }
        }

        close(rulefd);

        fprintf(stderr, "%s loaded [%d]\n", rulejob[jobid].filename, nbloaded);

    }
    fprintf(stderr, "[%d] EXITS\n", *tid);
    return NULL;
}
Esempio n. 30
0
void process_event_message(char* method, struct htsp_message_t* msg)
{
  struct event_t* event;
  uint32_t eventId;
  int do_insert = 0;

  htsp_get_uint(msg,"eventId",&eventId);

  pthread_mutex_lock(&events_mutex);
  event = event_get_nolock(eventId, msg->server);

#ifdef DEBUG_EVENTS
  if (strcmp(method,"eventUpdate")==0) {
    fprintf(stderr,"eventUpdate - %d\n",eventId);
  } else {
    fprintf(stderr,"eventAdd - %d\n",eventId);
  }
#endif

  if (event == NULL) {
    do_insert = 1;
    event = calloc(sizeof(struct event_t),1);
    event->eventId = eventId;
    if (strcmp(method,"eventUpdate")==0) {
      fprintf(stderr,"WARNING: eventUpdate received for non-existent event %d, adding instead.\n",eventId);
    }
  } else {
    event_free_items(event);
    memset(event,0,sizeof(event));
    if (strcmp(method,"eventAdd")==0) {
      fprintf(stderr,"WARNING: eventAdd received for existing event %d, updating instead.\n",eventId);
    }
  }

  htsp_get_uint(msg,"eventId",&event->eventId);
  htsp_get_uint(msg,"channelId",&event->channelId);
  htsp_get_int64(msg,"start",&event->start);
  htsp_get_int64(msg,"stop",&event->stop);
  event->title = htsp_get_string(msg,"title");
  event->description = htsp_get_string(msg,"description");
  htsp_get_uint(msg,"serieslinkId",&event->serieslinkId);
  event->serieslinkUri = htsp_get_string(msg,"serieslinkUri");
  htsp_get_uint(msg,"episodeId",&event->episodeId);
  htsp_get_uint(msg,"episodeNumber",&event->episodeNumber);
  htsp_get_uint(msg,"seasonNumber",&event->seasonNumber);
  event->episodeUri = htsp_get_string(msg,"episodeUri");
  htsp_get_uint(msg,"nextEventId",&event->nextEventId);

  //htsp_dump_message(msg);

  eventId = eventId * MAX_HTSP_SERVERS + msg->server;

  if (do_insert) {
#ifdef USE_AVL
    avl_insert(&events,(struct avl*)event);
#else
    if (eventId < MAX_EVENT_ID)
      events[eventId] = event;
#endif

#ifdef DEBUG_EVENTS
    struct event_t* event2 = event_get_nolock(eventId);
    if (event2 == NULL) {
      fprintf(stderr,"ERROR: Inserted event %d but could not retrieve it.\n",eventId);
    }
#endif
  }
  pthread_mutex_unlock(&events_mutex);
}