STDIN prevents activating of other file descriptors - c++

The following program is written to receive clients' messages and read user inputs from keyboard:
FD_ZERO(&masterfds);
FD_SET(udp_con, &masterfds);
FD_SET(0, &masterfds);
maxfds = udp_con;
while(exit == false)
{
FD_ZERO(&readfds);
readfds = masterfds;
selectFunc = select(maxfds+1, &readfds, NULL, NULL, &tv);
if(selectFunc < 0) {
message("error in select");
exit = true;
} else {
// The server has received something from a client
for(i = 0; i <= maxfds; i++) {
if(FD_ISSET(i, &readfds)) {
if(FD_ISSET(0, &readfds)) {
fgets(userInput, sizeof(userInput), stdin);
int len = strlen(userInput) - 1;
if (userInput[len] == '\n') {
userInput[len] = '\0';
}
cout<<"The user said: "<<userInput<<endl;
} else if(i == udp_con) {
cout<<"Datagram received"<<endl;
// After reading the user input, it never reaches here
}
}
}
}
}
The problem is that when I press the 'enter' key on the keyboard and the '0' file descriptor activates, the program will never activate any other file descriptor and it locks on the '0' file descriptor. How can I fix this bug?

You need to FD_CLR(0, readfds) after you test it with FD_ISSET(0, &readfds), or else it will always take that branch.
But you can simplify the algorithm by rewriting it. It's a good idea to get into the habit of formatting your code to make it easily readable.
FD_ZERO(&masterfds);
FD_SET(udp_con, &masterfds);
FD_SET(0, &masterfds);
maxfds = udp_con;
while (true) {
readfds = masterfds;
selectFunc = select(maxfds + 1, &readfds, NULL, NULL, &tv);
if (selectFunc < 0) {
message("error in select");
break;
}
// Check for input on stdin (fd 0).
if (FD_ISSET(0, &readfds)) {
fgets(userInput, sizeof(userInput), stdin);
int len = strlen(userInput) - 1;
if (userInput[len] == '\n') {
userInput[len] = '\0';
}
cout << "The user said: '" << userInput << "'" << endl;
}
// Check for input on the udp_con fd.
if (FD_ISSET(udp_con, &readfds)) {
cout << "Datagram received" << endl;
}
}

Related

Client-Server C++ alternative for _kbhit() function

My project is a Client-Server app (C++), more specifically a Group Chat.
I have built the Client and Server in 2 different solution in VS17.
Now, my problem is that when I want to send the message from one client to server-and the message to be redirected to the other clients connected- I do not want to be a blocking function, so I used _kbhit() function, but I doesn't work properly. Is there any alternative for input in the Client rather than kbhit() + getch() or cin ?
Client
char buffer[20];
int point = 0;
while (1)
{
if (!_kbhit()) {
char cur = _getch();
if (point > 19)
point = 19;
std::cout << cur;
if (cur != 13)
buffer[point++] = cur;
else {
buffer[point] = '\0';
point = 0;
}
}
BytesReceived = recv(sock, buf, 4096, 0);
if (BytesReceived != 0 && BytesReceived != -1)
{
cout << BytesReceived << endl;
cout << string(buf, 0, BytesReceived) << endl;
ZeroMemory(buf, 4096);
}
//cin >> userInput;
// non blocking input
//if(userInput.size()>0)
//int sendResult = send(sock, userInput.c_str(), userInput.size(), 0);
int sendResult = send(sock, buffer, point+1, 0);
In ncurses you could try nodelay() function to turn getch() into a non-blocking call, which returns ERR if no key-press is available.
I think that should be:
if (_kbhit () != 0) {
....
See: https://msdn.microsoft.com/en-us/library/58w7c94c.aspx

Implementing piping in c++

I'm trying to implement piping in C++. My method piped takes in an array of arguments along the line of yes | head -10 | wc. It creates pipes number of processes and changes the image of the processes to, following that example, yes, head -10, and wc. Then it creates pipes-2 pipes and redirects the input and output of the processes to the pipes.
It's not working correctly, and just prints each command separately without redirecting input/output.
#include "piped.h"
using namespace std;
void piped(char *stringList[], int pipes)
{
//stringList[] is list of arguments seperated by |
//pipes = number of arguments
pid_t processList[256];
char *curList[256];
//Create a new process for each job using fork
for(int i = 0; i < pipes; i++){
processList[i] = fork();
if (processList[i] < 0) {
cerr << "Couldn't create process\n";
exit(1);
}
}
int j = 0;
//Replace the image of each process with the appropriate commands
for(int i = 0; i < pipes; i++){
pid_t pid = processList[i];
if(pid == 0){
char *check = stringList[j];
int k = 0;
while(true){
curList[k] = check;
j+=1;
k+=1;
check = stringList[j];
if(check == NULL || strcmp(check, "|") == 0){
break;
}
}
j+=1;
curList[k] = NULL;
execvp(curList[0], curList);
cout << "Exec error!\n";
exit(1);
}
}
//Piping
//create n-2 pipes
//redirect the output of job i to the write end of pipe i
//redirect the input of job i to the read end of pipe i
for(int i = 0; i < pipes-1; i++){
int pipefd[2];
if(pipe(pipefd) < 0){
cout << "Pipe error!\n";
}
int pid1 = processList[i];
int pid2 = processList[i+1];
if(0 == pid2){
//Child 2
close(pipefd[1]);
dup2(pipefd[0],1);
close(pipefd[0]);
}
if(0 == pid1){
close(pipefd[0]);
dup2(pipefd[1], 0);
close(pipefd[1]);
}
}
//Wait for all jobs to terminate
for(int i = 0; i < pipes; i++){
pid_t pid = processList[i];
waitpid(pid, NULL, 0);
}
}

winsock recv returning 0 without shutdown from peer, different behavior from when compiling for console

I'm having an issue with winsock on windows 8.1 where recv keeps returning 0 randomly. I'm running both client and server on the same machine (thus all traffic is pointed at the loopback address) and i have breakpoints on any statement on both client and server which would shut down the sockets. But when the issue occurs the server is still operating normally, and hasn't shutdown anything, while the client has hit a breakpoint that only triggers on recv returning 0 or less.
The client keeps returning 0 from recv randomly (although always at the same point in my code) when the server VS 2013 project is set to compile as a windows program (rather than a console, in order to make it produce no window, it's supposed to be silent running). The bug doesn't seem to occur when i compile the server as a console application, as I've been debugging the program in that mode and only come across this issue when i switched compilation settings.
Is there any way to launch a console window when compiling as a windows application so i can see any debug statements?
Does winsock behave differently when compiling for the console vs compiling for a windows application?
Why would the client's recv return 0, when I've not sent a shutdown signal from the server?
My code, ask if there's any more you need:
Client
void recvLoop()
{
int recievedBytes = 1;
while (running && recievedBytes > 0)
{
WORD dataSize;
WORD dataType;
int recievedBytesA = ConnectSock.Recieve(&dataSize, sizeof(WORD));
if (recievedBytesA <= 0)
{
closing = true; //breakpoint set here
attemptKillThreads();
continue;
}
int recievedBytesB = ConnectSock.Recieve(&dataType, sizeof(WORD));
if (recievedBytesB <= 0)
{
closing = true; //breakpoint set here
attemptKillThreads();
continue;
}
unique_ptr<char[]> data(new char[dataSize]);
int recievedBytesC = ConnectSock.Recieve(data.get(), dataSize);
if (recievedBytesC <= 0)
{
closing = true; //breakpoint set here - Always triggers here
attemptKillThreads();
continue;
}
//use the received data.....
}
}
When this breaks recievedBytesA = 2, recievedBytesB = 2, recievedBytesC = 0, dataType = 0, dataSize = 0
ConnectSock is a global of type ConnectSocket. here is its Recieve()
int ConnectSocket::Recieve(void *recvbuf, int recvbuflen)
{
if (sock != INVALID_SOCKET)
{
int i = recv(sock, (char *)recvbuf, recvbuflen, 0);
if ((i == SOCKET_ERROR))
{
int err = 0;
err = WSAGetLastError();
if (err != WSAEINTR)
{
//ignore WSAEINTR as that's likely to be because of a shutdown complating a bit awkwardly
cout << "error: " << err << endl;
}
}
return i;
}
return -2;
}
Server:
void sendLoop()
{
int bytessent = 0;
QueuePack tosend;
while (running)
{
tosend = sendQueue.Dequeue();
if (tosend.packType == QueuePack::EXIT || tosend.packType == 0 || tosend.dSize == 0)
{
attemptKillThreads();
continue;
}
bytessent = Connection->SendData(&tosend.dSize, sizeof(WORD));
//cout used to see what exactly is being sent, even if it is garbage when converted to text
cout << tosend.dSize << endl;
cout << bytessent << endl;
if (bytessent <= 0)
{
attemptKillThreads();
continue;
}
bytessent = Connection->SendData(&tosend.packType, sizeof(WORD));
cout << tosend.dSize << endl;
cout << bytessent << endl;
if (bytessent <= 0)
{
attemptKillThreads();
continue;
}
bytessent = Connection->SendData(tosend.bufferPtr(), tosend.dSize);
cout << tosend.bufferPtr() << endl;
cout << bytessent << endl;
if (bytessent <= 0)
{
attemptKillThreads();
}
}
if (Connection->shutdownSock(SD_SEND) == SOCKET_ERROR)
{
Connection->closeSock();
}
}
SendData is literally a wrapper for send that uses a reinterpret_cast
int SendData(void * writeBuffer, int bufferSize)
{
return send(SocketManager.clientSocket, reinterpret_cast<char *>(writeBuffer), bufferSize, 0);
}
sendQueue is a Bounded blocking queue that holds QueuePacks
QueuePacks are used to transfer data, it's size and what kind of data it is between threads. both Client and server use this as it allows me to make sure data gets to the right thread on the client
Queuepack has 2 public variables packType and dSize of type WORD.
QueuePack::QueuePack() : packType(UND), dSize(0)
{
int h = 0; //debug statement to break on - never gets hit after initial collection construction occurs
}
QueuePack::QueuePack(const WORD type, WORD size, char * data) : packType(type), dSize(size)
{
//debug test and statement to break on
if (size == 0 || type == 0)
{
int h = 0; //breakpoint - never gets hit
}
dSize = (dSize < 1 ? 1 : dSize);
_buffer = make_unique<char[]>(dSize);
memcpy(_buffer.get(), data, dSize);
}
QueuePack::QueuePack(QueuePack &other) : packType(other.packType), dSize(other.dSize)
{
//debug test and statement to break on
if (other.dSize == 0 || other.packType == 0)
{
int h = 0; //breakpoint - never gets hit
}
if (&other == this)
{
return;
}
_buffer = make_unique<char[]>(dSize);
other.buffer(_buffer.get());
}
QueuePack QueuePack::operator= (QueuePack &other)
{
// check for self-assignment
if (&other == this)
{
return *this;
}
// reuse storage when possible
if (dSize != other.dSize)
{
_buffer.reset(new char[other.dSize]);
dSize = other.dSize;
}
packType = other.packType;
other.buffer(_buffer.get());
return *this;
}
QueuePack::~QueuePack()
{
}
HRESULT QueuePack::buffer(void* container)
{
try
{
memcpy(container, _buffer.get(), dSize);
}
catch (...)
{
return E_FAIL;
}
return S_OK;
}
char * QueuePack::bufferPtr()
{
return _buffer.get();
}
When this breaks recievedBytesA = 2, recievedBytesB = 2, recievedBytesC = 0, dataType = 0, dataSize = 0
You are calling ConnectSock.Recieve() when dataSize is 0. There is nothing to read, so Receive() reports that 0 bytes were read.
You need to add a check for that condition:
unique_ptr<char[]> data(new char[dataSize]);
if (dataSize != 0) // <-- add this
{
int recievedBytesC = ConnectSock.Recieve(data.get(), dataSize);
if (recievedBytesC <= 0)
{
closing = true;
attemptKillThreads();
continue;
}
}
Your code is also assuming that Recieve() reads all bytes that are requested, it is not handling the possibility that recv() may return fewer bytes. So you need to make Recieve() call recv() in a loop to guarantee that everything requested is actually read:
int ConnectSocket::Recieve(void *recvbuf, int recvbuflen)
{
if (sock == INVALID_SOCKET)
return -2;
char *buf = static_cast<char *>(recvbuf);
int total = 0;
while (recvbuflen > 0)
{
int i = recv(sock, buf, recvbuflen, 0);
if (i == SOCKET_ERROR)
{
int err = WSAGetLastError();
if (err != WSAEINTR)
{
//ignore WSAEINTR as that's likely to be because of a shutdown complating a bit awkwardly
cout << "error: " << err << endl;
}
return -1;
}
if (i == 0)
{
cout << "disconnected" << endl;
return 0;
}
buf += i;
recvbuflen -= i;
total += i;
}
return total;
}
Same with SendData(), as send() may return fewer bytes than requested:
int SendData(void * writeBuffer, int bufferSize)
{
if (SocketManager.clientSocket == INVALID_SOCKET)
return -2;
char *buf = static_cast<char *>(writeBuffer);
int total = 0;
while (bufferSize > 0)
{
int i = send(SocketManager.clientSocket, buf, bufferSize, 0);
if (i == SOCKET_ERROR)
{
int err = WSAGetLastError();
if (err != WSAEINTR)
{
//ignore WSAEINTR as that's likely to be because of a shutdown complating a bit awkwardly
cout << "error: " << err << endl;
}
return -1;
}
buf += i;
bufferSize -= i;
total += i;
}
return total;
}

What is causing a C++ Buffer Overrun error with fprintf?

I am trying to set up a Client, Router, Server in C++ with sockets and UDP using GoBackN windowing. I'm not sure why I'm getting a buffer overrun error in Client::write_log(), at the fprintf() line.
Main run() function
void Client::run()
{
srand ( time(NULL) );
//socket data types
SOCKET client_socket; // Client socket
SOCKADDR_IN sa_out; // fill with server info, IP, port
char buffer[RAWBUF_SIZE]; // Buffer
WSADATA wsadata; // WSA connection
char router[11]; // Host data
char cusername[128], filename[128], direction[3]; // Other header data
DWORD dwusername = sizeof(cusername); // Retains the size of the username
char trace_data[128];
FILE* logfile = fopen("client.log", "w");
try
{
if (WSAStartup(0x0202,&wsadata)!=0)
{
throw "Error in starting WSAStartup";
}
else
{
/* Display the wsadata structure */
cout<< endl
<< "wsadata.wVersion " << wsadata.wVersion << endl
<< "wsadata.wHighVersion " << wsadata.wHighVersion << endl
<< "wsadata.szDescription " << wsadata.szDescription << endl
<< "wsadata.szSystemStatus " << wsadata.szSystemStatus << endl
<< "wsadata.iMaxSockets " << wsadata.iMaxSockets << endl
<< "wsadata.iMaxUdpDg " << wsadata.iMaxUdpDg << endl << endl;
}
client_socket = open_port(PEER_PORT2);
prompt("Enter the router hostname: ",router);
sa_out = prepare_peer_connection(router, ROUTER_PORT2);
prompt("Enter a filename: ",filename); // Retrieve a filename from the client
prompt("Direction of transfer [get|put]: ", direction); // Retrieve a transfer direction
// Make sure the direction is one of get or put
if(!strcmp(direction,GET) || !strcmp(direction,PUT))
{
// Retrieve the local user name
GetUserName(cusername, &dwusername);
int selected = rand() % 256;
int received, verify;
int client_num = 0; // Client packet number
int server_num = 0; // Server packet number
int progress = 0;
int rcv;
cout << "Starting packet ID negotiation..." << endl;
while(1)
{
// Send a random number to the server
if(progress < 1)
{
memset(buffer, 0, sizeof(buffer));
sprintf(buffer,"RAND %d",selected);
cout << "Sending " << buffer << endl;
if((rcv = send_safe(client_socket, sa_out, buffer, RAWBUF_SIZE, 200)) == 201)
{
progress = 1;
}
else if(rcv != 200)
{
continue;
}
// Finally wait for a response from the server with the number
if(recv_safe(client_socket, sa_out, buffer, RAWBUF_SIZE, 100) == 100)
{
cout << "Received " << buffer << endl;
sscanf(buffer,"RAND %d %d",&verify,&received);
}
else
continue;
progress = 1;
}
// Send acknowledgement to the server along with our random number
memset(buffer, 0, sizeof(buffer));
sprintf(buffer, "RAND %d", received);
cout << "Sending " << buffer << endl;
if(send_safe(client_socket, sa_out, buffer, RAWBUF_SIZE, 201) != 201)
{
progress = 0;
continue;
}
break;
}
client_num = selected % WINDOW_SIZE + 1;
server_num = received % WINDOW_SIZE + 1;
cout << "Negotiated server start " << server_num << " and client start " << client_num << endl;
sprintf(trace_data, "Negotiated srv %d and cli %d", server_num, client_num);
write_log(logfile, cusername, trace_data);
// Send client headers
sprintf(buffer, HEADER, cusername, direction, filename);
while((rcv = send_safe(client_socket,sa_out,buffer,RAWBUF_SIZE,777)) != 777)
{
if(rcv == 101)
break;
}
// Perform a get request
if(!strcmp(direction,GET))
{
get(client_socket, sa_out, cusername, filename, client_num, server_num, logfile);
}
else if(!strcmp(direction,PUT))
{
put(client_socket, sa_out, cusername, filename, client_num, server_num, logfile);
}
}
else
{
throw "The method you requested does not exist, use get or put";
}
}
catch (const char *str)
{
cerr << str << WSAGetLastError() << endl;
}
//close the client socket and clean up
fclose(logfile);
closesocket(client_socket);
WSACleanup();
}
PUT() CODE
void Client::put(SOCKET s, SOCKADDR_IN sa, char * username, char* filename, int client_num, int server_num, FILE* logfile)
{
char window[FRAME_SIZE * WINDOW_SIZE]; // data retention window
char buffer[FRAME_SIZE]; // send buffer
int filesize;
int size = 0, sent = 0; // Trace variables
char tracebuf[128];
FILE* send_file;
fopen_s(&send_file, filename, "rb");
if(send_file != NULL)
{
// open the file
// Determines the file size
fseek(send_file, 0L, SEEK_END);
filesize = ftell(send_file);
fseek(send_file, 0L, SEEK_SET);
//write filesize to logfile
sprintf(tracebuf, "Filesize %d", filesize);
write_log(logfile, username, tracebuf);
//add file size to buffer
strncpy_s(buffer, "SIZ", 3);
memcpy(buffer + (3 * sizeof(char)), &filesize, sizeof(int));
//if filesize was sent to server successfully
if(send_safe(s,sa,buffer,FRAME_SIZE,101) == 101)
{
cout << "Sent filesize, starting transfer..." << endl;
//reset buffer
memset(buffer, 0, sizeof(buffer));
int count = 0;
int offset = 0;
int frames_outstanding = 0; //for frames not ACKED
int next = 0;
bool resend = false;
int packet_id;
int pid_max = WINDOW_SIZE + 1;
// Start sending the file
while (1)
{
// If the acks mismatch with the current send offset and there are frames not ACKED, this has to be a resend
if(next != offset && frames_outstanding > 0)
resend = true;
// Send as many frames as available for the given window size
while((!feof(send_file) && frames_outstanding < WINDOW_SIZE) || resend)
{
if(next == offset)
resend = false;
if(!resend)
{
if(feof(send_file))
break;
fread(buffer,1,FRAME_SIZE,send_file); // Read the next block of data
memcpy(window + (offset * FRAME_SIZE), buffer, FRAME_SIZE); // Store the data in the local window
//memcpy(window, buffer, FRAME_SIZE); // Store the data in the local window
send_packet(s, sa, buffer, FRAME_SIZE, offset); // Send the packet to peer
offset = (offset + 1) % pid_max; // Update the offset
frames_outstanding++;
}
else
{
// Resend by copying the data from the window
memcpy(buffer, window + (next * FRAME_SIZE), FRAME_SIZE);
send_packet(s, sa, buffer, FRAME_SIZE, next);
//log
sprintf(tracebuf, "Resending packet %d", next);
write_log(logfile, username, tracebuf);
next = (next + 1) % pid_max;
}
}
// Receive ACKs before continuing sending
//while the # of unacked frames are greater than 0
while(frames_outstanding > 0)
{
//if packet id < 0
if((packet_id = recv_packet(s,sa,buffer,FRAME_SIZE,next)) < 0)
{
if(count < filesize)
resend = true;
break;
}
// Receive acknowledgment from the client
if(!strncmp(buffer,"NAK", 3))
{
if(packet_id >= 0)
next = packet_id; // Set the next packet to the packet id
break;
}
else if(!strncmp(buffer,"ALL", 3))
{
frames_outstanding = 0;
break;
}
//log
sprintf(tracebuf, "Sent %d bytes", count);
write_log(logfile, username, tracebuf);
memset(buffer, 0, sizeof(buffer)); // Zero the buffer
next = (next + 1) % pid_max; // Update the next frame tracker
frames_outstanding--; // Another frame has been acked
}
if(feof(send_file) && frames_outstanding == 0)
break; // Break when done reading the file and all frames are acked
}
cout << "File transfer completed" << endl;
fclose(send_file);
}
else
{
fclose(send_file);
return put(s,sa,username,filename, client_num, server_num, logfile);
}
}
}
WRITE_LOG() CODE
void Client::write_log(FILE* logfile, char* username, char* message)
{
fprintf(logfile, "%s > %s\n", username, message);
memset(message, 0, sizeof(message));
}
Not at all sure what you actually intdended to do here:
memset(message, 0, sizeof(message));
but it's likely not doing what you intended. sizeof(message) is either 4 or, more likely, 8 on a modern system. So you are writing 8 zeros to message. Which may not be 8 bytes long in the first place.
Possibly you want:
memset(message, 0, strlen(message));
or:
message[0] = 0;
(Which will do set the string to "empty", but not fill the entire thing with zeros).

Tracking BufferOverrun in Socket Server

I am having a lot of trouble tracking down where I am getting a BufferOverrun in the code below when I send it socket data from my flash/as3 telnet client. I am mostly looking to find more memory leaks and such, so in addition to this problem, is there an easier way to check for buffer overflow/overrun than manual debugging?
/*
MTSocketServer
--------------
The purpose of this application is to have a client application that can connect to this server.
This server should be able to parse messages from connected users and to send them to other users.
*/
// Headers and Namespace
#include "stdafx.h"
#include "MTSocketServer.h"
using namespace std;
// Constants
#define BUFFERSIZE 1000
#define PORT 20248
// Global Variables
SOCKET server;
struct Client_Data
{
SOCKET client_socket;
string user_id;
};
list<Client_Data> clients;
// Method Prototypes
UINT Server_Thread(LPVOID pParams);
UINT Client_Thread(LPVOID pParams);
string Recv_String(SOCKET listener);
void Send_String(const char* message, SOCKET sender);
bool Identity_Exists(string id);
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
AfxBeginThread(Server_Thread, NULL);
while(_getch() != 27);
closesocket(server);
WSACleanup();
return 0;
}
UINT Server_Thread(LPVOID pParams)
{
// Spawn Server Thread
cout << "Main thread spawned, press ESC at any time to exit.\r\n";
WSADATA wsa_data;
SOCKADDR_IN server_location;
if (int wsa_return_val = WSAStartup(0x101, &wsa_data) != 0)
{
cout << "Incorrect version of 'Ws2_32.dll'.\r\n";
cout << "Client thread de-initialized.\r\n";
AfxEndThread(0, true);
return 1;
}
server_location.sin_family = AF_INET;
server_location.sin_addr.s_addr = INADDR_ANY;
server_location.sin_port = htons(20248);
server = socket(AF_INET, SOCK_STREAM, NULL);
if (server == INVALID_SOCKET)
{
cout << "Socket creation error.\r\n";
cout << "Client thread de-initialized.\r\n";
AfxEndThread(0, true);
return 1;
}
if (bind(server, (SOCKADDR*)&server_location, sizeof(server_location)) != 0)
{
cout << "Socket binding error.\r\n";
cout << "Client thread de-initialized.\r\n";
AfxEndThread(0, true);
return 1;
}
if (listen(server, 10) != 0)
{
cout << "Socket listening error.\r\n";
cout << "Client thread de-initialized.\r\n";
AfxEndThread(0, true);
return 1;
}
SOCKET client;
SOCKADDR_IN client_location;
int len_of_client = sizeof(client_location);
bool abort = false;
while(abort == false)
{
client = accept(server, (SOCKADDR*)&client_location, &len_of_client);
// Spawn Client Thread
cout << "Connection from " << inet_ntoa(client_location.sin_addr) << ". Client thread spawned.\r\n";
AfxBeginThread(Client_Thread, (LPVOID)client);
}
// De-Initialize Server Thread
cout << "Server thread de-initialized.\r\n";
AfxEndThread(0, true);
return 0;
}
UINT Client_Thread(LPVOID pParams)
{
SOCKET client = (SOCKET)pParams;
string client_id = "";
// Check if a client with the same ID is on already
send(client, "ID_ME", 6, 0);
client_id = Recv_String(client);
if (Identity_Exists(client_id))
{
Send_String("That ID is already taken. Please try another.", client);
} else
{
cout << "Created ID " << client_id << " successfully\r\n";
Send_String("Type 'send' to send a message, 'quit' to exit.", client);
Client_Data this_client;
this_client.user_id = client_id;
this_client.client_socket = client;
clients.push_back(this_client);
bool is_con = true;
while(is_con)
{
string response = Recv_String(client);
if (response == "send")
{
Send_String("What username to send to?", client);
string to_id = Recv_String(client);
if (Identity_Exists(to_id))
{
Send_String("Type your message below: ", client);
string temp = Recv_String(client) + "\n\0";
const char* message = temp.c_str();
for (list<Client_Data>::iterator iterator = clients.begin(), end = clients.end(); iterator != end; ++iterator)
{
if (to_id == iterator->user_id)
{
SOCKET temp = iterator->client_socket;
cout << temp;
Send_String(message, temp);
}
}
} else
{
Send_String("Invalid username specified", client);
}
}
else if (response == "quit")
{
Send_String("Quit Command Issued", client);
break;
}
else
{
Send_String("Invalid Command Issued", client);
}
}
}
// De-Initialize Client Thread
closesocket(client);
cout << "Client thread de-initialized.\r\n";
AfxEndThread(0, true);
return 0;
}
// Function to parse full string values since they are often recieved one at a time
string Recv_String(SOCKET listener)
{
char buffer[BUFFERSIZE];
string temp;
int numofbytes = 0;
while (true)
{
int num = recv(listener, buffer, BUFFERSIZE, 0);
numofbytes++;
buffer[num] = '\0';
if (buffer[num-1] == '\n')
break;
if(numofbytes >= BUFFERSIZE-1)
break;
temp += buffer;
strcpy(buffer, "");
}
return temp;
}
void Send_String(const char* message, SOCKET sender)
{
char buffer[BUFFERSIZE];
strcpy(buffer, message);
size_t size = strlen(message);
int sendtest = send(sender, buffer, size, 0);
strcpy(buffer, "");
}
bool Identity_Exists(string id)
{
for (list<Client_Data>::iterator iterator = clients.begin(), end = clients.end(); iterator != end; ++iterator)
{
if (id == iterator->user_id)
{
return true;
}
}
return false;
}
buffer[num] = '\0'; writes one beyond the buffer if num happens to be equal to BUFFERSIZE. It writes one below the buffer if num happens to be -1.
if (buffer[num-1] == '\n') though not a buffer overrun, is also wrong. The \n can be anywhere (from 0 to n-1) in the buffer.