/
session_ext.c
476 lines (384 loc) · 15.3 KB
/
session_ext.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
// -------------------------------------------------------------------
//
// Patron HTTP Client: Interface to libcurl
// Copyright (c) 2008 The Hive http://www.thehive.com/
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// -------------------------------------------------------------------
#include <ruby.h>
#include <curl/curl.h>
static VALUE mPatron = Qnil;
static VALUE cSession = Qnil;
static VALUE cRequest = Qnil;
static VALUE ePatronError = Qnil;
static VALUE eUnsupportedProtocol = Qnil;
static VALUE eURLFormatError = Qnil;
static VALUE eHostResolutionError = Qnil;
static VALUE eConnectionFailed = Qnil;
static VALUE ePartialFileError = Qnil;
static VALUE eTimeoutError = Qnil;
static VALUE eTooManyRedirects = Qnil;
struct curl_state {
CURL* handle;
char* upload_buf;
FILE* download_file;
FILE* upload_file;
FILE* debug_file;
char error_buf[CURL_ERROR_SIZE];
struct curl_slist* headers;
};
//------------------------------------------------------------------------------
// Curl Callbacks
//
// Takes data streamed from libcurl and writes it to a Ruby string buffer.
static size_t session_write_handler(char* stream, size_t size, size_t nmemb, VALUE out) {
rb_str_buf_cat(out, stream, size * nmemb);
return size * nmemb;
}
static size_t session_read_handler(char* stream, size_t size, size_t nmemb, char **buffer) {
size_t result = 0;
if (buffer != NULL && *buffer != NULL) {
int len = size * nmemb;
char *s1 = strncpy(stream, *buffer, len);
result = strlen(s1);
*buffer += result;
}
return result;
}
//------------------------------------------------------------------------------
// Object allocation
//
// Cleans up the Curl handle when the Session object is garbage collected.
void session_free(struct curl_state *curl) {
curl_easy_cleanup(curl->handle);
if (curl->debug_file) {
fclose(curl->debug_file);
curl->debug_file = NULL;
}
free(curl);
}
// Allocates curl_state data needed for a new Session object.
VALUE session_alloc(VALUE klass) {
struct curl_state* curl;
VALUE obj = Data_Make_Struct(klass, struct curl_state, NULL, session_free, curl);
return obj;
}
//------------------------------------------------------------------------------
// Method implementations
//
// Returns the version of the embedded libcurl as a string.
VALUE libcurl_version(VALUE klass) {
char* value = curl_version();
return rb_str_new2(value);
}
// Initializes the libcurl handle on object initialization.
// NOTE: This must be called from Session#initialize.
VALUE session_ext_initialize(VALUE self) {
struct curl_state *state;
Data_Get_Struct(self, struct curl_state, state);
state->handle = curl_easy_init();
return self;
}
// URL escapes the provided string.
VALUE session_escape(VALUE self, VALUE value) {
struct curl_state *state;
Data_Get_Struct(self, struct curl_state, state);
VALUE string = StringValue(value);
char* escaped = curl_easy_escape(state->handle,
RSTRING_PTR(string),
RSTRING_LEN(string));
VALUE retval = rb_str_new2(escaped);
curl_free(escaped);
return retval;
}
// Unescapes the provided string.
VALUE session_unescape(VALUE self, VALUE value) {
struct curl_state *state;
Data_Get_Struct(self, struct curl_state, state);
VALUE string = StringValue(value);
char* unescaped = curl_easy_unescape(state->handle,
RSTRING_PTR(string),
RSTRING_LEN(string),
NULL);
VALUE retval = rb_str_new2(unescaped);
curl_free(unescaped);
return retval;
}
// Callback used to iterate over the HTTP headers and store them in an slist.
static int each_http_header(VALUE header_key, VALUE header_value, VALUE self) {
struct curl_state *state;
Data_Get_Struct(self, struct curl_state, state);
VALUE name = rb_obj_as_string(header_key);
VALUE value = rb_obj_as_string(header_value);
VALUE header_str = Qnil;
header_str = rb_str_plus(name, rb_str_new2(": "));
header_str = rb_str_plus(header_str, value);
state->headers = curl_slist_append(state->headers, StringValuePtr(header_str));
return 0;
}
static void set_chunked_encoding(struct curl_state *state) {
state->headers = curl_slist_append(state->headers, "Transfer-Encoding: chunked");
}
static FILE* open_file(VALUE filename, char* perms) {
FILE* handle = fopen(StringValuePtr(filename), perms);
if (!handle) {
rb_raise(rb_eArgError, "Unable to open specified file.");
}
return handle;
}
// Set the options on the Curl handle from a Request object. Takes each field
// in the Request object and uses it to set the appropriate option on the Curl
// handle.
static void set_options_from_request(VALUE self, VALUE request) {
struct curl_state *state;
Data_Get_Struct(self, struct curl_state, state);
CURL* curl = state->handle;
VALUE headers = rb_iv_get(request, "@headers");
if (!NIL_P(headers)) {
if (rb_type(headers) != T_HASH) {
rb_raise(rb_eArgError, "Headers must be passed in a hash.");
}
rb_hash_foreach(headers, each_http_header, self);
}
ID action = SYM2ID(rb_iv_get(request, "@action"));
if (action == rb_intern("get")) {
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
VALUE download_file = rb_iv_get(request, "@file_name");
if (!NIL_P(download_file)) {
state->download_file = open_file(download_file, "w");
curl_easy_setopt(curl, CURLOPT_WRITEDATA, state->download_file);
} else {
state->download_file = NULL;
}
} else if (action == rb_intern("post") || action == rb_intern("put")) {
VALUE data = rb_iv_get(request, "@upload_data");
VALUE filename = rb_iv_get(request, "@file_name");
if (!NIL_P(data)) {
state->upload_buf = StringValuePtr(data);
int len = RSTRING_LEN(data);
if (action == rb_intern("post")) {
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, state->upload_buf);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, len);
} else {
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, &session_read_handler);
curl_easy_setopt(curl, CURLOPT_READDATA, &state->upload_buf);
curl_easy_setopt(curl, CURLOPT_INFILESIZE, len);
}
} else if (!NIL_P(filename)) {
set_chunked_encoding(state);
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
if (action == rb_intern("post")) {
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
}
state->upload_file = open_file(filename, "r");
curl_easy_setopt(curl, CURLOPT_READDATA, state->upload_file);
} else {
rb_raise(rb_eArgError, "Must provide either data or a filename when doing a PUT or POST");
}
} else if (action == rb_intern("head")) {
curl_easy_setopt(curl, CURLOPT_NOBODY, 1);
} else {
VALUE action_name = rb_funcall(request, rb_intern("action_name"), 0);
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, StringValuePtr(action_name));
}
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, state->headers);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, state->error_buf);
VALUE url = rb_iv_get(request, "@url");
if (NIL_P(url)) {
rb_raise(rb_eArgError, "Must provide a URL");
}
curl_easy_setopt(curl, CURLOPT_URL, StringValuePtr(url));
VALUE timeout = rb_iv_get(request, "@timeout");
if (!NIL_P(timeout)) {
curl_easy_setopt(curl, CURLOPT_TIMEOUT, FIX2INT(timeout));
}
timeout = rb_iv_get(request, "@connect_timeout");
if (!NIL_P(timeout)) {
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, FIX2INT(timeout));
}
VALUE redirects = rb_iv_get(request, "@max_redirects");
if (!NIL_P(redirects)) {
int r = FIX2INT(redirects);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, r == 0 ? 0 : 1);
curl_easy_setopt(curl, CURLOPT_MAXREDIRS, r);
}
VALUE proxy = rb_iv_get(request, "@proxy");
if (!NIL_P(proxy)) {
curl_easy_setopt(curl, CURLOPT_PROXY, StringValuePtr(proxy));
}
VALUE credentials = rb_funcall(request, rb_intern("credentials"), 0);
if (!NIL_P(credentials)) {
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, FIX2INT(rb_iv_get(request, "@auth_type")));
curl_easy_setopt(curl, CURLOPT_USERPWD, StringValuePtr(credentials));
}
VALUE insecure = rb_iv_get(request, "@insecure");
if(!NIL_P(insecure)) {
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 1);
}
if(state->debug_file) {
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_STDERR, state->debug_file);
}
}
// Use the info in a Curl handle to create a new Response object.
static VALUE create_response(CURL* curl) {
VALUE response = rb_class_new_instance(0, 0,
rb_const_get(mPatron, rb_intern("Response")));
char* url = NULL;
curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);
rb_iv_set(response, "@url", rb_str_new2(url));
long code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
rb_iv_set(response, "@status", INT2NUM(code));
long count = 0;
curl_easy_getinfo(curl, CURLINFO_REDIRECT_COUNT, &count);
rb_iv_set(response, "@redirect_count", INT2NUM(count));
return response;
}
// Raise an exception based on the Curl error code.
static VALUE select_error(CURLcode code) {
VALUE error = Qnil;
switch (code) {
case CURLE_UNSUPPORTED_PROTOCOL: error = eUnsupportedProtocol; break;
case CURLE_URL_MALFORMAT: error = eURLFormatError; break;
case CURLE_COULDNT_RESOLVE_HOST: error = eHostResolutionError; break;
case CURLE_COULDNT_CONNECT: error = eConnectionFailed; break;
case CURLE_PARTIAL_FILE: error = ePartialFileError; break;
case CURLE_OPERATION_TIMEDOUT: error = eTimeoutError; break;
case CURLE_TOO_MANY_REDIRECTS: error = eTooManyRedirects; break;
default: error = ePatronError;
}
return error;
}
// Perform the actual HTTP request by calling libcurl.
static VALUE perform_request(VALUE self) {
struct curl_state *state;
Data_Get_Struct(self, struct curl_state, state);
CURL* curl = state->handle;
// headers
VALUE header_buffer = rb_str_buf_new(32768);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, &session_write_handler);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, header_buffer);
// body
VALUE body_buffer = Qnil;
if (!state->download_file) {
body_buffer = rb_str_buf_new(32768);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &session_write_handler);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, body_buffer);
}
#if defined(HAVE_TBR) && defined(USE_TBR)
CURLcode ret = rb_thread_blocking_region(curl_easy_perform, curl, RUBY_UBF_IO, 0);
#else
CURLcode ret = curl_easy_perform(curl);
#endif
if (CURLE_OK == ret) {
VALUE response = create_response(curl);
if (!NIL_P(body_buffer)) {
rb_iv_set(response, "@body", body_buffer);
}
rb_funcall(response, rb_intern("parse_headers"), 1, header_buffer);
return response;
} else {
rb_raise(select_error(ret), "%s", state->error_buf);
}
}
// Cleanup after each request by resetting the Curl handle and deallocating all
// request related objects such as the header slist.
static VALUE cleanup(VALUE self) {
struct curl_state *state;
Data_Get_Struct(self, struct curl_state, state);
curl_easy_reset(state->handle);
if (state->headers) {
curl_slist_free_all(state->headers);
state->headers = NULL;
}
if (state->download_file) {
fclose(state->download_file);
state->download_file = NULL;
}
if (state->upload_file) {
fclose(state->upload_file);
state->upload_file = NULL;
}
state->upload_buf = NULL;
return Qnil;
}
VALUE session_handle_request(VALUE self, VALUE request) {
set_options_from_request(self, request);
return rb_ensure(&perform_request, self, &cleanup, self);
}
VALUE enable_cookie_session(VALUE self, VALUE file) {
struct curl_state *state;
Data_Get_Struct(self, struct curl_state, state);
CURL* curl = state->handle;
char* file_path = RSTRING_PTR(file);
if (file_path != NULL && strlen(file_path) != 0) {
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, file_path);
}
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, file_path);
return Qnil;
}
VALUE set_debug_file(VALUE self, VALUE file) {
struct curl_state *state;
Data_Get_Struct(self, struct curl_state, state);
char* file_path = RSTRING_PTR(file);
if(state->debug_file){
fclose(state->debug_file);
state->debug_file = NULL;
}
if(file_path != NULL && strlen(file_path) != 0) {
state->debug_file = open_file(file, "w");
} else {
state->debug_file = stderr;
}
return Qnil;
}
//------------------------------------------------------------------------------
// Extension initialization
//
void Init_session_ext() {
curl_global_init(CURL_GLOBAL_ALL);
rb_require("patron/error");
mPatron = rb_define_module("Patron");
ePatronError = rb_const_get(mPatron, rb_intern("Error"));
eUnsupportedProtocol = rb_const_get(mPatron, rb_intern("UnsupportedProtocol"));
eURLFormatError = rb_const_get(mPatron, rb_intern("URLFormatError"));
eHostResolutionError = rb_const_get(mPatron, rb_intern("HostResolutionError"));
eConnectionFailed = rb_const_get(mPatron, rb_intern("ConnectionFailed"));
ePartialFileError = rb_const_get(mPatron, rb_intern("PartialFileError"));
eTimeoutError = rb_const_get(mPatron, rb_intern("TimeoutError"));
eTooManyRedirects = rb_const_get(mPatron, rb_intern("TooManyRedirects"));
rb_define_module_function(mPatron, "libcurl_version", libcurl_version, 0);
cSession = rb_define_class_under(mPatron, "Session", rb_cObject);
cRequest = rb_define_class_under(mPatron, "Request", rb_cObject);
rb_define_alloc_func(cSession, session_alloc);
rb_define_method(cSession, "ext_initialize", session_ext_initialize, 0);
rb_define_method(cSession, "escape", session_escape, 1);
rb_define_method(cSession, "unescape", session_unescape, 1);
rb_define_method(cSession, "handle_request", session_handle_request, 1);
rb_define_method(cSession, "enable_cookie_session", enable_cookie_session, 1);
rb_define_method(cSession, "set_debug_file", set_debug_file, 1);
rb_define_const(cRequest, "AuthBasic", INT2FIX(CURLAUTH_BASIC));
rb_define_const(cRequest, "AuthDigest", INT2FIX(CURLAUTH_DIGEST));
rb_define_const(cRequest, "AuthAny", INT2FIX(CURLAUTH_ANY));
}