-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttps.c
More file actions
99 lines (85 loc) · 1.85 KB
/
Copy pathhttps.c
File metadata and controls
99 lines (85 loc) · 1.85 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
92
93
94
95
96
97
98
99
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <openssl/ssl.h>
#include <openssl/rand.h>
#include <openssl/crypto.h>
#include "https.h"
#include "socket.h"
/*
* @type: GET or POST
* @host: the remote host
* @port: the remote host port
* @path: the path to request
* @resp: response buffer
* @len: the length of response buffer
*/
int https_send_request(enum request type, const char *host, uint16_t port, const char *path, char *resp, int len)
{
char header[512];
int header_len;
if (type == GET)
header_len = http_build_get_header(host, path, header);
else if (type == POST)
header_len = http_build_post_header(host, path, header);
else
return -1;
SSL_library_init();
SSL_CTX *ctx = SSL_CTX_new(SSLv23_client_method());
if (ctx == NULL)
return -1;
SSL *ssl = SSL_new(ctx);
if (ssl == NULL)
goto free_ssl_ctx;
int sockfd = socket_connect(host, port);
if (sockfd < 0)
goto free_ssl;
if (SSL_set_fd(ssl, sockfd) == 0)
goto free_sockfd;
if (SSL_connect(ssl) != 1)
goto free_all;
int nleft = header_len;
int nwritten;
char *ptr = header;
while (nleft > 0) {
if ((nwritten = SSL_write(ssl, ptr, nleft)) <= 0) {
goto free_all;
}
nleft -= nwritten;
ptr += nwritten;
}
/* read response */
int nread;
ptr = resp;
for (;;) {
nread = SSL_read(ssl, ptr, len);
if (nread == 0) { /* receive done */
break;
} else if (nread < 0) {
goto free_all;
}
len -= nread;
ptr += nread;
if (len < 0) /* the buffer of resp is not enough */
goto free_all;
}
return ptr - resp;
free_ssl_ctx:
SSL_CTX_free(ctx);
return -1;
free_ssl:
SSL_CTX_free(ctx);
SSL_free(ssl);
return -1;
free_sockfd:
SSL_CTX_free(ctx);
SSL_free(ssl);
close(sockfd);
return -1;
free_all:
SSL_CTX_free(ctx);
SSL_free(ssl);
close(sockfd);
SSL_shutdown(ssl);
return -1;
}