This repository has been archived by the owner on Sep 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.cpp
321 lines (264 loc) · 8.12 KB
/
server.cpp
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/***
|* Created by Brian Yarbrough & Madison Solarana
|* Created on 11/10/2011
|* Last Modified on 11/12/2011
***/
// ### INCLUDES ################################################################
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <csignal>
#include <netdb.h>
#include "server.h"
using namespace std;
// ### GLOBAL VARIABLES ########################################################
unsigned short currentConnections = 0;
int socketfd, clientSockets[MAX_CLIENTS];
pthread_mutex_t clientMutex;
pthread_t threads[MAX_CLIENTS];
char clientNicks[MAX_CLIENTS][31]; // Should not be changed!
// #############################################################################
// ############################# START MAIN SCRIPT #############################
// #############################################################################
int main(int argc, char * argv[])
{
// ### LOAD PROGRAM PARAMETERS #############################################
unsigned short port = DEFAULT_PORT;
// Check the program arguments for port setting
if (argc >= 2)
{
port = strtol(argv[1], NULL, 10);
}
// ### INITIALIZE THE SOCKETS/NICKS ########################################
for (unsigned short i = 0; i < MAX_CLIENTS; i++)
{
clientSockets[i] = -1;
strcpy(clientNicks[i], "");
}
// ### SETUP THE SERVER ####################################################
struct sockaddr_in server_addr = { AF_INET, htons(port) };
struct sockaddr_in client_addr = { AF_INET };
socklen_t client_len = sizeof(client_addr);
// Create a stream socket
if ((socketfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
cerr << "* Error: Socket Creation Failed! *" << endl;
return 1;
}
// Bind the socket to an internet port
if (bind(socketfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1)
{
cerr << "* Error: Bind Failed! *" << endl;
return 1;
}
// Listen for clients
if (listen(socketfd, 1) == -1)
{
cerr << "* Error: Listen Failed! *" << endl;
return 1;
}
// Let the user know the server is now listening for clients
cout << "* Server is listening for clients... *" << endl;
// ### WATCH FOR ABORT, TERMINATE & INTERUPT SIGNALS #######################
signal(SIGABRT, &signalHandler);
signal(SIGTERM, &signalHandler);
signal(SIGINT, &signalHandler);
// ### LOOK FOR CONNECTING USERS ###########################################
int newsfd;
unsigned short cid;
while ((newsfd = accept(socketfd, (struct sockaddr *) &client_addr, &client_len)) > 0)
{
// Check if we are at MAX_CLIENTS currently
if (currentConnections >= MAX_CLIENTS)
{
cout << "* Connection to client refused! (Max Clients Exceeded) *" << endl;
write(newsfd, "* CODE 01 *", 11);
close(newsfd);
}
else
{
// Get the username of this client
char nick[31];
memset(nick, '\0', 31);
if (read(newsfd, nick, 30) <= 0)
{
// Kill this connection since we can't read in the nick
cout << "* Connection to client failed! *" << endl;
close(newsfd);
continue;
}
pthread_mutex_lock(&clientMutex);
// Check that no one else is using that nick
bool used = false;
for (unsigned short i = 0; i < MAX_CLIENTS; i++)
{
if (strcmp(nick, clientNicks[i]) == 0)
{
// Kill this connection as this nick is already in use
cout << "* Connection to client refused! (Nick Already In Use) *" << endl;
write(newsfd, "* CODE 02 *", 11);
close(newsfd);
used = true;
break;
}
}
if (used)
{
pthread_mutex_unlock(&clientMutex);
continue;
}
// Update the current connection count and add this user to the client sockets/nick arrays
for (cid = 0; cid < MAX_CLIENTS; cid++)
{
if (clientSockets[cid] == -1)
{
clientSockets[cid] = newsfd;
strcpy(clientNicks[cid], nick);
break;
}
}
currentConnections++;
pthread_mutex_unlock(&clientMutex);
// Handle this new client
if (pthread_create(&threads[currentConnections], NULL, handleClient, (void *) cid) != 0)
{
// Failed to create the thread, so remove the client, kill the connection and let the server know
pthread_mutex_lock(&clientMutex);
currentConnections--;
clientSockets[cid] = -1;
strcpy(clientNicks[cid], "");
pthread_mutex_unlock(&clientMutex);
cerr << "* Connection to client failed! (Failed To Create New Thread) *" << endl;
write(newsfd, "* CODE 03 *", 11);
close(newsfd);
}
}
}
// ### CLOSE OUT THE SERVER ################################################
// Should never reach this, but just in case
close(socketfd);
return 0;
}
// #############################################################################
// ############################## END MAIN SCRIPT ##############################
// #############################################################################
// ### FUNCTION DEFINITIONS ####################################################
/***
|* @func signalHandler
|* @desc Handles abort, terminate & interupt signals.
|*
|* @param int signal The signal the script recieved.
***/
void signalHandler(int signal)
{
// Let each client know the server is going down
writeToAll("* CODE 00 *");
// Disallow new connections
pthread_mutex_lock(&clientMutex);
// Let the user know the server is going down
cout << "* Server is shutting down... *" << endl;
// Wait 10 seconds
sleep(10);
// Kill the server
close(socketfd);
pthread_mutex_unlock(&clientMutex);
// Let the user know the server has shut down
cout << "* Server has shut down! *" << endl;
exit(0);
}
/***
|* @func handleClient
|* @desc Handles a new client. (For use with pthread_create only!)
***/
void * handleClient(void * cid)
{
unsigned short clientID = (long) cid;
char buffer[226];
// Let everyone know that this user has joined
strcpy(buffer, "* ");
strcat(buffer, clientNicks[clientID]);
strcat(buffer, " has connected! *");
writeToAllOthers(buffer, clientID);
cout << buffer << endl;
// Check if we have hit MAX_CLIENTS
if (currentConnections >= MAX_CLIENTS)
{
cout << "* Max Clients Reached! *" << endl;
}
// Start waiting for more responses from the client
memset(buffer, '\0', 226);
while (read(clientSockets[clientID], buffer, 225) > 0)
{
writeMessage(buffer, clientID);
memset(buffer, '\0', 226);
}
// Remove this client
pthread_mutex_lock(&clientMutex);
close(clientSockets[clientID]);
clientSockets[clientID] = -1;
// Let everyone know that this user has disconnected
strcpy(buffer, "* ");
strcat(buffer, clientNicks[clientID]);
strcat(buffer, " has disconnected! *");
strcpy(clientNicks[clientID], "");
currentConnections--;
pthread_mutex_unlock(&clientMutex);
writeToAllOthers(buffer, clientID);
cout << buffer << endl;
// Close out this thread
pthread_exit(NULL);
}
/***
|* @func writeToAll
|* @desc Writes a message to all clients.
|*
|* @param char[] message The message to write to all clients.
***/
void writeToAll(const char message[])
{
pthread_mutex_lock(&clientMutex);
for (unsigned short i = 0; i < MAX_CLIENTS; i++)
{
if (clientSockets[i] != -1)
{
write(clientSockets[i], message, strlen(message));
}
}
pthread_mutex_unlock(&clientMutex);
}
/***
|* @func writeToAllOthers
|* @desc Writes a message to all clients except the one the message is from.
|*
|* @param char[] message The message to write to all clients.
|* @param unsigned short from The client this message is from.
***/
void writeToAllOthers(const char message[], unsigned short from)
{
pthread_mutex_lock(&clientMutex);
for (unsigned short i = 0; i < MAX_CLIENTS; i++)
{
if (clientSockets[i] != -1 && i != from)
{
write(clientSockets[i], message, strlen(message));
}
}
pthread_mutex_unlock(&clientMutex);
}
/***
|* @func writeMessage
|* @desc Formats a message before writing it to all clients except the one the message is from.
|*
|* @param char[] message The message to write to all clients.
|* @param unsigned short from The client this message is from.
***/
void writeMessage(const char message[], unsigned short from)
{
char send[256];
// Append the user's nick to the message
strcpy(send, clientNicks[from]);
strcat(send, ": ");
strcat(send, message);
// Write the message to everyone else
writeToAllOthers(send, from);
}