summaryrefslogtreecommitdiff
path: root/request.h
blob: 9eb914c8961638fa13553f81946d9e195386daca (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
#ifndef RTCLIENT_REQUEST_H
#define RTCLIENT_REQUEST_H

#if defined(ANDROID) && defined(DEBUG)
#include <android/log.h>
#endif
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <curl/curl.h>

extern CURL *curl;
extern char *server_url;

inline void request(size_t (*writefunction)(void *, size_t, size_t, void *)
		, void *writedata, struct curl_httppost *post, char *fmt, ...)
{
	va_list ap;
	char *p, *sval;
	unsigned int ival;
	size_t length = strlen(server_url) + strlen(fmt);

	va_start(ap, fmt);
	for (p = fmt; *p; p++) {
		if (*p != '%')
			continue;
		switch(*++p) {
			case 's':
				sval = va_arg(ap, char *);
				length += strlen(sval) - 2;
				break;
			case 'd':
				ival = va_arg(ap, unsigned int);
				do {
					length++;
				} while (ival / 10);
				length -= 2;
				break;
			default:
				break;
		}
	}
	va_end(ap);

	char url[length + 1];
	strcpy(url, server_url);

	va_start(ap, fmt);
	for (p = fmt; *p; p++) {
		if (*p != '%')
			continue;
		switch(*++p) {
			case 's':
				sval = va_arg(ap, char *);
				strcat(url, sval);
				break;
			case 'd':
				ival = va_arg(ap, unsigned int);
				sprintf(url, "%s%d", url, ival);
				break;
			default:
				break;
		}
	}
	va_end(ap);

	curl_easy_setopt(curl, CURLOPT_URL, url);
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunction);
	if (writedata)
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, writedata);
	else
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, stdout);
	if (post)
		curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
	else
		curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);

#ifdef DEBUG
	CURLcode res =
#endif // DEBUG
		curl_easy_perform(curl);
#ifdef DEBUG
	if (res != CURLE_OK) {
		const char *error = curl_easy_strerror(res);
#ifdef ANDROID
		__android_log_print(ANDROID_LOG_ERROR, "librtclient", "%s: %s"
				, __func__, error);
#else
		fprintf(stderr, "%s: %s\n", __func__, error);
#endif // ANDROID
	}
#endif // DEBUG
}

#endif // RTCLIENT_REQUEST_H