-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
91 lines (83 loc) · 2.4 KB
/
main.cpp
File metadata and controls
91 lines (83 loc) · 2.4 KB
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
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define SA struct sockaddr
#define MAX 1024
#define PORT 3333
using namespace std;
int get_word(char **string);
bool stringEqual(int len, char *p, const char *q);
int getKey(char **string);
bool encrypt(char*, char*);
char *unmask(char*);
char response[] =
"HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n" "\r\n";
//"Sec-WebSocket-Protocol: chat\r\n\r\n";
//97 = s3pPL...
void func(int sockfd) {
char buff[MAX];
bzero(buff, MAX);
read(sockfd, buff, sizeof(buff));
char *string = buff;
int i = getKey(&string);
if (i) {
printf("%s\n", string);
if (encrypt(string, &response[97])) {
printf("%s\n%d\n", response, (int)sizeof(response));
write(sockfd, response, sizeof(response)-1);
while(1) {
bzero(buff, MAX);
i = read(sockfd, buff, sizeof(buff));
printf("%d\n", i);
// for (int j = 0; j < i; j++) printf("%02X\n", buff[j]);
char *s = unmask(buff);
if (s) cout << s << endl;
i = get_word(&s);
if (stringEqual(i, s, "echo")) {
s += 2;
s[0] = (char)0x81;
i = 2;
while (s[i]) i++;
s[1] = i - 2;
write(sockfd, s, i);
}
if (!(buff[1] & 127)) break;
}
}
}
}
int main() {
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
cout << "socket creation failed...\n";
exit(0);
} else cout << "socket successfully created..\n";
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
cout << "socket bind failed...\n";
exit(0);
} else cout << "Socket successfully binded..\n";
if ((listen(sockfd, 5)) != 0) {
cout << "Listen failed...\n";
exit(0);
} else cout << "Server listening..\n";
len = sizeof(cli);
connfd = accept(sockfd, (SA*)&cli, (socklen_t*)&len);
if (connfd < 0) {
cout << "server accept failed..\n";
exit(0);
} else cout << "server accept the client...\n";
func(connfd);
close(sockfd);
}