-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
111 lines (98 loc) · 2.67 KB
/
main.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cobrecht <cobrecht@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/05/28 13:50:28 by rda-cost #+# #+# */
/* Updated: 2015/06/09 14:38:19 by cobrecht ### ########.fr */
/* */
/* ************************************************************************** */
#include "ncurses_shell.h"
#include <fcntl.h>
#include <unistd.h>
#define LOG "log.txt"
#define MOD S_IRUSR | S_IWUSR |S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH
static void log_txt(char *lg)
{
int fd;
const mode_t mode = MOD;
fd = open(LOG, O_RDWR | O_CREAT | O_APPEND, mode);
write(fd, lg, strlen(lg));
write(fd, "\n", 1);
close(fd);
}
static void net_receive(t_ncurses *nc, t_net *net)
{
char *output;
net_select(net);
if (net->server_response)
{
output = stringf("server > %s", net->server_response);
nc_add(nc, output);
log_txt(output);
free(net->server_response);
free(output);
net->server_response = NULL;
}
}
static void net_alert(t_ncurses *nc, t_net *net)
{
int i;
if (net->alert)
{
i = -1;
while (net->alert[++i])
nc_add(nc, net->alert[i]);
i = -1;
while (net->alert[++i])
free(net->alert[i]);
free(net->alert);
net->alert = NULL;
}
}
static void input_manager(t_ncurses *nc, t_net *client, t_alias *alias)
{
char *zappy_cmd;
if (!client->is_connected && net_parse(nc->input, client))
net_connect(client);
else if (!strcmp(nc->input, "help"))
nc_print_help(nc);
else
{
if ((zappy_cmd = alias_to_cmd(&(alias->map_alias), nc->input)))
{
log_txt(zappy_cmd);
net_send(client, zappy_cmd);
}
else
{
log_txt(nc->input);
net_send(client, nc->input);
}
}
}
int main(int argc, char **argv)
{
t_ncurses nc;
t_net client;
t_alias alias;
(void)argc;
if (!nc_start(&nc, argv))
return (nc_delete(&nc));
net_init(&client);
alias_init(&(alias.map_alias), &(alias.map_cmd));
while (!nc.stopped)
{
nc_loop(&nc);
if (nc.input != NULL)
input_manager(&nc, &client, &alias);
net_alert(&nc, &client);
if (client.is_connected)
net_receive(&nc, &client);
}
if (client.is_connected)
net_close(&client);
return (nc_delete(&nc));
}