summaryrefslogtreecommitdiff
path: root/src/http/http.c
blob: 4576d04d8270402f8faebc3d2ed446f8387004cf (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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
/*
Copyright (c) 2015
	Michał Cichoń <thedmd@interia.pl>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "config.h"
#include "http.h"
#include <Windows.h>
#include <winhttp.h>
#pragma comment(lib, "winhttp.lib")

struct _http_t {
	HINTERNET		session;
	HINTERNET		connection;
	wchar_t*		endpoint;
	wchar_t*		securePort;
	wchar_t*		autoProxy;
	wchar_t*		proxy;
	wchar_t*		proxyUsername;
	wchar_t*		proxyPassword;
	char*			error;
};

static char* HttpToString(const wchar_t* wideString, int size);
static wchar_t* HttpToWideString(const char* string, int size);
static bool HttpCreateConnection (http_t http);
static void HttpCloseConnection (http_t http);
static void HttpSetLastError (http_t http, const char* message);
static void HttpSetLastErrorW (http_t http, const wchar_t* message);
static void HttpSetLastErrorFromWinHttp (http_t http);
static char* HttpFormatWinApiError (DWORD errorCode, HINSTANCE module);
static char* HttpFormatWinHttpError (DWORD errorCode);
static void HttpClearProxy (http_t http);

# define WINHTTP_SAFE(condition) do { if (condition) break; HttpSetLastErrorFromWinHttp (http); return false; } while (false)
# define WINHTTP_SAFE_DONE(condition) do { if (condition) break; HttpSetLastErrorFromWinHttp (http); goto done; } while (false)

static char* HttpToString(const wchar_t* wideString, int size) {
	int utfSize = WideCharToMultiByte(CP_UTF8, 0, wideString, size, NULL, 0, NULL, NULL);
	char* utfMessage = malloc(utfSize + 1);
	if (utfMessage)	{
		utfMessage[utfSize] = 0;
		WideCharToMultiByte(CP_UTF8, 0, wideString, size, utfMessage, utfSize, NULL, NULL);
	}
	return utfMessage;
}

static wchar_t* HttpToWideString(const char* string, int size) {
	int wideSize = MultiByteToWideChar(CP_UTF8, 0, string, size, NULL, 0);
	int wideBytes = (wideSize + 1) * sizeof(wchar_t);
	wchar_t* wideMessage = malloc(wideBytes);
	if (wideMessage) {
		wideMessage[wideSize] = 0;
		MultiByteToWideChar(CP_UTF8, 0, string, size, wideMessage, wideSize);
	}
	return wideMessage;
}


static bool HttpCreateConnection (http_t http) {
	INTERNET_PORT defaultPort = INTERNET_DEFAULT_PORT;

	HttpCloseConnection (http);

	http->session = WinHttpOpen(
		L"WinHTTP/1.0",
		WINHTTP_ACCESS_TYPE_NO_PROXY,
		WINHTTP_NO_PROXY_NAME,
		WINHTTP_NO_PROXY_BYPASS,
		0);
	WINHTTP_SAFE(http->session != NULL);

	WinHttpSetTimeouts(http->session,
		60 * 1000,  // DNS time-out
		60 * 1000,  // connect time-out
		30 * 1000,  // send time-out
		30 * 1000); // receive time-out

	http->connection = WinHttpConnect(
		http->session,
		http->endpoint,
		defaultPort,
		0);
	WINHTTP_SAFE(http->connection != NULL);

	return true;
}

static void HttpCloseConnection (http_t http) {
	if (http->connection) {
		WinHttpCloseHandle(http->connection);
		http->connection = NULL;
	}

	if (http->session) {
		WinHttpCloseHandle(http->session);
		http->session = NULL;
	}
}

static void HttpSetLastError (http_t http, const char* message) {
	free(http->error);
	http->error = NULL;

	if (message)
		http->error = strdup(message);
}

static void HttpSetLastErrorW (http_t http, const wchar_t* message) {
	free(http->error);
	http->error = NULL;

	if (message)
		http->error = HttpToString(message, wcslen(message));
}

static void HttpSetLastErrorFromWinHttp (http_t http) {
	free(http->error);
	http->error = NULL;

	DWORD error = GetLastError();
	if (error)
		http->error = HttpFormatWinHttpError(error);
}

static char* HttpFormatWinApiError (DWORD errorCode, HINSTANCE module) {
	const int source_flag = module ? FORMAT_MESSAGE_FROM_HMODULE : FORMAT_MESSAGE_FROM_SYSTEM;

	HLOCAL buffer = NULL;
	int bufferLength = FormatMessageW(
		FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | source_flag,
		(void*)module,
		errorCode,
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		(LPWSTR)&buffer,
		0,
		NULL);

	if (bufferLength > 0) {
		char* message;

		wchar_t* wideMessage = (wchar_t*)buffer;

		/* Drop new line from the end. */
		wchar_t* wideMessageBack = wideMessage + bufferLength - 1;
		while (wideMessageBack > wideMessage && (*wideMessageBack == '\r' || *wideMessageBack == '\n'))
			--wideMessageBack;

		message = HttpToString (wideMessage, wideMessageBack - wideMessage + 1);

		LocalFree(buffer);

		return message;
	}
	else
		return NULL;
}

static char* HttpFormatWinHttpError (DWORD errorCode) {
	if (errorCode >= WINHTTP_ERROR_BASE && errorCode <= WINHTTP_ERROR_LAST) {
		HMODULE module = GetModuleHandleW(L"WinHTTP.dll");
		if (module) {
			char* message = HttpFormatWinApiError(errorCode, module);
			if (message)
				return message;
		}
	}

	return HttpFormatWinApiError(errorCode, NULL);
}

bool HttpInit(http_t* http, const char* endpoint, const char* securePort) {
	http_t out = malloc(sizeof(struct _http_t));
	if (!out)
		return false;
	memset(out, 0, sizeof(struct _http_t));

	out->endpoint   = HttpToWideString(endpoint, -1);
	out->securePort = HttpToWideString(securePort, -1);

	if (!HttpCreateConnection (out)) {
		HttpDestroy (out);
		return false;
	}

	*http = out;
	return true;
}

void HttpDestroy(http_t http) {
	if (http) {
		free(http->endpoint);
		free(http->securePort);
		http->endpoint = NULL;
		http->securePort = NULL;
		HttpCloseConnection (http);
		HttpClearProxy (http);
	}
	free(http);
}

static void HttpClearProxy (http_t http) {
	if (http->autoProxy) {
		free(http->autoProxy);
		http->autoProxy = NULL;
	}

	if (http->proxy) {
		free(http->proxy);
		http->proxy = NULL;
	}

	if (http->proxyUsername) {
		free(http->proxyUsername);
		http->proxyUsername = NULL;
	}

	if (http->proxyPassword) {
		free(http->proxyPassword);
		http->proxyPassword = NULL;
	}
}

bool HttpSetAutoProxy (http_t http, const char* url) {
	HttpClearProxy (http);
	if (HttpSetProxy (http, url)) {
		http->autoProxy = http->proxy;
		http->proxy     = NULL;
		return true;
	}
	else
		return false;
}

static void HttpUrlDecodeInplace (wchar_t* url)
{
	wchar_t* input = url;
	wchar_t* output = url;
	size_t size = wcslen (url);
	while (size > 0) {
		if (input[0] == '%' && iswxdigit(input[1]) && iswxdigit(input[2])) {
			wchar_t hex[3];
			hex[0] = input[1];
			hex[1] = input[2];
			hex[2] = 0;
			*output++ = (wchar_t)(wcstol (hex, NULL, 16));
			input += 3;
			size -= 3;
		}
		else {
			*output++ = *input++;
			--size;
		}
	}

	if (output < input) {
		*output = '\0';
	}
}

bool HttpSetProxy (http_t http, const char* url) {
	URL_COMPONENTS urlComponents;
	wchar_t* wideUrl = NULL;
	wchar_t* wideUrl2 = NULL;
	wchar_t* wideUsername = NULL;
	wchar_t* widePassword = NULL;

	ZeroMemory(&urlComponents, sizeof(urlComponents));
	urlComponents.dwStructSize      = sizeof(urlComponents);
	urlComponents.dwUserNameLength = -1;
	urlComponents.dwPasswordLength = -1;

	wideUrl = HttpToWideString(url, -1);
	if (WinHttpCrackUrl(wideUrl, wcslen(wideUrl), 0, &urlComponents)) {
		if (urlComponents.lpszUserName && urlComponents.dwUserNameLength > 0) {
			wideUsername = wcsdup(urlComponents.lpszUserName);
			wideUsername[urlComponents.dwUserNameLength] = 0;
			HttpUrlDecodeInplace (wideUsername);
		}
		if (urlComponents.lpszPassword && urlComponents.dwPasswordLength > 0) {
			widePassword = wcsdup(urlComponents.lpszPassword);
			widePassword[urlComponents.dwPasswordLength] = 0;
			HttpUrlDecodeInplace (widePassword);
		}
	}

	ZeroMemory(&urlComponents, sizeof(urlComponents));
	urlComponents.dwStructSize = sizeof(urlComponents);
	urlComponents.dwHostNameLength  = -1;
	urlComponents.dwUrlPathLength   = -1;

	if (!WinHttpCrackUrl(wideUrl, wcslen(wideUrl), 0, &urlComponents)) {
		free(wideUsername);
		free(widePassword);
		return false;
	}

	if (urlComponents.lpszHostName && urlComponents.dwHostNameLength > 0) {
		wideUrl2 = wcsdup(urlComponents.lpszHostName);
		wideUrl2[urlComponents.lpszUrlPath - urlComponents.lpszHostName] = 0;
	}

	free(wideUrl);

	HttpClearProxy(http);
	http->proxy         = wideUrl2;
	http->proxyUsername = wideUsername;
	http->proxyPassword = widePassword;
	return true;
}

bool HttpRequest(http_t http, PianoRequest_t * const request) {
	HINTERNET handle = NULL;
	wchar_t* wideQuery = NULL;
	bool requestSent = false;
	bool complete = false;
	int retryLimit = 3;
	size_t responseDataSize;

	wideQuery = HttpToWideString(request->urlPath, -1);
	WINHTTP_SAFE_DONE(wideQuery != NULL);

	handle = WinHttpOpenRequest(
		http->connection,
		L"POST",
		wideQuery,
		L"HTTP/1.1",
		WINHTTP_NO_REFERER,
		WINHTTP_DEFAULT_ACCEPT_TYPES,
		request->secure ? WINHTTP_FLAG_SECURE : 0);
	WINHTTP_SAFE_DONE(handle != NULL);

	if (http->proxy || http->autoProxy) {
		wchar_t* fullUrl;
		DWORD fullUrlSize = 0;
		WINHTTP_PROXY_INFO proxyInfo;
		bool success;

		if (http->autoProxy) {
			WINHTTP_AUTOPROXY_OPTIONS proxyOptions = { 0 };

			success = WinHttpQueryOption(request, WINHTTP_OPTION_URL, NULL, &fullUrlSize);
			WINHTTP_SAFE(!success && GetLastError() == ERROR_INSUFFICIENT_BUFFER);
			fullUrl = calloc(1, fullUrlSize + 1);
			success = WinHttpQueryOption(request, WINHTTP_OPTION_URL, fullUrl, &fullUrlSize);
			if (!success) {
				free(fullUrl);
				WINHTTP_SAFE(success);
			}

			proxyOptions.lpszAutoConfigUrl = http->autoProxy;
			proxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;

			if (!(success = WinHttpGetProxyForUrl(http->session, fullUrl, &proxyOptions, &proxyInfo))) {
				proxyOptions.fAutoLogonIfChallenged = true;
				success = WinHttpGetProxyForUrl(http->session, fullUrl, &proxyOptions, &proxyInfo);
			}

			if (!success) {
				free(fullUrl);
				WINHTTP_SAFE(success);
			}
		}
		else {
			proxyInfo.dwAccessType    = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
			proxyInfo.lpszProxy       = http->proxy;
			proxyInfo.lpszProxyBypass = NULL;
		}

		WINHTTP_SAFE(WinHttpSetOption(handle,
			WINHTTP_OPTION_PROXY,
			&proxyInfo, sizeof(proxyInfo)));

		if (http->proxyUsername && http->proxyPassword) {
			WINHTTP_SAFE(WinHttpSetCredentials(handle,
				WINHTTP_AUTH_TARGET_PROXY,
				WINHTTP_AUTH_SCHEME_BASIC,
				http->proxyUsername,
				http->proxyPassword,
				NULL));
		}
	}

	while (retryLimit > 0) {
		DWORD errorCode, statusCode, statusCodeSize;
		bool succeeded = false;
		bool retry = false;

		if (!requestSent) {
			size_t postDataSize = strlen(request->postData);
			succeeded = WinHttpSendRequest(handle,
				WINHTTP_NO_ADDITIONAL_HEADERS,
				0,
				request->postData,
				postDataSize,
				postDataSize,
				0);

			if (succeeded)
				requestSent = true;
		}

		if (requestSent)
			succeeded = WinHttpReceiveResponse(handle, NULL);

		errorCode = GetLastError();

		statusCode = 0;
		statusCodeSize = sizeof(statusCode);
		if (!WinHttpQueryHeaders(handle,
				WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
				WINHTTP_HEADER_NAME_BY_INDEX,
				&statusCode, &statusCodeSize, WINHTTP_NO_HEADER_INDEX)) {
			statusCode = 0;
		}

		if (succeeded && statusCode == 407) {
			wchar_t statusText[256] = { 0 };
			DWORD statusTextSize = sizeof(statusText) - 1;
			WinHttpQueryHeaders(handle,
				WINHTTP_QUERY_STATUS_TEXT,
				WINHTTP_HEADER_NAME_BY_INDEX,
				statusText, &statusTextSize, WINHTTP_NO_HEADER_INDEX);
			HttpSetLastErrorW (http, statusText);
			requestSent = false;
			retry       = true;
		}
		else {
			if (errorCode == ERROR_SUCCESS)
				break;

			switch (errorCode) {
				case ERROR_WINHTTP_RESEND_REQUEST:
					requestSent = false;
					/* pass trough */

				case ERROR_WINHTTP_NAME_NOT_RESOLVED:
				case ERROR_WINHTTP_CANNOT_CONNECT:
				case ERROR_WINHTTP_TIMEOUT:
					retry = true;
					break;

				default:
					HttpSetLastErrorFromWinHttp (http);
					goto done;
			}
		}

		if (retry)
			--retryLimit;
	}

	responseDataSize = 0;
	while (retryLimit > 0)
	{
		DWORD bytesLeft;
		char* writePtr;

		DWORD bytesAvailable = 0;
		if (!WinHttpQueryDataAvailable(handle, &bytesAvailable)) {
			WINHTTP_SAFE(GetLastError() == ERROR_WINHTTP_TIMEOUT);
			--retryLimit;
			continue;
		}

		if (0 == bytesAvailable)
			break;

		responseDataSize += bytesAvailable;
		request->responseData = realloc(request->responseData, responseDataSize + 1);

		writePtr = request->responseData + responseDataSize - bytesAvailable;
		writePtr[bytesAvailable] = 0;

		bytesLeft = bytesAvailable;
		while (bytesLeft > 0)
		{
			DWORD bytesRead = 0;
			if (!WinHttpReadData(handle, writePtr, bytesLeft, &bytesRead))
			{
				WINHTTP_SAFE(GetLastError() == ERROR_WINHTTP_TIMEOUT);
				if (--retryLimit == 0)
					break;

				continue;
			}

			bytesLeft -= bytesRead;
			writePtr  += bytesRead;
		}

		if (bytesLeft > 0)
			HttpSetLastError (http, "Maximum retries count exceeded");
	}

	if (retryLimit == 0)
		goto done;

	complete = true;

	HttpSetLastError (http, NULL);

done:
	free(wideQuery);
	return complete;
}

const char* HttpGetError(http_t http) {
	return http->error;
}