/
pkutils.c
532 lines (475 loc) · 12.3 KB
/
pkutils.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
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
529
530
531
532
/******************************************************************************
utils.c - Utility functions for pagekite.
This file is Copyright 2011-2015, The Beanstalks Project ehf.
This program is free software: you can redistribute it and/or modify it under
the terms of the Apache License 2.0 as published by the Apache Software
Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the Apache License for more details.
You should have received a copy of the Apache License along with this program.
If not, see: <http://www.apache.org/licenses/>
Note: For alternate license terms, see the file COPYING.md.
******************************************************************************/
#define PAGEKITE_CONSTANTS_ONLY
#include "pagekite.h"
#include "pkcommon.h"
#include "assert.h"
#include "pkutils.h"
#include <fcntl.h>
#include <ctype.h>
#ifndef _MSC_VER
#include <poll.h>
#define HAVE_POLL
#endif
int zero_first_crlf(int length, char* data)
{
int i;
for (i = 0; i < length-1; i++)
{
if ((data[i] == '\r') && (data[i+1] == '\n'))
{
data[i] = data[i+1] = '\0';
return i+2;
}
}
return 0;
}
int zero_first_whitespace(int length, char* data)
{
int i;
for (i = 0; i < length; i++)
{
if (isspace(data[i]))
{
data[i] = '\0';
return i+1;
}
}
return 0;
}
int zero_nth_char(int n, char c, int length, char* data)
{
int i;
for (i = 0; i < length; i++)
{
if (data[i] == c)
{
if (--n < 1) {
data[i] = '\0';
return i+1;
}
}
}
return 0;
}
char *skip_http_header(int length, const char* data)
{
int i, lfs;
int chunked = 0;
char *r = NULL;
char *p = "\0";
for (lfs = i = 0; i < length-1; i++) {
p = (char*) data + i;
if (*p == '\n') {
/* 12345678901234567890123456 = 26 bytes */
if (!strncasecmp(p + 1, "Transfer-Encoding: chunked", 26)) chunked = 1;
lfs++;
if (lfs == 2) {
if (chunked) {
r = strchr(p + 1, '\n');
if (r != NULL) return r + 1;
}
return p + 1;
}
}
else if (*p != '\r') {
lfs = 0;
}
}
return p;
}
char* collapse_whitespace(char* data)
{
char* w = data;
char* r = data;
while (*r) {
if (isspace(*r)) {
*w = ' ';
*r++;
if (!isspace(*r)) w++;
}
else {
*w++ = *r++;
}
}
*w = '\0';
return data;
}
int dbg_write(int sockfd, char *buffer, int bytes)
{
printf(">> %s", buffer);
return PKS_write(sockfd, buffer, bytes);
}
int set_non_blocking(int sockfd)
{
#ifndef _MSC_VER
int flags;
if ((0 <= (flags = fcntl(sockfd, F_GETFL, 0))) &&
(0 <= fcntl(sockfd, F_SETFL, flags | O_NONBLOCK))) return sockfd;
#else
ULONG nonBlocking = 1;
if (ioctlsocket(PKS(sockfd), FIONBIO, &nonBlocking) == NO_ERROR) {
return sockfd;
}
#endif
return -1;
}
int set_blocking(int sockfd)
{
#ifndef _MSC_VER
int flags;
if ((0 <= (flags = fcntl(sockfd, F_GETFL, 0))) &&
(0 <= fcntl(sockfd, F_SETFL, flags & (~O_NONBLOCK)))) return sockfd;
#else
ULONG blocking = 0;
if (ioctlsocket(PKS(sockfd), FIONBIO, &blocking) == NO_ERROR) {
return sockfd;
}
#endif
return -1;
}
void sleep_ms(int ms)
{
struct timeval tv;
tv.tv_sec = (ms / 1000);
tv.tv_usec = 1000 * (ms % 1000);
select(0, NULL, NULL, NULL, &tv);
}
int wait_fd(int fd, int timeout_ms)
{
#ifdef HAVE_POLL
struct pollfd pfd;
pfd.fd = fd;
pfd.events = (POLLIN | POLLPRI | POLLHUP);
return poll(&pfd, 1, timeout_ms);
#else
fd_set rfds;
struct timeval tv;
FD_ZERO(&rfds);
FD_SET(PKS(fd), &rfds);
tv.tv_sec = (timeout_ms / 1000);
tv.tv_usec = 1000 * (timeout_ms % 1000);
return select(fd+1, &rfds, NULL, NULL, &tv);
#endif
}
ssize_t timed_read(int sockfd, void* buf, size_t count, int timeout_ms)
{
ssize_t rv;
set_non_blocking(sockfd);
do {
if (0 <= (rv = wait_fd(sockfd, timeout_ms)))
rv = PKS_read(sockfd, buf, count);
} while (errno == EINTR);
set_blocking(sockfd);
return rv;
}
/* http://www.beej.us/guide/bgnet/output/html/multipage/inet_ntopman.html */
char *in_ipaddr_to_str(const struct sockaddr *sa, char *s, size_t maxlen)
{
switch (sa->sa_family) {
case AF_INET:
strncpy(s, inet_ntoa(((struct sockaddr_in *)sa)->sin_addr), maxlen);
break;
#ifdef HAVE_IPV6
case AF_INET6:
inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr),
s, maxlen);
break;
#endif
default:
strncpy(s, "Unknown AF", maxlen);
return NULL;
}
return s;
}
char *in_addr_to_str(const struct sockaddr *sa, char *s, size_t maxlen)
{
char* p;
switch (sa->sa_family) {
case AF_INET:
p = s;
*p++ = '[';
strncpy(p, inet_ntoa(((struct sockaddr_in *)sa)->sin_addr), maxlen-8);
p = s+strlen(s);
*p++ = ']';
*p++ = ':';
sprintf(p, "%d", ntohs(((struct sockaddr_in* )sa)->sin_port));
break;
#ifdef HAVE_IPV6
case AF_INET6:
p = s;
*p++ = '[';
inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr),
p, maxlen-8);
p = s+strlen(s);
*p++ = ']';
*p++ = ':';
sprintf(p, "%d", ntohs(((struct sockaddr_in6* )sa)->sin6_port));
break;
#endif
default:
strncpy(s, "Unknown AF", maxlen);
return NULL;
}
return s;
}
struct addrinfo* copy_addrinfo_data(struct addrinfo* dst, struct addrinfo* src)
{
free_addrinfo_data(dst);
if (src == NULL) return dst;
struct sockaddr* addr_buffer = malloc(src->ai_addrlen);
if (addr_buffer != NULL) {
memcpy(addr_buffer, src->ai_addr, src->ai_addrlen);
dst->ai_flags = src->ai_flags;
dst->ai_family = src->ai_family;
dst->ai_socktype = src->ai_socktype;
dst->ai_protocol = src->ai_protocol;
dst->ai_addrlen = src->ai_addrlen;
dst->ai_addr = addr_buffer;
dst->ai_canonname = (src->ai_canonname) ? strdup(src->ai_canonname) : NULL;
dst->ai_next = NULL;
return dst;
}
return NULL;
}
void free_addrinfo_data(struct addrinfo* dst)
{
if (dst->ai_canonname != NULL) free(dst->ai_canonname);
if (dst->ai_addr != NULL) free(dst->ai_addr);
dst->ai_addrlen = 0;
dst->ai_addr = NULL;
dst->ai_canonname = NULL;
}
int addrcmp(const struct sockaddr *a, const struct sockaddr *b)
{
if (a == NULL || b == NULL) return 3;
if (a->sa_family != b->sa_family) return 1;
switch (a->sa_family) {
case AF_INET:
return memcmp(&(((struct sockaddr_in*) a)->sin_addr),
&(((struct sockaddr_in*) b)->sin_addr),
sizeof(struct in_addr));
#ifdef HAVE_IPV6
case AF_INET6:
return memcmp(&(((struct sockaddr_in6*) a)->sin6_addr),
&(((struct sockaddr_in6*) b)->sin6_addr),
sizeof(struct in6_addr));
#endif
}
return 2;
}
int http_get(const char* url, char* result_buffer, size_t maxlen)
{
char *urlparse, *hostname, *port, *path;
struct addrinfo hints, *result, *rp;
char request[10240], *bp;
int sockfd, rlen, bytes, total_bytes;
/* http://hostname:port/foo */
urlparse = strdup(url);
hostname = urlparse+7;
while (*hostname && *hostname == '/') hostname++;
port = hostname;
while (*port && *port != '/' && *port != ':') port++;
if (*port == '/') {
path = port;
*path++ = '\0';
port = (url[5] == 's') ? "443" : "80";
}
else {
*port++ = '\0';
path = port;
while (*path && *path != '/') path++;
*path++ = '\0';
}
rlen = snprintf(request, 10240,
"GET /%s HTTP/1.1\r\nHost: %s\r\n\r\n", path, hostname);
if (10240 == rlen)
{
free(urlparse);
return -1;
}
total_bytes = 0;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if (0 == getaddrinfo(hostname, port, &hints, &result)) {
for (rp = result; rp != NULL; rp = rp->ai_next) {
if ((0 > (sockfd = PKS_socket(rp->ai_family, rp->ai_socktype,
rp->ai_protocol))) ||
PKS_fail(PKS_connect(sockfd, rp->ai_addr, rp->ai_addrlen)) ||
PKS_fail(PKS_write(sockfd, request, rlen))) {
if (sockfd >= 0) PKS_close(sockfd);
}
else {
total_bytes = 0;
bp = result_buffer;
do {
bytes = timed_read(sockfd, bp, maxlen-(1+total_bytes), 1000);
if (bytes > 0) {
bp += bytes;
total_bytes += bytes;
}
} while (bytes > 0);
*bp = '\0';
PKS_close(sockfd);
break;
}
}
freeaddrinfo(result);
}
free(urlparse);
return total_bytes;
}
void digest_to_hex(const unsigned char* digest, char *output)
{
int i,j;
char *c = output;
/* SHA1_DIGEST_SIZE == 20 */
for (i = 0; i < 20/4; i++) {
for (j = 0; j < 4; j++) {
sprintf(c,"%02x", digest[i*4+j]);
c += 2;
}
}
*c = '\0';
}
void pk_rlock_init(pk_rlock_t* rlock)
{
rlock->count = 0;
rlock->owner = pthread_self();
pthread_mutex_init(&(rlock->check_lock), NULL);
pthread_mutex_init(&(rlock->lock_lock), NULL);
}
void pk_rlock_lock(pk_rlock_t* rlock)
{
pthread_mutex_lock(&(rlock->check_lock));
if (!pthread_equal(pthread_self(), rlock->owner)) {
pthread_mutex_unlock(&(rlock->check_lock));
pthread_mutex_lock(&(rlock->lock_lock));
pthread_mutex_lock(&(rlock->check_lock));
rlock->owner = pthread_self();
rlock->count = 0;
}
rlock->count += 1;
pthread_mutex_unlock(&(rlock->check_lock));
}
void pk_rlock_unlock(pk_rlock_t* rlock)
{
pthread_mutex_lock(&(rlock->check_lock));
if (pthread_equal(pthread_self(), rlock->owner)) {
rlock->count -= 1;
if (rlock->count < 1) {
rlock->count = 0;
pthread_mutex_unlock(&(rlock->lock_lock));
}
}
else {
/* Allow other threads to force the release of the lock */
pthread_mutex_unlock(&(rlock->lock_lock));
rlock->count = 0;
}
pthread_mutex_unlock(&(rlock->check_lock));
}
#if PK_MEMORY_CANARIES
#define MAX_CANARIES 102400
void** canaries[MAX_CANARIES];
int canary_max = 0;
pthread_mutex_t canary_lock;
#endif
void remove_memory_canary(void** canary) {
#if PK_MEMORY_CANARIES
pthread_mutex_lock(&canary_lock);
for (int i = 0; i < canary_max; i++) {
if (canaries[i] == canary) {
if (canary_max > 1) {
canaries[i] = canaries[--canary_max];
}
else {
canary_max -= 1;
}
break;
}
}
pthread_mutex_unlock(&canary_lock);
#endif
(void) canary;
}
void add_memory_canary(void** canary) {
#if PK_MEMORY_CANARIES
if (*canary && (*canary == canary)) {
remove_memory_canary(canary);
}
pthread_mutex_lock(&canary_lock);
*canary = canary;
canaries[canary_max++] = canary;
assert(canary_max < MAX_CANARIES);
pthread_mutex_unlock(&canary_lock);
#endif
(void) canary;
}
int check_memory_canaries() {
#if PK_MEMORY_CANARIES
int i, bad;
pthread_mutex_lock(&canary_lock);
for (bad = i = 0; i < canary_max; i++) {
if (canaries[i] != *canaries[i]) {
fprintf(stderr, "%p != %p\n",
(void *) canaries[i], *canaries[i]);
bad++;
}
}
pthread_mutex_unlock(&canary_lock);
return bad;
#else
return 0;
#endif
}
void reset_memory_canaries() {
#if PK_MEMORY_CANARIES
pthread_mutex_lock(&canary_lock);
canary_max = 0;
pthread_mutex_unlock(&canary_lock);
#endif
}
void init_memory_canaries() {
#if PK_MEMORY_CANARIES
pthread_mutex_init(&canary_lock, NULL);
#endif
}
/* *** Tests *************************************************************** */
int utils_test(void)
{
#if PK_TESTS
char buffer1[60];
PK_MEMORY_CANARY;
strcpy(buffer1, "\r\n\r\n");
assert(2 == zero_first_crlf(4, buffer1));
strcpy(buffer1, "abcd\r\n\r\ndefghijklmnop");
int length = zero_first_crlf(strlen(buffer1), buffer1);
assert(length == 6);
assert((buffer1[4] == '\0') && (buffer1[5] == '\0') && (buffer1[6] == '\r'));
assert(strcmp(buffer1, "abcd") == 0);
strcpy(buffer1, "abcd\r\nfoo\r\n\r\ndef");
assert(strcmp(skip_http_header(strlen(buffer1), buffer1), "def") == 0);
#if PK_MEMORY_CANARIES
add_memory_canary(&canary);
PK_CHECK_MEMORY_CANARIES;
canary = (void*) 0;
assert(check_memory_canaries() == 1);
canary = &canary;
remove_memory_canary(&canary);
#endif
#endif
return 1;
}