Skip to content

Latest commit

 

History

History
2225 lines (1872 loc) · 62.5 KB

nph-offload.c

File metadata and controls

2225 lines (1872 loc) · 62.5 KB
 
1
2
3
// This is a C program that handles offloading of bandwidth from a web
// server. It's a sort of poor-man's Akamai. It doesn't need anything
// terribly complex (a webserver with cgi-bin support, a writable directory).
Oct 6, 2008
Oct 6, 2008
4
5
// It can run as a cgi-bin program, or as a quick-and-dirty standalone HTTP
// server.
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
//
// It works like this:
// - You have a webserver with dynamic content, and static content that
// may change arbitrarily (i.e. - various users making changes to their
// homepages, etc). This server is under a lot of load, mostly from
// the static content, which tends to be big. There may be multiple virtual
// hosts on this machine. We call this the "base" server.
// - You have at least one other webserver that you can use to offload some
// of the bandwidth. We call this the "offload" server.
// - You set up an Apache module (mod_offload) on the first server.
// mod_offload inserts itself into the request chain, and decides if a
// given file is safe static content (real file, not a script/cgi, no
// password, etc). In those cases, it sends a 302 redirect, pointing the
// client to the offload server.
// - The offload server gets a request from the redirected client. It then
// sends an HTTP HEAD request for the file in question to the base server
// while the client waits. It decides if it has the right file based on
// the HEAD. If it does, it serves the cached file.
// - If the file is out of date, or doesn't exist on the offload server, it
// sends a regular HTTP request for it to the base server and
// begins caching it. While caching it, it also feeds it to the client
// that has been waiting.
// - If another request comes in while the file is being cached, it will
// stream what is already there from disk, and then continue to feed as
// the rest shows up.
// !!! FIXME: issues to work out.
// - Need to have a way to clean out old files. If x.zip is on the base,
// gets cached, and then is deleted, it'll stay on the offload server
// forever. Getting a 404 from the HEAD request will clean it out, but
// the offload server needs to know to do that.
//
// Installation:
Oct 6, 2008
Oct 6, 2008
42
43
// You need a Unix-like system, like Linux, BSD, or Mac OS X. This won't
// work on Windows (try the PHP version there, you might have some luck).
Oct 6, 2008
Oct 6, 2008
45
46
// If you're building this as a standalone server, set the options you want,
// compile it and start it running.
Oct 6, 2008
Oct 6, 2008
48
49
50
51
52
// If you want to run as a cgi-bin program:
// You need Apache (or whatever) to push every web request to this program,
// presumably in a virtual host, if not the entire server.
//
// Assuming this program was at /www/cgi-bin/index.cgi, you would want to add
53
54
// this to Apache's config:
//
Oct 6, 2008
Oct 6, 2008
55
56
57
// AliasMatch ^.*$ "/www/cgi-bin/index.cgi"
//
// You might need a "AddHandler cgi-script .cgi" or some other magic.
58
59
60
61
62
//
// If you don't have control over the virtual host's config file, you can't
// use AliasMatch, but if you can put an .htaccess file in the root of the
// virtual host, you can get away with this:
//
Oct 6, 2008
Oct 6, 2008
63
// ErrorDocument 404 /cgi-bin/index.cgi
64
65
66
67
68
69
//
// This will make all missing files (everything) run the script, which will
// then cache and distribute the correct content, including overriding the
// 404 status code with the correct one. Be careful about files that DO exist
// in that vhost directory, though. They won't offload.
//
Oct 6, 2008
Oct 6, 2008
70
71
72
73
74
// In this case, Apache will report the correct status message to the client,
// but log all offloaded files as 404 Not Found. This can't be helped. Run
// the server as standalone on a different port and have Apache proxy to it,
// or don't use Apache at all.
//
75
76
77
78
79
80
// You can offload multiple base servers with one box: set up one virtual host
// on the offload server for each base server. This lets each base server
// have its own cache and configuration.
//
// Restart the server so the AliasMatch configuration tweak is picked up.
//
Oct 6, 2008
Oct 6, 2008
81
//
82
83
// This file is written by Ryan C. Gordon (icculus@icculus.org).
Oct 6, 2008
Oct 6, 2008
84
85
86
87
88
89
90
91
92
93
/*
* Building:
*
* Edit offload_server_config.h to fit your needs, or override #defines
* on the command line. I use a shell script that looks like this:
*
* #!/bin/sh
*
* exec gcc \
* -DGDEBUG=0 \
Oct 7, 2008
Oct 7, 2008
94
95
* -DGDEBUGTOFILE=1 \
* -DGDEBUGDIR='"/home/icculus/offload2.icculus.org/logs"' \
Oct 6, 2008
Oct 6, 2008
96
97
* -DSHM_NAME='"mod-offload-offload2-icculus-org"' \
* -DGBASESERVER='"icculus.org"' \
Oct 12, 2008
Oct 12, 2008
98
* -DGBASESERVERIP='"67.106.77.212"' \
Oct 6, 2008
Oct 6, 2008
99
100
101
* -DGLISTENPORT=9090 \
* -DGLISTENDAEMONIZE=1 \
* -DGLISTENTRUSTFWD='"127.0.0.1", "66.33.209.154"' \
Oct 7, 2008
Oct 7, 2008
102
* -DGOFFLOADDIR='"/home/icculus/offload2.icculus.org/cache"' \
Oct 6, 2008
Oct 6, 2008
103
* -DGMAXDUPEDOWNLOADS=1 \
Oct 6, 2008
Oct 6, 2008
104
* -DGLOGACTIVITY=1 \
Oct 7, 2008
Oct 7, 2008
105
* -DGLOGFILE='"/home/icculus/offload2.icculus.org/logs/access.log"' \
Oct 6, 2008
Oct 6, 2008
106
107
108
* -g -O0 -Wall -o offload-daemon /home/icculus/mod_offload/nph-offload.c -lrt
*/
109
110
111
112
113
114
115
116
117
118
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdarg.h>
#include <stdint.h>
#include <time.h>
#include <errno.h>
#include <semaphore.h>
#include <limits.h>
Aug 31, 2008
Aug 31, 2008
119
#include <fcntl.h>
Aug 31, 2008
Aug 31, 2008
120
#include <signal.h>
Aug 31, 2008
Aug 31, 2008
121
#include <sys/types.h>
122
123
#include <sys/stat.h>
#include <sys/socket.h>
Sep 4, 2008
Sep 4, 2008
124
#include <sys/mman.h>
125
#include <netdb.h>
Sep 30, 2008
Sep 30, 2008
126
127
#include <netinet/in.h>
#include <arpa/inet.h>
Oct 12, 2008
Oct 12, 2008
129
#define GVERSION "1.1.6"
130
131
132
133
#define GSERVERSTRING "nph-offload.c/" GVERSION
#include "offload_server_config.h"
Sep 30, 2008
Sep 30, 2008
134
135
136
137
138
#define OFFLOAD_NUMSTR2(x) #x
#define OFFLOAD_NUMSTR(x) OFFLOAD_NUMSTR2(x)
#define GBASESERVERPORTSTR OFFLOAD_NUMSTR(GBASESERVERPORT)
139
140
141
142
143
144
145
146
147
148
#ifdef __GNUC__
#define ISPRINTF(x,y) __attribute__((format (printf, x, y)))
#else
#define ISPRINTF(x,y)
#endif
#ifdef max
#undef max
#endif
Aug 31, 2008
Aug 31, 2008
149
// some getaddrinfo() flags that may not exist...
Sep 30, 2008
Sep 30, 2008
150
#ifndef AI_ALL
Sep 30, 2008
Sep 30, 2008
151
#define AI_ALL 0
Sep 30, 2008
Sep 30, 2008
152
#endif
Aug 31, 2008
Aug 31, 2008
153
154
155
156
157
158
159
160
161
162
#ifndef AI_ADDRCONFIG
#define AI_ADDRCONFIG 0
#endif
#ifndef AI_NUMERICSERV
#define AI_NUMERICSERV 0
#endif
#ifndef AI_V4MAPPED
#define AI_V4MAPPED 0
#endif
Sep 4, 2008
Sep 4, 2008
163
164
165
166
167
168
typedef int8_t int8;
typedef uint8_t uint8;
typedef int16_t int16;
typedef uint16_t uint16;
typedef int32_t int32;
typedef uint32_t uint32;
169
typedef int64_t int64;
Sep 4, 2008
Sep 4, 2008
170
typedef uint64_t uint64;
Sep 30, 2008
Sep 30, 2008
172
173
extern char **environ;
Aug 31, 2008
Aug 31, 2008
174
static int GIsCacheProcess = 0;
Oct 6, 2008
Oct 6, 2008
175
176
static int GHttpStatus = 0;
static int64 GBytesSent = 0;
Oct 1, 2008
Oct 1, 2008
177
178
static const char *Guri = NULL;
static const char *GRemoteAddr = NULL;
Oct 6, 2008
Oct 6, 2008
179
180
181
182
static const char *GReferer = NULL;
static const char *GUserAgent = NULL;
static const char *GReqVersion = NULL;
static const char *GReqMethod = NULL;
183
184
185
186
static char *GFilePath = NULL;
static void *GSemaphore = NULL;
static int GSemaphoreOwned = 0;
static FILE *GDebugFilePointer = NULL;
May 31, 2009
May 31, 2009
187
static int GSocket = -1;
Oct 13, 2008
Oct 13, 2008
189
190
191
192
193
#if !GNOCACHE
static char *GMetaDataPath = NULL;
#endif
194
195
196
197
198
199
200
201
static void failure_location(const char *, const char *, const char *);
static inline void failure(const char *httperr, const char *errmsg)
{
failure_location(httperr, errmsg, NULL);
} // failure
#if ( ((GDEBUG) && (GDEBUGTOFILE)) == 0 )
Aug 31, 2008
Aug 31, 2008
202
#define getDebugFilePointer() (NULL)
203
204
205
206
207
208
#else
static FILE *getDebugFilePointer(void)
{
if (GDebugFilePointer == NULL)
{
char buf[PATH_MAX];
Oct 7, 2008
Oct 7, 2008
209
snprintf(buf, sizeof(buf), GDEBUGDIR "/debug-%d", (int) getpid());
210
211
212
213
214
215
216
217
GDebugFilePointer = fopen(buf, "a");
} // if
return GDebugFilePointer;
} // getDebugFilePointer
#endif
#if ((!GDEBUG) && defined(__GNUC__))
Aug 31, 2008
Aug 31, 2008
218
#define debugEcho(fmt, ...) do {} while (0)
219
220
221
222
223
224
225
226
227
228
229
230
#else
static void debugEcho(const char *fmt, ...) ISPRINTF(1, 2);
static void debugEcho(const char *fmt, ...)
{
#if GDEBUG
#if !GDEBUGTOFILE
FILE *fp = stdout;
#else
FILE *fp = getDebugFilePointer();
#endif
if (fp != NULL)
{
Aug 31, 2008
Aug 31, 2008
231
232
233
if (GIsCacheProcess)
fputs("(cache process) ", fp);
234
235
236
237
238
239
240
241
242
243
244
245
va_list ap;
va_start(ap, fmt);
vfprintf(fp, fmt, ap);
va_end(ap);
fputs("\n", fp);
fflush(fp);
} // else
#endif
} // debugEcho
#endif
Sep 4, 2008
Sep 4, 2008
246
247
248
249
250
251
static void *createSemaphore(const int initialVal)
{
void *retval = NULL;
const int value = initialVal ? 0 : 1;
int created = 1;
Sep 4, 2008
Sep 4, 2008
252
retval = sem_open("SEM-" SHM_NAME, O_CREAT | O_EXCL, 0600, value);
Sep 4, 2008
Sep 4, 2008
253
254
255
256
if ((retval == (void *) SEM_FAILED) && (errno == EEXIST))
{
created = 0;
debugEcho("(semaphore already exists, just opening existing one.)");
Sep 4, 2008
Sep 4, 2008
257
retval = sem_open("SEM-" SHM_NAME, 0);
Sep 4, 2008
Sep 4, 2008
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
} // if
if (retval == (void *) SEM_FAILED)
return NULL;
return retval;
} // createSemaphore
static void getSemaphore(void)
{
debugEcho("grabbing semaphore...(owned %d time(s).)", GSemaphoreOwned);
if (GSemaphoreOwned++ > 0)
return;
if (GSemaphore != NULL)
{
if (sem_wait(GSemaphore) == -1)
failure("503 Service Unavailable", "Couldn't lock semaphore.");
} // if
else
{
debugEcho("(have to create semaphore...)");
GSemaphore = createSemaphore(0);
if (GSemaphore == NULL)
failure("503 Service Unavailable", "Couldn't allocate semaphore.");
} // else
} // getSemaphore
static void putSemaphore(void)
{
if (GSemaphoreOwned == 0)
return;
if (--GSemaphoreOwned == 0)
{
if (GSemaphore != NULL)
{
if (sem_post(GSemaphore) == -1)
failure("503 Service Unavailable", "Couldn't unlock semaphore.");
} // if
} // if
debugEcho("released semaphore...(now owned %d time(s).)", GSemaphoreOwned);
} // putSemaphore
static inline int process_dead(const pid_t pid)
{
return ( (pid <= 0) || ((kill(pid, 0) == -1) && (errno == ESRCH)) );
} // process_dead
#if GMAXDUPEDOWNLOADS <= 0
#define setDownloadRecord()
#define removeDownloadRecord()
#else
// we can track this many concurrent connections in a block of shared memory.
// If DownloadRecord is 24 bytes, then 512 records is 12 kilobytes (usually,
// three pages of memory). If you actually have more than this many concurrent
// connections then we'll just stop checking for dupes in things that didn't
// fit in the table...frankly, if your server is still standing with 512
// active HTTP downloads, you probably don't care about download accelerators
// anyhow. :)
#define MAX_DOWNLOAD_RECORDS 512
typedef struct
{
pid_t pid;
uint8 sha1[20];
} DownloadRecord;
static DownloadRecord *GAllDownloads = NULL;
static DownloadRecord *GMyDownload = NULL;
#define DUPE_FORBID_TEXT \
Sep 4, 2008
Sep 4, 2008
335
336
337
"403 Forbidden - " GSERVERSTRING "\n\n" \
"Your network address has too many connections for this specific file.\n" \
"Please disable any 'download accelerators' and try again.\n\n" \
Sep 4, 2008
Sep 4, 2008
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
typedef struct
{
uint32 state[5];
uint32 count[2];
uint8 buffer[64];
} Sha1;
static void Sha1_init(Sha1 *context);
static void Sha1_append(Sha1 *context, const uint8 *data, uint32 len);
static void Sha1_finish(Sha1 *context, uint8 digest[20]);
static void setDownloadRecord()
{
const pid_t mypid = getpid();
int dupes = 0;
int i = 0;
int fd = -1;
Sha1 sha1data;
uint8 sha1[20];
DownloadRecord *downloads = NULL;
const size_t maplen = sizeof (DownloadRecord) * MAX_DOWNLOAD_RECORDS;
Oct 1, 2008
Oct 1, 2008
360
if (GRemoteAddr == NULL)
Sep 4, 2008
Sep 4, 2008
361
362
363
364
365
366
return; // oh well.
GAllDownloads = GMyDownload = NULL;
getSemaphore();
Sep 4, 2008
Sep 4, 2008
367
fd = shm_open("/" SHM_NAME, (O_CREAT|O_EXCL|O_RDWR), (S_IREAD|S_IWRITE));
Sep 4, 2008
Sep 4, 2008
368
369
if (fd < 0)
{
Sep 4, 2008
Sep 4, 2008
370
fd = shm_open("/" SHM_NAME, (O_CREAT|O_RDWR),(S_IREAD|S_IWRITE));
Sep 4, 2008
Sep 4, 2008
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
if (fd < 0)
{
putSemaphore();
debugEcho("shm_open() failed: %s", strerror(errno));
return; // oh well.
} // if
} // if
ftruncate(fd, maplen);
void *ptr = mmap(0, maplen, (PROT_READ|PROT_WRITE), MAP_SHARED, fd, 0);
close(fd); // mapping remains.
if (ptr == MAP_FAILED)
{
putSemaphore();
debugEcho("mmap() failed: %s", strerror(errno));
return;
} // if
GAllDownloads = downloads = (DownloadRecord *) ptr;
Sha1_init(&sha1data);
Oct 1, 2008
Oct 1, 2008
393
Sha1_append(&sha1data, (const uint8 *) GRemoteAddr, strlen(GRemoteAddr) + 1);
Sep 4, 2008
Sep 4, 2008
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
Sha1_append(&sha1data, (const uint8 *) Guri, strlen(Guri) + 1);
Sha1_finish(&sha1data, sha1);
for (i = 0; i < MAX_DOWNLOAD_RECORDS; i++, downloads++)
{
const pid_t pid = downloads->pid;
if (pid <= 0) // unused slot.
GMyDownload = downloads; // take slot.
else if (memcmp(downloads->sha1, sha1, sizeof (sha1)) == 0)
{
// make sure this isn't a killed process.
if ( (pid == mypid) || (process_dead(pid)) )
{
debugEcho("pid #%d died at some point.", (int) pid);
downloads->pid = 0;
GMyDownload = downloads; // take slot.
} // if
else
{
debugEcho("pid #%d still alive, dupe slot.", (int) pid);
dupes++;
} // else
} // else if
} // for
debugEcho("Saw %d dupes.", dupes);
if (dupes >= GMAXDUPEDOWNLOADS)
failure("403 Forbidden", DUPE_FORBID_TEXT); // will put semaphore.
else if (GMyDownload == NULL) // Have fun, downloader accelerator!
debugEcho("no free download slots! Can't add ourselves.");
else
{
debugEcho("Got download slot #%d", (int) (GMyDownload-GAllDownloads));
GMyDownload->pid = mypid;
memcpy(GMyDownload->sha1, sha1, sizeof (sha1));
} // else
putSemaphore();
} // setDownloadRecord
static void removeDownloadRecord()
{
if (!GAllDownloads)
return;
getSemaphore();
if (GMyDownload != NULL)
GMyDownload->pid = 0;
putSemaphore();
munmap(GAllDownloads, sizeof (DownloadRecord) * MAX_DOWNLOAD_RECORDS);
GAllDownloads = GMyDownload = NULL;
} // removeDownloadRecord
#endif
Oct 6, 2008
Oct 6, 2008
453
454
455
456
457
458
459
460
461
462
// strftime()'s "%a" gives you locale-dependent strings...
static const char *GWeekday[] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
};
// strftime()'s "%b" gives you locale-dependent strings...
static const char *GMonth[] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
};
Sep 4, 2008
Sep 4, 2008
463
May 31, 2009
May 31, 2009
464
static void make_date_header(char *buf, const size_t buflen)
465
466
467
{
time_t now = time(NULL);
const struct tm *tm = gmtime(&now);
May 31, 2009
May 31, 2009
468
snprintf(buf, buflen, "Date: %s, %02d %s %d %02d:%02d:%02d GMT\r\n",
Oct 6, 2008
Oct 6, 2008
469
GWeekday[tm->tm_wday], tm->tm_mday, GMonth[tm->tm_mon],
470
tm->tm_year+1900, tm->tm_hour, tm->tm_min, tm->tm_sec);
May 31, 2009
May 31, 2009
471
472
} // make_date_header
Nov 6, 2009
Nov 6, 2009
473
474
#if GDEBUG
May 31, 2009
May 31, 2009
475
476
477
478
479
480
481
static void printf_date_header(FILE *out)
{
char buf[128];
if (out == NULL)
return;
make_date_header(buf, sizeof (buf));
fprintf(out, "%s", buf);
482
} // printf_date_header
Nov 6, 2009
Nov 6, 2009
483
#endif
May 31, 2009
May 31, 2009
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
static void terminate(void);
static void write_string(const int fd, const char *str)
{
size_t avail = strlen(str);
while (avail > 0)
{
ssize_t rc = write(fd, str, avail);
if ((rc == -1) && (errno == EINTR))
continue;
if (rc <= 0)
{
debugEcho("write_string(): write() failed! (%s)\n", strerror(errno));
terminate();
} // if
avail -= rc;
str += rc;
} // while
} // write_string
static void write_header(const char *key, const char *val)
{
write_string(GSocket, key);
write_string(GSocket, val);
write_string(GSocket, "\r\n");
} // write_header
static void write_date_header(void)
{
char buf[128];
make_date_header(buf, sizeof (buf));
write_string(GSocket, buf);
} // write_date_header
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
static int64 atoi64(const char *str)
{
int64 retval = 0;
int64 mult = 1;
int i = 0;
while (*str == ' ')
str++;
if (*str == '-')
{
mult = -1;
str++;
} // if
while (1)
{
const char ch = str[i];
if ((ch < '0') || (ch > '9'))
break;
i++;
} // for
while (--i >= 0)
{
const char ch = str[i];
retval += ((int64) (ch - '0')) * mult;
mult *= 10;
} // while
return retval;
} // atoi64
static void *xmalloc(const size_t len)
{
void *ptr = malloc(len);
if (ptr == NULL)
failure("500 Internal Server Error", "Out of memory.");
return ptr;
} // xmalloc
static char *xstrdup(const char *str)
{
char *ptr = (char *) xmalloc(strlen(str) + 1);
strcpy(ptr, str);
return ptr;
} // xstrdup
static char *makeStr(const char *fmt, ...) ISPRINTF(1, 2);
static char *makeStr(const char *fmt, ...)
{
va_list ap;
char ch;
va_start(ap, fmt);
const int len = vsnprintf(&ch, 1, fmt, ap);
va_end(ap);
char *retval = (char *) xmalloc(len + 1);
va_start(ap, fmt);
vsnprintf(retval, len + 1, fmt, ap);
va_end(ap);
return retval;
} // makeStr
// a hashtable would be more sane, but really, we're talking about a handful
// of items, so this is probably the lower memory option, and it's fast
// enough for the simplicity.
typedef struct list
{
const char *key;
const char *value;
struct list *next;
} list;
static const char *listSet(list **l, const char *key, const char *value)
{
// maybe substring of current item, so copy it before we free() anything.
const char *newvalue = xstrdup(value);
list *item = *l;
while (item)
{
if (strcmp(item->key, key) == 0)
break;
item = item->next;
} // while
if (item != NULL)
free((void *) item->value);
else
{
item = (list *) xmalloc(sizeof (list));
item->key = xstrdup(key);
item->next = *l;
*l = item;
} // else
item->value = newvalue;
return newvalue;
} // listSet
static const char *listFind(const list *l, const char *key)
{
const list *item = l;
while (item)
{
if (strcmp(item->key, key) == 0)
break;
item = item->next;
} // while
return item ? item->value : NULL;
} // listFind
static void listFree(list **l)
{
list *item = *l;
while (item)
{
list *next = item->next;
free((void *) item->key);
free((void *) item->value);
free(item);
item = next;
} // while
*l = NULL;
} // listFree
Oct 1, 2008
Oct 1, 2008
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
#if GSETPROCTITLE
#if defined(__linux__)
// okay.
#else
#warning GSETPROCTITLE not currently supported on this platform.
#undef GSETPROCTITLE
#define GSETPROCTITLE 0
#endif
#endif
#if !GSETPROCTITLE
#define copyEnv(x) getenv(x)
#define freeEnvCopies()
#else
static char **GArgv = NULL;
static char *GLastArgv = NULL;
static int GMaxArgvLen = 0;
static int GNoMoreGetEnv = 0;
static list *GEnvCopies = NULL;
static const char *copyEnv(const char *key)
{
const char *retval = listFind(GEnvCopies, key);
if ((retval == NULL) && (!GNoMoreGetEnv))
{
const char *envr = getenv(key);
if (envr != NULL)
retval = listSet(&GEnvCopies, key, envr);
} // if
return retval;
} // copyEnv
static inline void freeEnvCopies(void)
{
listFree(&GEnvCopies);
} // freeEnvCopies
#endif
Oct 6, 2008
Oct 6, 2008
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
#if !GLOGACTIVITY
#define outputLogEntry()
#else
static void outputLogEntry(void)
{
FILE *out = fopen(GLOGFILE, "a");
if (out == NULL)
debugEcho("Failed to open log file for append!");
else
{
// Apache Combined Log Format:
// http://httpd.apache.org/docs/1.3/logs.html#combined
// !!! FIXME: auth and identd?
time_t now = time(NULL);
const struct tm *tm = localtime(&now);
fprintf(out,
"%s - - [%02d/%s/%d:%02d:%02d:%02d %c%02d%02d]"
" \"%s %s%s%s\" %d %lld \"%s\" \"%s\"\n",
GRemoteAddr, tm->tm_mday, GMonth[tm->tm_mon],
tm->tm_year+1900, tm->tm_hour, tm->tm_min,
tm->tm_sec, (tm->tm_gmtoff < 0) ? '-' : '+',
(int) (abs((int) tm->tm_gmtoff) / (60*60)),
(int) (abs((int) tm->tm_gmtoff) % (60*60)),
GReqMethod ? GReqMethod : "",
Guri ? Guri : "",
(GReqVersion && *GReqVersion) ? " " : "",
GReqVersion ? GReqVersion : "",
GHttpStatus, (long long) GBytesSent,
GReferer ? GReferer : "-",
GUserAgent ? GUserAgent : "-");
fclose(out);
} // else
} // outputLogEntry
#endif
735
736
static void terminate(void)
{
Aug 31, 2008
Aug 31, 2008
737
738
739
if (!GIsCacheProcess)
{
debugEcho("offload program is terminating...");
Sep 4, 2008
Sep 4, 2008
740
removeDownloadRecord();
Oct 6, 2008
Oct 6, 2008
741
outputLogEntry();
Aug 31, 2008
Aug 31, 2008
742
743
744
while (GSemaphoreOwned > 0)
putSemaphore();
} // if
745
746
747
if (GDebugFilePointer != NULL)
fclose(GDebugFilePointer);
Oct 1, 2008
Oct 1, 2008
748
Oct 7, 2008
Oct 7, 2008
749
750
#if GLISTENPORT
char ch = 0;
May 31, 2009
May 31, 2009
751
752
753
shutdown(GSocket, SHUT_RDWR);
while (recv(GSocket, &ch, sizeof (ch), 0) > 0) {}
close(GSocket);
Oct 7, 2008
Oct 7, 2008
754
755
#endif
Oct 1, 2008
Oct 1, 2008
756
757
758
759
760
if (stdin) fclose(stdin);
if (stdout) fclose(stdout);
if (stderr) fclose(stderr);
stdin = stdout = stderr = NULL;
Oct 1, 2008
Oct 1, 2008
761
762
freeEnvCopies();
763
764
765
exit(0);
} // terminate
May 31, 2009
May 31, 2009
766
767
768
769
770
771
772
773
774
775
776
static void failure_location(const char *httperr, const char *errmsg,
const char *location)
{
if (strncasecmp(httperr, "HTTP", 4) == 0)
{
const char *ptr = strchr(httperr, ' ');
if (ptr != NULL)
httperr = ptr+1;
} // if
Oct 6, 2008
Oct 6, 2008
777
778
779
if (!GHttpStatus)
GHttpStatus = atoi(httperr);
780
781
782
783
debugEcho("failure() called:");
debugEcho(" %s", httperr);
debugEcho(" %s", errmsg);
May 31, 2009
May 31, 2009
784
if (GSocket != -1)
Aug 31, 2008
Aug 31, 2008
785
{
May 31, 2009
May 31, 2009
786
787
788
789
write_header("HTTP/1.1 ", httperr);
write_header("Status: ", httperr);
write_header("Server: ", httperr);
write_date_header();
Aug 31, 2008
Aug 31, 2008
790
if (location != NULL)
May 31, 2009
May 31, 2009
791
792
793
794
795
write_header("Location: ", location);
write_header("Connection: ", "close");
write_header("Content-type: ", "text/plain; charset=utf-8");
write_header("", "");
write_header("", errmsg);
Oct 6, 2008
Oct 6, 2008
796
GBytesSent += strlen(errmsg) + 2;
Aug 31, 2008
Aug 31, 2008
797
798
} // if
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
terminate();
} // failure_location
static int invalidContentRange(const int64 startRange, const int64 endRange,
const int64 max)
{
if ((startRange < 0) || (startRange >= max))
return 1;
else if ((endRange < 0) || (endRange >= max))
return 1;
else if (startRange > endRange)
return 1;
return 0;
} // invalidContentRange
#if !GDEBUG
Aug 31, 2008
Aug 31, 2008
817
#define debugInit(argc, argv, envp)
Aug 31, 2008
Aug 31, 2008
819
static void debugInit(int argc, char **argv, char **envp)
May 31, 2009
May 31, 2009
821
#if ((!GLISTENPORT) && (!GDEBUGTOFILE))
May 31, 2009
May 31, 2009
822
823
824
825
826
827
828
write_header("HTTP/1.1 ", "200 OK");
write_header("Status: ", "200 OK");
write_header("Content-type: ", "text/plain; charset=utf-8");
write_date_header();
write_header("Server: ", GSERVERSTRING);
write_header("Connection: ", "close");
write_header("", "");
Oct 6, 2008
Oct 6, 2008
829
GHttpStatus = 200;
830
831
832
833
834
835
836
#endif
debugEcho("%s", "");
debugEcho("%s", "");
debugEcho("%s", "");
debugEcho("Offload Debug Run!");
debugEcho("%s", "");
Aug 31, 2008
Aug 31, 2008
837
printf_date_header(getDebugFilePointer());
Aug 31, 2008
Aug 31, 2008
838
debugEcho("I am: %s", GSERVERSTRING);
839
840
debugEcho("Base server: %s", GBASESERVER);
debugEcho("User wants to get: %s", Guri);
Oct 1, 2008
Oct 1, 2008
841
debugEcho("Request from address: %s", GRemoteAddr);
Oct 6, 2008
Oct 6, 2008
842
843
844
debugEcho("Client User-Agent: %s", GUserAgent);
debugEcho("Referrer string: %s", GReferer);
debugEcho("Request method: %s", GReqMethod);
845
846
847
848
849
debugEcho("Timeout for HTTP HEAD request is %d", GTIMEOUT);
debugEcho("Data cache goes in %s", GOFFLOADDIR);
debugEcho("My PID: %d\n", (int) getpid());
debugEcho("%s", "");
debugEcho("%s", "");
Aug 31, 2008
Aug 31, 2008
850
851
852
853
854
855
856
857
858
859
860
861
int i;
debugEcho("Command line: %d items...", argc);
for (i = 0; i < argc; i++)
debugEcho(" argv[%d] = '%s'", i, argv[i]);
debugEcho("%s", "");
debugEcho("%s", "");
debugEcho("Environment...");
for (i = 0; envp[i]; i++)
debugEcho(" %s", envp[i]);
debugEcho("%s", "");
debugEcho("%s", "");
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
} // debugInit
#endif
static void readHeaders(const int fd, list **headers)
{
const time_t endtime = time(NULL) + GTIMEOUT;
int br = 0;
char buf[1024];
int seenresponse = 0;
while (1)
{
const time_t now = time(NULL);
int rc = -1;
fd_set rfds;
if (endtime >= now)
{
struct timeval tv;
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
tv.tv_sec = endtime - now;
tv.tv_usec = 0;
rc = select(fd+1, &rfds, NULL, NULL, &tv);
} // if
if ((rc <= 0) || (FD_ISSET(fd, &rfds) == 0))
failure("503 Service Unavailable", "Timeout while talking to offload host.");
// we can only read one byte at a time, since we don't want to
// read past end of headers, into actual content, here.
if (read(fd, buf + br, 1) != 1)
failure("503 Service Unavailable", "Read error while talking to offload host.");
if (buf[br] == '\r')
; // ignore these.
else if (buf[br] == '\n')
{
Aug 31, 2008
Aug 31, 2008
900
char *ptr = NULL;
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
if (br == 0) // empty line, end of headers.
return;
buf[br] = '\0';
if (seenresponse)
{
ptr = strchr(buf, ':');
if (ptr != NULL)
{
*(ptr++) = '\0';
while (*ptr == ' ')
ptr++;
listSet(headers, buf, ptr);
} // if
} // if
else
{
listSet(headers, "response", buf);
Sep 30, 2008
Sep 30, 2008
918
if (strncasecmp(buf, "HTTP/", 5) == 0)
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
{
ptr = strchr(buf + 5, ' ');
if (ptr != NULL)
{
char *start = ptr + 1;
ptr = strchr(start, ' ');
if (ptr != NULL)
*ptr = '\0';
listSet(headers, "response_code", start);
ptr = start;
} // if
} // if
seenresponse = 1;
} // else
if (ptr == NULL)
failure("503 Service Unavailable", "Bogus response from offload host server.");
br = 0;
} // if
else
{
br++;
if (br >= sizeof (buf))
failure("503 Service Unavailable", "Buffer overflow.");
} // else
} // while
} // readHeaders
static void doWrite(const int fd, const char *str)
{
const int len = strlen(str);
int bw = 0;
const time_t endtime = time(NULL) + GTIMEOUT;
while (bw < len)
{
const time_t now = time(NULL);
int rc = -1;
fd_set wfds;
if (endtime >= now)
{
struct timeval tv;
FD_ZERO(&wfds);
FD_SET(fd, &wfds);
tv.tv_sec = endtime - now;
tv.tv_usec = 0;
rc = select(fd+1, NULL, &wfds, NULL, &tv);
} // if
if ((rc <= 0) || (FD_ISSET(fd, &wfds) == 0))
failure("503 Service Unavailable", "Timeout while talking to offload base server.");
rc = write(fd, str + bw, len - bw);
if (rc <= 0) // error? closed connection?
failure("503 Service Unavailable", "Write error while talking to offload base server.");
bw += rc;
} // while
} // doWrite
static int doHttp(const char *method, list **headers)
{
Aug 31, 2008
Aug 31, 2008
983
int rc = -1;
Aug 31, 2008
Aug 31, 2008
984
985
struct addrinfo hints;
memset(&hints, '\0', sizeof (hints));
Sep 30, 2008
Sep 30, 2008
986
hints.ai_family = PF_UNSPEC;
Aug 31, 2008
Aug 31, 2008
987
hints.ai_socktype = SOCK_STREAM;
Sep 30, 2008
Sep 30, 2008
988
hints.ai_flags = AI_NUMERICSERV | AI_V4MAPPED | AI_ALL | AI_ADDRCONFIG;
Aug 31, 2008
Aug 31, 2008
989
990
struct addrinfo *dns = NULL;
Oct 12, 2008
Oct 12, 2008
991
if ((rc = getaddrinfo(GBASESERVERIP, GBASESERVERPORTSTR, &hints, &dns)) != 0)
Aug 31, 2008
Aug 31, 2008
992
993
{
debugEcho("getaddrinfo failure: %s", gai_strerror(rc));
994
failure("503 Service Unavailable", "Offload base server hostname lookup failure.");
Aug 31, 2008
Aug 31, 2008
995
} // if
996
997
998
999
1000
int fd = -1;
struct addrinfo *addr;
for (addr = dns; addr != NULL; addr = addr->ai_next)
{