This repository has been archived by the owner on May 25, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathras_server.cpp
66 lines (57 loc) · 1.55 KB
/
ras_server.cpp
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
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include <signal.h>
int main(int argc, char *argv[]) {
if(argc != 2) {
fprintf(stderr, "Usage: %s <port>\n", argv[0]);
exit(1);
}
char *execute_directory = getcwd(NULL, 0);
char shell_path[strlen(execute_directory) + 10];
sprintf(shell_path, "%s/shell", execute_directory);
free(execute_directory);
if (chdir(RAS_ROOT) == -1) {
fprintf(stderr, "Unable to change current directory to \"%s\".\n", RAS_ROOT);
exit(1);
}
signal(SIGCHLD, SIG_IGN);
int listen_fd;
struct sockaddr_in listen_addr;
memset(&listen_addr, 0, sizeof(listen_addr));
listen_addr.sin_family = AF_INET;
listen_addr.sin_addr.s_addr = htonl(INADDR_ANY);
listen_addr.sin_port = htons(atoi(argv[1]));
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if(listen_fd == -1) {
fputs("Cannot create socket.\n", stderr);
exit(2);
}
if(bind(listen_fd, (struct sockaddr *) &listen_addr, sizeof(listen_addr)) == -1) {
fputs("Cannot bind.\n", stderr);
exit(2);
}
if(listen(listen_fd, 1024) == -1) {
fputs("Cannot listen.\n", stderr);
exit(2);
}
while(1) {
int accept_fd = accept(listen_fd, NULL, NULL);
if (accept_fd >= 0 && fork() == 0) {
dup2(accept_fd, STDOUT_FILENO);
dup2(accept_fd, STDERR_FILENO);
dup2(accept_fd, STDIN_FILENO);
close(accept_fd);
close(listen_fd);
execlp(shell_path, shell_path, NULL);
fputs("Fail to start the shell", stderr);
exit(3);
}
close(accept_fd);
}
}