-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclientThread.c
More file actions
329 lines (282 loc) · 10.4 KB
/
Copy pathclientThread.c
File metadata and controls
329 lines (282 loc) · 10.4 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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <pthread.h>
#include <ctype.h>
#include <sys/stat.h>
#include <time.h>
#define BUFFER_SIZE 512
#define EXIT_KEYWORD "EXIT"
#define KICKED_OUT_MESSAGE ">> Kicked Out..."
#define REPORT_KICKED_OUT_MESSAGE ">> Kicked Out because of multiple reports..."
#define USERNAME_MESSAGE ">> USERNAME HAS ALREADY BEEN TAKEN..."
void error(char *msg){
perror(msg);
exit(0);
}
// unique sockedId for a client
int sockfd;
// message receiver from other clients will be present inside this file
char* fileName;
void sanitize_filename(char *name) {
for (int i = 0; name[i]; i++) {
if (!(isalnum(name[i]) || name[i] == '.' || name[i] == '_'))
name[i] = '_';
}
}
bool is_safe_filename(const char *name) {
if (strstr(name, "..")) return false;
if (strchr(name, '/')) return false;
if (strchr(name, '\\')) return false;
return true;
}
void encrypt_message(char* input, char* encrypted) {
// to send encrypted message to server
// message format "@username <message>"
// file format "@username @file <file name>"
// report format "#username"
// group format "$CREATE <groupName>" , "$JOIN <groupName>" "$LEAVE <groupName>" no encryption needed , as it is request to server
// group format "$groupName <message>"
// only message part needs to be encrypted
int len = strlen(input);
int pos = 0;
int last = 0;
if(!strcmp(input, EXIT_KEYWORD) ) {
while(input[pos] != '\0') encrypted[last++] = input[pos++];
encrypted[last]='\0';
return ;
}
// for group
if(input[0] == '$'){
char query[256], message[256];
sscanf(input,"$%s %s",query,message);
// no encryption for request to server
if( (strcmp(query,"CREATE") == 0) || (strcmp(query,"JOIN") == 0) || (strcmp(query,"LEAVE") == 0) || (strcmp(query,"SHOW_ALL")==0 ) ){
while(input[pos] != '\0') encrypted[last++] = input[pos++];
encrypted[last]='\0';
return ;
}
// add "$groupName" to encryted messagage
else{
while(input[pos] != ' ') encrypted[last++] = input[pos++];
encrypted[last++]=input[pos++];
}
}
// add "@username" or "#username" to encryted message
if(input[0] == '@' || input[0] == '#') {
while(input[last] != ' ' && input[last] != '\0') {
encrypted[pos++] = input[last++];
}
if(input[last] == ' ') encrypted[pos++] = input[last++];
}
// for adding the file text to encrypt message
if(input[last] == '@') {
while(input[last] != ' ' && input[last] != '\0') {
encrypted[pos++] = input[last++];
}
if(input[last] == ' ') encrypted[pos++] = input[last++];
// reads the fileName from the input message
char fileName[256];
snprintf(fileName, sizeof(fileName), "%s", input + last);
while(input[last] != '\0') {
encrypted[pos++] = input[last++];
}
encrypted[pos++] = ' ';
char fileData[1024] = {0};
FILE* file = fopen(fileName, "r");
if (!file) {
perror("File open failed");
encrypted[pos] = '\0';
return;
}
fgets(fileData, sizeof(fileData), file);
fclose(file);
// Encrypt fileData directly (reversed 3-digit ASCII)
int fdlen = strlen(fileData);
for (int i = fdlen - 1; i >= 0; i--) {
pos += sprintf(encrypted + pos, "%03d", (unsigned char)fileData[i]);
}
encrypted[pos] = '\0';
return;
}
// encrypt the message or fileContent
// takes the last character and add 3 digit ascii code in the encrypt message
len = strlen(input);
for(int i = len - 1; i >= last; i--) {
pos += sprintf(encrypted + pos, "%03d", (unsigned char)input[i]);
}
encrypted[pos] = '\0';
}
void decrypt_message(char* input, char* decrypted) {
// to dencrypt message received through server
// message format "@username[H:M] <message>"
// file format "@username[H:M] @file <file name> <content>"
// only message part needs to be dencrypted
int i = 0, j = 0;
char fileName[256];
bool gotFile = false;
memset(decrypted, 0, BUFFER_SIZE * 3);
// no decryption for direct response from server
if(input[0] == '>'){
while(input[i] != '.') decrypted[j++] = input[i++];
decrypted[j]='\0';
return ;
}
// copy the input message till username[H:M]
while(input[i] != ' ') decrypted[j++] = input[i++];
decrypted[j++] = input[i++];
decrypted[j++] = input[i++];
decrypted[j++] = input[i++];
// if input message type is file, we extract file name
if(input[i] == '@') {
gotFile = true;
i += 6;
int k = 1;
while(input[i + k - 1] != ' ') k++;
strncpy(fileName, input + i, k-1);
fileName[k-1] = '\0';
i += k;
}
// decrypt the message or file content
int len = strlen(input);
char temp[4];
int revIndex = 0, revLen = (len - i) / 3;
char reversed[revLen + 1];
while(input[i] >= '0' && input[i] <= '9' && input[i+1] >= '0' && input[i+1] <= '9' && input[i+2] >= '0' && input[i+2] <= '9') {
strncpy(temp, input + i, 3);
temp[3] = '\0';
reversed[revIndex++] = (char)atoi(temp);
i += 3;
}
reversed[revIndex] = '\0';
if(!gotFile) {
// if input was message type, add the message to decrypted message
for(int k = revIndex - 1; k >= 0; k--) decrypted[j++] = reversed[k];
decrypted[j] = '\0';
}
else {
// if input was file type, open the file <file name> and add the content
// inform the receiver that a file was sent by @username
FILE* file = fopen(fileName, "a+");
for(int k = revIndex - 1; k >= 0; k--) {
fprintf(file, "%c", reversed[k]);
}
fclose(file);
char message[512];
snprintf(message, sizeof(message), "I sent you a file named %s", fileName);
strcat(decrypted, message);
}
}
void* listen_messages(void *arg) {
char* buffer = (char*)malloc(BUFFER_SIZE);
char* decrypt = (char*)malloc(BUFFER_SIZE * 3);
// opening the Chat file
FILE* chatPad = (FILE*)arg;
if(!chatPad) {
perror("Error opening chat file in thread");
return NULL;
}
while(true){
memset(buffer, 0, BUFFER_SIZE);
memset(decrypt, 0, BUFFER_SIZE * 3);
ssize_t n = read(sockfd, buffer, BUFFER_SIZE - 1);
if(n > 0) {
buffer[n] = '\0';
// if message received from server contains "Kicked Out"
if(strcmp(buffer, KICKED_OUT_MESSAGE) == 0 ||
strcmp(buffer, REPORT_KICKED_OUT_MESSAGE) == 0 ||
strcmp(buffer, ">> Kicked Out due to idleness...") == 0){
printf("\nYou have been kicked out...\n");
fclose(chatPad);
_exit(EXIT_FAILURE);
}
if(strcmp(buffer, USERNAME_MESSAGE) == 0){
printf("\n%s\n", USERNAME_MESSAGE);
fclose(chatPad);
_exit(EXIT_FAILURE);
}
// decrypt the message received through server
decrypt_message(buffer, decrypt);
fprintf(chatPad, "%s\n", decrypt);
fflush(chatPad);
fflush(stdout);
}
else if(n == 0) {
// server has closed the connection
printf("\nServer closed the connection. Exiting...\n");
fclose(chatPad);
exit(0);
}
else error("ERROR reading from socket");
}
return NULL;
}
int main(int argc, char *argv[]) {
int portno;
struct sockaddr_in server_address;
struct hostent *server;
char* buffer = (char*)malloc(BUFFER_SIZE);
char* encrypt = (char*)malloc(BUFFER_SIZE * 3);
if(argc < 4) {
fprintf(stderr, "Usage: %s <hostname> <port> <name>\n", argv[0]);
exit(1);
}
// port number is thrid element
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0) error("ERROR opening socket");
// fetching host name using the ip address
server = gethostbyname(argv[1]);
if(server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
// clearing server_address and creating the headers and payload for connection
bzero((char *) &server_address, sizeof(server_address));
server_address.sin_family = AF_INET;
bcopy((char *)server->h_addr_list[0], (char *)&server_address.sin_addr.s_addr, server->h_length);
server_address.sin_port = htons(portno);
// connecting to server
if(connect(sockfd,(struct sockaddr *)&server_address,sizeof(server_address)) < 0) error("ERROR connecting");
// assigning the name to the client
bzero(buffer, BUFFER_SIZE);
snprintf(buffer, BUFFER_SIZE, "%s", argv[3]);
//opening the file with client name to see the message from other clients
fileName = (char*)malloc(strlen(argv[3]) + 20);
if(!fileName) error("Memory allocation failed");
mkdir("chat_logs", 0755);
snprintf(fileName, strlen(argv[3]) + 20, "chat_logs/%s.log", argv[3]);
printf("fileName: %s\n", fileName);
FILE* chatPad = fopen(fileName, "a+");
if(!chatPad) error("ERROR opening chat file");
// sending name of client to server
if(write(sockfd, buffer, strlen(buffer)) < 0) error("ERROR sending name");
// creating the thread for receiving response through server
pthread_t listener_thread;
if(pthread_create(&listener_thread, NULL, listen_messages, chatPad) != 0) error("ERROR creating thread");
while(true) {
printf("Enter message: ");
bzero(buffer, BUFFER_SIZE);
if(fgets(buffer, BUFFER_SIZE, stdin) == NULL) {
// EOF on stdin: send EXIT and break
write(sockfd, EXIT_KEYWORD, strlen(EXIT_KEYWORD));
break;
}
buffer[strcspn(buffer, "\n")] = 0;
fprintf(chatPad, "Me: %s\n", buffer);
fflush(chatPad);
// encrypting the message of client and then sending the encrypted message to server
encrypt_message(buffer, encrypt);
if(write(sockfd, encrypt, strlen(encrypt)) < 0) error("ERROR writing to socket");
}
fclose(chatPad);
free(fileName);
close(sockfd);
return 0;
}