summaryrefslogtreecommitdiff
path: root/src/couchdb/priv/couch_js/http.c
blob: 6c2a8a824c15219e0a984e24c624271c85f55cae (plain)
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
// 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.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <jsapi.h>
#include <curl/curl.h>

#include "utf8.h"

#ifdef XP_WIN
// Map some of the string function names to things which exist on Windows
#define strcasecmp _strcmpi
#define strncasecmp _strnicmp
#define snprintf _snprintf
#endif

typedef struct curl_slist CurlHeaders;

typedef struct {
    int             method;
    char*           url;
    CurlHeaders*    req_headers;
    jsint           last_status;
} HTTPData;

char* METHODS[] = {"GET", "HEAD", "POST", "PUT", "DELETE", "COPY", NULL};

#define GET     0
#define HEAD    1
#define POST    2
#define PUT     3
#define DELETE  4
#define COPY    5

static JSBool
go(JSContext* cx, JSObject* obj, HTTPData* http, char* body, size_t blen);

static JSString*
str_from_binary(JSContext* cx, char* data, size_t length);

static JSBool
constructor(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval)
{
    HTTPData* http = NULL;
    JSBool ret = JS_FALSE;

    http = (HTTPData*) malloc(sizeof(HTTPData));
    if(!http)
    {
        JS_ReportError(cx, "Failed to create CouchHTTP instance.");
        goto error;
    }

    http->method = -1;
    http->url = NULL;
    http->req_headers = NULL;
    http->last_status = -1;

    if(!JS_SetPrivate(cx, obj, http))
    {
        JS_ReportError(cx, "Failed to set private CouchHTTP data.");
        goto error;
    }
    
    ret = JS_TRUE;
    goto success;

error:
    if(http) free(http);

success:
    return ret;
}

static void
destructor(JSContext* cx, JSObject* obj)
{
    HTTPData* http = (HTTPData*) JS_GetPrivate(cx, obj);
    if(!http)
    {
        fprintf(stderr, "Unable to destroy invalid CouchHTTP instance.\n");
    }
    else
    {
        if(http->url) free(http->url);
        if(http->req_headers) curl_slist_free_all(http->req_headers);
        free(http);
    }
}

static JSBool
open(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval)
{    
    HTTPData* http = (HTTPData*) JS_GetPrivate(cx, obj);
    char* method = NULL;
    char* url = NULL;
    JSBool ret = JS_FALSE;
    int methid;

    if(!http)
    {
        JS_ReportError(cx, "Invalid CouchHTTP instance.");
        goto done;
    }

    if(argv[0] == JSVAL_VOID)
    {
        JS_ReportError(cx, "You must specify a method.");
        goto done;
    }

    method = enc_string(cx, argv[0], NULL);
    if(!method)
    {
        JS_ReportError(cx, "Failed to encode method.");
        goto done;
    }
    
    for(methid = 0; METHODS[methid] != NULL; methid++)
    {
        if(strcasecmp(METHODS[methid], method) == 0) break;
    }
    
    if(methid > COPY)
    {
        JS_ReportError(cx, "Invalid method specified.");
        goto done;
    }

    http->method = methid;

    if(argv[1] == JSVAL_VOID)
    {
        JS_ReportError(cx, "You must specify a URL.");
        goto done;
    }

    if(http->url)
    {
        free(http->url);
        http->url = NULL;
    }

    http->url = enc_string(cx, argv[1], NULL);
    if(!http->url)
    {
        JS_ReportError(cx, "Failed to encode URL.");
        goto done;
    }
    
    if(argv[2] != JSVAL_VOID && argv[2] != JSVAL_FALSE)
    {
        JS_ReportError(cx, "Synchronous flag must be false if specified.");
        goto done;
    }
    
    if(http->req_headers)
    {
        curl_slist_free_all(http->req_headers);
        http->req_headers = NULL;
    }
    
    // Disable Expect: 100-continue
    http->req_headers = curl_slist_append(http->req_headers, "Expect:");

    ret = JS_TRUE;

done:
    if(method) free(method);
    return ret;
}

static JSBool
setheader(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval)
{    
    HTTPData* http = (HTTPData*) JS_GetPrivate(cx, obj);
    char* keystr = NULL;
    char* valstr = NULL;
    char* hdrbuf = NULL;
    size_t hdrlen = -1;
    JSBool ret = JS_FALSE;

    if(!http)
    {
        JS_ReportError(cx, "Invalid CouchHTTP instance.");
        goto done;
    }

    if(argv[0] == JSVAL_VOID)
    {
        JS_ReportError(cx, "You must speciy a header name.");
        goto done;
    }

    keystr = enc_string(cx, argv[0], NULL);
    if(!keystr)
    {
        JS_ReportError(cx, "Failed to encode header name.");
        goto done;
    }
    
    if(argv[1] == JSVAL_VOID)
    {
        JS_ReportError(cx, "You must specify a header value.");
        goto done;
    }
    
    valstr = enc_string(cx, argv[1], NULL);
    if(!valstr)
    {
        JS_ReportError(cx, "Failed to encode header value.");
        goto done;
    }
    
    hdrlen = strlen(keystr) + strlen(valstr) + 3;
    hdrbuf = (char*) malloc(hdrlen * sizeof(char));
    if(!hdrbuf)
    {
        JS_ReportError(cx, "Failed to allocate header buffer.");
        goto done;
    }
    
    snprintf(hdrbuf, hdrlen, "%s: %s", keystr, valstr);
    http->req_headers = curl_slist_append(http->req_headers, hdrbuf);

    ret = JS_TRUE;

done:
    if(keystr) free(keystr);
    if(valstr) free(valstr);
    if(hdrbuf) free(hdrbuf);

    return ret;
}

static JSBool
sendreq(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval)
{
    HTTPData* http = (HTTPData*) JS_GetPrivate(cx, obj);
    char* body = NULL;
    size_t bodylen = 0;
    JSBool ret = JS_FALSE;
    
    if(!http)
    {
        JS_ReportError(cx, "Invalid CouchHTTP instance.");
        goto done;
    }

    if(argv[0] != JSVAL_VOID && argv[0] != JS_GetEmptyStringValue(cx))
    {
        body = enc_string(cx, argv[0], &bodylen);
        if(!body)
        {
            JS_ReportError(cx, "Failed to encode body.");
            goto done;
        }
    }

    ret = go(cx, obj, http, body, bodylen);

done:
    if(body) free(body);
    return ret;
}

static JSBool
status(JSContext* cx, JSObject* obj, jsval idval, jsval* vp)
{
    HTTPData* http = (HTTPData*) JS_GetPrivate(cx, obj);
    
    if(!http)
    {
        JS_ReportError(cx, "Invalid CouchHTTP instance.");
        return JS_FALSE;
    }
    
    if(INT_FITS_IN_JSVAL(http->last_status))
    {
        *vp = INT_TO_JSVAL(http->last_status);
        return JS_TRUE;
    }
    else
    {
        JS_ReportError(cx, "INTERNAL: Invalid last_status");
        return JS_FALSE;
    }
}

JSClass CouchHTTPClass = {
    "CouchHTTP",
    JSCLASS_HAS_PRIVATE
        | JSCLASS_CONSTRUCT_PROTOTYPE
        | JSCLASS_HAS_RESERVED_SLOTS(2),
    JS_PropertyStub,
    JS_PropertyStub,
    JS_PropertyStub,
    JS_PropertyStub,
    JS_EnumerateStub,
    JS_ResolveStub,
    JS_ConvertStub,
    destructor,
    JSCLASS_NO_OPTIONAL_MEMBERS
};

JSPropertySpec CouchHTTPProperties[] = {
    {"status", 0, JSPROP_READONLY, status, NULL},
    {0, 0, 0, 0, 0}
};

JSFunctionSpec CouchHTTPFunctions[] = {
    {"_open", open, 3, 0, 0},
    {"_setRequestHeader", setheader, 2, 0, 0},
    {"_send", sendreq, 1, 0, 0},
    {0, 0, 0, 0, 0}
};

JSObject*
install_http(JSContext* cx, JSObject* glbl)
{
    JSObject* klass = NULL;
    HTTPData* http = NULL;

    klass = JS_InitClass(
        cx,
        glbl,
        NULL,
        &CouchHTTPClass,
        constructor,
        0,
        CouchHTTPProperties,
        CouchHTTPFunctions,
        NULL,
        NULL
    );

    if(!klass)
    {
        fprintf(stderr, "Failed to initialize CouchHTTP class.\n");
        return NULL;
    }
    
    return klass;
}


// Curl Helpers

typedef struct {
    HTTPData*   http;
    JSContext*  cx;
    JSObject*   resp_headers;
    char*       sendbuf;
    size_t      sendlen;
    size_t      sent;
    char*       recvbuf;
    size_t      recvlen;
    size_t      read;
} CurlState;

/*
 * I really hate doing this but this doesn't have to be
 * uber awesome, it just has to work.
 */
CURL*       HTTP_HANDLE = NULL;
char        ERRBUF[CURL_ERROR_SIZE];

static size_t send_body(void *ptr, size_t size, size_t nmem, void *data);
static int seek_body(void *ptr, curl_off_t offset, int origin);
static size_t recv_body(void *ptr, size_t size, size_t nmem, void *data);
static size_t recv_header(void *ptr, size_t size, size_t nmem, void *data);

static JSBool
go(JSContext* cx, JSObject* obj, HTTPData* http, char* body, size_t bodylen)
{
    CurlState state;
    JSString* jsbody;
    JSBool ret = JS_FALSE;
    jsval tmp;
    
    state.cx = cx;
    state.http = http;
    
    state.sendbuf = body;
    state.sendlen = bodylen;
    state.sent = 0;

    state.recvbuf = NULL;
    state.recvlen = 0;
    state.read = 0;

    if(HTTP_HANDLE == NULL)
    {
        HTTP_HANDLE = curl_easy_init();
        curl_easy_setopt(HTTP_HANDLE, CURLOPT_READFUNCTION, send_body);
        curl_easy_setopt(HTTP_HANDLE, CURLOPT_SEEKFUNCTION,
                                        (curl_seek_callback) seek_body);
        curl_easy_setopt(HTTP_HANDLE, CURLOPT_HEADERFUNCTION, recv_header);
        curl_easy_setopt(HTTP_HANDLE, CURLOPT_WRITEFUNCTION, recv_body);
        curl_easy_setopt(HTTP_HANDLE, CURLOPT_NOPROGRESS, 1);
        curl_easy_setopt(HTTP_HANDLE, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        curl_easy_setopt(HTTP_HANDLE, CURLOPT_ERRORBUFFER, ERRBUF);
        curl_easy_setopt(HTTP_HANDLE, CURLOPT_COOKIEFILE, "");
        curl_easy_setopt(HTTP_HANDLE, CURLOPT_USERAGENT,
                                            "CouchHTTP Client - Relax");
    }
    
    if(!HTTP_HANDLE)
    {
        JS_ReportError(cx, "Failed to initialize cURL handle.");
        goto done;
    }

    if(http->method < 0 || http->method > COPY)
    {
        JS_ReportError(cx, "INTERNAL: Unknown method.");
        goto done;
    }

    curl_easy_setopt(HTTP_HANDLE, CURLOPT_CUSTOMREQUEST, METHODS[http->method]);
    curl_easy_setopt(HTTP_HANDLE, CURLOPT_NOBODY, 0);
    curl_easy_setopt(HTTP_HANDLE, CURLOPT_FOLLOWLOCATION, 1);
    curl_easy_setopt(HTTP_HANDLE, CURLOPT_UPLOAD, 0);
    
    if(http->method == HEAD)
    {
        curl_easy_setopt(HTTP_HANDLE, CURLOPT_NOBODY, 1);
        curl_easy_setopt(HTTP_HANDLE, CURLOPT_FOLLOWLOCATION, 0);
    }
    else if(http->method == POST || http->method == PUT)
    {
        curl_easy_setopt(HTTP_HANDLE, CURLOPT_UPLOAD, 1);
        curl_easy_setopt(HTTP_HANDLE, CURLOPT_FOLLOWLOCATION, 0);
    }
    
    if(body && bodylen)
    {
        curl_easy_setopt(HTTP_HANDLE, CURLOPT_INFILESIZE, bodylen);        
    }
    else
    {
        curl_easy_setopt(HTTP_HANDLE, CURLOPT_INFILESIZE, 0);
    }

    //curl_easy_setopt(HTTP_HANDLE, CURLOPT_VERBOSE, 1);

    curl_easy_setopt(HTTP_HANDLE, CURLOPT_URL, http->url);
    curl_easy_setopt(HTTP_HANDLE, CURLOPT_HTTPHEADER, http->req_headers);
    curl_easy_setopt(HTTP_HANDLE, CURLOPT_READDATA, &state);
    curl_easy_setopt(HTTP_HANDLE, CURLOPT_SEEKDATA, &state);
    curl_easy_setopt(HTTP_HANDLE, CURLOPT_WRITEHEADER, &state);
    curl_easy_setopt(HTTP_HANDLE, CURLOPT_WRITEDATA, &state);

    if(curl_easy_perform(HTTP_HANDLE) != 0)
    {
        JS_ReportError(cx, "Failed to execute HTTP request: %s", ERRBUF);
        goto done;
    }
    
    if(!state.resp_headers)
    {
        JS_ReportError(cx, "Failed to recieve HTTP headers.");
        goto done;
    }

    tmp = OBJECT_TO_JSVAL(state.resp_headers);
    if(!JS_DefineProperty(
        cx,
        obj,
        "_headers",
        tmp,
        NULL,
        NULL,
        JSPROP_READONLY
    ))
    {
        JS_ReportError(cx, "INTERNAL: Failed to set response headers.");
        goto done;
    }
    
    if(state.recvbuf) // Is good enough?
    {
        state.recvbuf[state.read] = '\0';
        jsbody = dec_string(cx, state.recvbuf, state.read+1);
        if(!jsbody)
        {
            // If we can't decode the body as UTF-8 we forcefully
            // convert it to a string by just forcing each byte
            // to a jschar.
            jsbody = str_from_binary(cx, state.recvbuf, state.read);
            if(!jsbody) {
                if(!JS_IsExceptionPending(cx)) {
                    JS_ReportError(cx, "INTERNAL: Failed to decode body.");
                }
                goto done;
            }
        }
        tmp = STRING_TO_JSVAL(jsbody);
    }
    else
    {
        tmp = JS_GetEmptyStringValue(cx);
    }
    
    if(!JS_DefineProperty(
        cx,
        obj,
        "responseText",
        tmp,
        NULL,
        NULL,
        JSPROP_READONLY
    ))
    {
        JS_ReportError(cx, "INTERNAL: Failed to set responseText.");
        goto done;
    }
    
    ret = JS_TRUE;

done:
    if(state.recvbuf) JS_free(cx, state.recvbuf);
    return ret;
}

static size_t
send_body(void *ptr, size_t size, size_t nmem, void *data)
{
    CurlState* state = (CurlState*) data;
    size_t length = size * nmem;
    size_t towrite = state->sendlen - state->sent;
    if(towrite == 0)
    {
        return 0;
    }

    if(length < towrite) towrite = length;

    //fprintf(stderr, "%lu %lu %lu %lu\n", state->bodyused, state->bodyread, length, towrite);

    memcpy(ptr, state->sendbuf + state->sent, towrite);
    state->sent += towrite;

    return towrite;
}

static int
seek_body(void* ptr, curl_off_t offset, int origin)
{
    CurlState* state = (CurlState*) ptr;
    if(origin != SEEK_SET) return -1;

    state->sent = (size_t) offset;
    return (int) state->sent;
}

static size_t
recv_header(void *ptr, size_t size, size_t nmem, void *data)
{
    CurlState* state = (CurlState*) data;
    char code[4];
    char* header = (char*) ptr;
    size_t length = size * nmem;
    size_t index = 0;
    JSString* hdr = NULL;
    jsuint hdrlen;
    jsval hdrval;
    
    if(length > 7 && strncasecmp(header, "HTTP/1.", 7) == 0)
    {
        if(length < 12)
        {
            return CURLE_WRITE_ERROR;
        }

        memcpy(code, header+9, 3*sizeof(char));
        code[3] = '\0';
        state->http->last_status = atoi(code);

        state->resp_headers = JS_NewArrayObject(state->cx, 0, NULL);
        if(!state->resp_headers)
        {
            return CURLE_WRITE_ERROR;
        }

        return length;
    }

    // We get a notice at the \r\n\r\n after headers.
    if(length <= 2)
    {
        return length;
    }

    // Append the new header to our array.
    hdr = dec_string(state->cx, header, length);
    if(!hdr)
    {
        return CURLE_WRITE_ERROR;
    }

    if(!JS_GetArrayLength(state->cx, state->resp_headers, &hdrlen))
    {
        return CURLE_WRITE_ERROR;
    }

    hdrval = STRING_TO_JSVAL(hdr);
    if(!JS_SetElement(state->cx, state->resp_headers, hdrlen, &hdrval))
    {
        return CURLE_WRITE_ERROR;
    }

    return length;
}

static size_t
recv_body(void *ptr, size_t size, size_t nmem, void *data)
{
    CurlState* state = (CurlState*) data;
    size_t length = size * nmem;
    char* tmp = NULL;
    
    if(!state->recvbuf)
    {
        state->recvlen = 4096;
        state->read = 0;
        state->recvbuf = JS_malloc(state->cx, state->recvlen);
    }
    
    if(!state->recvbuf)
    {
        return CURLE_WRITE_ERROR;
    }

    // +1 so we can add '\0' back up in the go function.
    while(length+1 > state->recvlen - state->read) state->recvlen *= 2;
    tmp = JS_realloc(state->cx, state->recvbuf, state->recvlen);
    if(!tmp) return CURLE_WRITE_ERROR;
    state->recvbuf = tmp;
   
    memcpy(state->recvbuf + state->read, ptr, length);
    state->read += length;
    return length;
}

JSString*
str_from_binary(JSContext* cx, char* data, size_t length)
{
    jschar* conv = (jschar*) JS_malloc(cx, length * sizeof(jschar));
    JSString* ret = NULL;
    size_t i;

    if(!conv) return NULL;

    for(i = 0; i < length; i++)
    {
        conv[i] = (jschar) data[i];
    }

    ret = JS_NewUCString(cx, conv, length);
    if(!ret) JS_free(cx, conv);

    return ret;
}