-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatServer5.c
More file actions
284 lines (247 loc) · 10 KB
/
Copy pathchatServer5.c
File metadata and controls
284 lines (247 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/queue.h>
#include "inet.h"
#include "common.h"
struct client_connections {
char name[32]; // User's nickname shown in server
int socket; // Current socket for client connection
int name_set; // If name is set (acts as bool)
int to_remove; // If client is to be removed (acts as bool)
LIST_ENTRY(client_connections) connections; // Linked list pointer
};
LIST_HEAD(listhead, client_connections);
int main(int argc, char **argv)
{
struct sockaddr_in cli_addr, serv_addr, dir_serv_addr;
fd_set readset;
struct listhead head; // Head of linked list
LIST_INIT(&head); // Initializing liked list
int num_of_clients = 0; // Initializing num of active clients
int first_connect = 0; // Bool - First Connection Message Check (idk why I all capped that, looks better ig)
if (argc != 3) { // if not 2 args
fprintf(stderr, "Invalid usage. Please include server name and port.\n\
Example: `./chatServer2 \"[Server Name]\" [Port]\n");
return EXIT_FAILURE;
}
size_t max_serv_name_size = 50; // max name size
char server_name[max_serv_name_size]; // name with max name size
int port; // socket
fprintf(stderr, "%s", argv[1]); // checking if first arg is a string for a name
if (snprintf(server_name, max_serv_name_size, "%s", argv[1]) < 0) {
fprintf(stderr, "Error: First argument is not a string.\n");
return EXIT_FAILURE;
}
if (sscanf(argv[2], "%d", &port) != 1) { // checks if second arg is a number
fprintf(stderr, "Error: Second argument is not a number.\n");
return EXIT_FAILURE;
}
if (port < 49152 || port > 65535) { // checks if second arg is a VALID number
fprintf(stderr, "Error: Port is out of bounds. Must be between 50000 and 65535 (inclusive).\n"); // Set bounds "lower" (higher) to obscure directory port
return EXIT_FAILURE;
}
/* Create communication endpoint */
int sockfd; /* Listening socket */
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("server: can't open stream socket");
return EXIT_FAILURE;
}
/* Add SO_REUSEADDRR option to prevent address in use errors (modified from: "Hands-On Network
* Programming with C" Van Winkle, 2019. https://learning.oreilly.com/library/view/hands-on-network-programming/9781789349863/5130fe1b-5c8c-42c0-8656-4990bb7baf2e.xhtml */
int true = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (void *)&true, sizeof(true)) < 0) {
perror("server: can't set stream socket address reuse option");
return EXIT_FAILURE;
}
/* Bind socket to local address */
memset((char *) &serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(port);
/* Bind to local IP/port before registering with the Directory Server to ensure
* that the port is available */
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
perror("server: can't bind local address");
return EXIT_FAILURE;
}
/* Create communication endpoint */
int dir_sockfd;
if ((dir_sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("server: can't open stream socket");
return EXIT_FAILURE;
}
/* Bind socket to local address */
memset((char *) &dir_serv_addr, 0, sizeof(dir_serv_addr));
dir_serv_addr.sin_family = AF_INET;
dir_serv_addr.sin_addr.s_addr = inet_addr(SERV_HOST_ADDR); /* hard-coded in inet.h */
dir_serv_addr.sin_port = htons(SERV_TCP_PORT); /* hard-coded in inet.h */
/* Connect to the server. */
if (connect(dir_sockfd, (struct sockaddr *) &dir_serv_addr, sizeof(dir_serv_addr)) < 0) {
perror("server: can't connect to directory server");
return EXIT_FAILURE;
}
/* TODO: Register with the directory server */
char init[MAX] = {'\0'};
snprintf(init, MAX, "SN%s:%d", server_name, port);
write(dir_sockfd, init, MAX);
/* Now you are ready to accept client connections */
listen(sockfd, 5);
for (;;) {
/* Initialize and populate your readset and compute maxfd */
FD_ZERO(&readset);
FD_SET(sockfd, &readset);
int max_fd = sockfd; //TO DO: add comp for directory socket
/* Look through current connections and figure out max_fd */
struct client_connections *client;
LIST_FOREACH(client, &head, connections) {
int sock = client->socket;
FD_SET(sock, &readset);
if (sock > max_fd) {
max_fd = sock;
}
}
if (select(max_fd+1, &readset, NULL, NULL, NULL) > 0) {
/* Check to see if our listening socket has a pending connection */
if (FD_ISSET(sockfd, &readset)) {
/* Accept a new connection request */
socklen_t clilen = sizeof(cli_addr);
int newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0) {
perror("server: accept error");
close (newsockfd);
close(sockfd);
continue; // continue operation, doesn't bother with failed attempted connection
//return EXIT_FAILURE;
}
else {
/* Adds new client to linked list */
struct client_connections *new_client = malloc(sizeof(struct client_connections));
new_client->socket = newsockfd;
new_client->name_set = 0;
new_client->to_remove = 0;
snprintf(new_client->name, 32, "temp_%d", num_of_clients);
num_of_clients++;
LIST_INSERT_HEAD(&head, new_client, connections);
}
}
struct client_connections *check;
LIST_FOREACH(check, &head, connections) {
int clientsock = check->socket; // Binds socket to client in linked list
if (FD_ISSET(clientsock, &readset)) {
/* FIXME: Modify the logic */
char s[MAX] = {'\0'}; // Client input
char output[MAX]; // Server output
//fprintf(stderr, "%s:%d Client message:\n%s\n", __FILE__, __LINE__, s); //DEBUG
ssize_t nread = read(clientsock, s, MAX);
if (nread <= 0) {
/* Not every error is fatal. Check the return value and act accordingly. */
//fprintf(stderr, "%s:%d Error reading from client\n", __FILE__, __LINE__);
perror("Error reading from client, disconnecting client...");
close (clientsock); // Close connection
check->to_remove = 1; // Mark for removal
continue; // Don't exit server, just continue to the next client in readset
} else {
/* Sets client name to a variable to avoid continued pointer checks -> more efficient but more memory, worth it since this is very little extra memory */
char client_name[32];
if (check->name_set == 1) {
snprintf(client_name, 32, "%s", check->name);
}
/* Client input case checks (without the cases, I found this easier) */
if (s[0] == 'N' || check->name_set == 0) { // N -> Name; Client is trying to set their name or comply with request for a different name
int is_name_good = 1; // Bool; Assume name is good until proven otherwise
snprintf(client_name, 32, "%s", s+1);
struct client_connections *name_check;
LIST_FOREACH(name_check, &head, connections) {
if (strncmp(client_name, name_check->name, 32) == 0) {
is_name_good = 0; // Name is taken -> Ask for a different name
}
}
if (is_name_good == 1) { // If name is not taken
if (first_connect == 0) {
snprintf(output, MAX, "U[%s is the first to join the chat room]", client_name); // U -> Update; First client in chat room
first_connect = 1;
}
else {
snprintf(output, MAX, "U[%s has joined the chat room]", client_name); // U -> Update; Multiple clients in chat room
}
snprintf(check->name, 32, "%s", client_name);
check->name_set = 1; // Marks client as compliant and good to enter chat room
}
else { // If name is taken
snprintf(output, MAX, "EN[Name is already taken. Please enter a different one.]"); // E -> Error, N -> Name; Error with Name
}
}
else if (s[0] == 'M') { // M -> Message
snprintf(output, MAX, "U[%s]: %s",client_name, s+1); // U -> Update
}
else if (s[0] == 'D') { // D -> Disconnect
snprintf(output, MAX, "U[%s has left the chat room]", client_name); // U -> Update
check->to_remove = 1; // Removal clears socket
}
else {
if (s[0] != 'C') {
snprintf(output, MAX, "EI[Invalid request. Disconnecting...]\n"); // E -> Error, I -> Input; Error with Input
check->to_remove = 1; // Needs to send message to client, removes after sending
}
else {
continue;
}
}
/* Send the reply to the client */
if (output[0] == 'E') {
write(clientsock, output, MAX);
}
else {
struct client_connections *server_message;
LIST_FOREACH(server_message, &head, connections) {
if (server_message->name_set == 1) {
write(server_message->socket, output, MAX);
}
}
}
}
}
}
// Checks to see what clients need to be removed, frees the memory allocated to that client, and removes from linked list
// Client will already be disconnected by this point, this is for server-side cleanup
struct client_connections *remove = LIST_FIRST(&head);
while(remove != NULL) {
struct client_connections *next = LIST_NEXT(remove, connections);
if (remove->to_remove == 1) {
LIST_REMOVE(remove, connections);
close(remove->socket);
free(remove);
num_of_clients--;
}
remove = next;
}
}
else {
if (errno == EINTR) {
continue;
} else if (errno == EBADF) {
perror("Error: Bad file descripter");
FD_ZERO(&readset);
} else if (errno == EINVAL) {
perror("Error: Bad nfds or timeout");
continue;
} else if (errno == ENOMEM) {
perror("Error: No memory available to allocate. Resetting...");
// Code from example in List man page, adjusted to be more precise with naming
struct client_connections *remove = LIST_FIRST(&head);
struct client_connections *iterator;
while (remove != NULL) {
iterator = LIST_NEXT(remove, connections);
close(remove->socket);
free(remove);
remove = iterator;
}
}
}
}
// return or exit(0) is implied; no need to do anything because main() ends
}