forked from rovinbhandari/FTP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_ftp.c
100 lines (78 loc) · 2.34 KB
/
server_ftp.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
#include <server_ftp.h>
size_t size_sockaddr = sizeof(struct sockaddr), size_packet = sizeof(struct packet);
void* serve_client(void*);
int main(void)
{
//BEGIN: initialization
struct sockaddr_in sin_server, sin_client;
int sfd_server, sfd_client, x;
short int connection_id = 0;
if((x = sfd_server = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
er("socket()", x);
memset((char*) &sin_server, 0, sizeof(struct sockaddr_in));
sin_server.sin_family = AF_INET;
sin_server.sin_port = htons(PORTSERVER);
sin_server.sin_addr.s_addr = htonl(INADDR_ANY);
if((x = bind(sfd_server, (struct sockaddr*) &sin_server, size_sockaddr)) < 0)
er("bind()", x);
if((x = listen(sfd_server, 1)) < 0)
er("listen()", x);
printf(ID "FTP Server started up @ local:%d. Waiting for client(s)...\n\n", PORTSERVER);
//END: initialization
while(1)
{
if((x = sfd_client = accept(sfd_server, (struct sockaddr*) &sin_client, &size_sockaddr)) < 0)
er("accept()", x);
printf(ID "Communication started with %s:%d\n", inet_ntoa(sin_client.sin_addr), ntohs(sin_client.sin_port));
fflush(stdout);
struct client_info* ci = client_info_alloc(sfd_client, connection_id++);
serve_client(ci);
}
close(sfd_server);
printf(ID "Done.\n");
fflush(stdout);
return 0;
}
void* serve_client(void* info)
{
int sfd_client, connection_id, x;
struct packet* data = (struct packet*) malloc(size_packet);
struct packet* shp;
char path[LENBUFFER];
struct client_info* ci = (struct client_info*) info;
sfd_client = ci->sfd;
connection_id = ci->cid;
while(1)
{
if((x = recv(sfd_client, data, size_packet, 0)) == 0)
{
fprintf(stderr, "client closed/terminated. closing connection.\n");
break;
}
shp = ntohp(data);
if(shp->type == TERM)
break;
shp->conid = connection_id;
if(shp->type == REQU)
{
//send info and then proceed to complete the request
shp->type = INFO;
strcpy(path, shp->buffer);
sprintf(shp->buffer, "File found. Processing...");
data = htonp(shp);
if((x = send(sfd_client, data, size_packet, 0)) != size_packet)
er("send()", x);
send_file(path, sfd_client, shp);
send_TERM(sfd_client, shp);
}
else
{
//show error, send TERM and break
fprintf(stderr, "packet incomprihensible. closing connection.\n");
send_TERM(sfd_client, shp);
break;
}
}
close(sfd_client);
fflush(stdout);
}