while loop for a game in C? - c

I have a word guessing game which I needs to repeat until the user types Q:. Generally, the answer is in a format A: answer. The game's using sockets!
Instead of while(1), I tried using while(buffer[0]!='Q') but that does not seem to work.
How do I keep making the client play the game?
Additionally, I also need to tell the user how many games he passed correctly?
while (1)
{
FD_ZERO(&readfds);
FD_SET(server_fd, &readfds);
int max_fd = server_fd;
for (int i = 0; i < NUMCLIENT; i++)
{
file_descriptor = client_sockets[i];
if (file_descriptor > 0)
{
FD_SET(file_descriptor, &readfds);
}
if (file_descriptor > max_fd)
{
max_fd = file_descriptor;
}
}
int return_value = select(max_fd + 1, &readfds, NULL, NULL, NULL);
if (return_value == -1)
{
printf("Select Error\n");
}
if (FD_ISSET(server_fd, &readfds))
{
if ((new_socket = accept(server_fd, (struct sockaddr *) &address,
(socklen_t*) &addrlen)) < 0)
{
perror("accept");
}
send(new_socket, greetings[0], strlen(greetings[0]), 0);
send(new_socket, greetings[1], strlen(greetings[1]), 0);
for (int i = 0; i < NUMCLIENT; i++)
{
if (client_sockets[i] == 0)
{
my_fortune(i);
client_sockets[i] = new_socket;
send(new_socket, client_challenges->question, strlen(client_challenges->question), 0);
break;
}
}
}
for (int i = 0; i < NUMCLIENT; i++)
{
file_descriptor = client_sockets[i];
if (file_descriptor == 0)
{
continue;
}
if (FD_ISSET(file_descriptor, &readfds))
{
memset(buffer, 0, 1024);
valread = read(file_descriptor, buffer, 1024);
if (valread == 0)
{
close(file_descriptor);
client_sockets[i] = 0;
continue;
}
printf("%s\n", buffer);
if (buffer[0] == 'A')
{
if (strlen(client_challenges->answer) == (strlen(buffer) - 4))
{
char store[100];
for (int i = 1; i <= strlen(client_challenges->answer); i++)
{
store[i - 1] = buffer[2 + i];
}
store[strcspn(store, "\r\n")] = 0;
if (strcmp(store, client_challenges->answer) == 0)
{
send(file_descriptor, correct, strlen(correct), 0);
//printf("O: Congratulation - challenge passed!\n");
}
else
{
send(file_descriptor, wrong, strlen(wrong), 0);
send(file_descriptor, client_challenges->answer, strlen(client_challenges->answer), 0);
}
//printf("Wrong guess - expected: %s",client_challenges->answer);}
}
else
{
send(file_descriptor, wrong, strlen(wrong), 0);
send(file_descriptor, client_challenges->answer, strlen(client_challenges->answer), 0);
}
//{printf("Wrong guess - expected: %s",client_challenges->answer);}
}
else if (buffer[0] == 'Q')
{
send(file_descriptor, ending, strlen(ending), 0);
exit(1);
}
else
{
send(file_descriptor, error, strlen(error), 0);
exit(1);
}
}
}
}

If there will only be 1 client, you can simply do
// Actual function to start the game
int play() {
int run = 1;
while (run) {
// run the game
// if game over,
run = 0;
}
return 0; // indicate the game ends gracefully
}
int main(int argc, char** argv) {
int run = 1;
int playAgain = 0;
while (run) {
if (play()) {
// Error: the game ends ungracefully
}
// Prompt for play again
if (!playAgain) {
run = 0;
}
}
// Bye
}
The reason is that the variable run is used to control the game flow. If the user quits or something went wrong, you can set run to 0 and the game will stop running.
If there are going to be multiple clients, you might want to have a look at pthread. Every time you receive a new connection, you can create a new thread with pthread_create and set the play function as start_routine and the fd as the argument. For example, you can try
int MAX_CLIENT = 5;
struct pthread_args {
int fd;
};
void* play(void* arg) {
struct pthread_args* args = (struct pthread_args*)arg;
int fd = args->fd;
// Start the game
}
int main(int argc, char** argv) {
pthread_t pth[MAX_CLIENT];
struct pthread_args pth_args;
int new_fd;
int i = 0;
while(1) { // The server continuously receive connections
// Accept connections
new_fd = accept(/*...*/)
if (new_fd < 0) {
// Error: accepting new connection
}
pth_args.fd = new_fd;
int r = pthread_create(&pth[i], NULL, play, &pth_args);
if (!r) {
// Error: creating thread
}
++i;
}
}
PS: You may want to have a look at pthread_detach as well.
Instead of while(1), I tried using while(buffer[0]!='Q') but that does not seem to work.
The reason while(buffer[0] == 'Q') doesn't work is because by the time the while check for the condition, the buffer (assuming it was declared outside of the while loop) might not be the same buffer anymore because you are looping over all clients and save the buffers from clients to the same buffer variable. So if there are 2 clients and the first client says 'Q' and the second client says 'A', the while sees buffer[0] as 'A' instead of 'Q' and hence continuing the game.
Also, I don't think exit(1) in else if (buffer[0] == 'Q') is a good idea. It kills the server and all clients will be forced to quit the game. Just remove the particular client from the client_sockets array.
:) Hope it helps

Related

Tcp server client Connection issue in C

so i am trying to implement a TCP server-client(s) using server ip and port. Connection between the two was established, with the use of threads.
Now i'm expecting the program to: for everytime a client joins or leave, if there are other clients present, then it will print "Client has joined/left the server" on these other clients screen. However if it is the only client present, it won't say the join or leave stuff and will proceed with asking user an input of what does the client wants to do.(user input is what the client has typed after this arrow ">")
What it is actually doing: When the first client has successfully joined the server, the command line remains empty, the ">" does not appear and even if you can type, no input is recorded by the client. As you connect a second client, that's when the arrow appears on the first client only and you can start inputting.
I would like to know which part i should edit to make my client when alone to start taking input without needing another client to join before doing so + When there are multiple clients and a client joins/leave, on the other clients' screen is printed "Client has joined/left the server"
Server code
void client_queuing(client_thr *cl){
pthread_mutex_lock(&cli_mutex);
for(int i=0; i < MAXLINE; ++i){
if(!cli[i]){
cli[i] = cl;
break;
}
}
pthread_mutex_unlock(&cli_mutex);
}
void client_removal(int uid){
pthread_mutex_lock(&cli_mutex);
for(int i=0; i < MAXLINE; ++i){
if(cli[i]){
if(cli[i]->uid == uid){
cli[i] = NULL;
break;
}
}
}
pthread_mutex_unlock(&cli_mutex);
}
void convey_msg(char *st, int uid){
pthread_mutex_lock(&cli_mutex);
for(int i=0; i<MAXLINE; ++i){
if(cli[i]){
if(cli[i]->uid != uid){
if(write(cli[i]->sockfd, st, strlen(st)) < 0){
perror("ERROR: Failure to write to descriptor");
break;
}
}
}
}
pthread_mutex_unlock(&cli_mutex);
}
void *man_cli(void *arg){
char buffer_o[SIZEOF_BUFFER];
char nickname[20];
int leave_flag = 0;
num_client++;
client_thr *clice = (client_thr *)arg;
// nickname
if(recv(clice->sockfd, nickname, 20, 0) <= 0 || strlen(nickname) >= 19){
printf("Name not Entered.\n");
leave_flag = 1;
}
else{
strcpy(cli->nickname, nickname);
sprintf(buffer_o, "A new user %s has joined SNC!\n", cli->nickname);
printf("%s", buffer_o);
convey_msg(buffer_o, clice->uid);
}
bzero(buffer_o, SIZEOF_BUFFER);
while(1){
if (leave_flag) {
break;
}
int receive = recv(clice->sockfd, buffer_o, SIZEOF_BUFFER, 0);
if (receive > 0){
if(strlen(buffer_o) > 0){
convey_msg(buffer_o, clice->uid);
array_trimming(buffer_o, strlen(buffer_o));
printf("%s -> %s\n", buffer_o, clice->nickname);
//printf("%s\n", buffer_o);
}
}
else if (receive == 0 || strcmp(buffer_o, "quit") == 0){
sprintf(buffer_o, "Server: %s has stopped chatting.\n", clice->nickname);
printf("%s", buffer_o);
convey_msg(buffer_o, clice->uid);
//trial
//strcpy(buffer_o, clice->nickname);
send(clice->sockfd, buffer_o, strlen(buffer_o)+1,0);
leave_flag = 1;
}
/* else {
printf("Error is -1\n");
leave_flag = 1;
} */
bzero(buffer_o, SIZEOF_BUFFER);
}
/* Delete client from queue and yield thread */
close(clice->sockfd);
client_removal(clice->uid);
free(clice);
num_client--;
pthread_detach(pthread_self());
return NULL;
}
client code
void handle_message_convey() {
char message[LENGTH] = {};
char buff[LENGTH + 20] = {};
while(1) {
flush_stdout();
fgets(message, LENGTH, stdin);
array_trimming(message, LENGTH);
if (strcmp(message, "quit") == 0) {
break;
}
else {
sprintf(buff, "%s: %s\n", nickname, message);
send(sockfd, buffer, strlen(buff), 0);
}
bzero(message, LENGTH);
bzero(buffer, LENGTH + 20);
}
quit_with_catch_ctrl_c(2);
}
void handle_message_recv() {
char message[LENGTH] = {};
while (1) {
int message_rcv = recv(sockfd, message, LEN, 0);
if (message_rcv > 0) {
printf("%s", message);
flush_stdout();
}
else if (message_rcv == 0) {
break;
}
else {
// nothing happens = -1
}
memset(message, 0, sizeof(message));
}
}
int main(){
recv(sock_fd, buffer_o, sizeof(buffer_o), 0);
//printf("%s \n", buffer_o);
pthread_t message_sending_thr;
if(pthread_create(&message_sending_thr, NULL, (void* ) handle_message_convey, NULL) != 0) {
printf("Error with pthread:");
}
//printf("Hello, Welcome!");
pthread_t message_del_thr;
if(pthread_create(&message_del_thr, NULL, (void *)handle_message_recv, NULL) != 0){
printf("Error with pthread");
}
}

thread function doesn't terminate until Enter is pressed

The following code (in the end) represents thread function which takes in ls command from remote client and send current working directory to that client.
It successfully sends but there is one issue:
When it stops sending completely, I want it to start listening again. At line:
printf("Enter 1 if you want to exit or 0 if you don't: ");
fgets(exit_status,MAX_SIZE,stdin);
It gets stuck and it is terminated (and starts another thread) when I press Enter
Which I don't understand why? and while I was debugging I saw above print statement executes after pressing Enter despite the debugger being at the end of function (means it passed this print statement).
I want it to start listening again automatically when it finish sending data.
If anyone wants to look at my full code here is the link:https://pastebin.com/9UmTkPge
void *server_socket_ls(void *arg) {
int* exit_status = (int*)malloc(sizeof(int));
*exit_status = 0;
while (*exit_status == 0) {
//socket code is here
//code for ls
char buffer[BUFFSIZE];
int received = -1;
char data[MAX];
memset(data,0,MAX);
// this will make server wait for another command to run until it receives exit
data[0] = '\0';
if((received = recv(new_socket, buffer,BUFFSIZE,0))<0){
perror("Failed");
}
buffer[received] = '\0';
strcat (data, buffer);
if (strcmp(data, "exit")==0) // this will force the code to exit
exit(0);
puts (data);
char *args[100];
setup(data,args,0);
int pipefd[2],lenght;
if(pipe(pipefd))
perror("Failed to create pipe");
pid_t pid = fork();
char path[MAX];
if(pid==0)
{
close(1); // close the original stdout
dup2(pipefd[1],1); // duplicate pipfd[1] to stdout
close(pipefd[0]); // close the readonly side of the pipe
close(pipefd[1]); // close the original write side of the pipe
execvp(args[0],args); // finally execute the command
}
else
if(pid>0)
{
close(pipefd[1]);
memset(path,0,MAX);
while(lenght=read(pipefd[0],path,MAX-1)){
printf("Data read so far %s\n", path);
if(send(new_socket,path,strlen(path),0) != strlen(path) ){
perror("Failed");
}
//fflush(NULL);
printf("Data sent so far %s\n", path);
memset(path,0,MAX);
}
close(pipefd[0]);
//removed so server will not terminate
}
else
{
printf("Error !\n");
exit(0);
}
printf("Enter 1 if you want to exit or 0 if you don't: ");
fgets(exit_status,MAX_SIZE,stdin);
}
}
There are many bugs:
In terminal_thread, input_command is allocated on each loop iteration -- a memory leak
Code to strip newline is broken
With .l, not specifying an IP address causes a segfault because token is NULL
The port number in terminal_thread for .l is 5126 which does not match the 9191 in the corresponding server code
After connecting, server_socket_file does not do anything.
In server_socket_ls, it loops on socket, bind, listen, and accept. The loop should start after the listen (i.e. only do accept in the loop and reuse the listening socket).
Other bugs marked in the code
I had to refactor the code and add some debug. It is annotated with the bugs. I use cpp conditionals to denote old vs. new code:
#if 0
// old code
#else
// new code
#endif
#if 1
// new code
#endif
Here is the code. I got minimal .l (remote ls) working:
Edit: Because of the update below running over SO space limits, I've elided the first code block I posted here.
Here is the debug.txt output:
term term: PROMPT
term term: FGETS
ls ls: ENTER
ls ls: SOCKET
file file: ENTER
ls ls: BIND prtNum=9191
file file: BIND portNum=6123
ls ls: LISTEN
term term: COMMAND '.l'
term term: port=9191
ls ls: ACCEPTED
term term: PROMPT
This program is exiting as soon as its stops sending data at exit(0) and so doesn't ask for exit_status. Is there a way somehow to make it not stop and instead the terminal prompt reappears along with servers listening at the back? –
Dragut
Because I sensed the urgency, I erred on the side of a partial solution now is better than a perfect solution too late.
I may have introduced a bug with an extraneous exit call in the ls server parent process (now fixed).
But, there are other issues ...
The main issue is that the server (for ls) is prompting the user whether to continue or not (on stdout/stdin). This doesn't work too well.
It's the client (i.e. terminal_thread) that should prompt the user. Or, as I've done it, the client will see exit at the command prompt, then send a packet with "exit" in it to the server, and terminate. Then, the server will see this command and terminate.
I refactored as much as I could without completely redoing everything.
I split off some code into functions. Some of the can/could be reused to implement the "file" server.
But, I'd put both functions into a single server thread. I'd have the server look at the "command" it gets and do either of the actions based on the command. Since there's no code for actually doing something in the "file" server [yet] it's difficult to rework.
One thing to fix [which I did not have time for]:
The .l command is of the form: .l [ip_address]. The default for ip_address is 127.0.0.1. But, this should be split into two commands (e.g.):
attach [ip_address]
ls [ls arguments]
Anyway, here's the updated code. I had to move a bit quickly, so it's not quite as clean as I'd like.
#include <netinet/in.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <stdbool.h>
#include <stdarg.h>
#if 1
#include <time.h>
#endif
#define BACKLOG 10
#define MAX_SIZE 200
#define BACKLOG 10
#define BUFFSIZE 2048
#define MAXPENDING 5
#define MAX 2048
__thread char *tid;
__thread char dbgstrbuf[1000];
FILE *xfdbg;
double tsczero = 0.0;
typedef struct server_arg {
int portNum;
} server_arg;
typedef struct server_arg1 {
int portNum;
} server_arg1;
double
tscgetf(void)
{
struct timespec ts;
double sec;
clock_gettime(CLOCK_MONOTONIC,&ts);
sec = ts.tv_nsec;
sec /= 1e9;
sec += ts.tv_sec;
sec -= tsczero;
return sec;
}
void
dbgprt(const char *fmt,...)
{
va_list ap;
char msg[1000];
char *bp = msg;
bp += sprintf(bp,"[%.9f/%4s] ",tscgetf(),tid);
va_start(ap,fmt);
bp += vsprintf(bp,fmt,ap);
va_end(ap);
fputs(msg,xfdbg);
}
const char *
dbgstr(const char *str,int len)
{
char *bp = dbgstrbuf;
if (len < 0)
len = strlen(str);
bp += sprintf(bp,"'");
for (int i = 0; i < len; ++i) {
int chr = str[i];
if ((chr > 0x20) && (chr <= 0x7E))
bp += sprintf(bp,"%c",chr);
else
bp += sprintf(bp,"{%2.2X}",chr);
}
bp += sprintf(bp,"'");
return dbgstrbuf;
}
void
setup(char inputBuffer[], char *args[], int *background)
{
const char s[4] = " \t\n";
char *token;
token = strtok(inputBuffer, s);
int i = 0;
while (token != NULL) {
args[i] = token;
i++;
// printf("%s\n", token);
token = strtok(NULL, s);
}
args[i] = NULL;
}
int
open_remote(const char *ip,unsigned short port)
{
int sock;
struct sockaddr_in echoserver;
dbgprt("open_remote: ENTER ip=%s port=%u\n",dbgstr(ip,-1),port);
if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
perror("Failed to create socket");
exit(1);
}
int enable = 1;
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable,
sizeof(int)) < 0) {
perror("error");
}
memset(&echoserver, 0, sizeof(echoserver));
echoserver.sin_family = AF_INET;
echoserver.sin_addr.s_addr = inet_addr(ip);
// NOTE/BUG: this port number does _not_ match any server port
#if 0
echoserver.sin_port = htons(5126);
#else
dbgprt("term: port=%u\n",port);
echoserver.sin_port = htons(port);
#endif
if (connect(sock, (struct sockaddr *) &echoserver,
sizeof(echoserver)) < 0) {
perror("Failed to connect with server");
exit(1);
}
dbgprt("open_remote: EXIT sock=%d\n",sock);
return sock;
}
void *
terminal_thread(void *arg)
{
// NOTE/FIX: do this _once_
#if 1
char *input_command = malloc(MAX_SIZE);
#endif
tid = "term";
char buffer[BUFFSIZE];
int sock_ls = -1;
while (1) {
dbgprt("term: PROMPT\n");
printf(">> ");
//memset(input_command,0,strlen(str));
// NOTE/BUG: this is a memory leak
#if 0
char *input_command = malloc(MAX_SIZE);
#endif
dbgprt("term: FGETS\n");
fgets(input_command, MAX_SIZE, stdin);
// NOTE/BUG: code is broken to strip newline
#if 0
if ((strlen(input_command) > 0) &&
(input_command[strlen(input_command) - 1] == '\n'))
input_command[strlen(input_command) - 1] = '\0';
#else
input_command[strcspn(input_command,"\n")] = 0;
#endif
dbgprt("term: COMMAND %s\n",dbgstr(input_command,-1));
char list[] = "ls";
char cp[] = "cp";
#if 0
char s[100];
printf("%s\n", getcwd(s,100));
chdir("Desktop");
printf("%s\n", getcwd(s,100));
#endif
// exit program (and exit server)
if (strcmp(input_command,"exit") == 0) {
if (sock_ls >= 0) {
dbgprt("term: SENDEXIT\n");
if (send(sock_ls,"exit",4,0) < 0) {
perror("send/exit");
exit(1);
}
break;
}
}
if (strcmp(input_command, list) == 0) {
// ls code will run here
}
if ((input_command[0] == '.') && (input_command[1] == 'l')) {
printf("remote ls\n");
char ip[20];
const char c[2] = " ";
// strcpy(str,input_command);
char *token;
// get the first token
token = strtok(input_command, c);
// walk through other tokens
int i = 0;
while (token != NULL && i != -1) {
token = strtok(NULL, c);
i--;
}
#if 1
if (token == NULL) {
token = "127.0.0.1";
printf("no IP address found -- using %s\n",token);
}
#endif
if (sock_ls < 0)
sock_ls = open_remote(token,9191);
char s[100];
strcpy(s, "ls");
// NOTE/BUG: this blows away the "s" in "ls" because s is _set_ with strcpy
#if 0
s[strlen(s) - 1] = '\0'; // fgets doesn't automatically discard '\n'
#endif
unsigned int echolen;
echolen = strlen(s);
int received = 0;
/* send() from client; */
if (send(sock_ls, s, echolen, 0) != echolen) {
perror("Mismatch in number of sent bytes");
}
fprintf(stdout, "Message from server: ");
int bytes = 0;
/* recv() from server; */
if ((bytes = recv(sock_ls, buffer, echolen, 0)) < 1) {
perror("Failed to receive bytes from server");
}
received += bytes;
buffer[bytes] = '\0';
/* Assure null terminated string */
fprintf(stdout, buffer);
bytes = 0;
// this d {...} while block will receive the buffer sent by server
do {
buffer[bytes] = '\0';
printf("%s\n", buffer);
} while ((bytes = recv(sock_ls, buffer, BUFFSIZE - 1, 0)) >= BUFFSIZE - 1);
buffer[bytes] = '\0';
printf("%s\n", buffer);
printf("\n");
continue;
}
}
dbgprt("term: EXIT\n");
return (void *) 0;
}
int
ls_loop(int new_socket)
{
dbgprt("ls_loop: ENTER new_socket=%d\n",new_socket);
//code for ls
char buffer[BUFFSIZE];
int received = -1;
char data[MAX];
int stop = 0;
while (1) {
memset(data, 0, MAX);
// this will make server wait for another command to run until it
// receives exit
data[0] = '\0';
if ((received = recv(new_socket, buffer, BUFFSIZE, 0)) < 0) {
perror("Failed");
}
buffer[received] = '\0';
strcpy(data, buffer);
dbgprt("ls_loop: COMMAND %s\n",dbgstr(data,-1));
// this will force the code to exit
#if 0
if (strcmp(data, "exit") == 0)
exit(0);
puts(data);
#else
if (strncmp(data, "exit", 4) == 0) {
dbgprt("ls_loop: EXIT/COMMAND\n");
stop = 1;
break;
}
#endif
char *args[100];
setup(data, args, 0);
int pipefd[2], length;
if (pipe(pipefd))
perror("Failed to create pipe");
pid_t pid = fork();
char path[MAX];
if (pid == 0) {
// NOTE/BUG: no need to close before dup2
#if 0
close(1); // close the original stdout
#endif
dup2(pipefd[1], 1); // duplicate pipfd[1] to stdout
close(pipefd[0]); // close the readonly side of the pipe
close(pipefd[1]); // close the original write side of the pipe
execvp(args[0], args); // finally execute the command
exit(1);
}
if (pid < 0) {
perror("fork");
exit(1);
}
dbgprt("ls_loop: PARENT\n");
close(pipefd[1]);
while (length = read(pipefd[0], path, MAX - 1)) {
dbgprt("ls_loop: DATAREAD %s\n",dbgstr(path,length));
if (send(new_socket, path, length, 0) != length) {
perror("Failed");
}
memset(path, 0, MAX);
}
close(pipefd[0]);
}
dbgprt("ls_loop: EXIT stop=%d\n",stop);
}
void *
server_socket_ls(void *arg)
{
tid = "ls";
dbgprt("lsmain: ENTER\n");
do {
server_arg *s = (server_arg *) arg;
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
dbgprt("lsmain: SOCKET\n");
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
int enable = 1;
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &enable,
sizeof(int)) < 0) {
perror("error");
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(s->portNum);
dbgprt("lsmain: BIND prtNum=%u\n",s->portNum);
if (bind(server_fd, (struct sockaddr *) &address, sizeof(address))
< 0) {
perror("bind failed");
}
dbgprt("lsmain: LISTEN\n");
if (listen(server_fd, 3) < 0) {
perror("listen");
}
while (1) {
if ((new_socket = accept(server_fd, (struct sockaddr *) &address,
(socklen_t *) & addrlen)) < 0) {
perror("accept");
}
dbgprt("lsmain: ACCEPTED\n");
int stop = ls_loop(new_socket);
close(new_socket);
if (stop) {
dbgprt("lsmain: STOP\n");
break;
}
}
} while (0);
dbgprt("lsmain: EXIT\n");
return (void *) 0;
}
void *
server_socket_file(void *arg)
{
tid = "file";
dbgprt("file: ENTER\n");
server_arg1 *s1 = (server_arg1 *) arg;
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
int enable = 1;
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int))
< 0) {
perror("error");
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(s1->portNum);
dbgprt("file: BIND portNum=%u\n",s1->portNum);
if (bind(server_fd, (struct sockaddr *) &address, sizeof(address)) < 0) {
perror("bind failed");
}
if (listen(server_fd, 3) < 0) {
perror("listen");
}
if ((new_socket = accept(server_fd, (struct sockaddr *) &address,
(socklen_t *) & addrlen)) < 0) {
perror("accept");
}
printf("Server Connected\n");
}
int
main(int argc, char const *argv[])
{
tid = "main";
tsczero = tscgetf();
server_arg *s = (server_arg *) malloc(sizeof(server_arg));
server_arg1 *s1 = (server_arg1 *) malloc(sizeof(server_arg1));
pthread_t id_1;
pthread_t id_2;
pthread_t id_3;
xfdbg = fopen("debug.txt","w");
setlinebuf(xfdbg);
if (pthread_create(&id_3, NULL, terminal_thread, NULL) != 0) {
perror("pthread_create");
}
// NOTE/BUG: this port (or the one below) doesn't match the client code
// port of 5126
s->portNum = 9191;
pthread_create(&id_1, NULL, server_socket_ls, s);
s1->portNum = 6123;
if (0)
pthread_create(&id_2, NULL, server_socket_file, s1);
pthread_join(id_1, NULL);
if (0)
pthread_join(id_2, NULL);
pthread_join(id_3, NULL);
// NOTE/BUG: pthread_exit in main thread is wrong
#if 0
pthread_exit(0);
#else
fclose(xfdbg);
return 0;
#endif
}
UPDATE:
Feedback 2: the program does make terminal thread to reappear, but it doesn't listen anymore. When I tried to send ls command again from remote pc, it just blocks (and debugging shows it is because it gets stuck at blocking receive function). –
Dragut
I tried to avoid too much refactoring, but now, I've added more changes. This version is almost a complete rearchitecting:
pthread_create is okay when testing, but isn't general enough if the server is on a different system.
Usually, the client and server are separate programs (e.g. we start the server in a different window or from systemd).
The server usually creates a subprocess/subthread to transfer the request (Below, I've done a fork but the server could do pthread_create).
This child process handles everything after the accept, so the server main process is free to loop on accept and have multiple simultaneous clients.
Because we're using stream sockets (e.g. TCP), each side needs to know when to stop reading. The usual is to create a struct that is a descriptor of the data to follow (e.g. xmsg_t below) that has a "type" and a "payload length".
Every bit of payload data that is sent/received is prefixed by such a descriptor.
In other words, we need a simple "protocol"
Now, we need two windows (they can be on different systems):
To start server: ./myprogram -s
To start client: ./myprogram
Here's the refactored code. It is annotated:
#include <netinet/in.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <stdbool.h>
#include <stdarg.h>
#if 1
#include <errno.h>
#include <time.h>
#include <sys/file.h>
#include <sys/wait.h>
#endif
#define MAXBUFF 2048 // max buffer size
#define MAXPENDING 5 // max number of connections (listen)
#define MAXARG 100 // max number of args
#define PORTNO 9191 // default port number
#if 0
#define STOP_SIGNO SIGTERM // stop signal to use
#else
#define STOP_SIGNO SIGHUP // stop signal to use
#endif
#define CLOSEME(_fd) \
do { \
dbgprt("CLOSEME fd=%d (" #_fd ")\n",_fd); \
if (_fd >= 0) \
close(_fd); \
_fd = -1; \
} while (0)
int opt_h; // 1=send HELO message
int opt_s; // 1=doserver, 0=doclient
int opt_n; // 1=run server command in foreground
char ipaddr[100] = { "127.0.0.1" };
unsigned short portno = PORTNO;
pid_t server_pid; // pid of server main process
volatile int server_signo; // signal received by server main
__thread char *tid;
__thread char dbgstrbuf[MAXBUFF + 1];
int dbgfd = -1;
double tsczero = 0.0;
typedef struct {
int xmsg_type;
int xmsg_paylen;
} xmsg_t;
enum {
XMSG_NOP,
XMSG_CMD,
XMSG_DATA,
XMSG_EOF,
};
double
tscgetf(void)
{
struct timespec ts;
double sec;
clock_gettime(CLOCK_MONOTONIC,&ts);
sec = ts.tv_nsec;
sec /= 1e9;
sec += ts.tv_sec;
sec -= tsczero;
return sec;
}
#if _USE_ZPRT_
#ifndef DEBUG
#define DEBUG 1
#endif
#endif
#if DEBUG
#define dbgprt(_fmt...) \
xdbgprt(__FUNCTION__,_fmt)
#else
#define dbgprt(_fmt...) \
do { } while (0)
#endif
void
xdbgprt(const char *fnc,const char *fmt,...)
{
va_list ap;
char msg[MAXBUFF * 4];
char *bp = msg;
int sverr = errno;
bp += sprintf(bp,"[%.9f/%4s] %s: ",tscgetf(),tid,fnc);
va_start(ap,fmt);
bp += vsprintf(bp,fmt,ap);
va_end(ap);
// when doing forks, we have to lock the stream to guarantee atomic,
// non-interspersed messages that are sequential
flock(dbgfd,LOCK_EX);
lseek(dbgfd,0,2);
ssize_t remlen = bp - msg;
ssize_t curlen;
for (bp = msg; remlen > 0; remlen -= curlen, bp += curlen) {
curlen = write(dbgfd,bp,remlen);
if (curlen < 0) {
perror("xdbgprt");
break;
}
}
flock(dbgfd,LOCK_UN);
errno = sverr;
}
const char *
dbgstr(const char *str,int len)
{
char *bp = dbgstrbuf;
if (len < 0)
len = strlen(str);
bp += sprintf(bp,"'");
for (int i = 0; i < len; ++i) {
int chr = str[i];
if ((chr > 0x20) && (chr <= 0x7E))
bp += sprintf(bp,"%c",chr);
else
bp += sprintf(bp,"{%2.2X}",chr);
}
bp += sprintf(bp,"'");
return dbgstrbuf;
}
// tokenize -- convert buffer to tokens
int
tokenize(char **argv,const char *cmdbuf)
{
static char tokbuf[MAXBUFF];
char **av = argv;
strcpy(tokbuf,cmdbuf);
char *token = strtok(tokbuf," ");
while (token != NULL) {
*av++ = token;
token = strtok(NULL," ");
}
*av = NULL;
return (av - argv);
}
// xsend -- send buffer (guaranteed delivery)
ssize_t
xsend(int sock,const void *vp,size_t buflen,int flags)
{
const char *buf = vp;
ssize_t curlen;
ssize_t totlen = 0;
dbgprt("ENTER buflen=%zu flags=%8.8X\n",buflen,flags);
for (; totlen < buflen; totlen += curlen) {
dbgprt("LOOP totlen=%zd\n",totlen);
curlen = send(sock,&buf[totlen],buflen - totlen,flags);
if (curlen <= 0)
break;
}
dbgprt("EXIT totlen=%zd\n",totlen);
return totlen;
}
// xrecv -- receive buffer (guaranteed delivery)
ssize_t
xrecv(int sock,void *vp,size_t buflen,int flags)
{
char *buf = vp;
ssize_t curlen;
ssize_t totlen = 0;
dbgprt("ENTER buflen=%zu flags=%8.8X\n",buflen,flags);
for (; totlen < buflen; totlen += curlen) {
dbgprt("LOOP totlen=%zu\n",totlen);
curlen = recv(sock,&buf[totlen],buflen - totlen,flags);
if (curlen <= 0)
break;
}
dbgprt("EXIT totlen=%zd\n",totlen);
return totlen;
}
// open_remote -- client open connection to server
int
open_remote(const char *ip,unsigned short port)
{
int sock;
struct sockaddr_in echoserver;
dbgprt("ENTER ip=%s port=%u\n",dbgstr(ip,-1),port);
if ((sock = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP)) < 0) {
perror("Failed to create socket");
exit(1);
}
// NOTE/BUG: only server (who does bind) needs to do this
#if 0
int enable = 1;
if (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&enable,sizeof(enable)) < 0) {
perror("error");
}
#endif
memset(&echoserver,0,sizeof(echoserver));
echoserver.sin_family = AF_INET;
echoserver.sin_addr.s_addr = inet_addr(ip);
echoserver.sin_port = htons(port);
if (connect(sock,(struct sockaddr *) &echoserver,sizeof(echoserver)) < 0) {
perror("Failed to connect with server");
exit(1);
}
dbgprt("EXIT sock=%d\n",sock);
return sock;
}
// send_cmd -- client send command to server and process reply
void
send_cmd(int type,const char *cmd,int paylen)
{
int sock;
xmsg_t xmsg;
char buffer[MAXBUFF];
dbgprt("ENTER type=%d\n",type);
// open socket to remote server
sock = open_remote(ipaddr,portno);
// send command descriptor
xmsg.xmsg_type = type;
if (paylen < 0)
paylen = strlen(cmd);
xmsg.xmsg_paylen = paylen;
xsend(sock,&xmsg,sizeof(xmsg),0);
// send command payload
xsend(sock,cmd,xmsg.xmsg_paylen,0);
fprintf(stdout,"Message from server:\n");
int received = 0;
int bytes;
// get all data that the server sends back
while (1) {
dbgprt("LOOP\n");
// get descriptor for next chunk
xrecv(sock,&xmsg,sizeof(xmsg),0);
// handle EOF from server
if (xmsg.xmsg_paylen <= 0)
break;
// get payload
bytes = recv(sock,buffer,xmsg.xmsg_paylen,0);
dbgprt("RCVD bytes=%d\n",bytes);
#if 0
if (bytes == 0)
break;
#endif
/* recv() from server; */
if (bytes < 0) {
perror("Failed to receive bytes from server");
break;
}
received += bytes;
dbgprt("PAYLOAD %s\n",dbgstr(buffer,bytes));
// send payload to terminal
fwrite(buffer,1,bytes,stdout);
}
close(sock);
dbgprt("EXIT\n");
}
void
doclient(void)
{
char cmdbuf[MAXBUFF];
char *argv[MAXARG];
tid = "clnt";
while (1) {
dbgprt("PROMPT\n");
printf(">> ");
fflush(stdout);
dbgprt("FGETS\n");
fgets(cmdbuf,sizeof(cmdbuf),stdin);
cmdbuf[strcspn(cmdbuf,"\n")] = 0;
dbgprt("COMMAND %s\n",dbgstr(cmdbuf,-1));
// tokenize the line
int argc = tokenize(argv,cmdbuf);
if (argc <= 0)
continue;
// set/display remote server IP address
if (strcmp(argv[0],"remote") == 0) {
if (argc >= 2)
strcpy(ipaddr,argv[1]);
if (ipaddr[0] != 0)
printf("REMOTE: %s\n",ipaddr);
continue;
}
// stop server
if (strcmp(argv[0],"stop") == 0) {
if (ipaddr[0] != 0) {
dbgprt("STOP/SERVER\n");
send_cmd(XMSG_CMD,cmdbuf,-1);
}
ipaddr[0] = 0;
continue;
}
// exit client program
if (strcmp(argv[0],"exit") == 0) {
dbgprt("STOP/CLIENT\n");
break;
}
// send command and echo response to terminal
send_cmd(XMSG_CMD,cmdbuf,-1);
}
dbgprt("EXIT\n");
}
// server_cmd -- process command on server
void
server_cmd(int new_socket)
{
xmsg_t xmsg;
char cmdbuf[MAXBUFF];
char *argv[MAXARG];
dbgprt("ENTER new_socket=%d\n",new_socket);
do {
// get command descriptor
xrecv(new_socket,&xmsg,sizeof(xmsg),0);
// get command text
xrecv(new_socket,cmdbuf,xmsg.xmsg_paylen,0);
cmdbuf[xmsg.xmsg_paylen] = 0;
dbgprt("COMMAND %s\n",dbgstr(cmdbuf,-1));
// tokenize the command
int argc = tokenize(argv,cmdbuf);
if (argc <= 0)
break;
// stop the server
if (strcmp(argv[0],"stop") == 0) {
dbgprt("KILL server_pid=%d\n",server_pid);
// FIXME -- we could send a "stopping server" message here
// send EOF to client
xmsg.xmsg_type = XMSG_EOF;
xmsg.xmsg_paylen = 0;
xsend(new_socket,&xmsg,sizeof(xmsg),0);
// signal the server main process to stop (cleanly)
if (opt_s)
server_signo = STOP_SIGNO;
else
kill(server_pid,STOP_SIGNO);
break;
}
int pipefd[2];
int length;
if (pipe(pipefd))
perror("Failed to create pipe");
pid_t pid = fork();
dbgprt("FORK pid=%d\n",pid);
// invoke the target program (under a pipe)
if (pid == 0) {
tid = "exec";
dbgprt("DUP2\n");
fflush(stdout);
int err = dup2(pipefd[1],1); // duplicate pipefd[1] to stdout
if (err < 0)
perror("dup2");
CLOSEME(pipefd[0]); // close the readonly side of the pipe
CLOSEME(pipefd[1]); // close the write side of the pipe
dbgprt("EXECVP\n");
CLOSEME(dbgfd);
if (opt_h) {
int len = sprintf(cmdbuf,"HELO\n");
write(1,cmdbuf,len);
}
execvp(argv[0],argv); // finally execute the command
perror("execvp");
exit(1);
}
// fork error
if (pid < 0) {
perror("fork");
exit(1);
}
dbgprt("PARENT\n");
CLOSEME(pipefd[1]);
// grab all output from the target program and send in packets to
// client
while (1) {
dbgprt("READBEG\n");
length = read(pipefd[0],cmdbuf,sizeof(cmdbuf));
dbgprt("READEND length=%d\n",length);
if (length < 0) {
perror("readpipe");
break;
}
if (length == 0)
break;
dbgprt("READBUF %s\n",dbgstr(cmdbuf,length));
// send descriptor for this chunk
xmsg.xmsg_type = XMSG_DATA;
xmsg.xmsg_paylen = length;
xsend(new_socket,&xmsg,sizeof(xmsg),0);
// send the payload
if (xsend(new_socket,cmdbuf,length,0) != length) {
perror("Failed");
}
}
CLOSEME(pipefd[0]);
// tell client we have no more data
xmsg.xmsg_paylen = 0;
xmsg.xmsg_type = XMSG_EOF;
xsend(new_socket,&xmsg,sizeof(xmsg),0);
} while (0);
CLOSEME(new_socket);
dbgprt("EXIT\n");
}
void
sighdr(int signo)
{
server_signo = signo;
}
void
doserver(void)
{
int server_fd,new_socket;
struct sockaddr_in address;
pid_t pid;
tid = "serv";
dbgprt("ENTER\n");
server_pid = getpid();
#if 0
signal(STOP_SIGNO,(void *) sighdr);
#else
struct sigaction act;
sigaction(STOP_SIGNO,NULL,&act);
act.sa_sigaction = (void *) sighdr;
sigaction(STOP_SIGNO,&act,NULL);
sigset_t set;
sigemptyset(&set);
sigaddset(&set,STOP_SIGNO);
sigprocmask(SIG_UNBLOCK,&set,NULL);
#endif
#if 0
int addrlen = sizeof(address);
#else
socklen_t addrlen = sizeof(address);
#endif
dbgprt("SOCKET\n");
// Creating socket file descriptor
if ((server_fd = socket(AF_INET,SOCK_STREAM,0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
int enable = 1;
if (setsockopt(server_fd,SOL_SOCKET,SO_REUSEADDR,&enable,sizeof(int)) < 0) {
perror("error");
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(portno);
dbgprt("BIND portno=%u\n",portno);
if (bind(server_fd,(struct sockaddr *) &address,sizeof(address)) < 0) {
perror("bind failed");
}
dbgprt("LISTEN\n");
if (listen(server_fd,MAXPENDING) < 0) {
perror("listen");
}
int pending = 0;
int status;
while (1) {
dbgprt("LOOP\n");
// reap all finished children
while (1) {
pid = waitpid(-1,&status,WNOHANG);
if (pid <= 0)
break;
dbgprt("REAP pid=%d pending=%d\n",pid,pending);
--pending;
}
// one of the children was given a stop command and it signaled us
if (server_signo) {
dbgprt("SIGNO server_signo=%d\n",server_signo);
break;
}
// wait for new connection from a client
// FIXME -- sending us a signal to stop cleanly is _broken_ because
// we do _not_ get an early return here (e.g. EINTR) -- we may need
// select with timeout
dbgprt("WAITACCEPT\n");
new_socket = accept(server_fd,(struct sockaddr *) &address,
(socklen_t *) &addrlen);
// stop cleanly
if (server_signo) {
dbgprt("SIGNO server_signo=%d\n",server_signo);
break;
}
if (new_socket < 0) {
if (errno == EINTR)
break;
perror("accept");
}
dbgprt("ACCEPTED\n");
// do command execution in main process (i.e. debug)
if (opt_n) {
server_cmd(new_socket);
continue;
}
pid = fork();
if (pid < 0) {
CLOSEME(new_socket);
continue;
}
// process the command in the child
if (pid == 0) {
server_cmd(new_socket);
exit(0);
}
++pending;
dbgprt("CHILD pid=%d\n",pid);
// server main doesn't need this after fork
#if 1
CLOSEME(new_socket);
#endif
}
// reap all children
while (pending > 0) {
pid = waitpid(-1,&status,0);
if (pid <= 0)
break;
dbgprt("REAP pid=%d pending=%d\n",pid,pending);
--pending;
}
dbgprt("EXIT\n");
}
int
main(int argc,char **argv)
{
--argc;
++argv;
for (; argc > 0; --argc, ++argv) {
char *cp = *argv;
if (*cp != '-')
break;
cp += 2;
switch (cp[-1]) {
case 'h':
opt_h = ! opt_h;
break;
case 'n': // do _not_ fork server
opt_n = ! opt_n;
break;
case 'p':
portno = (*cp != 0) ? atoi(cp) : PORTNO;
break;
case 's': // invoke server
opt_s = ! opt_s;
break;
}
}
tsczero = tscgetf();
#if DEBUG
int flags = O_WRONLY | O_APPEND;
if (opt_s)
flags |= O_TRUNC | O_CREAT;
dbgfd = open("debug.txt",flags,0644);
if (dbgfd < 0) {
perror("debug.txt");
exit(1);
}
#endif
if (opt_s)
doserver();
else
doclient();
#if DEBUG
if (dbgfd >= 0)
close(dbgfd);
#endif
return 0;
}

Trouble with converting single threaded HTTP server into multithreaded using pthreads

My single threaded HTTP Server works just fine, but I'm having trouble multithreading it. I know I am supposed to use pthreads, locks, and condition variables, but I can't get the logic set up properly. The trouble starts after listening to the server. Currently I have a struct that contains a client socket variable, a lock variable, a condition variable, and some variables necessary for parsing and storing headers. I create a struct array sized with the amount of threads, then create a pthread array sized with the amount of threads. I go into a while(1) loop which goes into a for loop and iterates through all the threads accepting each connection, calling pthread_create and passing them to my handle connections function, then closing the client socket. My handle connections then does the request handling that my single threaded http server did (reading, parsing, processing, constructing), then returns NULL. No request gets read when I run this using pthread_create, but if I run handle connections without the pthreads, it works just fine. And below I'll attach my code. Any help is appreciated
Thank you for commenting so well ...
Okay, I coded up, but not tested the changes.
Your loop is inherently single threaded, so a bit of refactoring is in order
You have to scan for an unused thread control slot after doing accept.
You have to pthread_join completed/done threads [from any prior invocations].
The thread function has to close the per-client socket [not main thread]
You need a global (file scope) mutex.
I've coded it up, but not tested it. I put #if 0 around most of what I clipped out and #if 1 around new code.
Note that number of simultaneous connections [second arg to listen], herein 5 has to be less than or equal to threadNum. Although I didn't do it, I'd just do listen(...,threadNum) instead of hardwiring it.
Here's the short code with just the relevant changes:
#if 1
pthread_mutex_t global_mutex = PTHREAD_MUTEX_INITIALIZER;
#endif
struct threadObject {
char method[5]; // PUT, HEAD, GET. HEAD==4 letters+null terminator
char filename[28]; // what is the file we are worried about. Max 27 ASCII characters (NULL terminated on 28)
char httpversion[9]; // HTTP/1.1
ssize_t content_length; // example: 13
uint16_t status_code; // status code for the request
char buffer[BUFFER_SIZE]; // buffer to transfer data
char rest_of_PUT[BUFFER_SIZE]; // incase client send part of PUT message in header
int client_sockd;
pthread_mutex_t *dispatch_lock;
const pthread_cond_t *job_pool_empty;
// pthread_mutex_t* log_lock;
// const pthread_cond_t* log_pool_empty;
pthread_mutex_t *read_write_lock;
pthread_cond_t *file_list_update;
// JobQueue* job_pool;
// LogQueue log_pool;
// bool is_logging;
#if 1
pthread_t tsk_threadid;
int tsk_inuse;
int tsk_done;
#endif
};
void *
handle_connections(void *ptr_thread)
{
// create a mutual exclusion to lock out any other threads from the function
// pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// pthread_mutex_lock(&mutex);
// operations go here
struct threadObject *thread = (struct threadObject *) ptr_thread;
// reset message after each loop
memset(thread->buffer, '\0', BUFFER_SIZE);
memset(thread->method, '\0', 5);
memset(thread->filename, '\0', 28);
memset(thread->httpversion, '\0', 9);
thread->content_length = 0;
thread->status_code = 0;
memset(thread->rest_of_PUT, '\0', BUFFER_SIZE);
// read message
if (read_http_response(thread) == true) {
// process message
process_request(thread);
}
// construct a response
construct_http_response(thread);
// unlock the function
// pthread_mutex_unlock(&mutex);
#if 1
close(thread->client_sockd);
pthread_mutex_lock(&global_mutex);
thread->tsk_done = 1;
pthread_mutex_unlock(&global_mutex);
#endif
return NULL;
}
int
main(int argc, char **argv)
{
// Create sockaddr_in with server information
if (argc < 2) {
perror("No arguments passed\n");
return -1;
}
// make sure port number is above 1024 and set the port # to it
if (atoi(argv[1]) < 1024) {
return 1;
}
char *port = argv[1];
// parse the command line args for options -l and -N. -l specifies it will use a log and the following parameter is the filename. -N specifies the number of threads it will use and the following parameter will be a number
int opt;
uint8_t threadNum = 1;
char *logName = NULL;
while ((opt = getopt(argc - 1, argv + 1, "N:l:")) != -1) {
if (opt == 'N') {
threadNum = atoi(optarg);
}
else if (opt == 'l') {
logName = optarg;
}
}
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(atoi(port));
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
socklen_t addrlen = sizeof(server_addr);
// Create server socket
int server_sockd = socket(AF_INET, SOCK_STREAM, 0);
// Need to check if server_sockd < 0, meaning an error
if (server_sockd < 0) {
perror("socket");
return 1;
}
// Configure server socket
int enable = 1;
// This allows you to avoid: 'Bind: Address Already in Use' error
int ret = setsockopt(server_sockd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
if (ret < 0) {
return EXIT_FAILURE;
}
// Bind server address to socket that is open
ret = bind(server_sockd, (struct sockaddr *) &server_addr, addrlen);
if (ret < 0) {
return EXIT_FAILURE;
}
// Listen for incoming connections
ret = listen(server_sockd, 5); // 5 should be enough, if not use SOMAXCONN
if (ret < 0) {
return EXIT_FAILURE;
}
struct threadObject thread[threadNum];
// Connecting with a client
struct sockaddr client_addr;
socklen_t client_addrlen = sizeof(client_addr);
// create a pthread array of size (number of threads). specify this will be using the handle connections function. join the threads together
#if 0
pthread_t thread_id[threadNum];
#endif
#if 1
struct threadObject *tsk = NULL;
int tskidx;
// clear out the thread structs
for (tskidx = 0; tskidx < threadNum; tskidx++) {
tsk = &thread[tskidx];
memset(tsk,0,sizeof(struct threadObject));
}
while (true) {
// accept connection
int client_sockd = accept(server_sockd, &client_addr, &client_addrlen);
pthread_mutex_lock(&global_mutex);
// join any previously completed threads
for (tskidx = 0; tskidx < threadNum; tskidx++) {
tsk = &thread[tskidx];
if (tsk->tsk_done) {
pthread_join(tsk->tsk_threadid,NULL);
tsk->tsk_inuse = 0;
tsk->tsk_done = 0;
}
}
// find unused task slot
for (tskidx = 0; tskidx < threadNum; tskidx++) {
tsk = &thread[tskidx];
if (! tsk->tsk_inuse)
break;
}
memset(tsk,0,sizeof(struct threadObject));
tsk->client_sockd = client_sockd;
tsk->tsk_inuse = 1;
pthread_mutex_unlock(&global_mutex);
// fire in the hole ...
pthread_create(&tsk->tsk_threadid, NULL, handle_connections, tsk);
}
#endif
#if 0
for (int i = 0; i < threadNum; i++) {
printf("\n[+] server is waiting...\n");
thread[i].client_sockd = accept(server_sockd, &client_addr, &client_addrlen);
handle_connections(&thread[i]);
// pthread_create(&thread_id[i], NULL, handle_connections, &thread[i]);
printf("Response Sent\n");
// close the current client socket
close(thread[i].client_sockd);
}
}
#endif
return EXIT_SUCCESS;
}
Here's the complete code [just in case I clipped out too much]:
#include <sys/socket.h>
#include <sys/stat.h>
#include <stdio.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <fcntl.h>
#include <unistd.h> // write
#include <string.h> // memset
#include <stdlib.h> // atoi
#include <stdbool.h> // true, false
#include <errno.h>
#include <sys/types.h>
#include <ctype.h>
#include <pthread.h>
#define BUFFER_SIZE 4096
#if 1
pthread_mutex_t global_mutex = PTHREAD_MUTEX_INITIALIZER;
#endif
struct threadObject {
char method[5]; // PUT, HEAD, GET. HEAD==4 letters+null terminator
char filename[28]; // what is the file we are worried about. Max 27 ASCII characters (NULL terminated on 28)
char httpversion[9]; // HTTP/1.1
ssize_t content_length; // example: 13
uint16_t status_code; // status code for the request
char buffer[BUFFER_SIZE]; // buffer to transfer data
char rest_of_PUT[BUFFER_SIZE]; // incase client send part of PUT message in header
int client_sockd;
pthread_mutex_t *dispatch_lock;
const pthread_cond_t *job_pool_empty;
// pthread_mutex_t* log_lock;
// const pthread_cond_t* log_pool_empty;
pthread_mutex_t *read_write_lock;
pthread_cond_t *file_list_update;
// JobQueue* job_pool;
// LogQueue log_pool;
// bool is_logging;
#if 1
pthread_t tsk_threadid;
int tsk_inuse;
int tsk_done;
#endif
};
//read in the header and store it in the appropriate places
bool
read_http_response(struct threadObject *thread)
{
printf("\nThis function will take care of reading message\n");
// how many bytes we're receiving from the header. also puts the message into the buffer
ssize_t bytes = recv(thread->client_sockd, thread->buffer, BUFFER_SIZE, 0);
// if nothing or too much gets sent in the header, return
if (bytes <= 0 || bytes >= BUFFER_SIZE) {
thread->status_code = 400;
printf("Too long or nothing in here\n");
return false;
}
// NULL terminate the last spot on the buffer
thread->buffer[bytes] = '\0';
// how many bytes we received
printf("[+] received %ld bytes from client\n[+] response: \n", bytes);
printf("those bytes are: %s\n", thread->buffer);
// make a char pointer pointer to the buffer to easily traverse it and parse it into the right spots
char *traverse = thread->buffer;
// first stop. sgnals the beginning of the filename
char *file = strstr(traverse, "/");
// 2nd stop. signls the beginning of the HTTP version. only 1.1 is accepted
char *http = strstr(traverse, "HTTP/1.1");
// 3rd stop. Signals the beginning of the content length
char *contlength1 = strstr(traverse, "Content-Length");
char *chunked = strstr(traverse, "chunked");
if (chunked != NULL) {
printf("MESSAGE NOT A FILE PUT\n");
thread->status_code = 403;
return false;
}
// store the method
sscanf(traverse, "%s", thread->method);
printf("method:%s\n", thread->method);
// if its not 1 of the 3 valid requests, throw 400 error
if (strcmp(thread->method, "GET") != 0 &&
strcmp(thread->method, "PUT") != 0 &&
strcmp(thread->method, "HEAD") != 0) {
thread->status_code = 400;
printf("Invalid Method:%s\n", thread->method);
return false;
}
// if the filename doesnt start with /, its invalid throw 400 error
if (*file != '/') {
thread->status_code = 400;
printf("bad filename\n");
return false;
}
// only store the filename portion after the required /
traverse = file + 1;
// to make sure the filename isnt too long
uint8_t size_check = 0;
// traverse filename until first whitespace
while (*traverse != ' ') {
// if any character in the filename isnt 1 of these, its invalid. throw 400 error
if (!isalnum(*traverse) && *traverse != '_' && *traverse != '-') {
// if theres no filename at all, throw a 404 error
if (size_check == 0) {
thread->status_code = 404;
printf("No file specified\n");
return thread->status_code;
}
thread->status_code = 400;
printf("Invalid filename character:%c\n", *traverse);
return false;
}
sscanf(traverse++, "%c", thread->filename + size_check++);
// if the filename breaks the 27 character limit, return a 400 error
if (size_check > 27) {
thread->status_code = 400;
printf("filename too long\n");
return false;
}
}
printf("filename:%s\n", thread->filename);
// if HTTP/1.1 isnt given, throw a 400 error
if (http == NULL) {
printf("HTTP/1.1 400 Bad Request\r\n\r\n");
thread->status_code = 400;
return false;
}
traverse = http;
// read in the http version until the first \r\n. this signals the end of the given version name
sscanf(traverse, "%[^\r\n]s", thread->httpversion);
printf("HTTP:%s\n", thread->httpversion);
// if its not a put request, this is the end of the header. return
if (strcmp(thread->method, "PUT") != 0) {
return true;
}
// for put requests only. traverse until the beginning of the content length
traverse = contlength1;
// last stop. signals the end of a normal PUT header. if a client wants to put some of the message in the header, it gets stored after this
char *end = strstr(traverse, "\r\n\r\n");
// if theres no \r\n\r\n, the header is bad. return 400
if (end == NULL) {
printf("bad header\n");
thread->status_code = 400;
return false;
}
// traverse to the next digit
while (!isdigit(*traverse)) {
// if theres no next digit after "content length", the header is bad. return 400
if (traverse == end) {
printf("bad header\n");
thread->status_code = 400;
return false;
}
traverse++;
}
// set to traverse to be sure fit the entire content length. use size_check to traverse through
char *temp = traverse;
size_check = 0;
// while its taking in digits, put them into the char array.
while (isdigit(*traverse)) {
sscanf(traverse++, "%c", temp + size_check++);
}
// convert the new string into numbers
thread->content_length = atoi(temp);
// if the content length is < 0 throw a 400 error
if (thread->content_length < 0) {
thread->status_code = 400;
printf("bad content length:%ld\n", thread->content_length);
return false;
}
// printf("Content Length:%ld\n", thread->content_length);
// move +4 spots to get to the end of this. if its a normal PUT, this will be the last spot. If the client puts part of the message in the header, it goes after this
traverse = end + 4;
// put the rest of the header into a char array to append later. if theres nothing, itll do nothing
strcpy(thread->rest_of_PUT, traverse);
// printf("Rest of PUT:%s\n", thread->rest_of_PUT);
// will only get here if status code is 0
return true;
}
//process the message we just recieved
void
process_request(struct threadObject *thread)
{
printf("\nProcessing Request\n");
// server side file descriptor
int fd;
// if the method is PUT
if (strcmp(thread->method, "PUT") == 0) {
// open the file for read only to check if its already there or not to set proper status code
fd = open(thread->filename, O_WRONLY);
// if it doesnt exist, set 201 status code
struct stat checkExist;
if (stat(thread->filename, &checkExist) != 0) {
thread->status_code = 201;
}
// if it exists, set 200 and overwrite
else {
struct stat fileStat;
fstat(fd, &fileStat);
// check write permission
if ((S_IWUSR & fileStat.st_mode) == 0) {
printf("MESSAGE NOT WRITEABLE PUT\n");
thread->status_code = 403;
return;
}
thread->status_code = 200;
}
// close it
close(fd);
// reopen it. this time for writing to or overwriting. if its there, overwrite it. if not, create it. cant use for status codes since it will always create a new file
fd = open(thread->filename, O_WRONLY | O_CREAT | O_TRUNC);
// printf("fd in process is:%d\n", fd);
// if theres a bad fd, throw a 403
if (fd < 0) {
printf("ERROR\n\n");
thread->status_code = 403;
return;
}
// to check that the amount of bytes sent = the amount received
ssize_t bytes_recv,
bytes_send;
// if theres no body, put an empty file on the server
if (thread->content_length == 0) {
bytes_send = write(fd, '\0', 0);
}
// if there is a body, put it onto the new file created on the server and make sure the received bytes = the sent ones
else {
ssize_t total = 0,
len_track = thread->content_length;
while (thread->content_length != 0) {
bytes_recv = recv(thread->client_sockd, thread->buffer, BUFFER_SIZE, 0);
bytes_send = write(fd, thread->buffer, bytes_recv);
total += bytes_send;
// if the received bytes != the sent byes, send a 500 error
if (bytes_recv != bytes_send) {
thread->status_code = 500;
printf("Recieved != sent for put request\n");
return;
}
thread->content_length -= bytes_recv;
// printf("Bytes read:%ld\nBytes sent:%ld\nMessage content length:%ld\n", bytes_recv, bytes_send, message->content_length);
}
// if the content length != bytes sent, throw a 403 error
if (len_track != total) {
thread->status_code = 403;
printf("Content length != sent for put request\n");
return;
}
}
printf("Message status code:%d\n", thread->status_code);
// close the fd
close(fd);
return;
}
// if the method is GET or HEAD
else if (strcmp(thread->method, "GET") == 0 || strcmp(thread->method, "HEAD") == 0) {
// open the file for reading only
fd = open(thread->filename, O_RDONLY);
// if bad fd, throw a 404
struct stat fileStat;
fstat(fd, &fileStat);
// check read permission and if it exists
if (((S_IRUSR & fileStat.st_mode) == 0) || stat(thread->filename, &fileStat) != 0) {
printf("BAD GET\n");
thread->status_code = 404;
return;
}
else {
thread->status_code = 200;
thread->content_length = lseek(fd, 0, SEEK_END);
}
// close the fd
close(fd);
return;
}
}
void
construct_http_response(struct threadObject *thread)
{
printf("Constructing Response\n");
// size 22 since the largest code is 21 characters + NULL
char response[22];
// 200=OK, 201=CREATED, 400=BAD REQUEST, 403=FORBIDDEN, 404=NOT FOUND, 500=INTERNAL SERVER ERROR
if (thread->status_code == 200) {
strcpy(response, "OK");
}
else if (thread->status_code == 201) {
strcpy(response, "CREATED");
}
else if (thread->status_code == 400) {
strcpy(response, "BAD REQUEST");
}
else if (thread->status_code == 403) {
strcpy(response, "FORBIDDEN");
}
else if (thread->status_code == 404) {
strcpy(response, "NOT FOUND");
}
else if (thread->status_code == 500) {
strcpy(response, "INTERNAL SERVER ERROR");
}
else {
printf("Bad response...\n");
return;
}
dprintf(thread->client_sockd, "%s %d %s\r\nContent-Length: %ld\r\n\r\n", thread->httpversion, thread->status_code, response, thread->content_length);
if (strcmp(thread->method, "GET") == 0 && thread->status_code == 200) {
int fd = open(thread->filename, O_RDONLY);
ssize_t total = 0,
len_track = thread->content_length,
bytes_recv,
bytes_send;
while (thread->content_length != 0) {
bytes_recv = read(fd, thread->buffer, BUFFER_SIZE);
bytes_send = send(thread->client_sockd, thread->buffer, bytes_recv, 0);
if (bytes_recv != bytes_send) {
thread->status_code = 500;
close(fd);
printf("Recieved != sent for GET request\nReceived:%ld\nSent:%ld\n", bytes_recv, bytes_send);
dprintf(thread->client_sockd, "%s %d %s\r\nContent-Length: %ld\r\n\r\n", thread->httpversion, thread->status_code, response, thread->content_length);
close(fd);
return;
}
total += bytes_send;
thread->content_length -= bytes_recv;
}
if (total != len_track) {
thread->status_code = 403;
printf("Content length != recvd for GET request\n");
dprintf(thread->client_sockd, "%s %d %s\r\nContent-Length: %ld\r\n\r\n", thread->httpversion, thread->status_code, response, thread->content_length);
close(fd);
return;
}
close(fd);
}
}
void *
handle_connections(void *ptr_thread)
{
// create a mutual exclusion to lock out any other threads from the function
// pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// pthread_mutex_lock(&mutex);
// operations go here
struct threadObject *thread = (struct threadObject *) ptr_thread;
// reset message after each loop
memset(thread->buffer, '\0', BUFFER_SIZE);
memset(thread->method, '\0', 5);
memset(thread->filename, '\0', 28);
memset(thread->httpversion, '\0', 9);
thread->content_length = 0;
thread->status_code = 0;
memset(thread->rest_of_PUT, '\0', BUFFER_SIZE);
// read message
if (read_http_response(thread) == true) {
// process message
process_request(thread);
}
// construct a response
construct_http_response(thread);
// unlock the function
// pthread_mutex_unlock(&mutex);
#if 1
close(thread->client_sockd);
pthread_mutex_lock(&global_mutex);
thread->tsk_done = 1;
pthread_mutex_unlock(&global_mutex);
#endif
return NULL;
}
int
main(int argc, char **argv)
{
// Create sockaddr_in with server information
if (argc < 2) {
perror("No arguments passed\n");
return -1;
}
// make sure port number is above 1024 and set the port # to it
if (atoi(argv[1]) < 1024) {
return 1;
}
char *port = argv[1];
// parse the command line args for options -l and -N. -l specifies it will use a log and the following parameter is the filename. -N specifies the number of threads it will use and the following parameter will be a number
int opt;
uint8_t threadNum = 1;
char *logName = NULL;
while ((opt = getopt(argc - 1, argv + 1, "N:l:")) != -1) {
if (opt == 'N') {
threadNum = atoi(optarg);
}
else if (opt == 'l') {
logName = optarg;
}
}
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(atoi(port));
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
socklen_t addrlen = sizeof(server_addr);
// Create server socket
int server_sockd = socket(AF_INET, SOCK_STREAM, 0);
// Need to check if server_sockd < 0, meaning an error
if (server_sockd < 0) {
perror("socket");
return 1;
}
// Configure server socket
int enable = 1;
// This allows you to avoid: 'Bind: Address Already in Use' error
int ret = setsockopt(server_sockd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
if (ret < 0) {
return EXIT_FAILURE;
}
// Bind server address to socket that is open
ret = bind(server_sockd, (struct sockaddr *) &server_addr, addrlen);
if (ret < 0) {
return EXIT_FAILURE;
}
// Listen for incoming connections
ret = listen(server_sockd, 5); // 5 should be enough, if not use SOMAXCONN
if (ret < 0) {
return EXIT_FAILURE;
}
struct threadObject thread[threadNum];
// Connecting with a client
struct sockaddr client_addr;
socklen_t client_addrlen = sizeof(client_addr);
// create a pthread array of size (number of threads). specify this will be using the handle connections function. join the threads together
#if 0
pthread_t thread_id[threadNum];
#endif
#if 1
struct threadObject *tsk = NULL;
int tskidx;
// clear out the thread structs
for (tskidx = 0; tskidx < threadNum; tskidx++) {
tsk = &thread[tskidx];
memset(tsk,0,sizeof(struct threadObject));
}
while (true) {
// accept connection
int client_sockd = accept(server_sockd, &client_addr, &client_addrlen);
pthread_mutex_lock(&global_mutex);
// join any previously completed threads
for (tskidx = 0; tskidx < threadNum; tskidx++) {
tsk = &thread[tskidx];
if (tsk->tsk_done) {
pthread_join(tsk->tsk_threadid,NULL);
tsk->tsk_inuse = 0;
tsk->tsk_done = 0;
}
}
// find unused task slot
for (tskidx = 0; tskidx < threadNum; tskidx++) {
tsk = &thread[tskidx];
if (! tsk->tsk_inuse)
break;
}
memset(tsk,0,sizeof(struct threadObject));
tsk->client_sockd = client_sockd;
tsk->tsk_inuse = 1;
pthread_mutex_unlock(&global_mutex);
// fire in the hole ...
pthread_create(&tsk->tsk_threadid, NULL, handle_connections, tsk);
}
#endif
#if 0
for (int i = 0; i < threadNum; i++) {
printf("\n[+] server is waiting...\n");
thread[i].client_sockd = accept(server_sockd, &client_addr, &client_addrlen);
handle_connections(&thread[i]);
// pthread_create(&thread_id[i], NULL, handle_connections, &thread[i]);
printf("Response Sent\n");
// close the current client socket
close(thread[i].client_sockd);
}
}
#endif
return EXIT_SUCCESS;
}

Unix socket Multiple client group chat with client name in c

So far everything have been working perfectly. Just the problem I've been having is that I can't think of a way of assigning or i would say giving names to the clients who are connect to the server so that other clients who know is wrote a message
server:
while (1) {
FD_ZERO(&read_set);
//FD_ZERO(&write_set);
FD_SET(fd, &read_set);
//FD_SET(fd, &write_set);
for (i = 0; i < num_clients; i++) { //at first this part will not excute
FD_SET(clients[i], &read_set);
}
select(fd + num_clients + 1, &read_set, NULL, NULL, NULL);
if (FD_ISSET(fd, &read_set)) {
if ((clients[num_clients++] = accept(fd, NULL, NULL)) == -1) {
perror("accept error");
continue;
}
printf("we got a connection!\n");
}
for (i = 0; i < num_clients; i++) {
if (FD_ISSET(clients[i], &read_set)) {
msg = read(clients[i], buf, sizeof(buf));
if (msg > 0) {
int savedclnt = clients[i];
printf("client %d says: %s\n", i, buf);
for (int p = 0; p<num_clients; p++)
{
if (clients[p] != savedclnt) {
//write("from %d",clients[p]);
//char msg2 = strcat(clients[i],msg);
write(clients[p], buf, msg);
}
}
}
}
}
}
For what you're doing, you don't really need threads. From personal experience, a single threaded server would do the job just fine. Instead of having the main body wrap around a call to accept() you should use select() to see which file descriptors have input, something along the lines of...
fd_set readfds;
struct timeval timeout;
unsigned int num_clients;
unsigned int clients[100];
while(1)
{
FD_ZERO(&readfds);
FD_SET(sock, &readfds);
for(i=0; i<num_clients; i++)
{
FD_SET(clients[i],&readfds);
}
timeout.tv_sec=1;
timeout.tv_usec=0;
select(max_fds, &readfds, NULL, NULL, &timeout);
if(FD_ISSET(sock,&readfds))
{
clients[num_clients++] = accept(sock,(struct sockaddr *)&server,&size);
}
for(i=0;i<num_clients;i++)
{
if(FD_ISSET(clients[i],&readfds))
{
int err=read(clients[i],buf,1000);
if(err>0)
{
for(p=0;p<num_clients;p++)
{
write(clients[i],buf,err);
}
}
}
}
}
That code is just an example and needs error checking to see if a client has disconnected, a way of updating the list of clients and seeing if a client is ready to receive data. But hopefully it gives you the basic idea of where to go?

Segmentation fault on second call of a function

I'm doing a bit of socket programming and one of the nodes in the system runs this loop.
while(1) {
read_fd_set = active_fd_set;
waiting = select(FD_SETSIZE, &read_fd_set, NULL, NULL, NULL);
if (waiting < 0) {
error("ERROR on select");
}
for (i = 0; i < FD_SETSIZE; i++) {
if (FD_ISSET (i, &read_fd_set)) {
if (i == sockfd[S_IN]) {
proccess_packet(sockfd[S_IN], sockfd[R_OUT],
buffer, atoi(argv[7]));
}
if (i == sockfd[R_IN]) {
perror("yay");
proccess_packet(sockfd[R_IN], sockfd[S_OUT],
buffer, atoi(argv[7]));
}
}
}
}
When the initial sender sends a packet everything works fine, including the first call of "process_packet". But when the receiver sends its acknowledgement the program throws a segmentation fault without even entering "process_packet". So I assume it is the call itself considering the perror still triggers before.
void proccess_packet(int sockfd_in, int sockfd_out,
Packet buffer, int p_trans)
{
int n;
bzero(&buffer,BUFLEN);
n = read(sockfd_in,&buffer,BUFLEN);
if (n < 0) {
error("ERROR reading from socket");
}
if(buffer.magicno == 0x497E) {
//if((double)rand()/ (double)((unsigned)RAND_MAX + 1) > p_trans) {
write(sockfd_out,&buffer,sizeof(buffer));
//}
}
}
EDIT:
typedef struct {
int magicno;
int type;
int seqno;
int dataLen;
char* data;
} Packet;

Resources