-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.c
419 lines (310 loc) · 8.19 KB
/
api.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
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
#include "api.h"
/**
* Create a URL from a variable number of strings. The first is assumed
* to the base URL. The strings following are assumed to apart of the path.
* Eg.:
* createURL(5, "https://example.com", "/the", "answer/", "/is/", "42")
* -> "https://example.com/the/answer/is/42"
* @param count The number of strings provided.
* @return A heap-allocated string.
*/
static char* createURL(int count, ...) {
va_list argList;
size_t bytes = 0, cap = INIT_URL_STR_LEN;
char* url = malloc(cap);
if (!url) {
// out of memory
return NULL;
}
va_start(argList, count);
// loop through the provided strings
for (int i = 0; i < count; i++) {
char* str = va_arg(argList, char*);
size_t len = strlen(str);
bool appendLeading = (str[0] != '/' && i != 0);
if (str[len - 1] == '/') {
// skip the trailing slash
len -= 1;
}
size_t newLen = len + bytes;
if (appendLeading) {
// add an extra byte to accomodate a leading slash
newLen += 1;
}
if (newLen > cap) {
// allocate another INIT_URL_STR_LEN bytes
cap += INIT_URL_STR_LEN;
char* ptr = realloc(url, cap);
if (!ptr) {
// re-allocation failed
free(url);
va_end(argList);
return NULL;
}
url = ptr;
}
if (appendLeading) {
// append a slash before copying the string
url[bytes++] = '/';
}
// copy the string
for (size_t j = 0; j < len; j++) {
url[bytes + j] = str[j];
}
bytes += len;
}
va_end(argList);
if (bytes == cap) {
// add a byte for the null terminator
char* ptr = realloc(url, cap + 1);
if (!ptr) {
free(url);
return NULL;
}
}
// append a null terminator
url[bytes] = '\0';
return url;
}
/**
* Attach a variable number of headers to the curl handle.
* @param curl
* @param count The number of headers to attach.
* @return A pointer to the attached headers. Remember to free it!
*/
static struct curl_slist* attachHeaders(CURL* curl, int count, ...) {
va_list argList;
struct curl_slist* headers = NULL;
va_start(argList, count);
for (int i = 0; i < count; i++) {
struct curl_slist* temp = curl_slist_append(headers, va_arg(argList, char*));
if (!temp) {
curl_slist_free_all(headers);
return NULL;
}
headers = temp;
}
va_end(argList);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
return headers;
}
static void commonOptions(CURL* curl) {
// prevent the request from taking too long
curl_easy_setopt(curl, CURLOPT_TIMEOUT, REQ_TIMEOUT);
#ifdef CURL_SKIP_VERIFY
// skip TLS verification
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
#endif
}
/**
* Creates the password header. I.e. "Channel-Password: <password>".
* @param password
* @return A heap allocated string.
*/
char* createPasswordHeader(const char* password) {
// one extra for null terminator
char* header = malloc(strlen(HEADER_CHAN_PW) + strlen(password) + 1);
if (!header) {
// out of memory
return NULL;
}
strcpy(header, HEADER_CHAN_PW);
strcat(header, password);
return header;
}
/**
* Initialise a curl handle to publish data. Sets the URL, Content-Type header,
* Channel-Password header, and write callbacks. Returns a pointer to the attached
* headers that must be freed after the curl handle is no longer required.
* @param curl Curl easy handle.
* @param base Base URL. Eg.: "localhost:3000". Trailing slash optional.
* @param cID The channel ID to post the data to.
* @param pw The password of the channel.
* @return Must be freed when the curl handle is no longer required.
*/
struct curl_slist* publishInit(CURL* curl, const char* base,
const char* cID, const char* pwHeader) {
struct curl_slist* headers = attachHeaders(
curl, 2, "Content-Type: application/json", pwHeader
);
if (!headers) {
return NULL;
}
char* url = createURL(3, base, PUB_ENDPOINT, cID);
if (!url) {
curl_easy_reset(curl);
curl_slist_free_all(headers);
return NULL;
}
// attach the url
curl_easy_setopt(curl, CURLOPT_URL, url);
return headers;
}
/**
* Sends the JSON body to the already initialised and set URL.
* @param curl Curl easy handle. Must be initialised with publishInit.
* @param json The JSON string to attach as the request body.
* @return Must be freed once used.
*/
int publish(CURL* curl, const char* json) {
// attach the body
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json);
// run the request
Response* res = performRequest(curl);
if (!res) {
return ARE_OUT_OF_MEM;
}
CURLcode cc = res->curlCode;
int status = res->status;
// response no longer required
freeResponse(res);
if (cc != 0) {
printf("Libcurl error: %s (%d)\n", curl_easy_strerror(cc), cc);
return ARE_CURL;
}
if (status >= 400) {
printf("Request error: %d\n", status);
if (status < 500) {
return ARE_REQ;
}
return ARE_SERVER;
}
return 0;
}
/**
* Get the channels from the API and parse them as JSON.
* @param ptr Dereferenced and assigned the result of cJSON_Parse.
* @return 0 on success, non-zero corresponding to errors in error.h.
*/
int getChannels(cJSON** ptr) {
CURL* curl = curl_easy_init();
if (!curl) {
return ARE_OUT_OF_MEM;
}
// set timeout and peer verification status
commonOptions(curl);
// allocate a url string
char* url = createURL(2, API_URL, CHAN_ENDPOINT);
if (!url) {
curl_easy_cleanup(curl);
return ARE_OUT_OF_MEM;
}
// attach the url
curl_easy_setopt(curl, CURLOPT_URL, url);
free(url);
// run the request
Response* res = performRequest(curl);
// no longer require the curl handle
curl_easy_cleanup(curl);
if (!res) {
return ARE_OUT_OF_MEM;
}
CURLcode cc = res->curlCode;
if (cc != CURLE_OK) {
freeResponse(res);
printf("Libcurl error: %s (%d)\n", curl_easy_strerror(cc), cc);
if (cc == CURLE_OPERATION_TIMEDOUT) {
// request took longer than REQ_TIMEOUT
return ARE_REQ_TIMEOUT;
}
return ARE_CURL;
}
if (res->status >= 400) {
// something went wrong with the request
int status = res->status;
printf("Request error: %d\n", status);
freeResponse(res);
if (status < 500) {
return ARE_REQ;
}
return ARE_SERVER;
}
cJSON* array = cJSON_Parse(res->body->data);
// no longer require the response object
freeResponse(res);
if (!array) {
return ARE_OUT_OF_MEM;
}
*ptr = array;
return 0;
}
/**
* Verify the provided password is correct by "logging in" to a channel.
* @param id Channel ID.
* @param pw The password to test.
* @return Zero on success, non-zero on failure (as described in error.h).
*/
int channelLogin(char* id, char* pw) {
CURL* curl = curl_easy_init();
if (!curl) {
return ARE_OUT_OF_MEM;
}
// attach common options
commonOptions(curl);
// create a url string
char* url = createURL(3, API_URL, CHAN_ENDPOINT, id);
if (!url) {
curl_easy_cleanup(curl);
return ARE_OUT_OF_MEM;
}
// attach the url
curl_easy_setopt(curl, CURLOPT_URL, url);
free(url);
// attach the password in a JSON body
cJSON* raw = cJSON_CreateObject();
if (!raw) {
curl_easy_cleanup(curl);
return ARE_OUT_OF_MEM;
}
if (!cJSON_AddStringToObject(raw, "password", pw)) {
curl_easy_cleanup(curl);
return ARE_OUT_OF_MEM;
}
// convert to a string
char* body = cJSON_Print(raw);
// no longer need the raw object
cJSON_Delete(raw);
if (!body) {
curl_easy_cleanup(curl);
return ARE_OUT_OF_MEM;
}
// attach the body to the request
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body);
// set and attach json content type header
struct curl_slist* headers = attachHeaders(
curl, 1, "Content-Type: application/json");
if (!headers) {
curl_easy_cleanup(curl);
free(body);
return ARE_OUT_OF_MEM;
}
// run the request
Response* res = performRequest(curl);
// no longer need the curl handle, json body, and headers
curl_easy_cleanup(curl);
curl_slist_free_all(headers);
free(body);
if (!res) {
return ARE_OUT_OF_MEM;
}
CURLcode cc = res->curlCode;
int status = res->status;
freeResponse(res);
if (cc != 0) {
printf("Libcurl error: %s (%d)\n", curl_easy_strerror(cc), cc);
// curl handling error
if (cc == CURLE_OPERATION_TIMEDOUT) {
// request timed out
return ARE_REQ_TIMEOUT;
}
return ARE_CURL;
}
if (status >= 400) {
printf("Request error: %d\n", status);
if (status < 500) {
return ARE_REQ;
}
return ARE_SERVER;
}
return 0;
}