summaryrefslogtreecommitdiff
path: root/set4/task31.c
blob: 1c613dd145983feedb3b74176d2e7a67e5226882 (plain)
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
#include "../lib/lib.h"
#include "../lib/lib2.h"
#include "../lib/lib3.h"
#include "../lib/lib4.h"
#include <time.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <math.h>

int get_max(long *numbers, int length)
{
	long max;
	int ret;
	int i;

	for(i=0;i<length;i++) {
		if(numbers[i] > max) {
			max = numbers[i];
			ret = i;
		}
	}

	return ret;
}

int main(int argc, char **argv)
{
	int socket_fd;
	struct sockaddr_in serv_addr;
	char *server_addr = "127.0.0.1";
	char *http_request_template = "GET /?file=neu&signature=%s HTTP/1.1\r\n\r\n";
	// sha1 is 20 bytes, in hex 40
	char *signature = malloc(40+1);
	char *http_request = malloc(strlen(http_request_template) + 20);
	memset(signature, '0', 40+1);
	signature[40] = '\0';
	struct timespec time;
	int i, j;
	char c;
	long response_times[16];
	char *response = malloc(2000);


	for(i=0;i<40;i++) {
		for(j=0;j<16;j++) {
			// connect to localhost:80
			socket_fd = socket(AF_INET, SOCK_STREAM, 0);

			if (socket_fd == -1)
				perror("Can not create socket");

			serv_addr.sin_family = AF_INET;
			serv_addr.sin_port = htons(8080);
			serv_addr.sin_addr.s_addr = inet_addr(server_addr);

			if(connect(socket_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
				perror("Can not connect");
			}
			// send http request
			// brute force every byte of the signature
			c = j > 9 ? 'a' + (j-10) : '0' + j;
			signature[i] = c;
			sprintf(http_request, http_request_template, signature);
			//printf("request: %s\n", http_request);
			clock_gettime(CLOCK_MONOTONIC, &time);
			long start_time = (time.tv_sec * 1000000 + time.tv_nsec/1000);

			write(socket_fd, http_request, strlen(http_request));


			read(socket_fd, response, 2000);

			clock_gettime(CLOCK_REALTIME, &time);

			long stop_time = time.tv_sec * 1000000 + time.tv_nsec/1000;

			memset(response, 0, 2000);
			response_times[j] = (stop_time) - (start_time);

			close(socket_fd);
		}
		// ok now choose the right one (the one where the latency is max
		int index = get_max(response_times, 16);
		signature[i] = index > 9 ? 'a' + (index-10) : '0' + index;
		printf("signature so far: %s\n", signature);
	}
}