-
Notifications
You must be signed in to change notification settings - Fork 0
/
ftserver.c
428 lines (337 loc) · 10.2 KB
/
ftserver.c
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/*
** Morgan Brenner
** brennemo@oregonstate.edu
** CS 372 Program 2
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <dirent.h>
#define BUFFER_SIZE 1000
void *get_in_addr(struct sockaddr *sa) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
/*
** Function: fillAddrStruct
**
** Description:
**
** Parameters: port: port number specified in command line
** Returns: pointer to addrinfo to use to create socket
*/
struct addrinfo* fillAddrStruct(char *port) {
struct addrinfo hints, *servinfo;
struct sigaction sa;
int rv;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, port, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
exit(1);
}
return servinfo;
}
/*
** Function: startup
**
** Description: creates and binds socket
**
** Parameters: servinfo: pointer returned by fillAddrStruct
** Returns: sockfd: socket file descriptor
*/
int startup(struct addrinfo *servinfo) {
int sockfd;
if ((sockfd = socket(servinfo->ai_family, servinfo->ai_socktype,
servinfo->ai_protocol)) == -1) {
fprintf(stderr, "server: socket");
}
//bind socket
if (bind(sockfd, servinfo->ai_addr, servinfo->ai_addrlen) == -1) {
close(sockfd);
fprintf(stderr, "server: bind");
exit(1);
}
return sockfd;
}
/*
** Function: initiateOnDataConnection
**
** Description: connects to data connection running on client
**
** Parameters: host: client's host
** port: port number of data connection, specified by client
** Returns: socketfd: socket file descriptor
*/
int initiateOnDataConnection(char *host, char *port) {
struct addrinfo hints, *res;
char ipstr[INET_ADDRSTRLEN];
int socketfd;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM; //TCP
hints.ai_flags = AI_PASSIVE;
//fill addrinfo struct
printf("connection q host: %s, port: %s\n", host, port);
if (getaddrinfo(host, port, &hints, &res) != 0) {
fprintf(stderr,"error: getaddrinfo\n"); return -1;
}
//create socket
socketfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (socketfd == -1) { fprintf(stderr,"error: socket\n"); return -1; }
//establish connection
//status = connect(socketfd, res->ai_addr, res->ai_addrlen);
if (connect(socketfd, res->ai_addr, res->ai_addrlen) == -1) {
fprintf(stderr,"error: data connection\n");
close(socketfd);
return -1;
}
freeaddrinfo(res); //free linked list
return socketfd;
}
/*
** Function: listDirectory
**
** Description: reads file names from current directory, stores names in
** a string delimited by newlines, and sends string to client
**
** Parameters: host: client's host
** port: port number of data connection, specified by client
** Returns: 0 on success, -1 on failure
*/
int listDirectory(char* host, char* port) {
int q_fd; //data connection file descriptor
char fileNames[BUFFER_SIZE];
DIR *dp;
struct dirent *ep;
int n;
memset(fileNames, '\0', sizeof fileNames);
dp = opendir("./");
if (dp != NULL)
{
//build string containing all filenames, separated by newlines
while (ep = readdir(dp)) {
strcat(fileNames, ep->d_name);
strcat(fileNames, "\n");
}
(void)closedir(dp);
}
else {
fprintf(stderr, "error: opendir\n");
return -1;
}
//printf("%s", fileNames);
q_fd = initiateOnDataConnection(host, port);
if (q_fd == -1) { return -1; }
//test sending a short string without loop
printf("Sending directory contents to %s:%s\n", host, port);
n = send(q_fd, fileNames, strlen(fileNames), 0);
close(q_fd);
return n==-1?-1:0;
}
/*
** Function: findFile
**
** Description: searches for file in the current directory
** and returns the result
**
** Parameters: fileName: name of file to search for
** Returns: 1 if found, 0 if not found
*/
int findFile(char* fileName) {
DIR *dp;
struct dirent *ep;
dp = opendir("./");
if (dp != NULL) {
while (ep = readdir(dp)) {
if (strcmp(ep->d_name, fileName) == 0) {
return 1;
}
}
}
return 0; //file not found
}
/*
** Function: getFileSize
**
** Description: gets the size of the file to be sent to the client
**
** Parameters: fileName: name of file to open
** Returns: size of file
*/
unsigned long getFileSize(char* fileName) {
unsigned long fileSize;
FILE* requestedFile = fopen(fileName, "r");
fseek(requestedFile, 0, SEEK_END);
fileSize = ftell(requestedFile);
fseek(requestedFile, 0, SEEK_SET);
fclose(requestedFile);
return fileSize;
}
/*
** Function: sendFile
**
** Description: connects to client on data connection, then repeatedly
** reads and sends 1000-byte chunks of file to client
**
** Parameters: fileName: name of file to send
** Parameters: host: client's host
** port: port number of data connection, specified by client
** Returns: 0 on success, -1 on failure
*/
int sendFile(char* fileName, char* host, char* port) {
int q_fd; //data connection file descriptor
FILE* requestedFile = fopen(fileName, "r");
char fileLine[BUFFER_SIZE];
unsigned long fileSize;
int len, bytesleft, n;
int total = 0; // how many bytes we've sent
fileSize = getFileSize(fileName);
q_fd = initiateOnDataConnection(host, port);
if (q_fd == -1) { return -1; }
printf("Sending \"%s\" to %s:%s\n", fileName, host, port);
len = fileSize;
bytesleft = len;
memset(fileLine, '\0', sizeof fileLine);
//read and send 1000-byte chunks until bytes sent reaches the size of the file
while(total < len) {
fgets(fileLine, (sizeof fileLine) - 1, requestedFile);
n = send(q_fd, fileLine, strlen(fileLine), 0);
if (n == -1) { break; }
total += n;
bytesleft -= n;
//printf("line: %s\n", fileLine);
memset(fileLine, '\0', sizeof fileLine);
}
sleep(1); //let last packet arrive before "@@"
send(q_fd, "@@", 3, 0); //"@@" lets client know this is the end of the transfer
fclose(requestedFile);
close(q_fd);
return n==-1?-1:0;
}
/*
** Function: handleRequest
**
** Description: gets and parses client's, checks options, and completes
** requested transfer
**
** Parameters:
** Returns:
*/
int handleRequest(int new_fd, char* clientHost) {
char dataPort[6];
char fileName[BUFFER_SIZE];
char buffer[BUFFER_SIZE];
char errorMessage[15] = "FILE NOT FOUND";
char* p; //ptr for stringtok
memset(fileName, '\0', sizeof fileName);
memset(buffer, '\0', sizeof buffer);
//get command from client
recv(new_fd, buffer, BUFFER_SIZE - 1, 0);
//send directory contents
if (strncmp(buffer, "l", 1) == 0) {
p = strtok (buffer, " "); //command
p = strtok (NULL, " "); //port
if (p != NULL) {
memcpy(dataPort, p, strlen(p));
} else {
fprintf(stderr, "error: data port");
return 1;
}
printf("List directory requested on port %s.\n", clientHost);
if (listDirectory(clientHost, dataPort) == -1) { fprintf(stderr, "error: list directory\n"); return 1; };
}
//send file
else if (strncmp(buffer, "g", 1) == 0) {
p = strtok (buffer, " "); //command
p = strtok (NULL, " "); //file name
if (p != NULL) {
memcpy(fileName, p, strlen(p));
} else {
fprintf(stderr, "error: file name");
return 1;
}
p = strtok (NULL, " "); //port
if (p != NULL) {
memcpy(dataPort, p, strlen(p));
} else {
fprintf(stderr, "error: data port");
return 1;
}
//send error message if not found
if (!findFile(fileName)) {
fprintf(stderr, "File not found. Sending error message to %s:%s\n", clientHost, dataPort);
send(new_fd, errorMessage, strlen(errorMessage), 0);
return 1;
} else {
send(new_fd, "ok", 3, 0);
//get ok to connect to data socket
memset(buffer, '\0', sizeof buffer);
while (strcmp(buffer, "ok") != 0) {
memset(buffer, '\0', sizeof buffer);
recv(new_fd, buffer, BUFFER_SIZE - 1, 0);
}
//send file to client
printf("File \"%s\" requested on port %s.\n", fileName, dataPort);
if (sendFile(fileName, clientHost, dataPort) == -1 ) { fprintf(stderr, "error: send file\n"); return 1; }
}
} else {
fprintf(stderr, "error: invalid command\n");
return 1;
}
return 0;
}
int main(int argc, char *argv[]) {
int sockfd, new_fd; // listen on sock_fd, new connection on new_fd
struct addrinfo hints, *servinfo;
struct sockaddr_in their_addr; // connector's address information
socklen_t sin_size;
char s[INET_ADDRSTRLEN];
char clientHost[1024], clientService[20]; //getnameinfo
//validate command line parameters
if (argc != 2) { fprintf(stderr,"USAGE: ./ftserver <SERVER_PORT>\n"); exit(1); }
//check that ports are numbers, not reserved ports, or out of range
if (atoi(argv[1]) == 0 || atoi(argv[1]) < 1024 || atoi(argv[1]) > 65535) {
fprintf(stderr,"USAGE: ./ftserver <SERVER_PORT>\n"); exit(1);
}
servinfo = fillAddrStruct(argv[1]); //get addrinfo with port number
sockfd = startup(servinfo); //create and bind socket
freeaddrinfo(servinfo);
if (servinfo == NULL) {
fprintf(stderr, "server: failed to bind\n");
exit(1);
}
if (listen(sockfd, 1) == -1) {
fprintf(stderr, "error: listen");
exit(1);
}
//start on host A
printf("Server open on %s\n", argv[1]);
//repeatedly wait on <PORTNUM> for client (until terminated by SIGINT)
while(1) {
sin_size = sizeof their_addr;
//establish TCP control connection on <SERVER_PORT>, i.e., connection P
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
fprintf(stderr, "error: accept");
continue;
}
//get name of client host and port number
getnameinfo((struct sockaddr *)&their_addr, sizeof their_addr, clientHost, sizeof clientHost, clientService, sizeof clientService, 0);
printf("Connection from %s.\n", clientHost);
//wait on connection P for command from ftclient
handleRequest(new_fd, clientHost);
//close connection P and terminate
close(new_fd);
}
return 0;
}