/
mk_utils.c
512 lines (419 loc) · 11.7 KB
/
mk_utils.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
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* Monkey HTTP Server
* ==================
* Copyright 2001-2015 Monkey Software LLC <eduardo@monkey.io>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* local headers */
#include <monkey/monkey.h>
#include <monkey/mk_core.h>
#include <monkey/mk_utils.h>
#include <monkey/mk_file.h>
#include <monkey/mk_config.h>
#include <monkey/mk_socket.h>
#include <monkey/mk_clock.h>
#include <monkey/mk_user.h>
#include <monkey/mk_cache.h>
#include <monkey/mk_tls.h>
#include <assert.h>
#include <ctype.h>
#include <stdarg.h>
#include <time.h>
#include <inttypes.h>
#include <sys/socket.h>
#include <sys/stat.h>
#if defined (__linux__)
#include <sys/prctl.h>
#endif
/* stacktrace */
#include <dlfcn.h>
#ifndef NO_BACKTRACE
#include <execinfo.h>
#endif
#define MK_UTILS_GMT_DATEFORMAT "%a, %d %b %Y %H:%M:%S GMT"
/* Date helpers */
static const char mk_date_wd[][6] = {"Sun, ", "Mon, ", "Tue, ", "Wed, ", "Thu, ", "Fri, ", "Sat, "};
static const char mk_date_ym[][5] = {"Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ", "Jul ",
"Aug ", "Sep ", "Oct ", "Nov ", "Dec "};
static int mk_utils_gmt_cache_get(char **data, time_t date)
{
unsigned int i;
struct mk_gmt_cache *gcache = MK_TLS_GET(mk_tls_cache_gmtext);
if (mk_unlikely(!gcache)) {
return MK_FALSE;
}
for (i = 0; i < MK_GMT_CACHES; i++) {
if (date == gcache[i].time) {
memcpy(*data, gcache[i].text, 32);
gcache[i].hits++;
return MK_TRUE;
}
}
return MK_FALSE;
}
static void mk_utils_gmt_cache_add(char *data, time_t time)
{
unsigned int i, min = 0;
struct mk_gmt_cache *gcache = MK_TLS_GET(mk_tls_cache_gmtext);
for (i = 1; i < MK_GMT_CACHES; i++) {
if (gcache[i].hits < gcache[min].hits)
min = i;
}
gcache[min].hits = 1;
gcache[min].time = time;
memcpy(gcache[min].text, data, 32);
}
/*
*This function given a unix time, set in a mk_ptr_t
* the date in the RFC1123 format like:
*
* Wed, 23 Jun 2010 22:32:01 GMT
*
* it also adds a 'CRLF' at the end
*/
int mk_utils_utime2gmt(char **data, time_t date)
{
const int size = 31;
unsigned short year, mday, hour, min, sec;
char *buf=0;
struct tm *gtm;
if (date == 0) {
if ((date = time(NULL)) == -1) {
return -1;
}
}
else {
/* Maybe it's converted already? */
if (mk_utils_gmt_cache_get(data, date) == MK_TRUE) {
return size;
}
}
/* Convert unix time to struct tm */
gtm = MK_TLS_GET(mk_tls_cache_gmtime);
/* If this function was invoked from a non-thread context it should exit */
mk_bug(!gtm);
gtm = gmtime_r(&date, gtm);
if (!gtm) {
return -1;
}
/* struct tm -> tm_year counts number of years after 1900 */
year = gtm->tm_year + 1900;
/* Signed division is slow, by using unsigned we gain 25% speed */
mday = gtm->tm_mday;
hour = gtm->tm_hour;
min = gtm->tm_min;
sec = gtm->tm_sec;
/* Compose template */
buf = *data;
/* Week day */
memcpy(buf, mk_date_wd[gtm->tm_wday], 5);
buf += 5;
/* Day of the month */
*buf++ = ('0' + (mday / 10));
*buf++ = ('0' + (mday % 10));
*buf++ = ' ';
/* Month */
memcpy(buf, mk_date_ym[gtm->tm_mon], 4);
buf += 4;
/* Year */
*buf++ = ('0' + (year / 1000) % 10);
*buf++ = ('0' + (year / 100) % 10);
*buf++ = ('0' + (year / 10) % 10);
*buf++ = ('0' + (year % 10));
*buf++ = ' ';
/* Hour */
*buf++ = ('0' + (hour / 10));
*buf++ = ('0' + (hour % 10));
*buf++ = ':';
/* Minutes */
*buf++ = ('0' + (min / 10));
*buf++ = ('0' + (min % 10));
*buf++ = ':';
/* Seconds */
*buf++ = ('0' + (sec / 10));
*buf++ = ('0' + (sec % 10));
/* GMT Time zone + CRLF */
memcpy(buf, " GMT\r\n\0", 7);
/* Add new entry to the cache */
mk_utils_gmt_cache_add(*data, date);
/* Set mk_ptr_t data len */
return size;
}
time_t mk_utils_gmt2utime(char *date)
{
time_t new_unix_time;
struct tm t_data;
memset(&t_data, 0, sizeof(struct tm));
if (!strptime(date, MK_UTILS_GMT_DATEFORMAT, (struct tm *) &t_data)) {
return -1;
}
new_unix_time = timegm((struct tm *) &t_data);
return (new_unix_time);
}
int mk_buffer_cat(mk_ptr_t *p, char *buf1, int len1, char *buf2, int len2)
{
/* Validate lengths */
if (mk_unlikely(len1 < 0 || len2 < 0)) {
return -1;
}
/* alloc space */
p->data = (char *) mk_mem_malloc(len1 + len2 + 1);
/* copy data */
memcpy(p->data, buf1, len1);
memcpy(p->data + len1, buf2, len2);
p->data[len1 + len2] = '\0';
/* assign len */
p->len = len1 + len2;
return 0;
}
/* Convert hexadecimal to int */
int mk_utils_hex2int(char *hex, int len)
{
int i = 0;
int res = 0;
char c;
while ((c = *hex++) && i < len) {
res *= 0x10;
if (c >= 'a' && c <= 'f') {
res += (c - 0x57);
}
else if (c >= 'A' && c <= 'F') {
res += (c - 0x37);
}
else if (c >= '0' && c <= '9') {
res += (c - 0x30);
}
else {
return -1;
}
i++;
}
if (res < 0) {
return -1;
}
return res;
}
/* If the URI contains hexa format characters it will return
* convert the Hexa values to ASCII character
*/
char *mk_utils_url_decode(mk_ptr_t uri)
{
int tmp, hex_result;
unsigned int i;
int buf_idx = 0;
char *buf;
char hex[3];
if ((tmp = mk_string_char_search(uri.data, '%', uri.len)) < 0) {
return NULL;
}
i = tmp;
buf = mk_mem_malloc_z(uri.len + 1);
if (i > 0) {
memcpy(buf, uri.data, i);
buf_idx = i;
}
while (i < uri.len) {
if (uri.data[i] == '%' && i + 2 < uri.len) {
memcpy(hex, uri.data + i + 1, 2);
hex[2] = '\0';
hex_result = mk_utils_hex2int(hex, 2);
if (hex_result != -1) {
buf[buf_idx] = hex_result;
}
else {
mk_mem_free(buf);
return NULL;
}
i += 2;
}
else {
buf[buf_idx] = uri.data[i];
}
i++;
buf_idx++;
}
buf[buf_idx] = '\0';
return buf;
}
/* Run current process in background mode (daemon, evil Monkey >:) */
int mk_utils_set_daemon()
{
pid_t pid;
if ((pid = fork()) < 0){
mk_err("Error: Failed creating to switch to daemon mode(fork failed)");
exit(EXIT_FAILURE);
}
if (pid > 0) /* parent */
exit(EXIT_SUCCESS);
/* set files mask */
umask(0);
/* Create new session */
setsid();
if (chdir("/") < 0) { /* make sure we can unmount the inherited filesystem */
mk_err("Error: Unable to unmount the inherited filesystem in the daemon process");
exit(EXIT_FAILURE);
}
/* Our last STDOUT messages */
mk_details();
mk_info("Background mode ON");
fclose(stderr);
fclose(stdout);
return 0;
}
/* Write Monkey's PID */
int mk_utils_register_pid()
{
int fd;
char pidstr[MK_MAX_PID_LEN];
struct flock lock;
struct stat sb;
if (mk_config->pid_status == MK_TRUE)
return -1;
if (!stat(mk_config->pid_file_path, &sb)) {
/* file exists, perhaps previously kepts by SIGKILL */
unlink(mk_config->pid_file_path);
}
if ((fd = open(mk_config->pid_file_path,
O_WRONLY | O_CREAT | O_CLOEXEC, 0444)) < 0) {
mk_err("Error: I can't log pid of monkey");
exit(EXIT_FAILURE);
}
/* create a write exclusive lock for the entire file */
lock.l_type = F_WRLCK;
lock.l_start = 0;
lock.l_whence = SEEK_SET;
lock.l_len = 0;
if (fcntl(fd, F_SETLK, &lock) < 0) {
close(fd);
mk_err("Error: I cannot set the lock for the pid of monkey");
exit(EXIT_FAILURE);
}
sprintf(pidstr, "%i", getpid());
ssize_t write_len = strlen(pidstr);
if (write(fd, pidstr, write_len) != write_len) {
close(fd);
mk_err("Error: I cannot write the lock for the pid of monkey");
exit(EXIT_FAILURE);
}
mk_config->pid_status = MK_TRUE;
return 0;
}
/* Remove PID file */
int mk_utils_remove_pid()
{
mk_user_undo_uidgid();
if (unlink(mk_config->pid_file_path)) {
mk_warn("cannot delete pidfile\n");
}
mk_config->pid_status = MK_FALSE;
return 0;
}
pthread_t mk_utils_worker_spawn(void (*func) (void *), void *arg)
{
pthread_t tid;
pthread_attr_t thread_attr;
pthread_attr_init(&thread_attr);
pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE);
if (pthread_create(&tid, &thread_attr, (void *) func, arg) < 0) {
mk_libc_error("pthread_create");
exit(EXIT_FAILURE);
}
return tid;
}
int mk_utils_worker_rename(const char *title)
{
#if defined (__linux__)
return prctl(PR_SET_NAME, title, 0, 0, 0);
#elif defined (__APPLE__)
return pthread_setname_np(title);
#else
(void) title;
return -1;
#endif
}
#ifdef NO_BACKTRACE
void mk_utils_stacktrace(void) {}
#else
void mk_utils_stacktrace(void)
{
unsigned int i;
int ret;
size_t size;
void *arr[10];
Dl_info d;
printf("[stack trace]\n");
size = backtrace(arr, 10);
for (i = 1; i < size && i < 10; i++) {
ret = dladdr(arr[i], &d);
if (ret == 0 || !d.dli_sname) {
printf(" #%i 0x%016" PRIxPTR " in \?\?\?\?\?\?\?()\n",
(i - 1), (uintptr_t) arr[i]);
continue;
}
printf(" #%i 0x%016" PRIxPTR " in %s() from %s\n",
(i - 1), (uintptr_t) arr[i], d.dli_sname, d.dli_fname);
}
}
#endif
/*
* This hash generation function is taken originally from Redis source code:
*
* https://github.com/antirez/redis/blob/unstable/src/dict.c#L109
*
* ----
* MurmurHash2, by Austin Appleby
* Note - This code makes a few assumptions about how your machine behaves -
* 1. We can read a 4-byte value from any address without crashing
* 2. sizeof(int) == 4
*
* And it has a few limitations -
*
* 1. It will not work incrementally.
* 2. It will not produce the same results on little-endian and big-endian
* machines.
*/
unsigned int mk_utils_gen_hash(const void *key, int len)
{
/* 'm' and 'r' are mixing constants generated offline.
They're not really 'magic', they just happen to work well. */
uint32_t seed = 5381;
const uint32_t m = 0x5bd1e995;
const int r = 24;
/* Initialize the hash to a 'random' value */
uint32_t h = seed ^ len;
/* Mix 4 bytes at a time into the hash */
const unsigned char *data = (const unsigned char *)key;
while(len >= 4) {
uint32_t k = *(uint32_t*) data;
k *= m;
k ^= k >> r;
k *= m;
h *= m;
h ^= k;
data += 4;
len -= 4;
}
/* Handle the last few bytes of the input array */
switch(len) {
case 3: h ^= data[2] << 16;
case 2: h ^= data[1] << 8;
case 1: h ^= data[0]; h *= m;
};
/* Do a few final mixes of the hash to ensure the last few
* bytes are well-incorporated. */
h ^= h >> 13;
h *= m;
h ^= h >> 15;
return (unsigned int) h;
}