summaryrefslogtreecommitdiff
path: root/util.c
blob: eaee2d5ede82397f7ad428b04244c47b90290265 (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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/* See COPYING file for copyright and license details. */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "util.h"
#ifndef WINVER
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#else
#include <winsock2.h>
#include <ws2tcpip.h>
#endif

/* plundered from suckless' sic */
conn *dial(char *host, char *port, int ssl)
{
	static struct addrinfo hints;
	int srv;
	struct addrinfo *res, *r;
	conn *c;
	c = malloc(sizeof(conn));
	c->fd = -1;

	#ifdef WINVER
	WSADATA w;
	if(WSAStartup(MAKEWORD(2,2), &w)!= 0) {
		fprintf(stderr, "error: failed to start winsock\n");
		return c;
	}
	#endif

	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	if(getaddrinfo(host, port, &hints, &res) != 0) {
		fprintf(stderr, "error: cannot resolve hostname %s\n", host);
		return c;
	}
	for(r = res; r; r = r->ai_next) {
		if((srv = socket(r->ai_family, r->ai_socktype, r->ai_protocol)) == -1)
			continue;
		if(connect(srv, r->ai_addr, r->ai_addrlen) == 0)
			break;
		close(srv);
	}
	freeaddrinfo(res);
	if(!r) {
		fprintf(stderr, "error: cannot connect to host %s\n", host);
		return c;
	}

	c->fd = srv;
	c->sslcontext = NULL;
	c->sslhandle = NULL;

	if(ssl) {
		SSL_load_error_strings();
		SSL_library_init();
		if((c->sslcontext = SSL_CTX_new(SSLv23_client_method())) == NULL) {
		/*if((c->sslcontext = SSL_CTX_new(TLS_client_method())) == NULL) {*/
			ERR_print_errors_fp(stderr);
		}
		if((c->sslhandle = SSL_new(c->sslcontext)) == NULL) {
			ERR_print_errors_fp(stderr);
		}
		if(SSL_set_fd(c->sslhandle, c->fd) != 1) {
			ERR_print_errors_fp(stderr);
		}
		if(SSL_connect(c->sslhandle) != 1) {
			ERR_print_errors_fp(stderr);
		}

	}
	return c;
}

int request(char *host, int ssl, char *request, char *savecookie, char **body, int istext)
{
	size_t l, res;
	int i, p;
	char m[256];
	char cookie[COOKIEMAX] = "";
	char port[4];
	char *headpos;
	size_t headsize, bodysize;
	char headline[BUFSIZ] = "";
	char *buf, *cur, *pos;
	conn *c;

	if(ssl) {
		strcpy(port, "443");
	} else {
		strcpy(port, "80");
	}
	c = dial(host, port, ssl);
	if(c->fd == -1) {
		return 0;
	}

	if(ssl) {
		if(!SSL_write(c->sslhandle, request, strlen(request))) {
			ERR_print_errors_fp(stderr);
			return 0;
		}
	} else {
		if(!write(c->fd, request, strlen(request))) {
			return 0;
		}
	}

	/* download everything into buf */
	l = 0;
	buf = malloc(sizeof(char *) * BUFSIZ);
	/* TODO: rewrite this so it's clear that only the read call differs, e.g. with
	 *       macros as ii does it, or maybe as a function pointer or something */
	if(ssl) {
		for(; buf != NULL && (res = SSL_read(c->sslhandle, buf+l, BUFSIZ)) > 0; l+=res)
			buf = realloc(buf, sizeof(char *) * (l+BUFSIZ));
	} else {
		for(; buf != NULL && (res = read(c->fd, buf+l, BUFSIZ)) > 0; l+=res)
			buf = realloc(buf, sizeof(char *) * (l+BUFSIZ));
	}

	/* strstr to find end of header */
	if((headpos = strstr(buf, "\r\n\r\n")) == NULL) {
		free(buf);
		return 0;
	}
	headpos += 4;
	headsize = headpos - buf;
	bodysize = l - headsize;
	if(istext) {
		bodysize++; /* for null terminator */
	}

	/* memcopy from there into a large enough buf */
	if((*body = malloc(sizeof(char *) * bodysize)) == NULL) {
		free(buf);
		return 0;
	}
	memcpy(*body, headpos, sizeof(char *) * (l - headsize));
	if(istext) {
		(*body)[bodysize - 1] = '\0';
	}

	/* parse header as needed */
	snprintf(m, 256, "Set-Cookie: %%%ds;", COOKIEMAX-1);
	cur = buf;
	while((pos = strstr(cur, "\r\n")) != NULL && cur < (headpos - 4)) {
		strncpy(headline, cur, pos - cur);
		headline[pos - cur] = '\0';
		cur = pos + 2;

		if(sscanf(headline, "HTTP/%d.%d %d", &i, &i, &p) == 3 && p != 200) {
			if(p == 403)
				fprintf(stderr, "403 forbidden: your IP address may be temporarily blocked\n");
			free(buf);
			free(*body);
			return 0;
		}

		if(savecookie != NULL && sscanf(headline, m, cookie)) {
			strncat(savecookie, cookie, COOKIEMAX - strlen(savecookie) - 1);
		}
	}

	free(buf);

	return l;
}

int get(char *host, int ssl, char *path, char *sendcookie, char *savecookie, char **body, int istext)
{
	char h[BUFSIZ] = "";
	char c[COOKIEMAX] = "";

	if(sendcookie && sendcookie[0])
		snprintf(c, COOKIEMAX, "\r\nCookie: %s", sendcookie);
	snprintf(h, BUFSIZ, "GET %s HTTP/1.0\r\nUser-Agent: getxbook-"VERSION \
	                    " (not mozilla)\r\nHost: %s%s\r\n\r\n", path, host, c);

	return request(host, ssl, h, savecookie, body, istext);
}

int post(char *host, int ssl, char *path, char *sendcookie, char *savecookie, char *data, char **body, int istext)
{
	char h[BUFSIZ] = "";
	char c[COOKIEMAX] = "";

	if(sendcookie && sendcookie[0])
		snprintf(c, COOKIEMAX, "\r\nCookie: %s", sendcookie);
	snprintf(h, BUFSIZ, "POST %s HTTP/1.0\r\nUser-Agent: getxbook-"VERSION \
	                    " (not mozilla)\r\nContent-Length: %d\r\n" \
	                    "Content-Type: application/x-www-form-urlencoded\r\n" \
	                    "Host: %s%s\r\n\r\n%s\r\n",
	                    path, (int)strlen(data), host, c, data);

	return request(host, ssl, h, savecookie, body, istext);
}

int gettofile(char *host, int ssl, char *url, char *sendcookie, char *savecookie, char *savepath, int istext)
{
	char *buf = 0;
	FILE *f;
	size_t i, l;

	if(!(l = get(host, ssl, url, sendcookie, savecookie, &buf, istext))) {
		fprintf(stderr, "Could not download %s\n", url);
		return 1;
	}
	if((f = fopen(savepath, "wb")) == NULL) {
		fprintf(stderr, "Could not create file %s\n", savepath);
		free(buf); return 1;
	}

	for(i=0; i < l; i+=BUFSIZ)
		if(!fwrite(buf+i, l-i > BUFSIZ ? BUFSIZ : l-i, 1, f)) {
			fprintf(stderr, "Error writing file %s\n", savepath);
			free(buf); fclose(f); return 1;
		}

	free(buf);
	fclose(f);

	return 0;
}

int renameifjpg(char *path)
{
	FILE *f;
	char *newpath, *c;

	if((f = fopen(path, "rb")) == NULL)
		return 1;

	if(fgetc(f) == 255) {
		if((newpath = malloc(strlen(path) + 1)) == NULL) {
			fclose(f);
			return 1;
		}
		strncpy(newpath, path, strlen(path)+1);
		c = strrchr(newpath, '.');
		strncpy(c+1, "jpg\0", 4);

		if(rename(path, newpath)) {
			free(newpath);
			fclose(f);
			return 1;
		}
		free(newpath);
	}

	fclose(f);

	return 0;
}