Home > Mobile >  Chat room using socket programming with select() - winsock - C
Chat room using socket programming with select() - winsock - C

Time:11-29

I try to create a server-client application where the server provides a chat service to all clients that connect to the server. The server and client use cryptographic algorithms and protocols to secure data transmitted over the network. I can't figure out why the chat code isn't working properly.

I use the select() function to operate multiple drawers at the same time. If I use only a piece of code when multiple clients connect to the server and send data to the server and it gets everything, that's fine, but as soon as I try to write a piece of code that would be a chat function, even if multiple clients connect, the server serves only the last connected client. I use a link dynamic list to store the necessary client information, and when I can list currently connected clients, if I don't use part of the chat room code, all clients I connect will be accepted, and as soon as I use the chat room code part, only the last connected client.

This is code for server:

 while(1) {
        fd_set reads;
        reads = master;

        //The select function determines the status of one or more sockets, waiting if necessary, to perform synchronous I/O
        if (select(max_socket 1, &reads, 0, 0, 0) < 0) {
            fprintf(stderr, "select() failed. (%d)\n", GETSOCKETERRNO());
            return 1;
        }

        SOCKET i;
        //Loop through each possible socket 
        for(i = 1; i <= max_socket;   i) {
            if (FD_ISSET(i, &reads)) {

                //If socket_listen, create TCP connection of accept() function
                 if (i == socket_listen) {
                    //
                    client_info = create_client();
                    client_info->client_len = sizeof(client_info->client_address);
                    client_info->sock_fd = accept(socket_listen,
                            (struct sockaddr*) &client_info->client_address,
                            &client_info->client_len);

                    if (!ISVALIDSOCKET(client_info->sock_fd)) {
                        fprintf(stderr, "accept() failed. (%d)\n",
                                GETSOCKETERRNO());
                        return 1;
                    }

                    FD_SET(client_info->sock_fd, &master);
                    if (client_info->sock_fd > max_socket)
                        max_socket = client_info->sock_fd;
                
                    //Prints the client address using the getnameinfo() function
                    getnameinfo((struct sockaddr*)&client_info->client_address,
                            client_info->client_len,
                            client_info->address_buffer, 
                            100, 0, 0,
                            NI_NUMERICHOST);
                    printf("New connection %s\n", client_info->address_buffer);
                    

                    printf("\nWaiting for succeses Salt handshake...\n");

                    //Salt handshake 
                    salt_hndshk(client_info);

                    //Insert client to the list of clients
                    insert(p_list, client_info);

                    //List of clients connected to the server with a successful Salt handshake       
                    listing_clients(p_list);
      
                } else {
                    
                    memset(rx_buffer, 0, sizeof(hndsk_buffer));

                    //Search for clients by sockets and the is in the list
                    //the server decrypts the data from the client

                    CLIENT *client_decrypt = create_client();

                    client_decrypt = search_client(p_list, i);

                    ret_msg = salt_read_begin_pom(&client_decrypt->channel, rx_buffer, 
                                       sizeof(rx_buffer), &msg_in, pom_buffer, &decrypt_size);
                       
                    //Check if SALT_ERROR from message
                   if(ret_msg == SALT_ERROR) {
                        printf("\tThe client disconnects from the server.\n");
                        printf("\tThe server has closed him socket\n");
                        realese_client(p_list, client_decrypt);
                        FD_CLR(i, &master);
                        CLOSESOCKET(i);
                        continue;
                    }

                    //Freeing client memory
                    free(client_decrypt);
                }

            //Chat room service 
                
                SOCKET j;
                    for(j = 1; j <= max_socket;   j){
                        if(FD_ISSET(j, &master)){
                            if (j == socket_listen || j == i){
                                continue;

                            } else {
                                memset(rx_buffer, 0, sizeof(hndsk_buffer));

                                //Search for clients by sockets and the is in the list
                                CLIENT *client_encrypt = create_client();
                                client_encrypt = search_client(p_list, j);

                                //Prepare data before send
                                salt_write_begin(tx_buffer, sizeof(tx_buffer), &msg_out);

                                //Copy clear text message to be encrypted to next encrypted package
                                salt_write_next(&msg_out, (uint8_t * )pom_buffer, decrypt_size);

                                //Wrapping, creating encrpted messages
                                salt_write_execute(&client_encrypt->channel, &msg_out, false);

                                //Freeing client memory
                                free(client_encrypt);
                            }
                            
                        } //if(FD_ISSET(j, &master)
                    } //for(j = 1; j <= max_socket;   j)
                   
            //Finish chat room service

            } //if FD_ISSET
        } //for i to max_socket
    }

There is a link to the application on this link:

tcp_salt

CodePudding user response:

You have logic errors in both of your inner for loops.

When reading from/writing to a non-listening client socket, DO NOT call create_client() at all, you are creating memory leaks with it:

CLIENT *client_decrypt = create_client();
client_decrypt = search_client(...); // <-- LEAK!
CLIENT *client_encrypt = create_client();
client_encrypt = search_client(...); // <-- LEAK!

Call create_client() ONLY when you accept() a new client. And DO NOT call free() on any CLIENT you read from/write to. Call that ONLY when you are removing a CLIENT from p_list.

You are corrupting your p_list on each loop iteration, leaving it with a bunch of dangling pointers to invalid CLIENTs.

Also, your writing code is not checking for errors to disconnect and remove dead clients.

Try something more like this:

while(1) {
    fd_set reads;
    reads = master;

    //The select function determines the status of one or more sockets, waiting if necessary, to perform synchronous I/O
    if (select(max_socket 1, &reads, 0, 0, 0) < 0) {
        fprintf(stderr, "select() failed. (%d)\n", GETSOCKETERRNO());
        return 1;
    }

    //Loop through each possible socket 
    for(SOCKET i = 1; i <= max_socket;   i) {
        if (!FD_ISSET(i, &master)) {
            continue;
        }
        if (FD_ISSET(i, &reads)) {

            //If socket_listen, create TCP connection of accept() function
            if (i == socket_listen) {
                //
                CLIENT *client_info = create_client();
                client_info->client_len = sizeof(client_info->client_address);
                client_info->sock_fd = accept(socket_listen,
                        (struct sockaddr*) &client_info->client_address,
                        &client_info->client_len);

                if (!ISVALIDSOCKET(client_info->sock_fd)) {
                    fprintf(stderr, "accept() failed. (%d)\n",
                            GETSOCKETERRNO());
                    return 1;
                }

                FD_SET(client_info->sock_fd, &master);
                if (client_info->sock_fd > max_socket)
                    max_socket = client_info->sock_fd;
            
                //Prints the client address using the getnameinfo() function
                getnameinfo((struct sockaddr*)&client_info->client_address,
                        client_info->client_len,
                        client_info->address_buffer, 
                        100, 0, 0,
                        NI_NUMERICHOST);
                printf("New connection %s\n", client_info->address_buffer);

                printf("\nWaiting for succesful Salt handshake...\n");

                //Salt handshake 
                salt_hndshk(client_info);

                //Insert client to the list of clients
                insert(p_list, client_info);

                //List of clients connected to the server with a successful Salt handshake       
                listing_clients(p_list);

                continue;
            }
                
            memset(rx_buffer, 0, sizeof(rx_buffer));

            //Search for clients by sockets and the is in the list
            //the server decrypts the data from the client

            CLIENT *client_decrypt = search_client(p_list, i);

            ret_msg = salt_read_begin_pom(&client_decrypt->channel, rx_buffer, 
                                   sizeof(rx_buffer), &msg_in, pom_buffer, &decrypt_size);
                   
            //Check if SALT_ERROR from message
            if (ret_msg == SALT_ERROR) {
                printf("\tThe client disconnects from the server.\n");
                printf("\tThe server has closed his socket\n");
                release_client(p_list, client_decrypt);
                free(client_decrypt);
                CLOSESOCKET(i);
                FD_CLR(i, &master);
                continue;
            }

            //Chat room service 
            for(SOCKET j = 1; j <= max_socket;   j){
                if (!FD_ISSET(j, &master) || j == socket_listen || j == i){
                    continue;
                }

                memset(rx_buffer, 0, sizeof(rx_buffer));

                //Search for clients by sockets and the is in the list
                CLIENT *client_encrypt = search_client(p_list, j);

                //Prepare data before send
                ret_msg = salt_write_begin(tx_buffer, sizeof(tx_buffer), &msg_out);

                //Copy clear text message to be encrypted to next encrypted package
                if (ret_msg != SALT_ERROR)
                    ret_msg = salt_write_next(&msg_out, (uint8_t * )pom_buffer, decrypt_size);

                //Wrapping, creating encrpted messages
                if (ret_msg != SALT_ERROR
                    ret_msg = salt_write_execute(&client_encrypt->channel, &msg_out, false);

                //Check if SALT_ERROR from message
                if (ret_msg == SALT_ERROR) {
                    printf("\tThe client disconnects from the server.\n");
                    printf("\tThe server has closed his socket\n");
                    release_client(p_list, client_decrypt);
                    free(client_decrypt);
                    CLOSESOCKET(i);
                    FD_CLR(i, &master);
                    continue;
                }
            }
        } 
    }
}
  • Related