File: headers.cpp

package info (click to toggle)
libperlbal-xs-httpheaders-perl 0.20-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 188 kB
  • sloc: cpp: 500; perl: 110; pascal: 69; makefile: 3
file content (687 lines) | stat: -rw-r--r-- 20,914 bytes parent folder | download | duplicates (2)
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
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
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
/******************************************************************************
 * Perlbal XS HTTPHeaders class                                               *
 * Written by Mark Smith (junior@sixapart.com)                                *
 *                                                                            *
 * This program is free software; you can redistribute it and/or modify it    *
 * under the same terms as Perl itself.                                       *
 *                                                                            *
 * Copyright 2004 Danga Interactive, Inc.                                     *
 * Copyright 2005 Six Apart, Ltd.                                             *
 ******************************************************************************/

#include "headers.h"

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

using namespace std;

/******************************************************************************
 * HELPER FUNCTIONS ***********************************************************
 ******************************************************************************/
int skip_spaces(char **ptr) {
    // should be safe, as string terminates with \0, so we won't hit that
    // as long as we're looking to match spaces only
    int i = 0;
    while (**ptr == ' ') {
        i++;
        (*ptr)++;
    }
    return i;
}

int skip_to_space(char **ptr) {
    // safe as we stop incrementing if we hit a \n or a \0
    int i = 0;
    while (**ptr != ' ' && **ptr != '\0') {
        // only increase length if this isn't an \r... we only want to count real stuff
        i++;
        (*ptr)++;
    }
    return i;
}

// FIXME: the following two functions can be optimized so as not to do the \r check in
// the main loop; just look for \r in the while and increment *ptr by two if we have an
// \r\n after the while loop... I'm too lazy to do it now
int skip_to_eol(char **ptr) {
    // safe as we stop incrementing if we hit a \n or a \0
    int i = 0;
    while (**ptr != '\n' && **ptr != '\0') {
        // only increase length if this isn't an \r... we only want to count real stuff
        if (**ptr != '\r')
            i++;
        (*ptr)++;
    }
    if (**ptr == '\n')
        (*ptr)++;
    return i;
}

int skip_to_colon(char **ptr) {
    // safe as we stop incrementing if we hit a colon, \n, or \0
    int i = 0;
    while (**ptr != ':') {
        if (**ptr == '\r' || **ptr == '\n' || **ptr == '\0')
            return 0; // invalid line? make them bomb
        i++;
        (*ptr)++;
    }
    if (**ptr == ':')
        (*ptr)++;
    return i;
}

int parseVersionNumber(char *ptr, char **newptr) {
    int i = 0, j = 0;

    // find width of first number
    while (isdigit(ptr[i])) i++;
    if (i == 0 || i > 4 || ptr[i] != '.') return 0;

    // find width of second number
    while (isdigit(ptr[i+j+1])) j++;
    if (j == 0 || j > 4) return 0;

    // update newptr with data
    *newptr = (ptr + i + j + 1);

    // now extract into ret
    int ret = atoi(ptr) * 1000 + atoi(ptr+i+1);
    return ret;
}


/******************************************************************************
 * HTTPHEADERS CLASS **********************************************************
 ******************************************************************************/

HTTPHeaders::HTTPHeaders() {
    /* initialize our internal data */
    versionNumber = 0;
    statusCode = 0;
    headersType = 0;
    method = 0;
    sv_uri = NULL;
    sv_firstLine = NULL;
    sv_methodString = NULL;
    hdrs = NULL;
    hdrtail = NULL;
}

HTTPHeaders::~HTTPHeaders() {
    if (sv_uri) {
        SvREFCNT_dec(sv_uri);
    }
    if (sv_firstLine) {
        SvREFCNT_dec(sv_firstLine);
    }
    if (sv_methodString) {
        SvREFCNT_dec(sv_methodString);
    }

    /* free header structs we're using */
    Header *next = NULL;
    while (hdrs) {
        next = hdrs->next;
        freeHeader(hdrs);
        hdrs = next;
    }
}

void HTTPHeaders::freeHeader(Header *hdr) {
    // now free this header
    Safefree(hdr->key);
    SvREFCNT_dec(hdr->sv_value);
    Safefree(hdr);
}


int HTTPHeaders::parseHeaders(SV *headers) {
    // make sure headers is a reference
    if (!SvROK(headers))
        return 0;
    
    // setup variables we're going to use
    int state = 0; // 0 = parsing first line, 1 = parsing headers
    int len = 0;
    char *initial = SvPV_nolen(SvRV(headers)); // point to the beginning of headers
    char *pptr, *ptr = initial;
    Header *lasthdr = NULL;

    // loop while we haven't hit the end
    while (*ptr != '\0') {
        // state 0 is when we haven't gotten anything and we're reading in
        // the first line for processing
        if (state == 0) {
            if (!strncmp(ptr, "HTTP/", 5)) {
                headersType = H_RESPONSE;
                // FIXME: this probably isn't safe if the headers are really short
                // because we're just randomly referencing into headers
                versionNumber = parseVersionNumber(ptr + 5, &ptr);
                if (versionNumber <= 0)
                    return 0;

                // now we want to get the code, which should be next after some spaces
                skip_spaces(&ptr);

                // get the code
                statusCode = strtol(ptr, &ptr, 10);

                // now skip to the end of line
                skip_to_eol(&ptr);

                // now copy our first line.  we do this weird thing with \r and \n in order
                // to remove any trailing \r\ns from our first line.
                len = ptr - initial;
                while (initial[len - 1] == '\r' || initial[len - 1] == '\n')
                    len--;
                sv_firstLine = newSVpvn(initial, len);
                if (!sv_firstLine)
                    return 0;

                // now continue on to doing actual header parsing
                state = 1;
                continue;
            }

            // must be a request
            headersType = H_REQUEST;
            if (!strncmp(ptr, "GET ", 4)) {
                ptr += 4;
                method = M_GET;
            } else if (!strncmp(ptr, "POST ", 5)) {
                ptr += 5;
                method = M_POST;
            } else if (!strncmp(ptr, "HEAD ", 5)) {
                ptr += 5;
                method = M_HEAD;
            } else if (!strncmp(ptr, "OPTIONS ", 8)) {
                ptr += 8;
                method = M_OPTIONS;
            } else if (!strncmp(ptr, "PUT ", 4)) {
                ptr += 4;
                method = M_PUT;
            } else if (!strncmp(ptr, "DELETE ", 7)) {
                ptr += 7;
                method = M_DELETE;
            } else {
                pptr = ptr;
                len = skip_to_space(&ptr);
                if (len) {
                    sv_methodString = newSVpvn(pptr, len);
                    if (!sv_methodString)
                        return 0;
                } else {
                    // nothing, error
                    return 0;
                }

                skip_spaces(&ptr);
            }

            // now we need to read in the URI
            pptr = ptr;
            len = skip_to_space(&ptr);
            if (len) {
                // now get the URI
                sv_uri = newSVpvn(pptr, len);
                if (!sv_uri)
                    return 0;
            }

            // now we need to determine the version
            skip_spaces(&ptr);
            if (!strncmp(ptr, "HTTP/", 5)) {
                // FIXME: this probably isn't safe if the headers are really short
                // because we're just randomly referencing into headers
                versionNumber = parseVersionNumber(ptr + 5, &ptr);
                if (versionNumber <= 0)
                    return 0;
                skip_to_eol(&ptr);

                // now copy our first line.  we do this weird thing with \r and \n in order
                // to remove any trailing \r\ns from our first line.
                len = ptr - initial;
                while (initial[len - 1] == '\r' || initial[len - 1] == '\n')
                    len--;
                sv_firstLine = newSVpvn(initial, len);
                if (!sv_firstLine)
                    return 0;
            } else {
                return 0;
            }

            // cool, start parsing the headers now
            state = 1;
        } else if (state == 1) {
            // if it starts with space or tab then go ahead and append to previous header
            if (*ptr == ' ' || *ptr == '\t') {
                // we have to have lasthdr, or something drastically bad happened
                if (!lasthdr)
                    return 0;

                // get the whole line, the whole thing is just being appended
                pptr = ptr;
                len = skip_to_eol(&ptr);

                // len should never be 0 in this case, but in case it is...
                if (!len)
                    return 0;

                // append this data to the end
                sv_catpv(lasthdr->sv_value, "\r\n");
                sv_catpvn(lasthdr->sv_value, pptr, len);
                continue;
            }

            // normal case; we're going to get something.  first see if we're up against a blank line
            // or the end of string marker, and if so, we're done (but successfully!)
            if (*ptr == '\r' || *ptr == '\n' || *ptr == '\0')
                return 1;

            // now let's find a colon if we can
            pptr = ptr;
            len = skip_to_colon(&ptr);

            // if skip_to_colon returns 0, it hit the end with no colon, so this isn't a valid request
            if (!len)
                return 0;

            // jump 'ptr' to the beginning of this line's data
            skip_spaces(&ptr);

            // now see if we have another copy of this header already
            Header *hdr = findHeader(pptr, len);
            if (hdr) {
                // basically, responses can have Set-Cookie headers... if we're in a response
                // and handling a Set-Cookie header, we just want to append it to our header
                // list like normal.  in requests, or in non-Set-Cookie headers, we want to
                // append to our previous header
                if (isRequest() || strncasecmp(hdr->key, "Set-Cookie", len)) {
                    // find out how long this line is
                    pptr = ptr;
                    len = skip_to_eol(&ptr);
                    
                    // simply append ", " and our data
                    sv_catpvn(hdr->sv_value, ", ", 2);
                    sv_catpvn(hdr->sv_value, pptr, len);
                    continue;
                }
            }

            // now create a new header to store this line's data
            New(0, hdr, 1, Header);
            if (!hdr)
                return 0;
            Poison(hdr, 1, Header);

            // set it up
            hdr->keylen = len;
            hdr->prev = NULL;
            hdr->next = NULL;
            hdr->key = NULL;
            hdr->sv_value = NULL;
            hdrtail = hdr;

            // copy in the header name... note we don't have to insert a null
            // at the end of hdr->key because we use Newz which zeros the allocated space
            Newz(0, hdr->key, len + 1, char);
            if (!hdr->key)
                return 0;
            Copy(pptr, hdr->key, len, char);

            // and jump to the end of the line, fail if we got nothing
            pptr = ptr;
            len = skip_to_eol(&ptr);

            // copy this as our value
            hdr->sv_value = newSVpvn(pptr, len);
            if (!hdr->sv_value)
                return 0;

            // now insert this into our list
            if (lasthdr) {
                hdr->prev = lasthdr;
                lasthdr->next = hdr;
                lasthdr = hdr;
            } else {
                hdrs = hdr;
                lasthdr = hdr;
            }

        }
    }

    // if we get here we're done, so return state
    return state;
}

SV *HTTPHeaders::getReconstructed() {
    // reconstitute the header we got... pretty much just firstLine + all the headers
    SV *res = newSVpvn("", 0);
    if (!res) return &PL_sv_undef;
    SvGROW(res, 768);

    // print in the first line
    if (!sv_firstLine) {
        SvREFCNT_dec(res);
        return &PL_sv_undef;
    }
    sv_catsv(res, sv_firstLine);
    sv_catpv(res, "\r\n");

    // now over each header
    for (Header *cur = hdrs; cur; cur = cur->next) {
        if (!cur->key) {
            SvREFCNT_dec(res);
            return &PL_sv_undef;
        }
        sv_catpv(res, cur->key);
        sv_catpv(res, ": ");

        if (!cur->sv_value) {
            SvREFCNT_dec(res);
            return &PL_sv_undef;
        }
        sv_catsv(res, cur->sv_value);
        sv_catpv(res, "\r\n");
    }

    // tack on final \r\n
    sv_catpv(res, "\r\n");

    // return our scalar
    return res;
}

Header *HTTPHeaders::findHeader(char *which, int len) {
    // make sure we got something
    if (!which) return NULL;
    int wlen = len ? len : strlen(which);
    if (!wlen) return NULL;

    // now iterate and find the header
    for (Header *cur = hdrs; cur; cur = cur->next) {
        // very fast shortcut; check lengths which will rule out most of the
        // headers that we have in our list, as most don't share a length
        if (wlen != cur->keylen)
            continue;

        // do a bytewise comparison...
        if (!strncasecmp(cur->key, which, wlen))
            return cur;
    }

    // failure
    return NULL;
}

SV *HTTPHeaders::getHeader(char *which) {
    Header *hdr = findHeader(which);
    if (!hdr)
        return &PL_sv_undef;

    // return a reference to our sv after incrementing its refcount
    SvREFCNT_inc(hdr->sv_value);
    return hdr->sv_value;
}

void HTTPHeaders::setHeader(char *which, char *value) {
    Header *hdr = findHeader(which);

    // now get the length of value
    int vlen = value ? strlen(value) : 0;

    // behavior changes depending on whether we're setting or unsetting
    if (vlen) {
        // if we have no header in the lineup, we need to create one and stick it on the end
        if (!hdr) {
            // nope, create a new one
            New(0, hdr, 1, Header);
            if (!hdr)
                return; // FIXME: way to report error here? :/
            Poison(hdr, 1, Header);

            // initialize this header
            hdr->key = NULL;
            hdr->keylen = 0;
            hdr->prev = NULL;
            hdr->next = NULL;
            hdr->sv_value = NULL;

            // link this in (hdrtail becomes our prev, us its next, we the new tail)
            // don't you love dealing with everything manually?
            if (hdrtail) {
                hdrtail->next = hdr;
                hdr->prev = hdrtail;
            }
            if (!hdrs)
                hdrs = hdr;
            hdrtail = hdr;
        }

        // free up header value, as we're giving it a new one
        if (hdr->sv_value) {
            SvREFCNT_dec(hdr->sv_value);
        }

        // now copy the new value
        hdr->sv_value = newSVpvn(value, vlen);
        if (!hdr->sv_value)
            return; // FIXME: as above, error?

        // free up old key if we had one
        if (hdr->key) {
            Safefree(hdr->key);
        }

        // copy in the header name
        int wlen = strlen(which);
        Newz(0, hdr->key, wlen + 1, char);
        Copy(which, hdr->key, wlen, char);
        hdr->keylen = wlen;

    } else {
        // return if we don't have a header (unset what doesn't exist? sure thing!)
        if (!hdr)
            return;

        // no value, so they're removing it
        if (hdr->prev) {
            // previous implies we're a link in the chain, so point our previous
            // header to point at the next one past us (drop us from the link)
            hdr->prev->next = hdr->next;
        } else {
            // no previous, so this was the head header
            hdrs = hdr->next;
        }

        // and now update our next to point to our previous...
        if (hdr->next) {
            // we have someone after us, point them up at the top
            hdr->next->prev = hdr->prev;
        } else {
            // nothing past us, so we were the last header, so point hdrtail at
            // the one before us now
            hdrtail = hdr->prev;
        }

        freeHeader(hdr);
    }
}

int HTTPHeaders::getMethod() {
    return method;
}

SV *HTTPHeaders::getMethodString() {
    if (sv_methodString) {
        SvREFCNT_inc(sv_methodString);
        return sv_methodString;
    } else
        return &PL_sv_undef;
}

int HTTPHeaders::getStatusCode() {
    return statusCode;
}

int HTTPHeaders::getVersionNumber() {
    return versionNumber;
}

bool HTTPHeaders::isRequest() {
    return headersType == H_REQUEST;
}

bool HTTPHeaders::isResponse() {
    return headersType == H_RESPONSE;
}

SV *HTTPHeaders::getURI() {
    if (sv_uri) {
        SvREFCNT_inc(sv_uri);
        return sv_uri;
    } else
        return &PL_sv_undef;
}

SV *HTTPHeaders::getHeadersList() {
    if (hdrs) {
        AV *header_names = (AV*) sv_2mortal((SV*)newAV());
        for (Header *cur = hdrs; cur; cur = cur->next) {
            av_push(header_names, newSVpv(cur->key, cur->keylen));
        }
        return newRV((SV*)header_names);
    } else
        return &PL_sv_undef;
}

SV *HTTPHeaders::setURI(char *uri) {
    int urilen = uri ? strlen(uri) : 0;
    SV *temp_uri = newSVpvn(uri, urilen);

    if (!temp_uri)
        return &PL_sv_undef;

    // Select which method we're using and turn it into a string
    const char *methodstr;

    switch(method) {
        case M_GET:
            methodstr = "GET";
            break;
        case M_POST:
            methodstr = "POST";
            break;
        case M_OPTIONS:
            methodstr = "OPTIONS";
            break;
        case M_PUT:
            methodstr = "PUT";
            break;
        case M_DELETE:
            methodstr = "DELETE";
            break;
        case M_HEAD:
            methodstr = "HEAD";
            break;
        default:
            if (sv_methodString) {
                methodstr = SvPV_nolen(sv_methodString);
                break;
            } else
                return &PL_sv_undef;
    }

    // Reconstruct the first line
    SV *temp_firstLine;
    if (versionNumber)
        temp_firstLine = newSVpvf("%s %s HTTP/%d.%d",
                                  methodstr, uri, int(versionNumber / 1000), versionNumber % 1000);
    else
        temp_firstLine = newSVpvf("%s %s",
                                  methodstr, uri);

    // Overwrite the SVs we were preparing
    if (sv_uri)
        SvREFCNT_dec(sv_uri);

    sv_uri = temp_uri;

    if (sv_firstLine)
        SvREFCNT_dec(sv_firstLine);

    sv_firstLine = temp_firstLine;

    // Increment refcount and put sv_uri on the return stack to indicate success.
    SvREFCNT_inc(sv_uri);
    return sv_uri;
}

void HTTPHeaders::setStatusCode(int code) {
    statusCode = code;
}

void HTTPHeaders::setCodeText(int code, char *codetext) {
    // only if response
    if (isRequest())
        return;

    // nothing if they're the same
    if (statusCode == code)
        return;

    // verify we have a line (already got headers)
    if (!sv_firstLine)
        return;

    // set and rebuild sv_firstLine
    statusCode = code;
    SV *temp = newSVpvf("HTTP/%d.%d %d %s",
                        int(versionNumber / 1000), versionNumber % 1000, code, codetext);

    // save our new line, get rid of old one
    SvREFCNT_dec(sv_firstLine);
    sv_firstLine = temp;
}

void HTTPHeaders::setVersionNumber(int version) {
    // if we don't have a first line, die
    if (!sv_firstLine)
        return;
    
    // generate new sv with new HTTP/ etc
    SV *temp = newSVpvf("HTTP/%d.%d", int(version / 1000), version % 1000);
    char *initial = SvPV_nolen(sv_firstLine);
    char *ptr = initial;

    // variable codepaths
    if (isResponse()) {
        // responses are easy... find first space, and concat from that point on
        // onto the end of temp
        skip_to_space(&ptr);
        sv_catpv(temp, ptr);
    } else {
        // requests are more difficult, we have to find the last space...
        skip_to_space(&ptr);
        skip_spaces(&ptr);
        skip_to_space(&ptr);
        skip_spaces(&ptr);

        // now create in temp2 what we need
        SV *temp2 = newSVpvn(initial, ptr - initial);
        sv_catsv(temp2, temp);
        SvREFCNT_dec(temp);
        temp = temp2;
    }

    // free up our first line, it's now temp
    SvREFCNT_dec(sv_firstLine);
    sv_firstLine = temp;

    // store for people to get at
    versionNumber = version;
}