-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmain.c
114 lines (104 loc) · 2.88 KB
/
cmain.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* cmain.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ttshivhu <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/08/15 09:00:29 by ttshivhu #+# #+# */
/* Updated: 2018/08/15 12:07:28 by ttshivhu ### ########.fr */
/* */
/* ************************************************************************** */
#include <ftp.h>
static void receive_data(int sock_fd, size_t size)
{
char buff[BUFF_SIZE];
size_t received;
size_t c;
received = 0;
while (received < size)
{
c = recv(sock_fd, buff, BUFF_SIZE, 0);
write(1, buff, c);
received += c;
}
received ? ft_putchar('\n') : 0;
}
static void process_commands(int sock_fd, char *str)
{
size_t size;
char cmd[BUFF_SIZE];
send(sock_fd, str, sizeof(cmd), 0);
if (!ft_strncmp(str, "put", 3))
client_put(sock_fd, ft_strchr(str, ' ') + 1);
if (!ft_strncmp(str, "get", 3))
client_get(sock_fd, ft_strchr(str, ' ') + 1);
if (!ft_strncmp(str, "quit", 4))
exit(0);
recv(sock_fd, &size, sizeof(size_t), 0);
receive_data(sock_fd, size);
}
static int check_local(char *cmd)
{
if (!ft_strncmp("clear", cmd, 5))
{
ft_putstr("\e[1;1H\e[2J");
return (1);
}
if (!ft_strncmp("lcd", cmd, 3))
{
local_cd(ft_strchr(cmd, ' ') + 1);
return (1);
}
if (!ft_strncmp("lpwd", cmd, 4))
{
local_pwd();
return (1);
}
if (!ft_strncmp("lls", cmd, 3))
{
local_ls(cmd);
return (1);
}
return (0);
}
static void ftp_shell(int sock_fd)
{
int ret;
char *cmd;
char *tmp;
tmp = readline("\x1b[34mftp >\x1b[0m ");
cmd = ft_strtrim(tmp);
tmp ? free(tmp) : 0;
ret = ft_strlen(cmd);
if (ret == 0)
ft_putchar('\n');
if (ret == 1 || check_local(cmd))
{
cmd ? free(cmd) : 0;
return ;
}
process_commands(sock_fd, cmd);
cmd ? free(cmd) : 0;
}
int main(int c, char **v)
{
struct sockaddr_in addr;
struct hostent *host;
int fd;
if (c != 3)
ft_die("Usage: ./client host port\n", 1);
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
ft_die(ERROR" client socket creation failed\n", 1);
addr.sin_family = AF_INET;
addr.sin_port = htons(ft_atoi(v[2]));
if ((host = gethostbyname(v[1])) == NULL)
ft_die(ERROR" check your host\n", 1);
ft_memcpy(&addr.sin_addr.s_addr, host->h_addr, host->h_length);
if (connect(fd, (void*)&(addr), sizeof(addr)) < 0)
ft_die(ERROR" unable to connect\n", 1);
ft_putstr("\e[1;1H\e[2J");
while (42)
ftp_shell(fd);
return (0);
}