Exemple #1
0
void dbg_lua_handle_command(struct dbg_state* state, void* ud, freed_bstring name, list_t* parameters)
{
    struct lua_debugst* ds;
    struct customarg_entry* carg;
    char* cstr;
    unsigned int i, k;
    int paramtbl;

    // Convert the name to lowercase.
    btolower(name.ref);
    cstr = bstr2cstr(name.ref, '0');

    // Loop through all of the modules.
    for (k = 0; k < list_size(&modules); k++)
    {
        ds = list_get_at(&modules, k);

        // Set stack top (I don't know why the top of the
        // stack is negative!)
        lua_settop(ds->state, 0);

        // Search handler table for entries.
        lua_getglobal(ds->state, HANDLER_TABLE_COMMANDS_NAME);
        lua_getfield(ds->state, -1, cstr);
        if (!lua_istable(ds->state, -1))
        {
            // No such entry.
            lua_pop(ds->state, 2);
            continue;
        }

        // Call the handler function.
        lua_getfield(ds->state, -1, HANDLER_FIELD_FUNCTION_NAME);
        dbg_lua_push_state(ds, state, ud);
        lua_newtable(ds->state);
        paramtbl = lua_gettop(ds->state);
        for (i = 0; i < list_size(parameters); i++)
        {
            carg = list_get_at(parameters, i);

            lua_newtable(ds->state);
            if (carg->type == DBG_CUSTOMARG_TYPE_PATH)
                lua_pushstring(ds->state, "PATH");
            else if (carg->type == DBG_CUSTOMARG_TYPE_PARAM)
                lua_pushstring(ds->state, "PARAM");
            else if (carg->type == DBG_CUSTOMARG_TYPE_STRING)
                lua_pushstring(ds->state, "STRING");
            else
                lua_pushstring(ds->state, "NUMBER");
            lua_setfield(ds->state, -2, "type");
            if (carg->type == DBG_CUSTOMARG_TYPE_PATH)
                lua_pushstring(ds->state, carg->path->data);
            else if (carg->type == DBG_CUSTOMARG_TYPE_PARAM)
                lua_pushstring(ds->state, carg->param->data);
            else if (carg->type == DBG_CUSTOMARG_TYPE_STRING)
                lua_pushstring(ds->state, carg->string->data);
            else
                lua_pushnumber(ds->state, carg->number);
            lua_setfield(ds->state, -2, "value");
            lua_rawseti(ds->state, paramtbl, i + 1);
        }
        if (lua_pcall(ds->state, 2, 0, 0) != 0)
        {
            printd(LEVEL_ERROR, "error: unable to call debugger command handler for '%s'.\n", name.ref->data);
            printd(LEVEL_ERROR, "%s\n", lua_tostring(ds->state, -1));
            bautodestroy(name);
            bcstrfree(cstr);
            lua_pop(ds->state, 2);
            list_iterator_stop(&modules);
            list_destroy(parameters);
            return;
        }

        bautodestroy(name);
        bcstrfree(cstr);
        lua_pop(ds->state, 2);
        list_iterator_stop(&modules);
        list_destroy(parameters);

        // The command may have started the virtual machine, check the
        // status of the VM and execute if needed.
        if (state->get_vm()->halted == false)
            vm_execute(state->get_vm(), NULL);

        return;
    }

    // There is no command to handle this.
    printd(LEVEL_ERROR, "no such command found.\n");

    // Clean up.
    list_destroy(parameters);
    bautodestroy(name);
    bcstrfree(cstr);
}
CK_RV C_Initialize(CK_VOID_PTR pInitArgs)
{
	CK_RV rv;
#if !defined(_WIN32)
	pid_t current_pid = getpid();
#endif
	int rc;
	unsigned int i;
	sc_context_param_t ctx_opts;

	/* Handle fork() exception */
#if !defined(_WIN32)
	if (current_pid != initialized_pid) {
		C_Finalize(NULL_PTR);
	}
	initialized_pid = current_pid;
	in_finalize = 0;
#endif

	if (context != NULL) {
		sc_debug(context, SC_LOG_DEBUG_NORMAL, "C_Initialize(): Cryptoki already initialized\n");
		return CKR_CRYPTOKI_ALREADY_INITIALIZED;
	}

	rv = sc_pkcs11_init_lock((CK_C_INITIALIZE_ARGS_PTR) pInitArgs);
	if (rv != CKR_OK)
		goto out;

	/* set context options */
	memset(&ctx_opts, 0, sizeof(sc_context_param_t));
	ctx_opts.ver        = 0;
	ctx_opts.app_name   = "opensc-pkcs11";
	ctx_opts.thread_ctx = &sc_thread_ctx;
	
	rc = sc_context_create(&context, &ctx_opts);
	if (rc != SC_SUCCESS) {
		rv = CKR_GENERAL_ERROR;
		goto out;
	}

	/* Load configuration */
	load_pkcs11_parameters(&sc_pkcs11_conf, context);

	/* List of sessions */
	list_init(&sessions);
	list_attributes_seeker(&sessions, session_list_seeker);
	
	/* List of slots */
	list_init(&virtual_slots);
	list_attributes_seeker(&virtual_slots, slot_list_seeker);
	
	/* Create a slot for a future "PnP" stuff. */
	if (sc_pkcs11_conf.plug_and_play) {
		create_slot(NULL);
	}
	/* Create slots for readers found on initialization */
	for (i=0; i<sc_ctx_get_reader_count(context); i++) {
		initialize_reader(sc_ctx_get_reader(context, i));
	}

	/* Set initial event state on slots */
	for (i=0; i<list_size(&virtual_slots); i++) {
		sc_pkcs11_slot_t *slot = (sc_pkcs11_slot_t *) list_get_at(&virtual_slots, i);
		slot->events = 0; /* Initially there are no events */
	}

out:	
	if (context != NULL)
		sc_debug(context, SC_LOG_DEBUG_NORMAL, "C_Initialize() = %s", lookup_enum ( RV_T, rv ));

	if (rv != CKR_OK) {
		if (context != NULL) {
			sc_release_context(context);
			context = NULL;
		}
		/* Release and destroy the mutex */
		sc_pkcs11_free_lock();
	}

	return rv;
}
Exemple #3
0
value 
grappa_CAML_inversions (value genes1, value genes2, 
        value c_num_genes, value dist) {
    CAMLparam4(genes1, genes2, c_num_genes, dist);
    CAMLlocal3(resulttmp, result, r);
    List intermediate_reversals_list;
    int num_genes, i, /*j,*/ inv_dist;
    //struct genome_arr_t *genes1_arr, *genes2_arr;
    struct genome_struct *permutation, *origin;
    int *temp_genes;
    Reversal *rev; Reversal revrev;
    result = Val_int(0); /* We start with the empty list */

    inv_dist = Int_val(dist);

    permutation = (struct genome_struct *) Data_custom_val (genes1);
    origin = (struct genome_struct *) Data_custom_val (genes2);
    /* First one in should be ancestor-- the permutation that you want to
       transform into the descendant (even though "origin" is a confusing
       thing to call descendant) */
    num_genes = Int_val(c_num_genes);

    temp_genes = (int *)malloc(num_genes * sizeof(int));

    if (0 == num_genes) CAMLreturn(result);
    /* Initialize list that will be used to store the sorting reversals
       found between the permutations at each step. */
    init_list(&intermediate_reversals_list, (num_genes + 1) * num_genes,
            sizeof(Reversal *));

    i = 0;

    do {

        clear_list(&intermediate_reversals_list);

        find_all_sorting_reversals(&intermediate_reversals_list, NULL, permutation,
                origin, num_genes, NULL);

        if  (list_size(&intermediate_reversals_list) > 0) {
            revrev = list_get(&intermediate_reversals_list, 0).revelement;
            rev = &revrev;
            copy_with_reversal(temp_genes, permutation->genes, num_genes, rev);
            permcopy(permutation->genes, temp_genes, num_genes);
            r = caml_alloc_tuple(2);
            Store_field(r,0,Val_int(rev->start + 1));
            Store_field(r,1,Val_int(rev->stop));
            resulttmp = caml_alloc(2,0);
            Store_field(resulttmp,0,r);
            Store_field(resulttmp,1,result);
            result = resulttmp;
        }

        i++;

    } while (list_size(&intermediate_reversals_list) > 0);

    fflush(stdout); /* Change so can be stderr, too? */

    CAMLreturn(result);
}
Exemple #4
0
	// por default creamos la tarea de complejidad minima
	tarea tarea = internalTarea_crear(descripcion, tiempo, COMPLEJIDAD_MINIMA);
	tarea->subtareas = NULL;
	tarea->impuestos = NULL;
	return tarea;
}

float Tarea_costo(tarea unaTarea) {
	float costoBase = internalTarea_costoBase(unaTarea);
	float costoTotal = costoBase;
	int cantidadSubtareas = list_size(unaTarea->subtareas);
	for_each(cantidadSubtareas, i) {
		tarea subtarea = list_get(unaTarea->subtareas, i);
		costoTotal = costoTotal + Tarea_costo(subtarea);
	}
	int cantidadImpuestos = list_size(unaTarea->impuestos);
	for_each(cantidadImpuestos, j) {
		impuesto unImpuesto = list_get(unaTarea->impuestos, j);
		costoTotal = costoTotal + Impuesto_monto(unImpuesto, costoBase);
	}

	return costoTotal;
}

float Tarea_tiempoTotal(tarea unaTarea) {
	return unaTarea->tiempo;
}

char* Tarea_asString(tarea unaTarea) {
	return unaTarea->descripcion;
}
Exemple #5
0
void connector_run(connector_t c,uint32_t ms)
{
	int32_t i = 0;
	uint32_t tick,_timeout,_ms;
	int32_t size;
	int32_t total;
	struct pending_connect *pc;
	struct timeval timeout;
	tick = GetSystemMs();
	_timeout = tick + ms;
	
	struct link_list *_l = LINK_LIST_CREATE();
	mutex_lock(c->lock);
	link_list_swap(_l,c->extern_pending_connect);
	mutex_unlock(c->lock);
	while(pc = LINK_LIST_POP(struct pending_connect*,_l))
	{
		if(c->fd_seisize >= FD_SETSIZE)
		{
			pc->call_back(-1,pc->ip,pc->port,pc->ud);
			free(pc);
		}
		else
		{
			FD_SET(pc->real_fd,&c->Set);
			LINK_LIST_PUSH_BACK(c->_pending_connect,pc);
			++c->fd_seisize;
		}
	}
	LINK_LIST_DESTROY(&_l);
	
	do{
		_ms = _timeout - tick;
		timeout.tv_sec = 0;
		timeout.tv_usec = 1000*_ms;
		size = list_size(c->_pending_connect);
		if(size == 0)
			return;
		if((total = select(1024,0,&c->Set,0, &timeout)) >0 )
		{
			for(; i < size; ++i)
			{
				pc = LINK_LIST_POP(struct pending_connect*,c->_pending_connect);
				if(pc)
				{
					if(FD_ISSET(pc->real_fd, &c->Set))
					{
						pc->call_back(pc->sock,pc->ip,pc->port,pc->ud);
						free(pc);
						--c->fd_seisize;
					}
					else
						LINK_LIST_PUSH_BACK(c->_pending_connect,pc);
				}
			}
		}
		FD_ZERO(&c->Set);
		tick = GetSystemMs();
		size = list_size(c->_pending_connect);
		i = 0;
		for(; i < (int32_t)size; ++i)
		{
			pc = LINK_LIST_POP(struct pending_connect*,c->_pending_connect);
			if(tick >= pc->timeout)
			{
				pc->call_back(-1,pc->ip,pc->port,pc->ud);
				free(pc);
				--c->fd_seisize;
			}
			else
			{
				LINK_LIST_PUSH_BACK(c->_pending_connect,pc);
				FD_SET(pc->real_fd,&c->Set);
			}
		}
		tick = GetSystemMs();
	}while(tick < _timeout);
}
Exemple #6
0
int lexer_preppend_token(struct lexer *lx, struct token *t)
{
	list_push_head(lx->token_queue, t);
	return list_size(lx->token_queue);
}
Exemple #7
0
void server_database_id(socket_t * client, http_request_t * req) {
	char strbuf[10240] = "";
	char buf[1000];
	if (strcmp(req->method, "GET") == 0){
		for (int i = 12; i < strlen(req->uri); i++)
			if (req->uri[i] < '0' || req->uri[i] > '9')
			{
				error_massage("wrong request!!", client);
				return;
			}
		FILE * file = fopen("Admins.xml", "r");
		while(fgets(buf, 1000, file) != NULL)
		{
			strcat(strbuf, buf);
			puts(buf);
		}
		list_t list = xml_to_list(strbuf);
		char id[10];
		for (int i = 12; i < strlen(req->uri); i++)
		{
			id[i - 12] = req->uri[i];
		}
		int id_int = atoi(id);
		if (id_int > list_size(list))
		{
			error_massage("client whith such id don't exist!!", client);
			return;
		}
		//puts(((struct admin_s *)list_get(list, 0))->name);
		char * text = list_to_html_id(list, id_int - 1);
		if (text == NULL)
		{
			error_massage("unknown error", client);
			return;
		}
		puts(id);
		sprintf(strbuf,
			"HTTP/1.1 200 OK\n"
			"Content-Type: text/html\n"
			"Content-Length: %u\n"
			"Connection: keep-alive\n"
			"\n%s", strlen(text), text);
		//free(allStudentsJson);
		free (text);
		fclose(file);
		socket_write_string(client, strbuf);
		socket_close(client);
	}
	else if (strcmp(req->method, "DELETE") == 0)
	{
		/*for (int i = 12; i < strlen(req->uri); i++)
			if (req->uri[i] < '0' || req->uri[i] > '9')
			{
				error_massage("wrong request!!", client);
				return;
			}*/
		FILE * file = fopen("Admins.xml", "r");
		while(fgets(buf, 1000, file) != NULL)
		{
			strcat(strbuf, buf);
			puts(buf);
		}
		list_t list = xml_to_list(strbuf);
		char id[10];
		for (int i = 12; i < strlen(req->uri); i++)
		{
			if (req->uri[i] != '#')
				id[i - 12] = req->uri[i];
			else id[i - 12] = '\0';
		}
		puts(id);
		int id_int = atoi(id);
		if (id_int > list_size(list))
		{
			error_massage("client whith such id don't exist!!", client);
			return;
		}
		list_del(list, id_int - 1);
		char * text = list_to_xml1(list);
		fclose(file);
		file = fopen("Admins.xml", "w");
		fprintf(file, "%s", text);
		free (text);
		//puts(((struct admin_s *)list_get(list, 0))->name);
		text = list_to_html(list);
		if (text == NULL)
		{
			error_massage("unknown error", client);
			return;
		}
		puts(id);
		sprintf(strbuf,
			"HTTP/1.1 200 OK\n"
			"Content-Type: text/html\n"
			"Content-Length: %u\n"
			"Connection: keep-alive\n"
			"\n%s", strlen(text), text);
		//free(allStudentsJson);*/
		free (text);
		fclose(file);
		socket_write_string(client, strbuf);
		socket_close(client);
	}
	else if (strcmp(req->method, "OPTIONS") == 0)
	{
		sprintf(strbuf,
            "HTTP/1.1 200 OK\n"
            "Access-Control-Allow-Origin: *\n"
            "Access-Control-Allow-Methods: DELETE\n"
            "\n");
		socket_write_string(client, strbuf);
		socket_close(client);
	}
}
Exemple #8
0
void next_video (onlineTV_t tv)
{
    list_del(tv->playlist, list_size(tv->playlist) - 1);
    if(((video_t *)list_get(tv->playlist, list_size(tv->playlist) - 1))->type == 1) // 1 це тип відео, 0 - реклама
        event(tv);
}
Exemple #9
0
int get_watchers_count (onlineTV_t tv)
{
    return list_size(tv->watchers);
}
Exemple #10
0
void ddbg_disassemble(int start, int difference)
{
    int i = 0;
    unsigned int ii = 0;
    bool found = false;
    struct inst inst;
    struct dbg_sym* sym;
    struct dbg_sym_payload_line* payload_line;
    struct dbg_sym_payload_label* payload_label;

    if (start < 0 || difference < 0)
    {
        printd(LEVEL_DEFAULT, "Invalid parameters provided to 'disassemble'.");
        return;
    }

    if (difference == 0)
        difference = (flash_size - start);

    while (i < difference)
    {
        // Show symbols.
        if (symbols != NULL)
        {
            for (ii = 0; ii < list_size(symbols); ii++)
            {
                sym = list_get_at(symbols, ii);
                switch (sym->type)
                {
                    case DBGFMT_SYMBOL_LINE:
                        payload_line = (struct dbg_sym_payload_line*)sym->payload;
                        if (payload_line->address == start + i)
                        {
                            found = true;
                            printd(LEVEL_DEFAULT, "0x%04X (0x%04X) (%s:%d):\n", start + i, vm->ram[start + i], payload_line->path->data, payload_line->lineno);

                        }
                        break;
                    case DBGFMT_SYMBOL_LABEL:
                        payload_label = (struct dbg_sym_payload_label*)sym->payload;
                        if (payload_label->address == start + i)
                        {
                            found = true;
                            printd(LEVEL_DEFAULT, "0x%04X (0x%04X) (%s):\n", start + i, vm->ram[start + i], payload_label->label->data);

                        }
                        break;
                }
            }
            if (!found) printd(LEVEL_DEFAULT, "0x%04X (0x%04X):\n", start + i, vm->ram[start + i]);
        }
        else
            printd(LEVEL_DEFAULT, "0x%04X (0x%04X): ", start + i, vm->ram[start + i]);

        // Disassemble.
        inst = vm_disassemble(vm, start + i, true);
        if (symbols != NULL)
            printd(LEVEL_DEFAULT, "    ");
        if (vm->pc == start + i)
            printd(LEVEL_DEFAULT, " >>> ");
        else
            printd(LEVEL_DEFAULT, "     ");
        if (inst.original.full == 0x0)
            printd(LEVEL_DEFAULT, "<null>\n");
        else if (inst.pretty.op == NULL)
            printd(LEVEL_DEFAULT, "???\n");
        else if (inst.original.op == OP_NONBASIC)
            printd(LEVEL_DEFAULT, "%s %s\n", inst.pretty.op->data, inst.pretty.a->data);
        else
            printd(LEVEL_DEFAULT, "%s %s, %s\n", inst.pretty.op->data, inst.pretty.b->data, inst.pretty.a->data);
        i += inst.size;
    }

    printd(LEVEL_DEFAULT, "\n");
}
Exemple #11
0
struct cluster *nearest_neighbor_clustering(struct list *initial_clusters, double (*cmp)(struct cluster *, struct cluster *))
{
	struct cluster *top, *closest, *subtop;
	struct list   *stack;
	struct itable *active_clusters;
	double dclosest, dsubtop;

	int merge = 0;

	list_first_item(initial_clusters);
	top = list_next_item(initial_clusters);

	/* Return immediately if top is NULL, or there is a unique
	 * initial cluster */
	if(list_size(initial_clusters) < 2)
		return top;

	stack = list_create(0);
	list_push_head(stack, top);

	/* Add all of the initial clusters as active clusters. */
	active_clusters = itable_create(0);
	while( (top = list_next_item(initial_clusters)) ) 
		itable_insert(active_clusters, (uintptr_t) top, (void *) top);

	do
	{
		/* closest might be NULL if all of the clusters are in
		 * the stack now. subtop might be NULL if top was the
		 * only cluster in the stack */
		top     = list_pop_head( stack );
		closest = cluster_nearest_neighbor(active_clusters, top, cmp);
		subtop  = list_peek_head( stack );

		dclosest = -1;
		dsubtop  = -1;

		if(closest)
			dclosest = cluster_ward_distance(top, closest);

		if(subtop)
			dsubtop = cluster_ward_distance(top, subtop);

		/* The nearest neighbor of top is either one of the
		 * remaining active clusters, or the second topmost
		 * cluster in the stack */
		if( closest && subtop )
		{
			/* Use pointer address to systematically break ties. */
			if(dclosest < dsubtop || ((dclosest == dsubtop) && (uintptr_t)closest < (uintptr_t)subtop)) 
				merge = 0;
			else 
				merge = 1;
		}
		else if( subtop )
			merge = 1;
		else if( closest )
			merge = 0;
		else
			fatal("Zero clusters?\n"); //We should never reach here.

		if(merge)
		{
			/* If the two topmost clusters in the stack are
			 * mutual nearest neighbors, merge them into a single
			 * cluster */
			subtop = list_pop_head( stack );
			list_push_head(stack, cluster_merge(top, subtop));
		}
		else
		{
			/* Otherwise, push the nearest neighbor of top to the
			 * stack */
			itable_remove(active_clusters, (uintptr_t) closest);
			list_push_head(stack, top);
			list_push_head(stack, closest);
		}

		debug(D_DEBUG, "stack: %d  active: %d  closest: %lf subtop: %lf\n", 
				list_size(stack), itable_size(active_clusters), dclosest, dsubtop);

		/* If there are no more active_clusters, but there is not
		 * a single cluster in the stack, we try again,
		 * converting the clusters in the stack into new active
		 * clusters. */
		if(itable_size(active_clusters) == 0 && list_size(stack) > 3)
		{
			itable_delete(active_clusters);
			return nearest_neighbor_clustering(stack, cmp);
		}

	}while( !(itable_size(active_clusters) == 0 && list_size(stack) == 1) );

	/* top is now the root of a cluster hierarchy, of
	 * cluster->right, cluster->left. */
	top = list_pop_head(stack);

	list_delete(stack);
	itable_delete(active_clusters);

	return top;
}
Exemple #12
0
void ddbg_precycle_hook(vm_t* vm, uint16_t pos, void* ud)
{
    unsigned int i = 0;
    struct breakpoint* bk;
    uint16_t op, a, b;

    // Handle any symbols that are at this cycle.
    list_t* symbols = ddbg_get_symbols(vm->pc);
    list_iterator_start(symbols);
    while (list_iterator_hasnext(symbols))
        dbg_lua_handle_hook_symbol(&lstate, NULL, bautofree((bstring)list_iterator_next(symbols)));
    list_iterator_stop(symbols);
    list_empty(symbols);
    free(symbols);

    // Handle custom Lua commands.
    dbg_lua_handle_hook(&lstate, NULL, bautofree(bfromcstr("precycle")), pos);

    // Check to see if Lua halted the VM and return if it did.
    if (vm->halted)
        return;

    // Handle breakpoints.
    if (!ignore_next_breakpoint)
    {
        for (i = 0; i < list_size(&breakpoints); i++)
        {
            bk = (struct breakpoint*)list_get_at(&breakpoints, i);

            if (vm->pc == bk->addr)
            {
                vm->halted = true;
                ignore_next_breakpoint = true;
                vm_hook_break(vm); // Required for UI to update correctly.
                if (bk->temporary)
                    list_delete_at(&breakpoints, i--);
                if (!bk->silent)
                    ddbg_disassemble(max_int32((int32_t)vm->pc - 10, 0x0), min_int32((int32_t)vm->pc + 10, 0x10000) - vm->pc);
                printd(LEVEL_DEFAULT, "Breakpoint hit at 0x%04X.\n", bk->addr);
                return;
            }
        }
    }
    ignore_next_breakpoint = false;

    // Handle backtrace.
    op = INSTRUCTION_GET_OP(vm->ram[vm->pc]);
    a = INSTRUCTION_GET_A(vm->ram[vm->pc]);
    b = INSTRUCTION_GET_B(vm->ram[vm->pc]);
    if ((op == OP_SET && b == PC) || (op == OP_NONBASIC && b == NBOP_JSR))
    {
        // FIXME: This doesn't handle every valid value correctly..
        if (a == PUSH_POP)
            list_delete_at(&backtrace, list_size(&backtrace) - 1);
        else if (a == NXT_LIT)
        {
            printd(LEVEL_DEBUG, "jumping literally from 0x%04X to 0x%04X (0x%04X).\n", vm->pc, vm->ram[vm->pc + 1], vm->pc + 1);
            list_append(&backtrace, backtrace_entry_create(vm->pc, vm->ram[vm->pc + 1]));
        }
        else if (a == NXT)
        {
            //list_append(&backtrace, backtrace_entry_create(vm->pc, vm->ram[vm->ram[vm->pc+1]]));
        }
        else
        {
            // Unhandled.
            printd(LEVEL_DEBUG, "warning: unhandled backtrace jump occurred.\n");
        }
    }
}
void* conectarseConWorkersRedLocal(void* params){
	parametrosReduccionLocal* infoRedLocal= (parametrosReduccionLocal*)params;
	respuesta confirmacionWorker;
	int numeroNodo;

	int socketWorker = crearSocket();
	struct sockaddr_in direccion = cargarDireccion(infoRedLocal->ip.cadena,infoRedLocal->puerto);
	if(!conectarCon(direccion, socketWorker, 2)){//2 id master
		mandarFalloEnReduccion();
		return 0;

	}

	log_trace(loggerMaster, "Conexion con Worker %d para estos tmp %d", infoRedLocal->numero, list_size(infoRedLocal->archivosTemporales));

	struct stat fileStat;
	if(stat(miJob->rutaReductor.cadena,&fileStat) < 0){
		printf("No se pudo abrir el archivo\n");
		return 0;
	}

	int fd = open(miJob->rutaReductor.cadena,O_RDWR);
	int size = fileStat.st_size;

	infoRedLocal->contenidoScript.cadena = mmap(NULL,size,PROT_READ,MAP_SHARED,fd,0);
	infoRedLocal->contenidoScript.longitud = size;

	empaquetar(socketWorker, mensajeProcesarRedLocal, 0, infoRedLocal);

	confirmacionWorker = desempaquetar(socketWorker);

	if (munmap(infoRedLocal->contenidoScript.cadena, infoRedLocal->contenidoScript.longitud) == -1){
		perror("Error un-mmapping the file");
		exit(EXIT_FAILURE);
	}
	close(fd);

	switch(confirmacionWorker.idMensaje){

	case mensajeRedLocalCompleta:
		log_trace(loggerMaster, "Informo a  YAMA fin Reduccion Local en nodo %d.",infoRedLocal->numero);
		numeroNodo = *(int*)confirmacionWorker.envio;
		empaquetar(socketYama, mensajeRedLocalCompleta, 0 , &numeroNodo);
		finalizarTiempo(estadisticas->tiempoFinRedLocal,numeroNodo);
		estadisticas->cantTareas[RED_LOCAL]++;
		break;

	case mensajeDesconexion:
	case mensajeFalloRedLocal:
		log_trace(loggerMaster, "Informo a  YAMA fallo en Reduccion Local en nodo %d.",infoRedLocal->numero);
		estadisticas->cantFallos++;
		mandarFalloEnReduccion();
		break;
	}
	return 0;
}
void csv_archive( csv_context_t* csv_buffer_list, buffer_t* url_str,
                  st_info_t* st_info )
{
    csv_buffer_t* csv_buffer;
    csv_row_t* csv_row;
    uint8_t* msh_data;
    size_t msh_length = 0;
    csv_buffer_t* final_csv = NULL;

    char time_string[32];

    // Step through the csv buffers list
    list_iterator_stop(csv_buffer_list);
    list_iterator_start(csv_buffer_list);
    while (list_iterator_hasnext(csv_buffer_list)) 
    {
        // Grab one buffer from the list
        csv_buffer = (csv_buffer_t*)list_iterator_next(csv_buffer_list);
        if (gDebug)
        {
          printf("%s[%d]: elapsed time %d <> %d TM_HOUR\n",
            csv_buffer->header->description, csv_buffer->header->channel,
            (int)(csv_buffer->end_time - csv_buffer->start_time), TM_HOUR);
        }
        while ((csv_buffer->end_time - csv_buffer->start_time) >= TM_HOUR) 
        {
            // Compress the csv data to FMash format
            fmash_csv_to_msh(csv_buffer, &msh_data, &msh_length);
            if (gDebug) {
                // Brag about our accomplishments
                fprintf(stdout, "compressed data size is %lu bytes\n", (unsigned long)msh_length);
                format_data(msh_data, msh_length, 0, 0);

                //* Verify the contents of the buffer are correct...
                if (!fmash_msh_to_csv( &final_csv, msh_data, msh_length )) {
                    fprintf(stdout, "FMash to CSV conversion failed\n");
                    goto queue_it;
                }
                if (!final_csv) {
                    fprintf(stdout, "final_csv not created\n");
                    goto queue_it;
                }
                if (!final_csv->header) {
                    fprintf(stdout, "final_csv->header not created\n");
                    goto queue_it;
                }
                if (!final_csv->list) {
                    fprintf(stdout, "final_csv->list not created\n");
                    goto queue_it;
                }
                fprintf(stdout, "=== FMASH VERIFICATION =================================\n");
                fprintf(stdout, "    file:         %s\n", csv_buffer->file_name);
                fprintf(stdout, "    channel:      %d\n", csv_buffer->header->channel);
                fprintf(stdout, "    description:  %s\n", csv_buffer->header->description);
                fprintf(stdout, "    lines:        %d\n", list_size(final_csv->list));
                list_iterator_stop(final_csv->list);
                list_iterator_start(final_csv->list);
                    fprintf(stdout, "        ---------------------- ----------- ----------- ----------- \n");
                    fprintf(stdout, "       | Timestamp            | Average   | High      | Low       |\n");
                    fprintf(stdout, "        ---------------------- ----------- ----------- ----------- \n");
                while (list_iterator_hasnext(final_csv->list))
                {
                    csv_row = (csv_row_t*)list_iterator_next(final_csv->list);
                    strftime(time_string, 31, "%Y/%m/%d %H:%M:%S", gmtime(&(csv_row->timestamp)));
                    printf("       | %s | % 9d | % 9d | % 9d |\n", time_string,
                           csv_row->average, csv_row->high, csv_row->low );
                }
                printf("\n");
                list_iterator_stop(final_csv->list);
                final_csv = csv_buffer_destroy(final_csv);
                fflush(stdout);
                // */
            }
 queue_it:
            // Add this as an opaque record
            if (msh_data && msh_length) {
                QueueOpaque(msh_data, msh_length, st_info->station,
                            st_info->network, st_info->csv_chan,
                            st_info->location, FALCON_IDSTRING);
                free(msh_data);
                msh_data = NULL;
            }
        }
        csv_buffer = NULL;
    }
    list_iterator_stop(csv_buffer_list);
}
Exemple #15
0
static void message_receive(int32_t s)
{
    size_t l = 0;
    time_t date = time(NULL);

    /* send greeting, wait for response */
    socket_send(s, MESSAGE_220);
    char *r = socket_read(s, &l);
    validate(MESSAGE_LHLO, r);
    char *cname = strdup(r + strlen(MESSAGE_LHLO));
    free(r);

    /* send welcome, wait for sender */
    {
        char *x = NULL;
        for (int i = strlen(cname); i > 0; i--)
            if (isspace(cname[i]))
                cname[i] = '\0';
        asprintf(&x, MESSAGE_250A, cname);
        if (!x)
            die("out of memory @ %s:%i", __FILE__, __LINE__ - 2);
        free(cname);
        socket_send(s, x);
        free(x);
    }
    r = socket_read(s, &l);
    validate(MESSAGE_FROM, r);
    char *from = extract_address(r);
    free(r);

    /* ok, wait for recipients (loop until DATA) */
    list_t *rcpt = list_create(NULL);
    while (true)
    {
        socket_send(s, MESSAGE_250);
        r = socket_read(s, &l);
        if (!strncmp(MESSAGE_DATA, r, strlen(MESSAGE_DATA)))
            break;
        validate(MESSAGE_RCPT, r);
        list_append(&rcpt, extract_address(r));
        free(r);
    }
    free(r);

    /* send 352, wait for .\n\r */
    socket_send(s, MESSAGE_354);
    char *data = NULL;
    uint64_t dl = 1;
    while (true)
    {
        r = socket_read(s, &l);
        if (!strcmp(MESSAGE_STOP, r))
            break;
        char *x = realloc(data, l + dl);
        if (!x)
            die("out of memory @ %s:%i", __FILE__, __LINE__ - 2);
        data = x;
        if ((x = convert_from_prefix(r)))
        {
            free(r);
            r = x;
            l++;
        }
        uint8_t dd = convert_double_dot(r);
        if (dd)
            l--;
        memcpy(data + dl, r + dd, l);
        dl += l;
        free(r);
    }
    free(r);
    if (data)
        convert_new_line(data);
    data[dl - 1] = '\0';

    /* ok, wait for QUIT */
    uint64_t rcpts = list_size(rcpt);
    for (unsigned i = 0; i < rcpts; i++)
    {
        char *x = NULL;
        asprintf(&x, MESSAGE_250C, (char *)list_get(rcpt, i));
        socket_send(s, x);
        free(x);
    }
    r = socket_read(s, &l);
    validate(MESSAGE_QUIT, r);
    free(r);
    /* bye, close */
    socket_send(s, MESSAGE_221);

    /*
     * TODO if To: address contains @domain.example.com
     * forward the message to an actual outbound mail hander
     * -- and--
     * check if the domain/host is localhost (or local hostname)
     */
    for (unsigned i = 0; i < rcpts; i++)
    {
        char *emadr = (char *)list_get(rcpt, i);
        char *at = strchrnul(emadr, '@');
        char *usr = strndup(emadr, at - emadr);

        /* lookup the user; if root, find alias instead */
        if (!strcmp(ROOT, usr))
            usr = root_alias;
        struct passwd *pw = getpwnam(usr);
        if (!pw)
            continue;
        uid_t uid = pw->pw_uid;
        gid_t gid = pw->pw_gid;
        /* write the message to the mail box */
        char *mesg = NULL;
        asprintf(&mesg, "From %s %s%s\n", from, ctime(&date), data);
        char *mbn = NULL;
        asprintf(&mbn, "%s/%s", mbox_dir, usr);
        int64_t mbox = open(mbn, O_WRONLY | O_APPEND | O_CREAT | F_WRLCK);
        if (mbox < 0)
            die("could not access mail box %s", mbn);
        free(mbn);
        write(mbox, mesg, strlen(mesg));
        fchown(mbox, uid, gid);
        fchmod(mbox, S_IRUSR | S_IWUSR);
        close(mbox);
        free(mesg);
    }
    list_delete(&rcpt, true);
    free(from);
    free(data);
}
Exemple #16
0
void event(onlineTV_t tv)
{
    for (int i = 0; i < list_size(tv->watchers); i++)
        ((watcher_t *)list_get(tv->watchers, i))->callback(get_cur_video(tv));
}
Exemple #17
0
int lexer_push_token(struct lexer *lx, struct token *t)
{
	list_push_tail(lx->token_queue, t);
	return list_size(lx->token_queue);
}
Exemple #18
0
watcher_t * onlineTV_get_watcher(onlineTV_t tv, int pos)
{
    if (pos >= list_size(tv->watchers))
        return NULL;
    return list_get(tv->watchers, pos);
}
Exemple #19
0
unsigned int sc_ctx_get_reader_count(sc_context_t *ctx)
{
	return list_size(&ctx->readers);
}
Exemple #20
0
int onlineTV_get_count_watchers(onlineTV_t tv)
{
    return list_size(tv->watchers);
}
Exemple #21
0
VALUE call_tree_children(VALUE self)
{
    list children = get_call_tree(self)->children;
    return rb_ary_new4(list_size(children), list_data(children));
}
Exemple #22
0
video_t * get_cur_video(onlineTV_t tv)
{
    return (video_t *)list_get(tv->playlist, list_size(tv->playlist) - 1);
}
Exemple #23
0
int main(int argc, char *argv[])
{
    // TEST
    //test_linked_list();

    if(argc != 2) {
        printf("Please give file name!");
        return 0;
    }

    FILE *file = fopen(argv[1], "r");
    if(NULL == file) {
        fprintf(stderr, "Can't open %s for reading!", argv[1]);
        return 0;
    }

    // General list to be used while reading file
    struct linked_list *list = NULL;
    char fname[65];
    char fowner[33];
    int fsize;
    struct file f;
    struct node *node;

    // One line from commands file
    char *line;

    // One of the operations (0 -10)
    int op;

    // Rest of line
    char rline[256];

    while((line = read_line(file)) != NULL) {
        sscanf(line, "%d %255[^\n]", &op, rline);

        switch(op) {
            case 0:
                if(list == NULL) {
                    fprintf(stderr, "There is no list to delete!");
                } else {
                    delete_list(list);
                }
                break;
            case 1:
                list = new_list();
                break;
            case 2:
                display_list(list);
                break;
            case 3:
                printf("List empty: %d\n", list_empty(list));
                break;
            case 4:
                printf("List size: %d\n", list_size(list));
                break;
            case 5:
                sscanf(rline, "%s %s %d", fname, fowner, &fsize);

                strncpy(f.fname, fname, 65);
                strncpy(f.owner, fowner, 33);
                f.size = fsize;

                node = new_node(f);

                push_front(node, list);
                break;
            case 6:
                sscanf(rline, "%s %s %d", fname, fowner, &fsize);

                strncpy(f.fname, fname, 65);
                strncpy(f.owner, fowner, 33);
                f.size = fsize;

                node = new_node(f);

                push_back(node, list);
                break;
            case 7:
                pop_front(list);
                break;
            case 8:
                pop_back(list);
                break;
            case 9:
                node = front(list);
                printf("Front: ");
                display_file(node->data);
                break;
            case 10:
                node = back(list);
                printf("Back: ");
                display_file(node->data);
                break;
            default:
                break;
        }
    }

    return 0;
}
Exemple #24
0
struct obj_conf *conf_init( int argc, char **argv ) {
	struct obj_conf *conf = myalloc( sizeof( struct obj_conf ) );
	int opt = 0;
	int i = 0;

	/* Defaults */
	conf->mode = CONF_CONSOLE;
	conf->p2p_port = PORT_DHT_DEFAULT;
	conf->dns_port = PORT_DNS_DEFAULT;
	conf->verbosity = CONF_VERBOSE;
	conf->bootstrap_port = PORT_DHT_DEFAULT;
	conf->announce_port = PORT_WWW_USER;
	conf->cores = unix_cpus();
	conf->bool_realm = FALSE;
#ifdef POLARSSL
	conf->bool_encryption = FALSE;
	memset( conf->key, '\0', BUF_SIZE );
#endif
	memset( conf->null_id, '\0', SHA1_SIZE );
	strncpy( conf->realm, CONF_REALM, BUF_OFF1 );
	strncpy( conf->bootstrap_node, MULTICAST_DEFAULT, BUF_OFF1 );
	rand_urandom( conf->node_id, SHA1_SIZE );

	/* Arguments */
	while( ( opt = getopt( argc, argv, "a:dhk:ln:p:P:qr:x:y:" ) ) != -1 ) {
		switch( opt ) {
			case 'a':
				conf->announce_port = str_safe_port( optarg );
				break;
			case 'd':
				conf->mode = CONF_DAEMON;
				break;
			case 'h':
				conf_usage( argv[0] );
				break;
			case 'k':
#ifdef POLARSSL
				snprintf( conf->key, BUF_SIZE, "%s", optarg );
				conf->bool_encryption = TRUE;
#endif
				break;
			case 'l':
				snprintf( conf->bootstrap_node, BUF_SIZE,
						"%s", BOOTSTRAP_DEFAULT );
				break;
			case 'n':
				sha1_hash( conf->node_id, optarg, strlen( optarg ) );
				break;
			case 'p':
				conf->p2p_port = str_safe_port( optarg );
				break;
			case 'P':
				conf->dns_port = str_safe_port( optarg );
				break;
			case 'q':
				conf->verbosity = CONF_BEQUIET;
				break;
			case 'r':
				snprintf( conf->realm, BUF_SIZE, "%s", optarg );
				conf->bool_realm = TRUE;
				break;
			case 'x':
				snprintf( conf->bootstrap_node, BUF_SIZE, "%s", optarg );
				break;
			case 'y':
				conf->bootstrap_port = str_safe_port( optarg );
				break;
			default: /* '?' */
				conf_usage( argv[0] );
		}
	}

	/* Get non-option values. */
	for( i=optind; i<argc; i++ ) {
		hostname_put( argv[i], conf->node_id, conf->realm, conf->bool_realm );
	}

	if( list_size( _main->hostname ) <= 0 ) {
		conf_usage( argv[0] );
	}

	if( conf->p2p_port == 0 ) {
		fail( "Invalid P2P port number (-p)" );
	}

	if( conf->dns_port == 0 ) {
		fail( "Invalid DNS port number (-P)" );
	}

	if( conf->dns_port == conf->p2p_port ) {
		fail( "P2P port (-p) and DNS port (-P) must not be the same." );
	}

	if( conf->bootstrap_port == 0 ) {
		fail( "Invalid bootstrap port number (-y)" );
	}

	if( conf->announce_port == 0 ) {
		fail( "Invalid announce port number (-a)" );
	}

	if( conf->cores < 1 || conf->cores > 128 ) {
		fail( "Invalid number of CPU cores" );
	}


	return conf;
}
Exemple #25
0
respuestaSolicitudTransformacion* moverClock(infoNodo* workerDesignado, t_list* listaNodos, bool** nodosPorBloque, t_list* infoBloques,int job){
	int i;
	int cantidadBloques = list_size(infoBloques);
	infoBloque* bloque = malloc(sizeof(infoBloque));
	respuestaSolicitudTransformacion* respuestaAMaster = malloc(sizeof(respuestaSolicitudTransformacion));
	respuestaAMaster->workers = list_create();
	for(i=0;i<cantidadBloques;i++){
		bloque = (infoBloque*)list_get(infoBloques, i);

		usleep(config.RETARDO_PLANIFICACION*1000);

		if(bloqueEstaEn(workerDesignado,nodosPorBloque,i)){
			if(workerDesignado->disponibilidad > 0){
				modificarCargayDisponibilidad(workerDesignado);
				agregarBloqueANodoParaEnviar(bloque,workerDesignado,respuestaAMaster,job);
				log_trace(logger, "Bloque %i asignado al worker %i | Disp %i",bloque->numeroBloque, workerDesignado->numero, workerDesignado->disponibilidad);

				workerDesignado = avanzarClock(workerDesignado, listaNodos);
				if(workerDesignado->disponibilidad <= 0){
					workerDesignado->disponibilidad += getDisponibilidadBase();
					workerDesignado = avanzarClock(workerDesignado, listaNodos);
				}

			}
			else{
				restaurarDisponibilidad(workerDesignado);
				workerDesignado = avanzarClock(workerDesignado, listaNodos);
				if(workerDesignado->disponibilidad <= 0){
					workerDesignado->disponibilidad += getDisponibilidadBase();
					//while(workerDesignado->disponibilidad <= 0 && bloqueEstaEn(workerDesignado,nodosPorBloque,i)){
						workerDesignado = obtenerProximoWorkerConBloque(listaNodos,i,workerDesignado->numero);
					//}
				}

				modificarCargayDisponibilidad(workerDesignado);

				agregarBloqueANodoParaEnviar(bloque,workerDesignado,respuestaAMaster,job);
				log_trace(logger, "Bloque %i asignado al worker %i | Disp %i",bloque->numeroBloque, workerDesignado->numero, workerDesignado->disponibilidad);
				workerDesignado = avanzarClock(workerDesignado, listaNodos);

				if(workerDesignado->disponibilidad <= 0){
					workerDesignado->disponibilidad += getDisponibilidadBase();
					workerDesignado = avanzarClock(workerDesignado, listaNodos);
				}
			}
		}
		else {
			printf("El worker %d no tiene el bloque %d \n",workerDesignado->numero,bloque->numeroBloque);
			infoNodo* proximoWorker = obtenerProximoWorkerConBloque(listaNodos,i,workerDesignado->numero);
			modificarCargayDisponibilidad(proximoWorker);

			agregarBloqueANodoParaEnviar(bloque,proximoWorker,respuestaAMaster,job);
			log_trace(logger, "Bloque %i asignado al worker %i | Disp %i",bloque->numeroBloque, proximoWorker->numero, proximoWorker->disponibilidad);
		}

	}


	return respuestaAMaster;

}
Exemple #26
0
int tsp(List *vertices, const TspVertex *start, List *tour, int (*match)
   (const void *key1, const void *key2)) {

TspVertex          *tsp_vertex,
                   *tsp_start,
                   *selection;

ListElmt           *element;

double             minimum,
                   distance,
                   x,
                   y;

int                found,
                   i;

/*****************************************************************************
*                                                                            *
*  Initialize the list for the tour.                                         *
*                                                                            *
*****************************************************************************/

list_init(tour, NULL);

/*****************************************************************************
*                                                                            *
*  Initialize all of the vertices in the graph.                              *
*                                                                            *
*****************************************************************************/

found = 0;

for (element = list_head(vertices); element != NULL; element =
   list_next(element)) {

   tsp_vertex = list_data(element);

   if (match(tsp_vertex, start)) {

      /***********************************************************************
      *                                                                      *
      *  Start the tour at the start vertex.                                 *
      *                                                                      *
      ***********************************************************************/

      if (list_ins_next(tour, list_tail(tour), tsp_vertex) != 0) {

         list_destroy(tour);
         return -1;

      }

      /***********************************************************************
      *                                                                      *
      *  Save the start vertex and its coordinates.                          *
      *                                                                      *
      ***********************************************************************/

      tsp_start = tsp_vertex;
      x = tsp_vertex->x;
      y = tsp_vertex->y;

      /***********************************************************************
      *                                                                      *
      *  Color the start vertex black.                                       *
      *                                                                      *
      ***********************************************************************/

      tsp_vertex->color = black;
      found = 1;

      }

   else {

      /***********************************************************************
      *                                                                      *
      *  Color all other vertices white.                                     *
      *                                                                      *
      ***********************************************************************/

      tsp_vertex->color = white;

   }

}

/*****************************************************************************
*                                                                            *
*  Return if the start vertex was not found.                                 *
*                                                                            *
*****************************************************************************/

if (!found) {

   list_destroy(tour);
   return -1;

}

/*****************************************************************************
*                                                                            *
*  Use the nearest-neighbor heuristic to compute the tour.                   *
*                                                                            *
*****************************************************************************/

i = 0;

while (i < list_size(vertices) - 1) {

   /**************************************************************************
   *                                                                         *
   *  Select the white vertex closest to the previous vertex in the tour.    *
   *                                                                         *
   **************************************************************************/

   minimum = DBL_MAX;

   for (element = list_head(vertices); element != NULL; element =
      list_next(element)) {

      tsp_vertex = list_data(element);

      if (tsp_vertex->color == white) {

         distance = sqrt(pow(tsp_vertex->x-x,2.0) + pow(tsp_vertex->y-y,2.0));

         if (distance < minimum) {

            minimum = distance;
            selection = tsp_vertex;

         }

      }

   }

   /**************************************************************************
   *                                                                         *
   *  Save the coordinates of the selected vertex.                           *
   *                                                                         *
   **************************************************************************/

   x = selection->x;
   y = selection->y;

   /**************************************************************************
   *                                                                         *
   *  Color the selected vertex black.                                       *
   *                                                                         *
   **************************************************************************/

   selection->color = black;

   /**************************************************************************
   *                                                                         *
   *  Insert the selected vertex into the tour.                              *
   *                                                                         *
   **************************************************************************/

   if (list_ins_next(tour, list_tail(tour), selection) != 0) {

      list_destroy(tour);
      return -1;

   }

   /**************************************************************************
   *                                                                         *
   *  Prepare to select the next vertex.                                     *
   *                                                                         *
   **************************************************************************/

   i++;

}

/*****************************************************************************
*                                                                            *
*  Insert the start vertex again to complete the tour.                       *
*                                                                            *
*****************************************************************************/

if (list_ins_next(tour, list_tail(tour), tsp_start) != 0) {

   list_destroy(tour);
   return -1;

}

return 0;

}
CK_RV C_GetSlotList(CK_BBOOL       tokenPresent,  /* only slots with token present */
		    CK_SLOT_ID_PTR pSlotList,     /* receives the array of slot IDs */
		    CK_ULONG_PTR   pulCount)      /* receives the number of slots */
{
	CK_SLOT_ID_PTR found = NULL;
	unsigned int i;
	CK_ULONG numMatches;
	sc_pkcs11_slot_t *slot;
	sc_reader_t *prev_reader = NULL;
	CK_RV rv;

	if (pulCount == NULL_PTR)
		return CKR_ARGUMENTS_BAD;

	if ((rv = sc_pkcs11_lock()) != CKR_OK) {
		return rv;
	}

	sc_debug(context, SC_LOG_DEBUG_NORMAL, "C_GetSlotList(token=%d, %s)", tokenPresent,
		 (pSlotList==NULL_PTR && sc_pkcs11_conf.plug_and_play)? "plug-n-play":"refresh");

	/* Slot list can only change in v2.20 */
	if (pSlotList == NULL_PTR && sc_pkcs11_conf.plug_and_play) {
		/* Trick NSS into updating the slot list by changing the hotplug slot ID */
		sc_pkcs11_slot_t *hotplug_slot = list_get_at(&virtual_slots, 0);
		hotplug_slot->id--;
		sc_ctx_detect_readers(context); 
	}

	card_detect_all();

	found = malloc(list_size(&virtual_slots) * sizeof(CK_SLOT_ID));

	if (found == NULL) {
		rv = CKR_HOST_MEMORY;
		goto out;
	}

	prev_reader = NULL;
	numMatches = 0;
	for (i=0; i<list_size(&virtual_slots); i++) {
	        slot = (sc_pkcs11_slot_t *) list_get_at(&virtual_slots, i);
		/* the list of available slots contains:
		 * - if present, virtual hotplug slot;
		 * - any slot with token;
		 * - without token(s), one empty slot per reader;
		 */
	        if ((!tokenPresent && !slot->reader) 
				|| (!tokenPresent && slot->reader != prev_reader) 
				|| (slot->slot_info.flags & CKF_TOKEN_PRESENT))
			found[numMatches++] = slot->id;
		prev_reader = slot->reader;
	}

	if (pSlotList == NULL_PTR) {
		sc_debug(context, SC_LOG_DEBUG_NORMAL, "was only a size inquiry (%d)\n", numMatches);
		*pulCount = numMatches;
		rv = CKR_OK;
		goto out;
	}

	if (*pulCount < numMatches) {
		sc_debug(context, SC_LOG_DEBUG_NORMAL, "buffer was too small (needed %d)\n", numMatches);
		*pulCount = numMatches;
		rv = CKR_BUFFER_TOO_SMALL;
		goto out;
	}

	memcpy(pSlotList, found, numMatches * sizeof(CK_SLOT_ID));
	*pulCount = numMatches;
	rv = CKR_OK;

	sc_debug(context, SC_LOG_DEBUG_NORMAL, "returned %d slots\n", numMatches);

out:
	if (found != NULL) {
		free (found);
		found = NULL;
	}
	sc_pkcs11_unlock();
	return rv;
}
static LONG HPReadBundleValues(void)
{
	LONG rv;
	DIR *hpDir;
	struct dirent *currFP = NULL;
	char fullPath[FILENAME_MAX];
	char fullLibPath[FILENAME_MAX];
	int listCount = 0;

	hpDir = opendir(PCSCLITE_HP_DROPDIR);

	if (NULL == hpDir)
	{
		Log1(PCSC_LOG_ERROR, "Cannot open PC/SC drivers directory: " PCSCLITE_HP_DROPDIR);
		Log1(PCSC_LOG_ERROR, "Disabling USB support for pcscd.");
		return -1;
	}

	/* allocate a first array */
	driverSize = DRIVER_TRACKER_INITIAL_SIZE;
	driverTracker = calloc(driverSize, sizeof(*driverTracker));
	if (NULL == driverTracker)
	{
		Log1(PCSC_LOG_CRITICAL, "Not enough memory");
		(void)closedir(hpDir);
		return -1;
	}

#define GET_KEY(key, values) \
	rv = LTPBundleFindValueWithKey(&plist, key, values); \
	if (rv) \
	{ \
		Log2(PCSC_LOG_ERROR, "Value/Key not defined for " key " in %s", \
			fullPath); \
		continue; \
	}

	while ((currFP = readdir(hpDir)) != 0)
	{
		if (strstr(currFP->d_name, ".bundle") != 0)
		{
			unsigned int alias;
			list_t plist, *values;
			list_t *manuIDs, *productIDs, *readerNames;
			char *CFBundleName;
			char *libraryPath;

			/*
			 * The bundle exists - let's form a full path name and get the
			 * vendor and product ID's for this particular bundle
			 */
			(void)snprintf(fullPath, sizeof(fullPath), "%s/%s/Contents/Info.plist",
				PCSCLITE_HP_DROPDIR, currFP->d_name);
			fullPath[sizeof(fullPath) - 1] = '\0';

			rv = bundleParse(fullPath, &plist);
			if (rv)
				continue;

			/* get CFBundleExecutable */
			GET_KEY(PCSCLITE_HP_LIBRKEY_NAME, &values)
			libraryPath = list_get_at(values, 0);
			(void)snprintf(fullLibPath, sizeof(fullLibPath),
				"%s/%s/Contents/%s/%s",
				PCSCLITE_HP_DROPDIR, currFP->d_name, PCSC_ARCH,
				libraryPath);
			fullLibPath[sizeof(fullLibPath) - 1] = '\0';

			GET_KEY(PCSCLITE_HP_MANUKEY_NAME, &manuIDs)
			GET_KEY(PCSCLITE_HP_PRODKEY_NAME, &productIDs)
			GET_KEY(PCSCLITE_HP_NAMEKEY_NAME, &readerNames)

			/* Get CFBundleName */
			rv = LTPBundleFindValueWithKey(&plist, PCSCLITE_HP_CFBUNDLE_NAME,
				&values);
			if (rv)
				CFBundleName = NULL;
			else
				CFBundleName = strdup(list_get_at(values, 0));

			/* while we find a nth ifdVendorID in Info.plist */
			for (alias=0; alias<list_size(manuIDs); alias++)
			{
				char *value;

				/* variables entries */
				value = list_get_at(manuIDs, alias);
				driverTracker[listCount].manuID = strtol(value, NULL, 16);

				value = list_get_at(productIDs, alias);
				driverTracker[listCount].productID = strtol(value, NULL, 16);

				driverTracker[listCount].readerName = strdup(list_get_at(readerNames, alias));

				/* constant entries for a same driver */
				driverTracker[listCount].bundleName = strdup(currFP->d_name);
				driverTracker[listCount].libraryPath = strdup(fullLibPath);
				driverTracker[listCount].CFBundleName = CFBundleName;

#ifdef DEBUG_HOTPLUG
				Log2(PCSC_LOG_INFO, "Found driver for: %s",
					driverTracker[listCount].readerName);
#endif
				listCount++;
				if (listCount >= driverSize)
				{
					int i;

					/* increase the array size */
					driverSize += DRIVER_TRACKER_SIZE_STEP;
#ifdef DEBUG_HOTPLUG
					Log2(PCSC_LOG_INFO,
						"Increase driverTracker to %d entries", driverSize);
#endif
					driverTracker = realloc(driverTracker,
						driverSize * sizeof(*driverTracker));
					if (NULL == driverTracker)
					{
						Log1(PCSC_LOG_CRITICAL, "Not enough memory");
						driverSize = -1;
						(void)closedir(hpDir);
						return -1;
					}

					/* clean the newly allocated entries */
					for (i=driverSize-DRIVER_TRACKER_SIZE_STEP; i<driverSize; i++)
					{
						driverTracker[i].manuID = 0;
						driverTracker[i].productID = 0;
						driverTracker[i].bundleName = NULL;
						driverTracker[i].libraryPath = NULL;
						driverTracker[i].readerName = NULL;
						driverTracker[i].CFBundleName = NULL;
					}
				}
			}
			bundleRelease(&plist);
		}
	}

	driverSize = listCount;
	(void)closedir(hpDir);

#ifdef DEBUG_HOTPLUG
	Log2(PCSC_LOG_INFO, "Found drivers for %d readers", listCount);
#endif

	return 0;
} /* HPReadBundleValues */
Exemple #29
0
int master_main(const char *host, int port, const char *addr) {
	time_t idle_stoptime;
	struct link *master = NULL;
	int num_workers, i;
	struct mpi_queue_job **workers;

	struct itable *active_jobs = itable_create(0);
	struct itable *waiting_jobs = itable_create(0);
	struct list   *complete_jobs = list_create();

	MPI_Comm_size(MPI_COMM_WORLD, &num_workers);

	workers = malloc(num_workers * sizeof(*workers));
	memset(workers, 0, num_workers * sizeof(*workers));	
	
	idle_stoptime = time(0) + idle_timeout;

	while(!abort_flag) {
		char line[MPI_QUEUE_LINE_MAX];

		if(time(0) > idle_stoptime) {
			if(master) {
				printf("mpi master: gave up after waiting %ds to receive a task.\n", idle_timeout);
			} else {
				printf("mpi master: gave up after waiting %ds to connect to %s port %d.\n", idle_timeout, host, port);
			}
			break;
		}


		if(!master) {
			char working_dir[MPI_QUEUE_LINE_MAX];
			master = link_connect(addr, port, idle_stoptime);
			if(!master) {
				sleep(5);
				continue;
			}

			link_tune(master, LINK_TUNE_INTERACTIVE);
			
			link_readline(master, line, sizeof(line), time(0) + active_timeout);

			memset(working_dir, 0, MPI_QUEUE_LINE_MAX);
			if(sscanf(line, "workdir %s", working_dir) == 1) {
				MPI_Bcast(working_dir, MPI_QUEUE_LINE_MAX, MPI_CHAR, 0, MPI_COMM_WORLD);
			} else {
				link_close(master);
				master = NULL;
				continue;
			}
		}
		
		if(link_readline(master, line, sizeof(line), time(0) + short_timeout)) {
			struct mpi_queue_operation *op;
			int jobid, mode;
			INT64_T length;
			char path[MPI_QUEUE_LINE_MAX];
			op = NULL;
			
			debug(D_MPI, "received: %s\n", line);

			if(!strcmp(line, "get results")) {
				struct mpi_queue_job *job;
				debug(D_MPI, "results requested: %d available\n", list_size(complete_jobs));
				link_putfstring(master, "num results %d\n", time(0) + active_timeout, list_size(complete_jobs));
				while(list_size(complete_jobs)) {
					job = list_pop_head(complete_jobs);
					link_putfstring(master, "result %d %d %d %lld\n", time(0) + active_timeout, job->jobid, job->status, job->result, job->output_length);
					if(job->output_length) {
						link_write(master, job->output, job->output_length, time(0)+active_timeout);
					}
					mpi_queue_job_delete(job);
				}

			} else if(sscanf(line, "work %d %lld", &jobid, &length)) {
				op = malloc(sizeof(*op));
				memset(op, 0, sizeof(*op));
				op->type = MPI_QUEUE_OP_WORK;
				op->buffer_length = length+1;
				op->buffer = malloc(length+1);
				op->buffer[op->buffer_length] = 0;
				link_read(master, op->buffer, length, time(0) + active_timeout);
				op->result = -1;
				
			} else if(sscanf(line, "stat %d %s", &jobid, path) == 2) {
				op = malloc(sizeof(*op));
				memset(op, 0, sizeof(*op));
				op->type = MPI_QUEUE_OP_STAT;
				sprintf(op->args, "%s", path);
				op->result = -1;
				
			} else if(sscanf(line, "unlink %d %s", &jobid, path) == 2) {
				op = malloc(sizeof(*op));
				memset(op, 0, sizeof(*op));
				op->type = MPI_QUEUE_OP_UNLINK;
				sprintf(op->args, "%s", path);
				op->result = -1;
				
			} else if(sscanf(line, "mkdir %d %s %o", &jobid, path, &mode) == 3) {
				op = malloc(sizeof(*op));
				memset(op, 0, sizeof(*op));
				op->type = MPI_QUEUE_OP_MKDIR;
				sprintf(op->args, "%s %o", path, mode);
				op->result = -1;
				
			} else if(sscanf(line, "close %d", &jobid) == 1) {
				op = malloc(sizeof(*op));
				memset(op, 0, sizeof(*op));
				op->type = MPI_QUEUE_OP_CLOSE;
				op->result = -1;
				
//			} else if(sscanf(line, "symlink %d %s %s", &jobid, path, filename) == 3) {
//			} else if(sscanf(line, "put %d %s %lld %o", &jobid, filename, &length, &mode) == 4) {
//			} else if(sscanf(line, "rget %d %s", &jobid, filename) == 2) {
//			} else if(sscanf(line, "get %d %s", &jobid, filename) == 2) {
//			} else if(sscanf(line, "thirdget %d %d %s %[^\n]", &jobid, &mode, filename, path) == 4) {
//			} else if(sscanf(line, "thirdput %d %d %s %[^\n]", &jobid, &mode, filename, path) == 4) {
			} else if(!strcmp(line, "exit")) {
				break;
			} else {
				abort_flag = 1;
				continue;
			}
			if(op) {
				struct mpi_queue_job *job;
					job = itable_lookup(active_jobs, jobid);
				if(!job) {
					job = itable_lookup(waiting_jobs, jobid);
				}
				if(!job) {
					job = malloc(sizeof(*job));
					memset(job, 0, sizeof(*job));
					job->jobid = jobid;
					job->operations = list_create();
					job->status = MPI_QUEUE_JOB_WAITING;
					job->worker_rank = -1;
					itable_insert(waiting_jobs, jobid, job);
				}
				list_push_tail(job->operations, op);
			}
			idle_stoptime = time(0) + idle_timeout;
		} else {
			link_close(master);
			master = 0;
			sleep(5);
		}
		
		int num_waiting_jobs = itable_size(waiting_jobs);
		int num_unvisited_jobs = itable_size(active_jobs);
		for(i = 1; i < num_workers && (num_unvisited_jobs > 0 || num_waiting_jobs > 0); i++) {
			struct mpi_queue_job *job;
			struct mpi_queue_operation *op;
			int flag = 0;
			UINT64_T jobid;

			if(!workers[i]) {
				if(num_waiting_jobs) {
					itable_firstkey(waiting_jobs);
					itable_nextkey(waiting_jobs, &jobid, (void **)&job);
					itable_remove(waiting_jobs, jobid);
					itable_insert(active_jobs, jobid, job);
					workers[i] = job;
					num_waiting_jobs--;
					job->worker_rank = i;
					job->status = MPI_QUEUE_JOB_READY;
				} else {
					continue;
				}
			} else {
				num_unvisited_jobs--;
				if(workers[i]->status == MPI_QUEUE_JOB_BUSY) {
					MPI_Test(&workers[i]->request, &flag, &workers[i]->mpi_status);
					if(flag) {
						op = list_pop_head(workers[i]->operations);
						if(op->output_length) {
							op->output_buffer = malloc(op->output_length);
							MPI_Recv(op->output_buffer, op->output_length, MPI_BYTE, workers[i]->worker_rank, 0, MPI_COMM_WORLD, &workers[i]->mpi_status);
						}
						
						workers[i]->status = MPI_QUEUE_JOB_READY;

						if(op->type == MPI_QUEUE_OP_WORK || op->result < 0) {
							if(workers[i]->output)
								free(workers[i]->output);
							workers[i]->output = op->output_buffer;
							op->output_buffer = NULL;
							workers[i]->output_length = op->output_length;
							workers[i]->result = op->result;
							if(op->result < 0) {
								workers[i]->status = MPI_QUEUE_JOB_FAILED | op->type;
								op->type = MPI_QUEUE_OP_CLOSE;
								list_push_head(workers[i]->operations, op);
								op = NULL;
							}
						}
						if(op) {
							if(op->buffer)
								free(op->buffer);
							if(op->output_buffer)
								free(op->output_buffer);
							free(op);
						}
					}
				}
			}
			
			if( workers[i]->status != MPI_QUEUE_JOB_BUSY && list_size(workers[i]->operations)) {
				op = list_peek_head(workers[i]->operations);
				
				if(op->type == MPI_QUEUE_OP_CLOSE) {
					itable_remove(active_jobs, workers[i]->jobid);
					list_push_tail(complete_jobs, workers[i]);
					if(!(workers[i]->status & MPI_QUEUE_JOB_FAILED))
						workers[i]->status = MPI_QUEUE_JOB_COMPLETE;
					workers[i] = NULL;
					i--;
					continue;
				}
				
				MPI_Send(op, sizeof(*op), MPI_BYTE, workers[i]->worker_rank, 0, MPI_COMM_WORLD);
				if(op->buffer_length) {
					MPI_Send(op->buffer, op->buffer_length, MPI_BYTE, workers[i]->worker_rank, 0, MPI_COMM_WORLD);
					free(op->buffer);
					op->buffer_length = 0;
					op->buffer = NULL;
				}
				MPI_Irecv(op, sizeof(*op), MPI_BYTE, workers[i]->worker_rank, 0, MPI_COMM_WORLD, &workers[i]->request);
				workers[i]->status = MPI_QUEUE_JOB_BUSY;
			}
		}
	}


	/** Clean up waiting & complete jobs, send Exit commands to each worker */
	if(!master) {
		// If the master link hasn't been set up yet
		// the workers will be waiting for the working directory
		char line[MPI_QUEUE_LINE_MAX];
		memset(line, 0, MPI_QUEUE_LINE_MAX);
		MPI_Bcast(line, MPI_QUEUE_LINE_MAX, MPI_CHAR, 0, MPI_COMM_WORLD);
	} else {
		link_close(master);
	}

	for(i = 1; i < num_workers; i++) {
		struct mpi_queue_operation *op, close;
		memset(&close, 0, sizeof(close));
		close.type = MPI_QUEUE_OP_EXIT;
		
		if(workers[i]) {
			if(workers[i]->status == MPI_QUEUE_JOB_BUSY) {
				MPI_Wait(&workers[i]->request, &workers[i]->mpi_status);
				op = list_peek_head(workers[i]->operations);
				
				if(op->output_length) {
					op->output_buffer = malloc(op->output_length);
					MPI_Recv(op->output_buffer, op->output_length, MPI_BYTE, workers[i]->worker_rank, 0, MPI_COMM_WORLD, &workers[i]->mpi_status);
				}
			}
			itable_remove(active_jobs, workers[i]->jobid);
			list_push_tail(complete_jobs, workers[i]);
		}
		MPI_Send(&close, sizeof(close), MPI_BYTE, i, 0, MPI_COMM_WORLD);
	}

	itable_firstkey(waiting_jobs);
	while(itable_size(waiting_jobs)) {
		struct mpi_queue_job *job;
		UINT64_T jobid;

		itable_nextkey(waiting_jobs, &jobid, (void **)&job);
		itable_remove(waiting_jobs, jobid);
		list_push_tail(complete_jobs, job);
	}

	while(list_size(complete_jobs)) {
		mpi_queue_job_delete(list_pop_head(complete_jobs));
	}

	MPI_Finalize();
	return abort_flag;
}
Exemple #30
0
int stack_size(Stack *self)
{
    return list_size(self);
}