-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
98 lines (83 loc) · 2.59 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
#include "const.h"
#include "hash.c"
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
/**
* Downloads http://gradlex.blob.core.windows.net/poc/gradle.png . That's it.
* Using HTTP, not HTTPS. Hard coded checksum.
**/
int main() {
const long bufferSize = 65536;
const char *host = "gradlex.blob.core.windows.net";
char path[1000];
snprintf(path, 1000, "/poc/%s", hash);
printf("Download path: %s\n", path);
printf("Connecting...\n");
struct sockaddr_in serv_addr;
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct hostent *server = gethostbyname(host);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(80);
memcpy(&serv_addr.sin_addr.s_addr, server->h_addr, server->h_length);
if (connect(sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
printf("\nConnection Failed \n");
return -1;
}
FILE *f = fopen("gradlex2", "w");
if (f == NULL) {
printf("Error opening file!\n");
exit(1);
}
char header[1024];
snprintf(header, sizeof(header), "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", path, host);
send(sock, header, strlen(header), 0);
char buffer[bufferSize];
long res;
long dataSize = 0;
long messageSize = 0;
long totalSize = 0;
int p = 0;
printf("Downloading file...\n");
do {
res = read(sock, buffer, bufferSize);
if (dataSize == 0) {
char *cl = strstr(strstr(buffer, "Content-Length"), " ");
char *to = strstr(cl, "\r");
dataSize = strtol(cl, &to, 10);
char *end = strstr(buffer, "\r\n\r\n");
messageSize = end - buffer + dataSize + 4;
totalSize = messageSize;
fwrite(end + 4, 1, res - (messageSize - dataSize), f);
printf("0%%");
} else {
fwrite(buffer, 1, res, f);
}
messageSize -= res;
int np = 100 - (int) ((double) messageSize / (double) totalSize * 100);
if (np != p) {
p = np;
if (p % 10 == 0) {
printf("%d%%", p);
} else {
printf(".");
}
fflush(stdout);
}
} while (messageSize > 0);
fclose(f);
printf("\nFile downloaded, checking hash...\n");
char newHash[HASH_SIZE];
hashForFile("gradlex2", newHash);
printf("Hash: %s\n", newHash);
if (strcmp(hash, newHash) != 0) {
printf("Hash did not match :(\n");
return 1;
}
printf("Done!\n");
return 0;
}