-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.cpp
More file actions
339 lines (281 loc) · 8.48 KB
/
Server.cpp
File metadata and controls
339 lines (281 loc) · 8.48 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
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
// Lijo Raju 224101033
// 14 Jan 2023
// Assignment 1 Base 64 Encoding Server.cpp
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
using namespace std;
#define BUFFERSIZE 1024
#define ACK "Message Received"
#define FIN "Finished"
#define TYPE1 '1'
#define TYPE2 '2'
#define TYPE3 '3'
#define WAIT_TIME 5 // in seconds
#define TIMEOUT 3000 // in milli seconds
enum ErrorCode
{
PORT_NO_INVALID,
SOCKET_CREATION_FAILED,
SOCKET_BINDING_FAILED,
CONNECTION_ACCEPTING_FAILED,
ERROR_READING_MSG,
};
void serverProcess(int);
void listenClientProcesses(int);
void closeConnectionToClient(int, string);
void doClientServerCommunications(int, string);
void doBase64Decoding(char *);
void error(ErrorCode);
void printToConsole(string);
int main(int argc, char **argv)
{
int portno;
if (argc < 2)
{
error(PORT_NO_INVALID);
}
portno = atoi(argv[1]); // getting port no as CLI argument
if (portno < 0 || portno > 65534)
{
error(PORT_NO_INVALID);
}
serverProcess(portno);
return 0;
}
/**
* @brief Error handling utility fuction
* @param errCode the error code for which exception need to be handled
*/
void error(ErrorCode errCode)
{
string errorMsg;
switch (errCode)
{
case PORT_NO_INVALID:
errorMsg = "ERROR: Invalid Port No.";
break;
case SOCKET_CREATION_FAILED:
errorMsg = "ERROR: Socket Creation Failed.";
break;
case SOCKET_BINDING_FAILED:
errorMsg = "ERROR: Socket Binding Failed.";
break;
case CONNECTION_ACCEPTING_FAILED:
errorMsg = "ERROR: Acccepting Conncetion Failed.";
break;
case ERROR_READING_MSG:
errorMsg = "ERROR: Receiving Message From Client.";
break;
default:
break;
}
printToConsole(errorMsg);
exit(1);
}
/**
* @brief Printing console output
* @param msg the output to print
*/
void printToConsole(string msg)
{
cout << msg << endl;
}
/**
* @brief Starting server process
* @param portno the port no to which server socket to bind
*/
void serverProcess(int portno)
{
int sockfd;
struct sockaddr_in serverAddr;
// creating the socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
error(SOCKET_CREATION_FAILED);
}
printToConsole("COMPLETED: Server Socket Creation.");
// initializing serverAddr to null value
bzero((char *)&serverAddr, sizeof(serverAddr));
// setting serverAddr parameters
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(portno);
// binding the socket
if (bind(sockfd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0)
{
error(SOCKET_BINDING_FAILED);
}
printToConsole("COMPLETED: Server Socket Binding.");
listen(sockfd, 10); // second arg is queue length
printToConsole(("\nServer Is Up And Running.\nListening Incoming Connections On Port No " + to_string(portno)));
listenClientProcesses(sockfd);
}
/**
* @brief Listening incoming connections
* @param sockfd the server socket which is listening the client connections
*/
void listenClientProcesses(int sockfd)
{
int newsockfd;
socklen_t clientlen;
struct sockaddr_in clientAddr;
string clientIP;
pid_t pid;
do
{
// accepting new incoming connection
clientlen = sizeof(clientAddr);
newsockfd = accept(sockfd, (struct sockaddr *)&clientAddr, &clientlen);
if (newsockfd < 0)
{
error(CONNECTION_ACCEPTING_FAILED);
}
clientIP = inet_ntoa(clientAddr.sin_addr);
clientIP = clientIP + '/';
clientIP = clientIP + to_string(ntohs(clientAddr.sin_port));
printToConsole(("\nAccepted New Incoming Connection From Client IP/PortNo: " + clientIP));
// creating child process for handling client communications
if ((pid = fork()) == 0)
{
// child process
close(sockfd); // closing its listening socket
doClientServerCommunications(newsockfd, clientIP);
exit(0);
}
close(newsockfd); // parent process closes its connected client socket
} while (true);
}
/**
* @brief Client-Server communications
* @param newsockfd the new socket created for client communications
* @param clientIP the client IP/PortNo
*/
void doClientServerCommunications(int newsockfd, string clientIP)
{
char buffer[BUFFERSIZE];
do
{
bzero(buffer, sizeof(buffer)); // clearing buffer before reading msg
if (read(newsockfd, buffer, BUFFERSIZE) <= 0)
{
printToConsole("Client: " + clientIP);
error(ERROR_READING_MSG);
}
if (buffer[0] == TYPE3)
{
// client has send Type 3 msg
printToConsole(("\nClient " + clientIP + " Requested To Close Connection."));
break;
}
printToConsole(("\nNew Message Received From Client " + clientIP + "\n\nReceived Message:\n"));
printToConsole(buffer); // received msg from client
doBase64Decoding(buffer);
if (buffer[0] == TYPE1)
{
// sending ACK to client on recieving Type 1 Msg
send(newsockfd, ACK, strlen(ACK), 0);
}
} while (true);
closeConnectionToClient(newsockfd, clientIP);
}
/**
* @brief Closing conncetion gracefully
* @param newsockfd the new socket created for client communications
*/
void closeConnectionToClient(int newsockfd, string clientIP)
{
clock_t time;
char buffer[BUFFERSIZE];
bool receivedAck = false;
bzero(buffer, sizeof(buffer)); // clearing buffer before reading msg
send(newsockfd, ACK, strlen(ACK), 0); // send ACK to client
printToConsole("\nCONNECTION CLOSING: ACK Signal Send To Client " + clientIP);
sleep(WAIT_TIME);
send(newsockfd, FIN, strlen(FIN), 0); // send FIN to client
printToConsole("\nCONNECTION CLOSING: FIN Signal Send To Client " + clientIP);
time = clock();
while ((clock() - time) < TIMEOUT)
{
if (read(newsockfd, buffer, BUFFERSIZE) > 0)
{
printToConsole("\nCONNECTION CLOSING: Last ACK Received From Client " + clientIP);
receivedAck = true;
break;
}
}
if (!receivedAck)
printToConsole("\nACK TIMEOUT: Last ACK From Client " + clientIP + " Not Received.");
close(newsockfd);
printToConsole("\nConnection To Client " + clientIP + " Closed.");
}
/**
* @brief Base64 decoding
* @param encodedMsg the received msg from client
*/
void doBase64Decoding(char *encodedMsg)
{
int n = strlen(encodedMsg);
char *decodedMsg = (char *)malloc(BUFFERSIZE * sizeof(char));
int asciiValue, numberOfBits;
int j, p, k = 0;
for (int i = 1; i < n; i += 4)
{
j = i;
asciiValue = 0;
numberOfBits = 0;
while (j < (i + 4) && j < n)
{
if (encodedMsg[j] != '=')
{
asciiValue = asciiValue << 6;
numberOfBits += 6;
if (encodedMsg[j] >= 'A' && encodedMsg[j] <= 'Z')
{
asciiValue = asciiValue | (encodedMsg[j] - 'A');
}
else if (encodedMsg[j] >= 'a' && encodedMsg[j] <= 'z')
{
asciiValue = asciiValue | (encodedMsg[j] - 'a' + 26);
}
else if (encodedMsg[j] >= '0' && encodedMsg[j] <= '9')
{
asciiValue = asciiValue | (encodedMsg[j] - '0' + 52);
}
else if (encodedMsg[j] == '+')
{
asciiValue = asciiValue | 62;
}
else if (encodedMsg[j] == '/')
{
asciiValue = asciiValue | 63;
}
else
{
printToConsole(("ERROR: Unable To Decode " + encodedMsg[j]));
}
}
else
{
asciiValue = asciiValue >> 2;
numberOfBits -= 2;
}
j++;
}
while (numberOfBits > 0)
{
p = numberOfBits - 8;
decodedMsg[k++] = (asciiValue >> p) & 255;
numberOfBits -= 8;
}
}
decodedMsg[k] = '\0';
printToConsole("\nOriginal Message:\n");
printToConsole(decodedMsg); // original msg send by client
}