Exemple #1
0
/* ONLY CALL WHEN MUTEX ACQUIRED */
void add_active(bzz_thread_t *thread, bzz_t *lock) {
	// Determine thread color and remove from correct waiting list
	if(is_gold(thread)) {
		int position = list_locate(lock->waiting_gold_threads, thread);
		list_delete_at(lock->waiting_gold_threads, position);
	} else {
		int position = list_locate(lock->waiting_black_threads, thread);
		list_delete_at(lock->waiting_black_threads, position);
	}
	lock->active_threads++;
}
Exemple #2
0
void ddbg_delete_breakpoint(bstring file, int index)
{
    unsigned int i = 0;
    bool found = false;
    int32_t memory = ddbg_file_to_address(file, index);
    struct breakpoint* bk;

    // Did we get a valid result?
    if (memory == -1)
    {
        printd(LEVEL_DEFAULT, "Unable to resolve specified symbol.\n");
        return;
    }

    for (i = 0; i < list_size(&breakpoints); i++)
    {
        bk = (struct breakpoint*)list_get_at(&breakpoints, i);

        if (bk->addr == memory)
        {
            list_delete_at(&breakpoints, i--);
            found = true;
        }
    }

    if (found == true)
        printd(LEVEL_DEFAULT, "Breakpoint removed at 0x%04X.\n", memory);
    else
        printd(LEVEL_DEFAULT, "There was no breakpoint at %s:%d.\n", file->data, index);
}
Exemple #3
0
void ddbg_delete_breakpoint_identifier(bstring ident)
{
    // TODO: In the future when C functions are supported
    // in the debugging symbol format, we should probably
    // allow removing breakpoints by C function name as well.
    unsigned int i = 0;
    bool found = false;
    int32_t memory = ddbg_label_to_address(ident);
    struct breakpoint* bk;

    // Did we get a valid result?
    if (memory == -1)
    {
        printd(LEVEL_DEFAULT, "Unable to resolve specified symbol.\n");
        return;
    }

    for (i = 0; i < list_size(&breakpoints); i++)
    {
        bk = (struct breakpoint*)list_get_at(&breakpoints, i);

        if (bk->addr == memory)
        {
            list_delete_at(&breakpoints, i--);
            found = true;
        }
    }

    if (found == true)
        printd(LEVEL_DEFAULT, "Breakpoint removed at 0x%04X.\n", memory);
    else
        printd(LEVEL_DEFAULT, "There was no breakpoint on label %s.\n", ident->data);
}
Exemple #4
0
void main(int argc, char* argv[])
{
	list * l;
	list_iter it;
	intptr_t i;
	char* sv[] = { "fff", "zzz", "rrr", "bbb", "ggg", "hhh", "lll", "ttt" };
	
	//list test
	l = list_new();
	for (i=0; i<10; ++i) {
		(i%2 ? list_append(l, (void*)i): list_prepend(l, (void*)i));
	}
	list_insert_at(l, (void*)20,9);
	list_append(l, (void*)22);
	list_delete_item(l, (void*)22);
	list_delete_at(l, 10);
	list_dump(l, "%d\n");
	list_free(l);
	
	//string list test
	l = list_new_full(free);
	for(i=0; i<8; ++i) list_append(l, strdup(sv[i]));
	list_prepend(l, strdup("nine"));
	list_delete_item_comp(l, strdup("seven"), (list_comparator)strcmp);
	list_delete_item_comp(l, "eee", (list_comparator)strcmp);
	list_dump(l, "%s\n");
	list_free(l);
	
	l = list_new();
	for(i=0; i<8; ++i) list_insert_sorted_comp(l, sv[i], (list_comparator)strcmp);
	list_dump(l, "%s\n");
	list_free(l);
}
Exemple #5
0
///
/// Pops a scope from the stack.
///
void ppimpl_pop_scope(state_t* state)
{
    scope_t* scope;
    match_t* match;
    match_t* old;
    bstring name;
    size_t a, i;
    if (list_size(&state->scopes) == 0)
        return;
    scope = list_extract_at(&state->scopes, list_size(&state->scopes) - 1);

    // Delete text if this scope was silenced.
    if (!scope->active)
    {
        list_delete_range(&state->cached_output,
                scope->start_index,
                list_size(&state->cached_output) - 1);
    }

    // Delete handlers that were defined this scope.
    list_iterator_start(&scope->new_handlers);
    while (list_iterator_hasnext(&scope->new_handlers))
    {
        name = list_iterator_next(&scope->new_handlers);

        for (i = 0; i < list_size(&state->handlers); i++)
        {
            old = list_get_at(&state->handlers, i);
            if (biseq(name, old->text.ref))
            {
                // We need remove the old handler.
                // FIXME: Free the old handler.
                list_delete_at(&state->handlers, i);
                i--;
            }
        }

        bdestroy(name);
    }
    list_iterator_stop(&scope->new_handlers);
    list_destroy(&scope->new_handlers);

    // Restore handlers.
    for (a = 0; a < list_size(&scope->old_handlers); a++)
    {
        match = list_get_at(&scope->old_handlers, a);

        // Restore the old handler.
        list_append(&state->handlers, match);
        list_extract_at(&scope->old_handlers, a);
        a--;
    }
    list_destroy(&scope->old_handlers);

    // Free memory.
    free(scope);
}
Exemple #6
0
int main(int argc, const char *argv[])
{
	int i, ret;
	int arr[] = {12, 9, -1, 23, 2, 34, 6, 45};
	list *ptr = NULL, *ptr2 = NULL; 
	ptr = list_create();
	ptr2 = list_create();
	if (NULL == ptr) {
		printf("error\n");
		exit(1);
	}

	for (i = 0; i < sizeof(arr)/sizeof(*arr); i++) {
		ret = list_insert_at(ptr, DATA_INIT_INDEX, &arr[i]);
		if (ret < 0) {
			fprintf(stderr, "isnert err %d\n", ret);
			exit(1);
		}
	}

	list_display(ptr);

	int tmp = 100;
	list_insert_at(ptr, 1, &tmp);
	list_display(ptr);
	list_destory(ptr);

	for (i = 0; i < sizeof(arr)/sizeof(*arr); i++) {
		ret = list_order_insert(ptr2, &arr[i]);
		if (ret < 0) {
			fprintf(stderr, "isnert err %d\n", ret);
			exit(1);
		}
	}

	list_display(ptr2);

	tmp = 23;
	list_delete(ptr2, &tmp);
	list_display(ptr2);

	list_delete_at(ptr2, 2, &tmp);
	printf("delete_at %d\n", tmp);
	list_display(ptr2);

	return 0;
}
Exemple #7
0
/* removes every ack'd packet from unackd_packets
 * should be called AFTER updating send_unack
 */
static void packet_t_remove(context_t *ctx) {
    while (list_size(ctx->unackd_packets) > 0) {
        packet_t *oldpack = list_get_at(ctx->unackd_packets, 0);

        /* update RTO given this packet */
        update_rto(ctx, oldpack);


        /* if all the data in the packet was acknowledged, discard and delete from list */
        if (ctx->send_unack >= oldpack->seq_num + (oldpack->packet_size - sizeof(STCPHeader))) {
            free(oldpack->packet);
            oldpack->packet = NULL;
            list_delete_at(ctx->unackd_packets, 0);
        }
        else
            /* this packet and all beyond it are unacknowledged */
            break;
    }
    return;
}
Exemple #8
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");
        }
    }
}
Exemple #9
0
int udpclient(int argc, char *argv[])
{
    char *lhost, *lport, *phost, *pport, *rhost, *rport;
    list_t *clients = NULL;
    list_t *conn_clients;
    client_t *client;
    client_t *client2;
    socket_t *tcp_serv = NULL;
    socket_t *tcp_sock = NULL;
    socket_t *udp_sock = NULL;
    char data[MSG_MAX_LEN];
    char addrstr[ADDRSTRLEN];
    
    struct timeval curr_time;
    struct timeval check_time;
    struct timeval check_interval;
    struct timeval timeout;
    fd_set client_fds;
    fd_set read_fds;
    uint16_t tmp_id;
    uint8_t tmp_type;
    uint16_t tmp_len;
    uint16_t tmp_req_id;
    int num_fds;
    
    int ret;
    int i;
    
    signal(SIGINT, &signal_handler);

    i = 0;    
    lhost = (argc - i == 5) ? NULL : argv[i++];
    lport = argv[i++];
    phost = argv[i++];
    pport = argv[i++];
    rhost = argv[i++];
    rport = argv[i++];

    /* Check validity of ports (can't check ip's b/c might be host names) */
    ERROR_GOTO(!isnum(lport), "Invalid local port.", done);
    ERROR_GOTO(!isnum(pport), "Invalid proxy port.", done);
    ERROR_GOTO(!isnum(rport), "Invalid remote port.", done);
    
    srand(time(NULL));
    next_req_id = rand() % 0xffff;
    
    /* Create an empty list for the clients */
    clients = list_create(sizeof(client_t), p_client_cmp, p_client_copy,
                          p_client_free, 1);
    ERROR_GOTO(clients == NULL, "Error creating clients list.", done);

    /* Create and empty list for the connecting clients */
    conn_clients = list_create(sizeof(client_t), p_client_cmp, p_client_copy,
                               p_client_free, 1);
    ERROR_GOTO(conn_clients == NULL, "Error creating clients list.", done);

    /* Create a TCP server socket to listen for incoming connections */
    tcp_serv = sock_create(lhost, lport, ipver, SOCK_TYPE_TCP, 1, 1);
    ERROR_GOTO(tcp_serv == NULL, "Error creating TCP socket.", done);
    if(debug_level >= DEBUG_LEVEL1)
    {
        printf("Listening on TCP %s\n",
               sock_get_str(tcp_serv, addrstr, sizeof(addrstr)));
    }
    
    FD_ZERO(&client_fds);

    /* Initialize all the timers */
    timerclear(&timeout);
    check_interval.tv_sec = 0;
    check_interval.tv_usec = 500000;
    gettimeofday(&check_time, NULL);
    
    while(running)
    {
        if(!timerisset(&timeout))
            timeout.tv_usec = 50000;

        read_fds = client_fds;
        FD_SET(SOCK_FD(tcp_serv), &read_fds);

        ret = select(FD_SETSIZE, &read_fds, NULL, NULL, &timeout);
        PERROR_GOTO(ret < 0, "select", done);
        num_fds = ret;

        gettimeofday(&curr_time, NULL);

        /* Go through all the clients and check if didn't get an ACK for sent
           data during the timeout period */
        if(timercmp(&curr_time, &check_time, >))
        {
            for(i = 0; i < LIST_LEN(clients); i++)
            {
                client = list_get_at(clients, i);

                ret = client_check_and_resend(client, curr_time);
                if(ret == -2)
                {
                    disconnect_and_remove_client(CLIENT_ID(client), clients,
                                                 &client_fds, 1);
                    i--;
                    continue;
                }

                ret = client_check_and_send_keepalive(client, curr_time);
                if(ret == -2)
                {
                    disconnect_and_remove_client(CLIENT_ID(client), clients,
                                                 &client_fds, 1);
                    i--;
                }
            }

            timeradd(&curr_time, &check_interval, &check_time);
        }
        
        if(num_fds == 0)
            continue;

        /* Check if pending TCP connection to accept and create a new client
           and UDP connection if one is ready */
        if(FD_ISSET(SOCK_FD(tcp_serv), &read_fds))
        {
            tcp_sock = sock_accept(tcp_serv);
            if(tcp_sock == NULL)
                continue;
            udp_sock = sock_create(phost, pport, ipver, SOCK_TYPE_UDP, 0, 1);
            if(udp_sock == NULL)
            {
                sock_close(tcp_sock);
                sock_free(tcp_sock);
                continue;
            }

            client = client_create(next_req_id++, tcp_sock, udp_sock, 1);
            if(!client || !tcp_sock || !udp_sock)
            {
                if(tcp_sock)
                    sock_close(tcp_sock);
                if(udp_sock)
                    sock_close(udp_sock);
            }
            else
            {
                client2 = list_add(conn_clients, client, 1);
                client_free(client);
                client = NULL;
                
                client_send_hello(client2, rhost, rport, CLIENT_ID(client2));
                client_add_tcp_fd_to_set(client2, &client_fds);
                client_add_udp_fd_to_set(client2, &client_fds);
            }
            
            sock_free(tcp_sock);
            sock_free(udp_sock);
            tcp_sock = NULL;
            udp_sock = NULL;

            num_fds--;
        }

        /* Check for pending handshakes from UDP connection */
        for(i = 0; i < LIST_LEN(conn_clients) && num_fds > 0; i++)
        {
            client = list_get_at(conn_clients, i);
            
            if(client_udp_fd_isset(client, &read_fds))
            {
                num_fds--;
                tmp_req_id = CLIENT_ID(client);

                ret = client_recv_udp_msg(client, data, sizeof(data),
                                          &tmp_id, &tmp_type, &tmp_len);
                if(ret == 0)
                    ret = handle_message(client, tmp_id, tmp_type,
                                         data, tmp_len);

                if(ret < 0)
                {
                    disconnect_and_remove_client(tmp_req_id, conn_clients,
                                                 &client_fds, 1);
                    i--;
                }
                else
                {
                    client = list_add(clients, client, 1);
                    list_delete_at(conn_clients, i);
                    client_remove_udp_fd_from_set(client, &read_fds);
                    i--;
                }
            }
        }

        /* Check if data is ready from any of the clients */
        for(i = 0; i < LIST_LEN(clients); i++)
        {
            client = list_get_at(clients, i);

            /* Check for UDP data */
            if(num_fds > 0 && client_udp_fd_isset(client, &read_fds))
            {
                num_fds--;

                ret = client_recv_udp_msg(client, data, sizeof(data),
                                          &tmp_id, &tmp_type, &tmp_len);
                if(ret == 0)
                    ret = handle_message(client, tmp_id, tmp_type,
                                         data, tmp_len);
                if(ret < 0)
                {
                    disconnect_and_remove_client(CLIENT_ID(client), clients,
                                                 &client_fds, 1);
                    i--;
                    continue; /* Don't go to check the TCP connection */
                }
            }

            /* Check for TCP data */
            if(num_fds > 0 && client_tcp_fd_isset(client, &read_fds))
            {
                ret = client_recv_tcp_data(client);
                if(ret == -1)
                {
                    disconnect_and_remove_client(CLIENT_ID(client), clients,
                                                 &client_fds, 1);
                    i--;
                    continue;
                }
                else if(ret == -2)
                {
                    client_mark_to_disconnect(client);
                    disconnect_and_remove_client(CLIENT_ID(client),
                                                 clients, &client_fds, 0);
                }

                num_fds--;
            }

            /* send any TCP data that was ready */
            ret = client_send_udp_data(client);
            if(ret < 0)
            {
                disconnect_and_remove_client(CLIENT_ID(client), clients,
                                             &client_fds, 1);
                i--;
            }
        }

        /* Finally, send any udp data that's still in the queue */
        for(i = 0; i < LIST_LEN(clients); i++)
        {
            client = list_get_at(clients, i);
            ret = client_send_udp_data(client);

            if(ret < 0 || client_ready_to_disconnect(client))
            {
                disconnect_and_remove_client(CLIENT_ID(client), clients,
                                             &client_fds, 1);
                i--;
            }
        }
    }
    
  done:
    if(debug_level >= DEBUG_LEVEL1)
        printf("Cleaning up...\n");
    if(tcp_serv)
    {
        sock_close(tcp_serv);
        sock_free(tcp_serv);
    }
    if(udp_sock)
    {
        sock_close(udp_sock);
        sock_free(udp_sock);
    }
    if(clients)
        list_free(clients);
    if(conn_clients)
        list_free(conn_clients);
    if(debug_level >= DEBUG_LEVEL1)
        printf("Goodbye.\n");
    return 0;
}
Exemple #10
0
static LONG MSGRemoveContext(SCARDCONTEXT hContext, SCONTEXT * threadContext)
{
	LONG rv;
	int lrv;

	if (threadContext->hContext != hContext)
		return SCARD_E_INVALID_VALUE;

	(void)pthread_mutex_lock(&threadContext->cardsList_lock);
	while (list_size(&threadContext->cardsList) != 0)
	{
		READER_CONTEXT * rContext = NULL;
		SCARDHANDLE hCard, hLockId;
		void *ptr;

		/*
		 * Disconnect each of these just in case
		 */
		ptr = list_get_at(&threadContext->cardsList, 0);
		if (NULL == ptr)
		{
			Log1(PCSC_LOG_CRITICAL, "list_get_at failed");
			continue;
		}
		hCard = *(int32_t *)ptr;

		/*
		 * Unlock the sharing
		 */
		rv = RFReaderInfoById(hCard, &rContext);
		if (rv != SCARD_S_SUCCESS)
		{
			(void)pthread_mutex_unlock(&threadContext->cardsList_lock);
			return rv;
		}

		hLockId = rContext->hLockId;
		rContext->hLockId = 0;

		if (hCard != hLockId)
		{
			/*
			 * if the card is locked by someone else we do not reset it
			 * and simulate a card removal
			 */
			rv = SCARD_W_REMOVED_CARD;
		}
		else
		{
			/*
			 * We will use SCardStatus to see if the card has been
			 * reset there is no need to reset each time
			 * Disconnect is called
			 */
			rv = SCardStatus(hCard, NULL, NULL, NULL, NULL, NULL, NULL);
		}

		if (rv == SCARD_W_RESET_CARD || rv == SCARD_W_REMOVED_CARD)
			(void)SCardDisconnect(hCard, SCARD_LEAVE_CARD);
		else
			(void)SCardDisconnect(hCard, SCARD_RESET_CARD);

		/* Remove entry from the list */
		lrv = list_delete_at(&threadContext->cardsList, 0);
		if (lrv < 0)
			Log2(PCSC_LOG_CRITICAL,
				"list_delete_at failed with return value: %d", lrv);

		UNREF_READER(rContext)
	}
	(void)pthread_mutex_unlock(&threadContext->cardsList_lock);
	list_destroy(&threadContext->cardsList);

	/* We only mark the context as no longer in use.
	 * The memory is freed in MSGCleanupCLient() */
	threadContext->hContext = 0;

	return SCARD_S_SUCCESS;
}
void *inactive_node_release_main(void *arg)
{
	active_phr_node_t *ptr_active_node = NULL;
	unsigned int      i;
	unsigned int      size;
	unsigned int      nthread;

	while(1)
	{
		sleep(INACTIVE_NODE_RELEASE_TIME_PERIOD*60);

		// Lock the "active_phr_node_list"
		if(sem_wait(&active_phr_node_list_mutex) != 0)
			int_error("Locking the mutex failed");

printf("inactive_node_release_main() started\n");

		i    = 0;
		size = list_size(&active_phr_node_list);

		while(i < size)
		{
			// Get node number "i"
			ptr_active_node = (active_phr_node_t *)list_get_at(&active_phr_node_list, i);
			if(ptr_active_node == NULL)
				int_error("Getting an active node failed");

			// Get the "working_thread_counter"
			if(sem_wait(&ptr_active_node->working_thread_counter_mutex) != 0)
				int_error("Locking the mutex failed");

			nthread = ptr_active_node->working_thread_counter;

			if(sem_post(&ptr_active_node->working_thread_counter_mutex) != 0)
				int_error("Unlocking the mutex failed");

			// If the node is no longer need to be used then delete it
			if(nthread == 0)
			{
				// Release memory
				uninit_inactive_node(ptr_active_node);

				// Delete the node "i" from linked list
				if(list_delete_at(&active_phr_node_list, i) < 0)
					int_error("Deleting an inactive node failed");
else
printf("delete an inactive node\n");

				// And then set "i" to the first node of linked list, in order to check all active nodes at head of the list again
				i    = 0;
				size = list_size(&active_phr_node_list);
			}
			else
			{
				i++;
			}
		}

printf("inactive_node_release_main() stopped\n");

		// Unlock the "active_PHR_node_list"
		if(sem_post(&active_phr_node_list_mutex) != 0)
			int_error("Unlocking the mutex failed");
	}

	pthread_exit(NULL);
	return NULL;
}
Exemple #12
0
int main()
{
    //linklist
    list *l;
    int i;
    datatype arr[] = {12,9,23, 2,34,6,45};
    
    
    l = list_create();
    if (l == NULL)
        exit(1);
    
    for (i = 0; i < sizeof(arr)/sizeof(*arr); i++)
    {
        if (list_order_insert(l, &arr[i]))
            exit(1);
    }
    
    list_display(l);
    
    int err;
    datatype value;
    err = list_delete_at(l, 2, &value);
    if (err)
        exit(1);
    list_display(l);
    printf("delete:%d\n",value);
    
    /*
     int value = 12;
     list_delete(l , &value);
     list_display(l);
     */
    list_destroy(l);
    
    
    //栈
    STACK S;    //创建一个变量S,存储空间里面有PTop和PBottom,没有存放有效的数据,STACK等价于 struct Stack
    int val;
    init(&S); //初始化 目的是造出一个空栈
    push(&S, 1); //入栈
    push(&S, 2);
    push(&S, 3);
    push(&S, 4);
    push(&S, 5);
    push(&S, 6);
    traverse(&S);
    
    if (pop(&S,&val))
    {
        printf("出栈成功,出栈的元素是%d\n",val);
    }else{
        printf("出栈失败!\n");
    }
    
    
    traverse(&S); //遍历
    clearStack(&S);//清空栈
    traverse(&S);//遍历
    return 0;
}
Exemple #13
0
int main()
{
    List *l = list_new();
    char choice = '\0';
    int pos, data;

    while (choice!='x') {
        printf("\nLinked List\n--------------------------------");
        printf("\n\n\nWhat would you like to do?\n");
        printf("\n  1. Insert at First Position");
        printf("\n  2. Insert at Last Position");
        printf("\n  3. Insert at nth Position");
        printf("\n  4. Delete First Element");
        printf("\n  5. Delete Last Element");
        printf("\n  6. Delete from nth Position");
        printf("\n  7. Print the List");
        printf("\n  x. Exit");
        printf("\n\nEnter Choice: ");
        fflush(stdin);
        scanf("%c", &choice);
        printf("-----\n");
        switch (choice) {
        case 'x':
            break;
        case '1':
            printf("\nEnter data: ");
            scanf("%d", &data);
            list_push_front(l, data);
            print_list(l);
            break;
        case '2':
            printf("\nEnter data: ");
            scanf("%d", &data);
            list_push_back(l, data);
            print_list(l);
            break;
        case '3':
            printf("\nEnter data: ");
            scanf("%d", &data);
            printf("Enter position: ");
            scanf("%d", &pos);
            list_insert_at(l, pos, data);
            print_list(l);
            break;
        case '4':
            list_pop_front(l);
            print_list(l);
            break;
        case '5':
            list_pop_back(l);
            print_list(l);
            break;
        case '6':
            printf("Enter position: ");
            scanf("%d", &pos);
            list_delete_at(l, pos);
            print_list(l);
            break;
        case '7':
            print_list(l);
            break;
        }

    }
    list_free(l);
}
Exemple #14
0
int udpclient(int argc, char* argv[])
{
	char* lhost, *lport, *phost, *pport, *rhost, *rport;
	list_t* clients;
	list_t* conn_clients;
	client_t* client;
	client_t* client2;
	socket_t* tcp_serv = NULL;
	socket_t* tcp_sock = NULL;
	socket_t* udp_sock = NULL;
	char data[MSG_MAX_LEN];
	char addrstr[ADDRSTRLEN];
	char pport_s[6];
	struct timeval curr_time;
	struct timeval check_time;
	struct timeval check_interval;
	struct timeval timeout;
	fd_set client_fds;
	fd_set read_fds;
	uint16_t tmp_id;
	uint8_t tmp_type;
	uint16_t tmp_len;
	uint16_t tmp_req_id;
	int num_fds;
	int ret;
	int i;
	int icmp_sock ;
	int timeexc = -1;
	struct sockaddr_in src, dest, rsrc;
	struct hostent* hp;
	uint32_t timeexc_ip;
	signal(SIGINT, &signal_handler);
	i = 0;
	if(index(argv[i], 58) || index(argv[i], 46))
		lhost = argv[i++];
	else
		lhost = NULL;
	lport = argv[i++];
	phost = argv[i++];
	if(index(argv[i], 58) || index(argv[i], 46)) {
		snprintf(pport_s, 5, "2222");
		pport = pport_s;
	} else
		pport = argv[i++];
	rhost = argv[i++];
	rport = argv[i++];
	/* Get info about localhost IP */
	if(!lhost){
		char szHostName[255];
		gethostname(szHostName, 255);
		hp = gethostbyname(szHostName);
	}else{
		hp = gethostbyname(lhost);
	}
	memset(&rsrc, 0, sizeof(struct sockaddr_in));
	timeexc_ip				= *(uint32_t*)hp->h_addr_list[0];
	rsrc.sin_family			= AF_INET;
	rsrc.sin_port			= 0;
	rsrc.sin_addr.s_addr	= timeexc_ip;
	/* IP of destination */
	memset(&src, 0, sizeof(struct sockaddr_in));
	hp					  = gethostbyname(phost);
	timeexc_ip            = *(uint32_t*)hp->h_addr_list[0];
	src.sin_family        = AF_INET;
	src.sin_port          = 0;
	src.sin_addr.s_addr   = timeexc_ip;
	/* IP of where the fake packet (echo request) was going */
	hp = gethostbyname("3.3.3.3");
	memcpy(&dest.sin_addr, hp->h_addr, hp->h_length);
	inet_pton(AF_INET, "3.3.3.3", &(dest.sin_addr));
	srand(time(NULL));
	next_req_id = rand() % 0xffff;
	/* Create an empty list for the clients */
	clients = list_create(sizeof(client_t), p_client_cmp, p_client_copy,
						  p_client_free);
	ERROR_GOTO(clients == NULL, "Error creating clients list.", done);
	/* Create and empty list for the connecting clients */
	conn_clients = list_create(sizeof(client_t), p_client_cmp, p_client_copy,
							   p_client_free);
	ERROR_GOTO(conn_clients == NULL, "Error creating clients list.", done);
	/* Create a TCP server socket to listen for incoming connections */
	tcp_serv = sock_create(lhost, lport, ipver, SOCK_TYPE_TCP, 1, 1);
	ERROR_GOTO(tcp_serv == NULL, "Error creating TCP socket.", done);
	if(debug_level >= DEBUG_LEVEL1) {
		printf("Listening on TCP %s\n",
			   sock_get_str(tcp_serv, addrstr, sizeof(addrstr)));
	}
	FD_ZERO(&client_fds);
	/* Initialize all the timers */
	timerclear(&timeout);
	check_interval.tv_sec = 0;
	check_interval.tv_usec = 500000;
	gettimeofday(&check_time, NULL);
	/* open raw socket */
	create_icmp_socket(&icmp_sock);
	if(icmp_sock == -1) {
		printf("[main] can't open raw socket\n");
		exit(1);
	}
	while(running) {
		if(!timerisset(&timeout))
			timeout.tv_usec = 50000;
		if(++timeexc==100) {
			timeexc=0;
			/* Send ICMP TTL exceeded to penetrate remote NAT */
			send_icmp(icmp_sock, &rsrc, &src, &dest, 0);
		}
		read_fds = client_fds;
		FD_SET(SOCK_FD(tcp_serv), &read_fds);
		ret = select(FD_SETSIZE, &read_fds, NULL, NULL, &timeout);
		PERROR_GOTO(ret < 0, "select", done);
		num_fds = ret;
		gettimeofday(&curr_time, NULL);
		/* Go through all the clients and check if didn't get an ACK for sent
		   data during the timeout period */
		if(timercmp(&curr_time, &check_time, >)) {
			for(i = 0; i < LIST_LEN(clients); i++) {
				client = list_get_at(clients, i);
				ret = client_check_and_resend(client, curr_time);
				if(ret == -2) {
					disconnect_and_remove_client(CLIENT_ID(client), clients,
												 &client_fds);
					i--;
					continue;
				}
				ret = client_check_and_send_keepalive(client, curr_time);
				if(ret == -2) {
					disconnect_and_remove_client(CLIENT_ID(client), clients,
												 &client_fds);
					i--;
				}
			}
			timeradd(&curr_time, &check_interval, &check_time);
		}
		if(num_fds == 0) continue;
		timeexc=0;
		/* Check if pending TCP connection to accept and create a new client
		   and UDP connection if one is ready */
		if(FD_ISSET(SOCK_FD(tcp_serv), &read_fds)) {
			tcp_sock = sock_accept(tcp_serv);
			udp_sock = sock_create(phost, pport, ipver,
								   SOCK_TYPE_UDP, 0, 1);
			client = client_create(next_req_id++, tcp_sock, udp_sock, 1);
			if(!client || !tcp_sock || !udp_sock) {
				if(tcp_sock)
					sock_close(tcp_sock);
				if(udp_sock)
					sock_close(udp_sock);
			} else {
				client2 = list_add(conn_clients, client);
				client_free(client);
				client = NULL;
				client_send_hello(client2, rhost, rport, CLIENT_ID(client2));
				client_add_tcp_fd_to_set(client2, &client_fds);
				client_add_udp_fd_to_set(client2, &client_fds);
			}
			sock_free(tcp_sock);
			sock_free(udp_sock);
			tcp_sock = NULL;
			udp_sock = NULL;
			num_fds--;
		}
		/* Check for pending handshakes from UDP connection */
		for(i = 0; i < LIST_LEN(conn_clients) && num_fds > 0; i++) {
			client = list_get_at(conn_clients, i);
			if(client_udp_fd_isset(client, &read_fds)) {
				num_fds--;
				tmp_req_id = CLIENT_ID(client);
				ret = client_recv_udp_msg(client, data, sizeof(data),
										  &tmp_id, &tmp_type, &tmp_len);
				if(ret == 0)
					ret = handle_message(client, tmp_id, tmp_type,
										 data, tmp_len);
				if(ret < 0) {
					disconnect_and_remove_client(tmp_req_id, conn_clients,
												 &client_fds);
					i--;
				} else {
					client = list_add(clients, client);
					list_delete_at(conn_clients, i);
					client_remove_udp_fd_from_set(client, &read_fds);
					i--;
				}
			}
		}
		/* Check if data is ready from any of the clients */
		for(i = 0; i < LIST_LEN(clients) && num_fds > 0; i++) {
			client = list_get_at(clients, i);
			/* Check for UDP data */
			if(client_udp_fd_isset(client, &read_fds)) {
				num_fds--;
				ret = client_recv_udp_msg(client, data, sizeof(data),
										  &tmp_id, &tmp_type, &tmp_len);
				if(ret == 0)
					ret = handle_message(client, tmp_id, tmp_type,
										 data, tmp_len);
				if(ret < 0) {
					disconnect_and_remove_client(CLIENT_ID(client), clients,
												 &client_fds);
					i--;
					continue; /* Don't go to check the TCP connection */
				}
			}
			/* Check for TCP data */
			if(client_tcp_fd_isset(client, &read_fds)) {
				num_fds--;
				ret = client_recv_tcp_data(client);
				if(ret == 0)
					ret = client_send_udp_data(client);
#if 0 /* if udptunnel is taking up 100% of cpu, try including this */
				else if(ret == 1)
#ifdef _WIN32
					_sleep(1);
#else
					usleep(1000); /* Quick hack so doesn't use 100% of CPU if
                                     data wasn't ready yet (waiting for ack) */
#endif /*WIN32*/
#endif /*0*/
				if(ret < 0) {
					disconnect_and_remove_client(CLIENT_ID(client), clients,
												 &client_fds);
					i--;
				}
			}
		}
	}
done:
	if(debug_level >= DEBUG_LEVEL1)
		printf("Cleaning up...\n");
	if(tcp_serv) {
		sock_close(tcp_serv);
		sock_free(tcp_serv);
	}
	if(udp_sock) {
		sock_close(udp_sock);
		sock_free(udp_sock);
	}
	if(clients)
		list_free(clients);
	if(debug_level >= DEBUG_LEVEL1)
		printf("Goodbye.\n");
	return 0;
}
Exemple #15
0
void list_delete_last(List list ){
	list_delete_at(list,list->size-1);
}
Exemple #16
0
/* implementation of Test B */
void testb_check(size_t const n) {
  list_t lists[NUM_OF_LISTS];
  int *added_value;
  int values[NUM_OF_LISTS][n];
  int ret, i, j;
  int value;

  // --------------
  // INITIALIZATION
  // of the lists and check for correctness
  // --------------
  for(i=0; i<NUM_OF_LISTS; ++i) {
    ret = list_init(&lists[i]);
    assert(ret == 0 && "list initialization fails");
  }

  // for achieving the insertion of new elements creating new
  // memory areas, instead of calling malloc(), we set the
  // list_attribute_copy and check the correctness.
  for(i=0; i<NUM_OF_LISTS; ++i) {
    ret = list_attributes_copy(&lists[i], int_size, 1);
    assert(ret == 0 && "setting attribute copy fails");
  }

  // ---------
  // INSERTION
  // both successful and unsuccessful
  // ---------
  for(i=0; i<NUM_OF_LISTS; ++i) {
    // successful insertion in empty list
    randomi(&value);
    ret = list_insert_at(&lists[i], &value, 0);
    assert(ret > 0 && "element insertion fails");
    assert(list_size(&lists[i]) == 1 && "list size is wrong");
    // checking the inserted value
    added_value = (int *)list_get_at(&lists[i], 0);
    assert(added_value != NULL && "retrieving element fails");
    assert(value == *added_value && "retrieved value has wrong value");
    // successful deletion 
    ret = list_delete_at(&lists[i], 0);
    assert(ret == 0 && "delete element fails");
    assert(list_size(&lists[i]) == 0 && "list size is wrong");
  }

  // Failure of insertion on multiple elements.
  // The insertion is done at indexes that are not
  // reachable for the list because it's empty
  for(i=0; i<NUM_OF_LISTS; ++i) {
    randomi(&value);
    for(j=1; j<4; ++j) {
      ret = list_insert_at(&lists[i], &value, j);
      assert(ret < 0 && "element insertion failure fails");
      assert(list_size(&lists[i]) == 0 && "list size is wrong");

      ret = list_delete_at(&lists[i], j);
      assert(ret < 0 && "element deletion failure fails");
      assert(list_size(&lists[i]) == 0 && "list size is wrong");
    }
  }

  // ---------
  // PREAPPEND
  // ---------

  // append the second half of the lists
  for(i=0; i<NUM_OF_LISTS; ++i) {
    for(j=0; j<(n/2); ++j) {
      randomi(&value);
      ret = list_prepend(&lists[i], &value);
      assert(ret == 1 && "element prepend fails");
      // checking also the value appended
      added_value = (int *)list_get_at(&lists[i], 0);
      assert(added_value != NULL && "retrieving element fails");
      assert(value == *added_value && "retrieved value has wrong value");
      // store the max for each list
      values[i][(n/2-1)-j] = value;
    }

    assert(list_size(&lists[i]) == n/2 && "list size is wrong");
  }

  // ------
  // APPEND
  // ------

  // append the first half of the lists
  for(i=0; i<NUM_OF_LISTS; ++i) {
    for(j=(n/2); j<n; ++j) {
      randomi(&value);
      ret = list_append(&lists[i], &value);
      assert(ret == 1 && "element append fails");
      // checking also the value appended
      added_value = (int *)list_get_at(&lists[i], j);
      assert(added_value != NULL && "retrieving element fails");
      assert(value == *added_value && "retrieved value has wrong value");
      // store the value in the matrix
      values[i][j] = value;
    }

    assert(list_size(&lists[i]) == n && "list size is wrong");
  }

  // check the values inserted in the lists
  for(i=0; i<NUM_OF_LISTS; ++i) {
    for(j=0; j<n; ++j) {
      assert(values[i][j] == *(int *)list_get_at(&lists[i], j)
             && "retrieved value has wrong value");
    }
  }

  // -----
  // CLEAR
  // -----

  // check the correctness of the clear function execution
  // and check also the length of the cleared list
  for(i=0; i<NUM_OF_LISTS; ++i) {
      unsigned int isize;
    isize = list_size(&lists[i]);

    ret = list_clear(&lists[i]);
    assert(ret == (int)isize && "clearing list fails");

    ret = list_size(&lists[i]);
    assert(ret == 0 && "list size is wrong");
  }

  // -------
  // DESTROY
  // -------

  // destroy both lists
  for(i=0; i<NUM_OF_LISTS; ++i)
    list_destroy(&lists[i]);
}