The FreeRADIUS server $Id: 15bac2a4c627c01d1aa2047687b3418955ac7f00 $
Loading...
Searching...
No Matches
rest.c
Go to the documentation of this file.
1/*
2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15 */
16
17/**
18 * $Id: 33ddb2fc78305e6b36bc7764652ae8534b2073d2 $
19 *
20 * @brief Functions and datatypes for the REST (HTTP) transport.
21 * @file rest.c
22 *
23 * @copyright 2012-2021 Arran Cudbard-Bell (a.cudbardb@freeradius.org)
24 */
25RCSID("$Id: 33ddb2fc78305e6b36bc7764652ae8534b2073d2 $")
26
27#define LOG_PREFIX mctx->mi->name
28
29#include <ctype.h>
30#include <string.h>
31#include <time.h>
32
33#include <freeradius-devel/server/base.h>
34#include <freeradius-devel/server/log.h>
35#include <freeradius-devel/server/pool.h>
36#include <freeradius-devel/server/tmpl.h>
37#include <freeradius-devel/unlang/call.h>
38#include <freeradius-devel/util/skip.h>
39#include <freeradius-devel/util/value.h>
40
41#include <talloc.h>
42
43#include "rest.h"
44
45/** Table of encoder/decoder support.
46 *
47 * Indexes in this table match the http_body_type_t enum, and should be
48 * updated if additional enum values are added.
49 *
50 * @see http_body_type_t
51 */
53 REST_HTTP_BODY_UNKNOWN, // REST_HTTP_BODY_UNKNOWN
54 REST_HTTP_BODY_UNSUPPORTED, // REST_HTTP_BODY_UNSUPPORTED
55 REST_HTTP_BODY_UNSUPPORTED, // REST_HTTP_BODY_UNAVAILABLE
56 REST_HTTP_BODY_UNSUPPORTED, // REST_HTTP_BODY_INVALID
57 REST_HTTP_BODY_NONE, // REST_HTTP_BODY_NONE
58 REST_HTTP_BODY_CUSTOM, // REST_HTTP_BODY_CUSTOM
59 REST_HTTP_BODY_POST, // REST_HTTP_BODY_POST
60#ifdef HAVE_JSON
61 REST_HTTP_BODY_JSON, // REST_HTTP_BODY_JSON
62#else
64#endif
65 REST_HTTP_BODY_UNSUPPORTED, // REST_HTTP_BODY_XML
66 REST_HTTP_BODY_UNSUPPORTED, // REST_HTTP_BODY_YAML
67 REST_HTTP_BODY_INVALID, // REST_HTTP_BODY_HTML
68 REST_HTTP_BODY_PLAIN // REST_HTTP_BODY_PLAIN
69};
70
71/*
72 * Lib CURL doesn't define symbols for unsupported auth methods
73 */
74#ifndef CURLOPT_TLSAUTH_SRP
75# define CURLOPT_TLSAUTH_SRP 0
76#endif
77#ifndef CURLAUTH_BASIC
78# define CURLAUTH_BASIC 0
79#endif
80#ifndef CURLAUTH_DIGEST
81# define CURLAUTH_DIGEST 0
82#endif
83#ifndef CURLAUTH_DIGEST_IE
84# define CURLAUTH_DIGEST_IE 0
85#endif
86#ifndef CURLAUTH_GSSNEGOTIATE
87# define CURLAUTH_GSSNEGOTIATE 0
88#endif
89#ifndef CURLAUTH_NTLM
90# define CURLAUTH_NTLM 0
91#endif
92#ifndef CURLAUTH_NTLM_WB
93# define CURLAUTH_NTLM_WB 0
94#endif
95
96/*
97 * CURL headers do:
98 *
99 * #define curl_easy_setopt(handle,opt,param) curl_easy_setopt(handle,opt,param)
100 */
114
115/** Conversion table for method config values.
116 *
117 * HTTP verb strings for http_method_t enum values. Used by libcurl in the
118 * status line of the outgoing HTTP header, by rest_response_header for decoding
119 * incoming HTTP responses, and by the configuration parser.
120 *
121 * @note must be kept in sync with http_method_t enum.
122 *
123 * @see http_method_t
124 * @see fr_table_value_by_str
125 * @see fr_table_str_by_value
126 */
128 { L("DELETE"), REST_HTTP_METHOD_DELETE },
129 { L("GET"), REST_HTTP_METHOD_GET },
130 { L("PATCH"), REST_HTTP_METHOD_PATCH },
131 { L("POST"), REST_HTTP_METHOD_POST },
132 { L("PUT"), REST_HTTP_METHOD_PUT },
133 { L("UNKNOWN"), REST_HTTP_METHOD_UNKNOWN }
134};
136
137/** Conversion table for type config values.
138 *
139 * Textual names for http_body_type_t enum values, used by the
140 * configuration parser.
141 *
142 * @see http_body_Type_t
143 * @see fr_table_value_by_str
144 * @see fr_table_str_by_value
145 */
147 { L("html"), REST_HTTP_BODY_HTML },
148 { L("invalid"), REST_HTTP_BODY_INVALID },
149 { L("json"), REST_HTTP_BODY_JSON },
150 { L("none"), REST_HTTP_BODY_NONE },
151 { L("plain"), REST_HTTP_BODY_PLAIN },
152 { L("post"), REST_HTTP_BODY_POST },
153 { L("unavailable"), REST_HTTP_BODY_UNAVAILABLE },
154 { L("unknown"), REST_HTTP_BODY_UNKNOWN },
155 { L("unsupported"), REST_HTTP_BODY_UNSUPPORTED },
156 { L("xml"), REST_HTTP_BODY_XML },
157 { L("yaml"), REST_HTTP_BODY_YAML }
158};
160
162 { L("any"), REST_HTTP_AUTH_ANY },
163 { L("basic"), REST_HTTP_AUTH_BASIC },
164 { L("digest"), REST_HTTP_AUTH_DIGEST },
165 { L("digest-ie"), REST_HTTP_AUTH_DIGEST_IE },
166 { L("gss-negotiate"), REST_HTTP_AUTH_GSSNEGOTIATE },
167 { L("none"), REST_HTTP_AUTH_NONE },
168 { L("ntlm"), REST_HTTP_AUTH_NTLM },
169 { L("ntlm-winbind"), REST_HTTP_AUTH_NTLM_WB },
170 { L("safe"), REST_HTTP_AUTH_ANY_SAFE },
171 { L("srp"), REST_HTTP_AUTH_TLS_SRP }
172};
174
175/** Conversion table for "Content-Type" header values.
176 *
177 * Used by rest_response_header for parsing incoming headers.
178 *
179 * Values we expect to see in the 'Content-Type:' header of the incoming
180 * response.
181 *
182 * Some data types (like YAML) do no have standard MIME types defined,
183 * so multiple types, are listed here.
184 *
185 * @see http_body_Type_t
186 * @see fr_table_value_by_str
187 * @see fr_table_str_by_value
188 */
190 { L("application/json"), REST_HTTP_BODY_JSON },
191 { L("application/x-www-form-urlencoded"), REST_HTTP_BODY_POST },
192 { L("application/x-yaml"), REST_HTTP_BODY_YAML },
193 { L("application/yaml"), REST_HTTP_BODY_YAML },
194 { L("text/html"), REST_HTTP_BODY_HTML },
195 { L("text/plain"), REST_HTTP_BODY_PLAIN },
196 { L("text/x-yaml"), REST_HTTP_BODY_YAML },
197 { L("text/xml"), REST_HTTP_BODY_XML },
198 { L("text/yaml"), REST_HTTP_BODY_YAML }
199};
201
202/*
203 * Encoder specific structures.
204 * @todo split encoders/decoders into submodules.
205 */
206typedef struct {
207 char const *start; //!< Start of the buffer.
208 char const *p; //!< how much text we've sent so far.
209 size_t len; //!< Length of data
211
212#ifdef HAVE_JSON
213/** Flags to control the conversion of JSON values to fr_pair_ts.
214 *
215 * These fields are set when parsing the expanded format for value pairs in
216 * JSON, and control how json_pair_alloc_leaf and json_pair_alloc convert the JSON
217 * value, and move the new fr_pair_t into an attribute list.
218 *
219 * @see json_pair_alloc
220 * @see json_pair_alloc_leaf
221 */
222typedef struct {
223 int do_xlat; //!< If true value will be expanded with xlat.
224 int is_json; //!< If true value will be inserted as raw JSON
225 // (multiple values not supported).
226 fr_token_t op; //!< The operator that determines how the new VP
227 // is processed. @see fr_tokens_table
229#endif
230
231/** Frees a libcurl handle, and any additional memory used by context data.
232 *
233 * @param[in] randle fr_curl_io_request_t to close and free.
234 * @return returns true.
235 */
237{
238 curl_easy_cleanup(randle->candle);
239
240 return 0;
241}
242
243/** Creates a new connection handle for use by the FR connection API.
244 *
245 * Matches the fr_pool_connection_create_t function prototype, is passed to
246 * fr_pool_init, and called when a new connection is required by the
247 * connection pool API.
248 *
249 * Creates an instances of fr_curl_io_request_t, and rlm_rest_curl_context_t
250 * which hold the context data required for generating requests and parsing
251 * responses.
252 *
253 * @see fr_pool_init
254 * @see fr_pool_connection_create_t
255 * @see connection.c
256 */
257void *rest_mod_conn_create(TALLOC_CTX *ctx, void *instance, UNUSED fr_time_delta_t timeout)
258{
260
261 fr_curl_io_request_t *randle = NULL;
262 rlm_rest_curl_context_t *curl_ctx = NULL;
263
264 /*
265 * Allocate memory for the connection handle abstraction.
266 */
267 randle = fr_curl_io_request_alloc(ctx);
268 if (!randle) return NULL;
269
270 MEM(curl_ctx = talloc_zero(randle, rlm_rest_curl_context_t));
271
272 curl_ctx->headers = NULL; /* CURL needs this to be NULL */
273 curl_ctx->request.instance = inst;
274 curl_ctx->response.instance = inst;
275
276 randle->uctx = curl_ctx;
277 talloc_set_destructor(randle, _mod_conn_free);
278
279 return randle;
280}
281
282/** Copies a pre-expanded xlat string to the output buffer
283 *
284 * @param[out] out Char buffer to write encoded data to.
285 * @param[in] size Multiply by nmemb to get the length of ptr.
286 * @param[in] nmemb Multiply by size to get the length of ptr.
287 * @param[in] userdata rlm_rest_request_t to keep encoding state between calls.
288 * @return
289 * - Length of data (including NULL) written to ptr.
290 * - 0 if no more data to write.
291 */
292static size_t rest_encode_custom(void *out, size_t size, size_t nmemb, void *userdata)
293{
294 rlm_rest_request_t *ctx = userdata;
296
297 size_t freespace = (size * nmemb) - 1;
298 size_t len;
299 size_t to_copy;
300
301 /*
302 * Special case for empty body
303 */
304 if (data->len == 0) return 0;
305
306 /*
307 * If len > 0 then we must have these set.
308 */
309 fr_assert(data->start);
310 fr_assert(data->p);
311
312 to_copy = data->len - (data->p - data->start);
313 len = to_copy > freespace ? freespace : to_copy;
314 if (len == 0) return 0;
315
316 memcpy(out, data->p, len);
317 data->p += len;
318
319 return len;
320}
321
322/** Encodes fr_pair_t linked list in POST format
323 *
324 * This is a stream function matching the rest_read_t prototype. Multiple
325 * successive calls will return additional encoded fr_pair_ts.
326 * Only complete attribute headers @verbatim '<name>=' @endverbatim and values
327 * will be written to the ptr buffer.
328 *
329 * POST request format is:
330 * @verbatim <attribute0>=<value0>&<attribute1>=<value1>&<attributeN>=<valueN>@endverbatim
331 *
332 * All attributes and values are url encoded. There is currently no support for
333 * nested attributes, or attribute qualifiers.
334 *
335 * Nested attributes may be added in the future using
336 * @verbatim <attribute-outer>:<attribute-inner>@endverbatim
337 * to denotate nesting.
338 *
339 * Requires libcurl for url encoding.
340 *
341 * @see rest_decode_post
342 *
343 * @param[out] out Char buffer to write encoded data to.
344 * @param[in] size Multiply by nmemb to get the length of ptr.
345 * @param[in] nmemb Multiply by size to get the length of ptr.
346 * @param[in] userdata rlm_rest_request_t to keep encoding state between calls.
347 * @return
348 * - Length of data (including NULL) written to ptr.
349 * - 0 if no more data to write.
350 */
351static size_t rest_encode_post(void *out, size_t size, size_t nmemb, void *userdata)
352{
353 rlm_rest_request_t *ctx = userdata;
354 request_t *request = ctx->request; /* Used by RDEBUG */
355 fr_pair_t *vp;
356
357 size_t len = 0;
358 ssize_t slen;
359 size_t freespace = (size * nmemb) - 1;
360
361 char *p = out; /* Position in buffer */
362 char *encoded = p; /* Position in buffer of last fully encoded attribute or value */
363 char *escaped; /* Pointer to current URL escaped data */
364
365 /* Allow manual chunking */
366 if ((ctx->chunk) && (ctx->chunk <= freespace)) freespace = (ctx->chunk - 1);
367
368 if (ctx->state == READ_STATE_END) return 0;
369
370 /* Post data requires no headers */
372
373 while (freespace > 0) {
375 if (!vp) {
376 ctx->state = READ_STATE_END;
377
378 break;
379 }
380
381 RDEBUG2("Encoding attribute \"%s\"", vp->da->name);
382
383 if (ctx->state == READ_STATE_ATTR_BEGIN) {
384 escaped = curl_escape(vp->da->name, 0);
385 if (!escaped) {
386 REDEBUG("Failed escaping string \"%s\"", vp->da->name);
387 return 0;
388 }
389
390 len = strlen(escaped);
391 if (freespace < (1 + len)) {
392 curl_free(escaped);
393 /*
394 * Cleanup for error conditions
395 */
396 no_space:
397 *encoded = '\0';
398
399 len = encoded - (char *)out;
400
401 RDEBUG3("POST Data: %pV", fr_box_strvalue_len(out, len));
402
403 /*
404 * The buffer wasn't big enough to encode a single attribute chunk.
405 */
406 if (len == 0) {
407 REDEBUG("Failed encoding attribute");
408 } else {
409 RDEBUG3("Returning %zd bytes of POST data "
410 "(buffer full or chunk exceeded)", len);
411 }
412
413 return len;
414 }
415
416 len = snprintf(p, freespace, "%s=", escaped);
417 curl_free(escaped);
418 p += len;
419 freespace -= len;
420
421 /*
422 * We wrote the attribute header, record progress.
423 */
424 encoded = p;
426 }
427
428 /*
429 * Write out single attribute string.
430 */
431 slen = fr_pair_print_value_quoted(&FR_SBUFF_OUT(p, freespace), vp, T_BARE_WORD);
432 if (slen < 0) return 0;
433
434 RINDENT();
435 RDEBUG3("Length : %zd", (size_t)slen);
436 REXDENT();
437 if (slen > 0) {
438 escaped = curl_escape(p, (size_t)slen);
439 if (!escaped) {
440 REDEBUG("Failed escaping string \"%s\"", vp->da->name);
441 return 0;
442 }
443 len = strlen(escaped);
444
445 if (freespace < len) {
446 curl_free(escaped);
447 goto no_space;
448 }
449
450 len = strlcpy(p, escaped, len + 1);
451
452 curl_free(escaped);
453
454 RINDENT();
455 RDEBUG3("Value : %s", p);
456 REXDENT();
457
458 p += len;
459 freespace -= len;
460 }
461
462 /*
463 * there are more attributes, insert a separator
464 */
465 if (fr_dcursor_next(&ctx->cursor)) {
466 if (freespace < 1) goto no_space;
467 *p++ = '&';
468 freespace--;
469 }
470
471 /*
472 * We wrote one full attribute value pair, record progress.
473 */
474 encoded = p;
475
477 }
478
479 *p = '\0';
480
481 len = p - (char *)out;
482
483 RDEBUG3("POST Data: %s", (char *)out);
484 RDEBUG3("Returning %zd bytes of POST data", len);
485
486 return len;
487}
488
489#ifdef HAVE_JSON
490/** Encodes fr_pair_t linked list in JSON format
491 *
492 * This is a stream function matching the rest_read_t prototype. Multiple
493 * successive calls will return additional encoded fr_pair_ts.
494 *
495 * Only complete attribute headers
496 * @verbatim "<name>":{"type":"<type>","value":[' @endverbatim
497 * and complete attribute values will be written to ptr.
498 *
499 * If an attribute occurs multiple times in the request the attribute values
500 * will be concatenated into a single value array.
501 *
502 * JSON request format is:
503@verbatim
504{
505 "<attribute0>":{
506 "type":"<type0>",
507 "value":[<value0>,<value1>,<valueN>]
508 },
509 "<attribute1>":{
510 "type":"<type1>",
511 "value":[...]
512 },
513 "<attributeN>":{
514 "type":"<typeN>",
515 "value":[...]
516 },
517}
518@endverbatim
519 *
520 * @param[out] out Char buffer to write encoded data to.
521 * @param[in] size Multiply by nmemb to get the length of ptr.
522 * @param[in] nmemb Multiply by size to get the length of ptr.
523 * @param[in] userdata rlm_rest_request_t to keep encoding state between calls.
524 * @return
525 * - Length of data (including NULL) written to ptr.
526 * - 0 if no more data to write.
527 */
528static size_t rest_encode_json(void *out, size_t size, size_t nmemb, void *userdata)
529{
530 rlm_rest_request_t *ctx = userdata;
531 request_t *request = ctx->request;
533
534 size_t freespace = (size * nmemb) - 1; /* account for the \0 byte here */
535 size_t len;
536 size_t to_copy;
537 const char *encoded;
538
539 fr_assert(freespace > 0);
540
541 if (ctx->state == READ_STATE_INIT) {
542 encoded = fr_json_afrom_pair_list(data, &request->request_pairs, NULL);
543 if (!encoded) return -1;
544
545 data->start = data->p = encoded;
546 data->len = strlen(encoded);
547
548 RDEBUG3("JSON Data: %s", encoded);
549 RDEBUG3("Returning %zd bytes of JSON data", data->len);
550
552 }
553
554 to_copy = data->len - (data->p - data->start);
555 len = to_copy > freespace ? freespace : to_copy;
556
557 if (len == 0) return 0;
558
559 memcpy(out, data->p, len);
560 data->p += len;
561 return len;
562}
563#endif
564
565/** Emulates successive libcurl calls to an encoding function
566 *
567 * This function is used when the request will be sent to the HTTP server as one
568 * contiguous entity. A buffer of REST_BODY_ALLOC_CHUNK bytes is allocated and passed
569 * to the stream encoding function.
570 *
571 * If the stream function does not return 0, a new buffer is allocated which is
572 * the size of the previous buffer + REST_BODY_ALLOC_CHUNK bytes, the data from the
573 * previous buffer is copied, and freed, and another call is made to the stream
574 * function, passing a pointer into the new buffer at the end of the previously
575 * written data.
576 *
577 * This process continues until the stream function signals (by returning 0)
578 * that it has no more data to write.
579 *
580 * @param[out] out where the pointer to the alloced buffer should
581 * be written.
582 * @param[in] inst of rlm_rest.
583 * @param[in] func Stream function.
584 * @param[in] limit Maximum buffer size to alloc.
585 * @param[in] userdata rlm_rest_request_t to keep encoding state between calls to
586 * stream function.
587 * @return
588 * - Length of the data written to the buffer (excluding NULL).
589 * - -1 if alloc >= limit.
590 */
592 rest_read_t func, size_t limit, void *userdata)
593{
594 char *buff = NULL;
595 size_t alloc = REST_BODY_ALLOC_CHUNK; /* Size of buffer to alloc */
596 size_t used = 0; /* Size of data written */
597 size_t len = 0;
598
599 buff = talloc_array(NULL, char, alloc);
600 for (;;) {
601 len = func(buff + used, alloc - used, 1, userdata);
602 used += len;
603 if (!len) {
604 *out = buff;
605 return used;
606 }
607
608 alloc = alloc * 2;
609 if (alloc > limit) break;
610
611 MEM(buff = talloc_realloc(NULL, buff, char, alloc));
612 }
613
615
616 return -1;
617}
618
619/** (Re-)Initialises the data in a rlm_rest_request_t.
620 *
621 * Resets the values of a rlm_rest_request_t to their defaults.
622 *
623 * @param[in] section configuration data.
624 * @param[in] request Current request.
625 * @param[in] ctx to initialise.
626 */
627static void rest_request_init(rlm_rest_section_t const *section,
628 request_t *request, rlm_rest_request_t *ctx)
629{
630 /*
631 * Setup stream read data
632 */
633 ctx->section = section;
634 ctx->request = request;
635 ctx->state = READ_STATE_INIT;
636}
637
638/** Converts plain response into a single fr_pair_t
639 *
640 * @param[in] inst configuration data.
641 * @param[in] section configuration data.
642 * @param[in] randle fr_curl_io_request_t to use.
643 * @param[in] request Current request.
644 * @param[in] raw buffer containing POST data.
645 * @param[in] rawlen Length of data in raw buffer.
646 * @return
647 * - Number of fr_pair_t processed.
648 * - -1 on unrecoverable error.
649 */
651 request_t *request, UNUSED fr_curl_io_request_t *randle, char *raw, size_t rawlen)
652{
653 fr_pair_t *vp;
654
655 /*
656 * Empty response?
657 */
658 if (*raw == '\0') return 0;
659
660 /*
661 * Use rawlen to protect against overrun, and to cope with any binary data
662 */
664 fr_pair_value_bstrndup(vp, raw, rawlen, true);
665
666 RDEBUG2("%pP", vp);
667
668 return 1;
669}
670
671/** Converts POST response into fr_pair_ts and adds them to the request
672 *
673 * Accepts fr_pair_tS in the same format as rest_encode_post, but with the
674 * addition of optional attribute list qualifiers as part of the attribute name
675 * string.
676 *
677 * If no qualifiers are specified, will default to the request list.
678 *
679 * POST response format is:
680 * @verbatim [outer.][<list>.]<attribute0>=<value0>&[outer.][<list>.]<attribute1>=<value1>&[outer.][<list>.]<attributeN>=<valueN> @endverbatim
681 *
682 * @see rest_encode_post
683 *
684 * @param[in] instance configuration data.
685 * @param[in] section configuration data.
686 * @param[in] randle fr_curl_io_request_t to use.
687 * @param[in] request Current request.
688 * @param[in] raw buffer containing POST data.
689 * @param[in] rawlen Length of data in raw buffer.
690 * @return
691 * - Number of fr_pair_ts processed.
692 * - -1 on unrecoverable error.
693 */
694static int rest_decode_post(UNUSED rlm_rest_t const *instance, UNUSED rlm_rest_section_t const *section,
695 request_t *request, fr_curl_io_request_t *randle, char *raw, size_t rawlen)
696{
697 CURL *candle = randle->candle;
698
699 char const *p = raw, *q;
700
701 int count = 0;
702 int ret;
703
704 /*
705 * Empty response?
706 */
708 if (*p == '\0') return 0;
709
710 while (((q = strchr(p, '=')) != NULL) && (count < REST_BODY_MAX_ATTRS)) {
711 tmpl_t *dst;
713 fr_pair_list_t *vps;
714 TALLOC_CTX *ctx;
715 fr_dict_attr_t const *da;
716 fr_pair_t *vp;
717
718 char *name = NULL;
719 char *value = NULL;
720
721 char *expanded = NULL;
722
723 size_t len;
724 int curl_len; /* Length from last curl_easy_unescape call */
725
726 current = request;
727
728 name = curl_easy_unescape(candle, p, (q - p), &curl_len);
729 p = (q + 1);
730
731 /*
732 * Resolve attribute name to a dictionary entry and pairlist.
733 */
734 RDEBUG2("Parsing attribute \"%pV\"", fr_box_strvalue_len(name, curl_len));
735
736 if (tmpl_afrom_attr_str(request, NULL, &dst, name,
737 &(tmpl_rules_t){
738 .attr = {
739 .dict_def = request->proto_dict,
740 .list_def = request_attr_reply
741 }
742 }) <= 0) {
743 RPWDEBUG("Failed parsing attribute (skipping)");
744 talloc_free(dst);
745 goto skip;
746 }
747
748 if (tmpl_request_ptr(&current, tmpl_request(dst)) < 0) {
749 RWDEBUG("Attribute name refers to outer request but not in a tunnel (skipping)");
750 talloc_free(dst);
751 goto skip;
752 }
753
754 vps = tmpl_list_head(current, tmpl_list(dst));
755 if (!vps) {
756 RWDEBUG("List not valid in this context (skipping)");
757 talloc_free(dst);
758 goto skip;
759 }
760 ctx = tmpl_list_ctx(current, tmpl_list(dst));
761 da = tmpl_attr_tail_da(dst);
762
763 fr_assert(vps);
764
765 RINDENT();
766 RDEBUG3("Type : %s", fr_type_to_str(da->type));
767
768 q = strchr(p, '&');
769 len = (!q) ? (rawlen - (p - raw)) : (unsigned)(q - p);
770
771 value = curl_easy_unescape(candle, p, len, &curl_len);
772
773 /*
774 * If we found a delimiter we want to skip over it,
775 * if we didn't we do *NOT* want to skip over the end
776 * of the buffer...
777 */
778 p += (!q) ? len : (len + 1);
779
780 RDEBUG3("Length : %i", curl_len);
781 RDEBUG3("Value : \"%s\"", value);
782 REXDENT();
783
784 talloc_free(dst); /* Free our temporary tmpl */
785
786 RDEBUG2("Performing xlat expansion of response value");
787
788 if (xlat_aeval(request, &expanded, request, value, NULL, NULL) < 0) goto skip;
789
790 fr_assert(expanded);
791
792 MEM(vp = fr_pair_afrom_da(ctx, da));
793 if (!vp) {
794 REDEBUG("Failed creating valuepair");
795 talloc_free(expanded);
796
797 curl_free(name);
798 curl_free(value);
799
800 return count;
801 }
802
803 ret = fr_pair_value_from_str(vp, expanded, strlen(value), NULL, true);
804 TALLOC_FREE(expanded);
805 if (ret < 0) {
806 RWDEBUG("Incompatible value assignment, skipping");
808 goto skip;
809 }
810
811 fr_pair_append(vps, vp);
812
813 count++;
814
815 skip:
816 curl_free(name);
817 curl_free(value);
818
819 continue;
820 }
821
822 if (!count) REDEBUG("Malformed POST data \"%s\"", raw);
823
824 return count;
825
826}
827
828#ifdef HAVE_JSON
829/** Converts JSON "value" key into fr_pair_t.
830 *
831 * If leaf is not in fact a leaf node, but contains JSON data, the data will
832 * written to the attribute in JSON string format.
833 *
834 * @param[in] instance configuration data.
835 * @param[in] section configuration data.
836 * @param[in] ctx to allocate new fr_pair_ts in.
837 * @param[in] request Current request.
838 * @param[in] da Attribute to create.
839 * @param[in] flags containing the operator other flags controlling value
840 * expansion.
841 * @param[in] leaf object containing the fr_pair_t value.
842 * @return
843 * - #fr_pair_t just created.
844 * - NULL on error.
845 */
847 TALLOC_CTX *ctx, request_t *request,
848 fr_dict_attr_t const *da, json_flags_t *flags, json_object *leaf)
849{
850 char const *value;
851 char *expanded = NULL;
852 int ret;
853
854 fr_pair_t *vp;
855
857
858 if (json_object_is_type(leaf, json_type_null)) {
859 RDEBUG3("Got null value for attribute \"%s\" (skipping)", da->name);
860 return NULL;
861 }
862
863 MEM(vp = fr_pair_afrom_da(ctx, da));
864 if (!vp) {
865 RWDEBUG("Failed creating valuepair for attribute \"%s\" (skipping)", da->name);
866 return NULL;
867 }
868
870
871 switch (json_object_get_type(leaf)) {
872 case json_type_int:
873 if (flags->do_xlat) RWDEBUG("Ignoring do_xlat on 'int', attribute \"%s\"", da->name);
874 fr_value_box(&src, (int32_t)json_object_get_int(leaf), true);
875 break;
876
877 case json_type_double:
878 if (flags->do_xlat) RWDEBUG("Ignoring do_xlat on 'double', attribute \"%s\"", da->name);
879 fr_value_box(&src, (double)json_object_get_double(leaf), true);
880 break;
881
882 case json_type_string:
883 value = json_object_get_string(leaf);
884 if (flags->do_xlat && memchr(value, '%', json_object_get_string_len(leaf))) {
885 if (xlat_aeval(request, &expanded, request, value, NULL, NULL) < 0) {
887 return NULL;
888 }
889 fr_value_box_bstrndup_shallow(&src, NULL, expanded,
890 talloc_array_length(expanded) - 1, true);
891 } else {
893 json_object_get_string_len(leaf), true);
894 }
895 break;
896
897 default:
898 {
899 char const *str;
900 if (flags->do_xlat) RWDEBUG("Ignoring do_xlat on 'object', attribute \"%s\"", da->name);
901
902 /*
903 * Should encode any nested JSON structures into JSON strings.
904 *
905 * "I knew you liked JSON so I put JSON in your JSON!"
906 */
907 str = json_object_get_string(leaf);
908 if (!str) {
909 RWDEBUG("Failed getting string value for attribute \"%s\" (skipping)", da->name);
911 return NULL;
912 }
913 fr_value_box_strdup_shallow(&src, NULL, str, true);
914 }
915 }
916
917 ret = fr_value_box_cast(vp, &vp->data, da->type, da, &src);
918 talloc_free(expanded);
919 if (ret < 0) {
920 RWDEBUG("Failed parsing value for attribute \"%s\" (skipping)", da->name);
922 return NULL;
923 }
924
925 vp->op = flags->op;
926
927 return vp;
928}
929
930/** Processes JSON response and converts it into multiple fr_pair_ts
931 *
932 * Processes JSON attribute declarations in the format below. Will recurse when
933 * processing nested attributes. When processing nested attributes flags and
934 * operators from previous attributes are not inherited.
935 *
936 * JSON response format is:
937@verbatim
938{
939 "<attribute0>":{
940 "do_xlat":<bool>,
941 "is_json":<bool>,
942 "op":"<operator>",
943 "value":[<value0>,<value1>,<valueN>]
944 },
945 "<attribute1>":{
946 "value":{
947 "<nested-attribute0>":{
948 "op":"<operator>",
949 "value":<value0>
950 }
951 }
952 },
953 "<attribute2>":"<value0>",
954 "<attributeN>":[<value0>,<value1>,<valueN>]
955}
956@endverbatim
957 *
958 * JSON valuepair flags:
959 * - do_xlat (optional) Controls xlat expansion of values. Defaults to true.
960 * - is_json (optional) If true, any nested JSON data will be copied to the
961 * fr_pair_t in string form. Defaults to true.
962 * - op (optional) Controls how the attribute is inserted into
963 * the target list. Defaults to ':=' (T_OP_SET).
964 *
965 * If "op" is ':=' or '=', it will be automagically changed to '+=' for the
966 * second and subsequent values in multivalued attributes. This does not work
967 * between multiple attribute declarations.
968 *
969 * @see fr_tokens_table
970 *
971 * @param[in] instance configuration data.
972 * @param[in] section configuration data.
973 * @param[in] request Current request.
974 * @param[in] object containing root node, or parent node.
975 * @param[in] level Current nesting level.
976 * @param[in] max counter, decremented after each fr_pair_t is created,
977 * when 0 no more attributes will be processed.
978 * @return
979 * - Number of attributes created.
980 * - < 0 on error.
981 */
982static int json_pair_alloc(rlm_rest_t const *instance, rlm_rest_section_t const *section,
983 request_t *request, json_object *object, UNUSED int level, int max)
984{
985 int max_attrs = max;
986 tmpl_t *dst = NULL;
987
988 if (!json_object_is_type(object, json_type_object)) {
989#ifdef HAVE_JSON_TYPE_TO_NAME
990 REDEBUG("Can't process VP container, expected JSON object"
991 "got \"%s\" (skipping)",
992 json_type_to_name(json_object_get_type(object)));
993#else
994 REDEBUG("Can't process VP container, expected JSON object"
995 " (skipping)");
996#endif
997 return -1;
998 }
999
1000 /*
1001 * Process VP container
1002 */
1003 {
1004 json_object_object_foreach(object, name, value) {
1005 int i = 0, elements;
1006 struct json_object *element, *tmp;
1007 TALLOC_CTX *ctx;
1008
1009 json_flags_t flags = {
1010 .op = T_OP_SET,
1011 .do_xlat = 1,
1012 .is_json = 0
1013 };
1014
1015 request_t *current = request;
1016 fr_pair_list_t *vps;
1017 fr_pair_t *vp = NULL;
1018
1019 TALLOC_FREE(dst);
1020
1021 /*
1022 * Resolve attribute name to a dictionary entry and pairlist.
1023 */
1024 RDEBUG2("Parsing attribute \"%s\"", name);
1025
1026 if (tmpl_afrom_attr_str(request, NULL, &dst, name,
1027 &(tmpl_rules_t){
1028 .attr = {
1029 .dict_def = request->proto_dict,
1030 .list_def = request_attr_reply
1031 }
1032 }) <= 0) {
1033 RPWDEBUG("Failed parsing attribute (skipping)");
1034 continue;
1035 }
1036
1037 if (tmpl_request_ptr(&current, tmpl_request(dst)) < 0) {
1038 RWDEBUG("Attribute name refers to outer request but not in a tunnel (skipping)");
1039 continue;
1040 }
1041
1042 vps = tmpl_list_head(current, tmpl_list(dst));
1043 if (!vps) {
1044 RWDEBUG("List not valid in this context (skipping)");
1045 continue;
1046 }
1047 ctx = tmpl_list_ctx(current, tmpl_list(dst));
1048
1049 /*
1050 * Alternative JSON structure which allows operator,
1051 * and other flags to be specified.
1052 *
1053 * "<name>":{
1054 * "do_xlat":<bool>,
1055 * "is_json":<bool>,
1056 * "op":"<op>",
1057 * "value":<value>
1058 * }
1059 *
1060 * Where value is a:
1061 * - [] Multivalued array
1062 * - {} Nested Valuepair
1063 * - * Integer or string value
1064 */
1065 if (json_object_is_type(value, json_type_object)) {
1066 /*
1067 * Process operator if present.
1068 */
1069 if (json_object_object_get_ex(value, "op", &tmp)) {
1070 flags.op = fr_table_value_by_str(fr_tokens_table, json_object_get_string(tmp), 0);
1071 if (!flags.op) {
1072 RWDEBUG("Invalid operator value \"%s\" (skipping)",
1073 json_object_get_string(tmp));
1074 continue;
1075 }
1076 }
1077
1078 /*
1079 * Process optional do_xlat bool.
1080 */
1081 if (json_object_object_get_ex(value, "do_xlat", &tmp)) {
1082 flags.do_xlat = json_object_get_boolean(tmp);
1083 }
1084
1085 /*
1086 * Process optional is_json bool.
1087 */
1088 if (json_object_object_get_ex(value, "is_json", &tmp)) {
1089 flags.is_json = json_object_get_boolean(tmp);
1090 }
1091
1092 /*
1093 * Value key must be present if were using the expanded syntax.
1094 */
1095 if (!json_object_object_get_ex(value, "value", &tmp)) {
1096 RWDEBUG("Value key missing (skipping)");
1097 continue;
1098 }
1099
1100 /*
1101 * The value field now becomes the key we're operating on
1102 */
1103 value = tmp;
1104 }
1105
1106 /*
1107 * Setup fr_pair_afrom_da / recursion loop.
1108 */
1109 if (!flags.is_json && json_object_is_type(value, json_type_array)) {
1110 elements = json_object_array_length(value);
1111 if (!elements) {
1112 RWDEBUG("Zero length value array (skipping)");
1113 continue;
1114 }
1115 element = json_object_array_get_idx(value, 0);
1116 } else {
1117 elements = 1;
1118 element = value;
1119 }
1120
1121 /*
1122 * A JSON 'value' key, may have multiple elements, iterate
1123 * over each of them, creating a new fr_pair_t.
1124 */
1125 do {
1126 fr_pair_list_t tmp_list;
1127
1128 if (max_attrs-- <= 0) {
1129 RWDEBUG("At maximum attribute limit");
1130 talloc_free(dst);
1131 return max;
1132 }
1133
1134 /*
1135 * Automagically switch the op for multivalued attributes.
1136 */
1137 if (((flags.op == T_OP_SET) || (flags.op == T_OP_EQ)) && (i >= 1)) {
1138 flags.op = T_OP_ADD_EQ;
1139 }
1140
1141 if (json_object_is_type(element, json_type_object) && !flags.is_json) {
1142 /* TODO: Insert nested VP into VP structure...*/
1143 RWDEBUG("Found nested VP, these are not yet supported (skipping)");
1144
1145 continue;
1146
1147 /*
1148 vp = json_pair_alloc(instance, section,
1149 request, value,
1150 level + 1, max_attrs);*/
1151 } else {
1152 vp = json_pair_alloc_leaf(instance, section, ctx, request,
1153 tmpl_attr_tail_da(dst), &flags, element);
1154 if (!vp) continue;
1155 }
1156 RINDENT();
1157 RDEBUG2("%s:%pP", tmpl_list_name(tmpl_list(dst), ""), vp);
1158 REXDENT();
1159
1160 fr_pair_list_init(&tmp_list);
1161 fr_pair_append(&tmp_list, vp);
1162 radius_pairmove(current, vps, &tmp_list);
1163 /*
1164 * If we call json_object_array_get_idx on something that's not an array
1165 * the behaviour appears to be to occasionally segfault.
1166 */
1167 } while ((++i < elements) && (element = json_object_array_get_idx(value, i)));
1168 }
1169 }
1170
1171 talloc_free(dst);
1172
1173 return max - max_attrs;
1174}
1175
1176/** Converts JSON response into fr_pair_ts and adds them to the request.
1177 *
1178 * Converts the raw JSON string into a json-c object tree and passes it to
1179 * json_pair_alloc. After the tree has been parsed json_object_put is called
1180 * which decrements the reference count of the root node by one, and frees
1181 * the entire tree.
1182 *
1183 * @see rest_encode_json
1184 * @see json_pair_alloc
1185 *
1186 * @param[in] instance configuration data.
1187 * @param[in] section configuration data.
1188 * @param[in,out] request Current request.
1189 * @param[in] randle REST handle.
1190 * @param[in] raw buffer containing JSON data.
1191 * @param[in] rawlen Length of data in raw buffer.
1192 * @return
1193 * - The number of #fr_pair_t processed.
1194 * - -1 on unrecoverable error.
1195 */
1196static int rest_decode_json(rlm_rest_t const *instance, rlm_rest_section_t const *section,
1197 request_t *request, UNUSED fr_curl_io_request_t *randle, char *raw, UNUSED size_t rawlen)
1198{
1199 char const *p = raw;
1200
1201 struct json_object *json;
1202
1203 int ret;
1204
1205 /*
1206 * Empty response?
1207 */
1209 if (*p == '\0') return 0;
1210
1211 json = json_tokener_parse(p);
1212 if (!json) {
1213 REDEBUG("Malformed JSON data \"%s\"", raw);
1214 return -1;
1215 }
1216
1217 ret = json_pair_alloc(instance, section, request, json, 0, REST_BODY_MAX_ATTRS);
1218
1219 /*
1220 * Decrement reference count for root object, should free entire JSON tree.
1221 */
1222 json_object_put(json);
1223
1224 return ret;
1225}
1226#endif
1227
1228/** Processes incoming HTTP header data from libcurl.
1229 *
1230 * Processes the status line, and Content-Type headers from the incoming HTTP
1231 * response.
1232 *
1233 * Matches prototype for CURLOPT_HEADERFUNCTION, and will be called directly
1234 * by libcurl.
1235 *
1236 * @param[in] in Char buffer where inbound header data is written.
1237 * @param[in] size Multiply by nmemb to get the length of ptr.
1238 * @param[in] nmemb Multiply by size to get the length of ptr.
1239 * @param[in] userdata rlm_rest_response_t to keep parsing state between calls.
1240 * @return
1241 * - Length of data processed.
1242 * - 0 on error.
1243 */
1244static size_t rest_response_header(void *in, size_t size, size_t nmemb, void *userdata)
1245{
1246 rlm_rest_response_t *ctx = userdata;
1247 request_t *request = ctx->request; /* Used by RDEBUG */
1248
1249 char const *start = (char *)in, *p = start, *end = p + (size * nmemb);
1250 char *q;
1251 size_t len;
1252
1254
1255#ifndef NDEBUG
1256 if (ctx->instance->fail_header_decode) {
1257 REDEBUG("Forcing header decode failure");
1258 return 0;
1259 }
1260#endif
1261
1262 /*
1263 * This seems to be curl's indication there are no more header lines.
1264 */
1265 if (((end - p) == 2) && ((p[0] == '\r') && (p[1] == '\n'))) {
1266 /*
1267 * If we got a 100 Continue, we need to send additional payload data.
1268 * reset the state to WRITE_STATE_INIT, so that when were called again
1269 * we overwrite previous header data with that from the proper header.
1270 */
1271 if (ctx->code == 100) {
1272 RDEBUG2("Continuing...");
1273 ctx->state = WRITE_STATE_INIT;
1274 }
1275
1276 return (end - start);
1277 }
1278
1279 switch (ctx->state) {
1280 case WRITE_STATE_INIT:
1281 RDEBUG2("Processing response header");
1282
1283 /*
1284 * HTTP/<version> <reason_code>[ <reason_phrase>]\r\n
1285 *
1286 * "HTTP/1.1 " (9) + "100" (3) + "\r\n" (2) = 14
1287 * "HTTP/2 " (7) + "100" (3) + "\r\n" (2) = 12
1288 */
1289 if ((end - p) < 12) {
1290 REDEBUG("Malformed HTTP header: Status line too short");
1291 malformed:
1292 REDEBUG("Received %zu bytes of invalid header data: %pV",
1293 (end - start), fr_box_strvalue_len(in, (end - start)));
1294 ctx->code = 0;
1295
1296 /*
1297 * Indicate we parsed the entire line, otherwise
1298 * bad things seem to happen internally with
1299 * libcurl when we try and use it with asynchronous
1300 * I/O handlers.
1301 */
1302 return (end - start);
1303 }
1304 /*
1305 * Check start of header matches...
1306 */
1307 if (strncasecmp("HTTP/", p, 5) != 0) {
1308 REDEBUG("Malformed HTTP header: Missing HTTP version");
1309 goto malformed;
1310 }
1311 p += 5;
1312
1313 /*
1314 * Skip the version field, next space should mark start of reason_code.
1315 */
1316 q = memchr(p, ' ', (end - p));
1317 if (!q) {
1318 REDEBUG("Malformed HTTP header: Missing reason code");
1319 goto malformed;
1320 }
1321
1322 p = q;
1323
1324 /*
1325 * Process reason_code.
1326 *
1327 * " 100" (4) + "\r\n" (2) = 6
1328 */
1329 if ((end - p) < 6) {
1330 REDEBUG("Malformed HTTP header: Reason code too short");
1331 goto malformed;
1332 }
1333 p++;
1334
1335 /*
1336 * "xxx( |\r)" status code and terminator.
1337 */
1338 if (!isdigit(p[0]) || !isdigit(p[1]) || !isdigit(p[2]) || !((p[3] == ' ') || (p[3] == '\r'))) {
1339 REDEBUG("Malformed HTTP header: Reason code malformed. "
1340 "Expected three digits then space or end of header, got \"%pV\"",
1341 fr_box_strvalue_len(p, 4));
1342 goto malformed;
1343 }
1344
1345 /*
1346 * Convert status code into an integer value
1347 */
1348 q = NULL;
1349 ctx->code = (int)strtoul(p, &q, 10);
1350 fr_assert(q == (p + 3)); /* We check this above */
1351 p = q;
1352
1353 /*
1354 * Process reason_phrase (if present).
1355 */
1356 RINDENT();
1357 if (*p == ' ') {
1358 p++;
1359 q = memchr(p, '\r', (end - p));
1360 if (!q) goto malformed;
1361 RDEBUG2("Status : %i (%pV)", ctx->code, fr_box_strvalue_len(p, q - p));
1362 } else {
1363 RDEBUG2("Status : %i", ctx->code);
1364 }
1365 REXDENT();
1366
1368
1369 break;
1370
1372 if (((end - p) >= 14) &&
1373 (strncasecmp("Content-Type: ", p, 14) == 0)) {
1374 p += 14;
1375
1376 /*
1377 * Check to see if there's a parameter separator.
1378 */
1379 q = memchr(p, ';', (end - p));
1380
1381 /*
1382 * If there's not, find the end of this header.
1383 */
1384 if (!q) q = memchr(p, '\r', (end - p));
1385
1386 len = (size_t)(!q ? (end - p) : (q - p));
1388
1389 RINDENT();
1390 RDEBUG2("Type : %s (%pV)", fr_table_str_by_value(http_body_type_table, type, "<INVALID>"),
1391 fr_box_strvalue_len(p, len));
1392 REXDENT();
1393
1394 /*
1395 * Assume the force_to value has already been validated.
1396 */
1397 if (ctx->force_to != REST_HTTP_BODY_UNKNOWN) {
1398 if (ctx->force_to != ctx->type) {
1399 RDEBUG3("Forcing body type to \"%s\"",
1401 ctx->type = ctx->force_to;
1402 }
1403 /*
1404 * Figure out if the type is supported by one of the decoders.
1405 */
1406 } else {
1408 switch (ctx->type) {
1410 RWDEBUG("Couldn't determine type, using the request's type \"%s\".",
1412 break;
1413
1415 REDEBUG("Type \"%s\" is currently unsupported",
1417 break;
1418
1420 REDEBUG("Type \"%s\" is unavailable, please rebuild this module with the required "
1421 "library", fr_table_str_by_value(http_body_type_table, type, "<INVALID>"));
1422 break;
1423
1425 REDEBUG("Type \"%s\" is not a valid web API data markup format",
1427 break;
1428
1429 /* supported type */
1430 default:
1431 break;
1432 }
1433 }
1434 }
1435 break;
1436
1437 default:
1438 break;
1439 }
1440
1441 return (end - start);
1442}
1443
1444/** Processes incoming HTTP body data from libcurl.
1445 *
1446 * Writes incoming body data to an intermediary buffer for later parsing by
1447 * one of the decode functions.
1448 *
1449 * @param[in] in Char buffer where inbound header data is written
1450 * @param[in] size Multiply by nmemb to get the length of ptr.
1451 * @param[in] nmemb Multiply by size to get the length of ptr.
1452 * @param[in] userdata rlm_rest_response_t to keep parsing state between calls.
1453 * @return
1454 * - Length of data processed.
1455 * - 0 on error.
1456 */
1457static size_t rest_response_body(void *in, size_t size, size_t nmemb, void *userdata)
1458{
1459 rlm_rest_response_t *ctx = userdata;
1460 request_t *request = ctx->request; /* Used by RDEBUG */
1461
1462 char const *start = in, *p = start, *end = p + (size * nmemb);
1463 char *q;
1464
1465 size_t needed;
1466
1467 if (start == end) return 0; /* Nothing to process */
1468
1469#ifndef NDEBUG
1470 if (ctx->instance->fail_body_decode) {
1471 REDEBUG("Forcing body read failure");
1472 return 0;
1473 }
1474#endif
1475
1476 /*
1477 * Any post processing of headers should go here...
1478 */
1480
1481 switch (ctx->type) {
1485 while ((q = memchr(p, '\n', (end - p)))) {
1486 REDEBUG("%pV", fr_box_strvalue_len(p, q - p));
1487 p = q + 1;
1488 }
1489
1490 if (p != end) REDEBUG("%pV", fr_box_strvalue_len(p, end - p));
1491 break;
1492
1494 while ((q = memchr(p, '\n', (end - p)))) {
1495 RDEBUG3("%pV", fr_box_strvalue_len(p, q - p));
1496 p = q + 1;
1497 }
1498
1499 if (p != end) RDEBUG3("%pV", fr_box_strvalue_len(p, end - p));
1500 break;
1501
1502 default:
1503 {
1504 char *out_p;
1505
1506 if ((ctx->section->response.max_body_in > 0) && ((ctx->used + (end - p)) > ctx->section->response.max_body_in)) {
1507 REDEBUG("Incoming data (%zu bytes) exceeds max_body_in (%zu bytes). "
1508 "Forcing body to type 'invalid'", ctx->used + (end - p), ctx->section->response.max_body_in);
1510 TALLOC_FREE(ctx->buffer);
1511 break;
1512 }
1513
1514 needed = ROUND_UP(ctx->used + (end - p), REST_BODY_ALLOC_CHUNK);
1515 if (needed > ctx->alloc) {
1516 MEM(ctx->buffer = talloc_bstr_realloc(NULL, ctx->buffer, needed));
1517 ctx->alloc = needed;
1518 }
1519
1520 out_p = ctx->buffer + ctx->used;
1521 memcpy(out_p, p, (end - p));
1522 out_p += (end - p);
1523 *out_p = '\0';
1524 ctx->used += (end - p);
1525 }
1526 break;
1527 }
1528
1529 return (end - start);
1530}
1531
1532/** Print out the response text as error lines
1533 *
1534 * @param request The Current request.
1535 * @param handle fr_curl_io_request_t used to execute the previous request.
1536 */
1538{
1539 char const *p, *end;
1540 char *q;
1541 size_t len;
1542
1543 len = rest_get_handle_data(&p, handle);
1544 if (len == 0) return;
1545
1546 end = p + len;
1547
1548 RERROR("Server returned:");
1549 while ((q = memchr(p, '\n', (end - p)))) {
1550 RERROR("%pV", fr_box_strvalue_len(p, q - p));
1551 p = q + 1;
1552 }
1553
1554 if (p != end) RERROR("%pV", fr_box_strvalue_len(p, end - p));
1555}
1556
1557/** Print out the response text
1558 *
1559 * @param request The Current request.
1560 * @param handle fr_curl_io_request_t used to execute the previous request.
1561 */
1563{
1564 char const *p, *end;
1565 char *q;
1566 size_t len;
1567
1568 len = rest_get_handle_data(&p, handle);
1569 if (len == 0) return;
1570
1571 end = p + len;
1572
1573 RDEBUG3("Server returned:");
1574 while ((q = memchr(p, '\n', (end - p)))) {
1575 RDEBUG3("%pV", fr_box_strvalue_len(p, q - p));
1576 p = q + 1;
1577 }
1578
1579 if (p != end) RDEBUG3("%pV", fr_box_strvalue_len(p, end - p));
1580}
1581
1582/** (Re-)Initialises the data in a rlm_rest_response_t.
1583 *
1584 * This resets the values of the a rlm_rest_response_t to their defaults.
1585 * Must be called between encoding sessions.
1586 *
1587 * @see rest_response_body
1588 * @see rest_response_header
1589 *
1590 * @param[in] section that created the request.
1591 * @param[in] request Current request.
1592 * @param[in] ctx data to initialise.
1593 * @param[in] type Default http_body_type to use when decoding raw data, may be
1594 * overwritten by rest_response_header.
1595 * @param[in] header Where to write out headers, may be NULL.
1596 */
1597static void rest_response_init(rlm_rest_section_t const *section,
1598 request_t *request, rlm_rest_response_t *ctx, http_body_type_t type, tmpl_t *header)
1599{
1600 ctx->section = section;
1601 ctx->request = request;
1602 ctx->type = type;
1603 ctx->state = WRITE_STATE_INIT;
1604 ctx->alloc = 0;
1605 ctx->used = 0;
1606 ctx->code = 0;
1607 ctx->header = header;
1608 TALLOC_FREE(ctx->buffer);
1609}
1610
1611/** Extracts pointer to buffer containing response data
1612 *
1613 * @param[out] out Where to write the pointer to the buffer.
1614 * @param[in] randle used for the last request.
1615 * @return
1616 * - 0 if no data i available.
1617 * - > 0 if data is available.
1618 */
1619size_t rest_get_handle_data(char const **out, fr_curl_io_request_t *randle)
1620{
1621 rlm_rest_curl_context_t *ctx = talloc_get_type_abort(randle->uctx, rlm_rest_curl_context_t);
1622
1623 if (!ctx->response.buffer) return 0;
1624
1625 *out = ctx->response.buffer;
1626 return ctx->response.used;
1627}
1628
1629/** Configures body specific curlopts.
1630 *
1631 * Configures libcurl handle to use either chunked mode, where the request
1632 * data will be sent using multiple HTTP requests, or contiguous mode where
1633 * the request data will be sent in a single HTTP request.
1634 *
1635 * @param[in] mctx Call data.
1636 * @param[in] section configuration data.
1637 * @param[in] request Current request.
1638 * @param[in] randle fr_curl_io_request_t to configure.
1639 * @param[in] func to pass to libcurl for chunked.
1640 * transfers (NULL if not using chunked mode).
1641 * @return
1642 * - 0 on success.
1643 * - -1 on failure.
1644 */
1645static int rest_request_config_body(module_ctx_t const *mctx, rlm_rest_section_t const *section,
1646 request_t *request, fr_curl_io_request_t *randle, rest_read_t func)
1647{
1648 rlm_rest_t const *inst = talloc_get_type_abort(mctx->mi->data, rlm_rest_t);
1649 rlm_rest_curl_context_t *uctx = talloc_get_type_abort(randle->uctx, rlm_rest_curl_context_t);
1650 ssize_t len;
1651
1652 /*
1653 * We were provided with no read function, assume this means
1654 * no body should be sent.
1655 */
1656 if (!func) {
1657 FR_CURL_REQUEST_SET_OPTION(CURLOPT_POSTFIELDSIZE, 0);
1658 return 0;
1659 }
1660
1661 /*
1662 * Chunked transfer encoding means the body will be sent in
1663 * multiple parts.
1664 */
1665 if (section->request.chunk > 0) {
1666 FR_CURL_REQUEST_SET_OPTION(CURLOPT_READDATA, &uctx->request);
1667 FR_CURL_REQUEST_SET_OPTION(CURLOPT_READFUNCTION, func);
1668
1669 return 0;
1670 }
1671
1672 /*
1673 * If were not doing chunked encoding then we read the entire
1674 * body into a buffer, and send it in one go.
1675 */
1676 len = rest_request_encode_wrapper(&uctx->body, inst, func, REST_BODY_MAX_LEN, &uctx->request);
1677 if (len <= 0) {
1678 REDEBUG("Failed creating HTTP body content");
1679 return -1;
1680 }
1681 RDEBUG2("Content-Length will be %zu bytes", len);
1682
1683 fr_assert((len == 0) || (talloc_array_length(uctx->body) >= (size_t)len));
1684 FR_CURL_REQUEST_SET_OPTION(CURLOPT_POSTFIELDS, uctx->body);
1685 FR_CURL_REQUEST_SET_OPTION(CURLOPT_POSTFIELDSIZE, len);
1686
1687 return 0;
1688
1689error:
1690 return -1;
1691}
1692
1693/** Adds an additional header to a handle to use in the next reques
1694 *
1695 * @param[in] request Current request.
1696 * @param[in] randle used for the next request.
1697 * @param[in] header to add.
1698 * @param[in] validate whether to perform basic checks on the header
1699 * @return
1700 * - 0 on success.
1701 * - -1 on failure.
1702 */
1703int rest_request_config_add_header(request_t *request, fr_curl_io_request_t *randle, char const *header, bool validate)
1704{
1705 rlm_rest_curl_context_t *ctx = talloc_get_type_abort(randle->uctx, rlm_rest_curl_context_t);
1706 struct curl_slist *headers;
1707
1708 if (validate && !strchr(header, ':')) {
1709 RWDEBUG("Invalid HTTP header \"%s\" must be in format '<attribute>: <value>'. Skipping...",
1710 header);
1711 return -1;
1712 }
1713
1714 RINDENT();
1715 RDEBUG3("%s", header);
1716 REXDENT();
1717
1718 headers = curl_slist_append(ctx->headers, header);
1719 if (unlikely(!headers)) {
1720 REDEBUG("Failed to add header \"%s\"", header);
1721 return -1;
1722 }
1723 ctx->headers = headers;
1724
1725 return 0;
1726}
1727
1728/** See if the list of headers already contains a header
1729 *
1730 * @note Only compares the header name, not the value.
1731 *
1732 * @param[in] randle to check headers for.
1733 * @param[in] header to find.
1734 * @return
1735 * - true if yes
1736 * - false if no
1737 */
1738static bool rest_request_contains_header(fr_curl_io_request_t *randle, char const *header)
1739{
1740 rlm_rest_curl_context_t *ctx = talloc_get_type_abort(randle->uctx, rlm_rest_curl_context_t);
1741 struct curl_slist *headers = ctx->headers;
1742 char const *sep;
1743 size_t cmp_len;
1744
1745 sep = strchr(header, ':');
1746 cmp_len = sep ? (size_t)(sep - header) : strlen(header);
1747
1748 while (headers) {
1749 if (strncasecmp(headers->data, header, cmp_len) == 0) return true;
1750 headers = headers->next;
1751 }
1752
1753 return false;
1754}
1755
1756/** Configures request curlopts.
1757 *
1758 * Configures libcurl handle setting various curlopts for things like local
1759 * client time, Content-Type, and other FreeRADIUS custom headers.
1760 *
1761 * Current FreeRADIUS custom headers are:
1762 * - X-FreeRADIUS-Section The module section being processed.
1763 * - X-FreeRADIUS-Server The current virtual server the request_t is
1764 * passing through.
1765 *
1766 * Sets up callbacks for all response processing (buffers and body data).
1767 *
1768 * @param[in] mctx call data.
1769 * @param[in] section configuration data.
1770 * @param[in] randle to configure.
1771 * @param[in] request Current request.
1772 * @param[in] method to use (HTTP verbs PUT, POST, DELETE etc...).
1773 * @param[in] type Content-Type for request encoding, also sets
1774 * the default for decoding.
1775 * @param[in] uri buffer containing the expanded URI to send the request to.
1776 * @param[in] body_data (optional) custom body data. Must persist whilst we're
1777 * writing data out to the socket. Must be a talloced buffer
1778 * which is \0 terminated.
1779 * @return
1780 * - 0 on success (all opts configured).
1781 * - -1 on failure.
1782 */
1784 request_t *request, fr_curl_io_request_t *randle, http_method_t method,
1786 char const *uri, char const *body_data)
1787{
1788 rlm_rest_t const *inst = talloc_get_type_abort(mctx->mi->data, rlm_rest_t);
1789 rlm_rest_call_env_t *call_env = talloc_get_type_abort(mctx->env_data, rlm_rest_call_env_t);
1790 rlm_rest_curl_context_t *ctx = talloc_get_type_abort(randle->uctx, rlm_rest_curl_context_t);
1791 CURL *candle = randle->candle;
1792 fr_time_delta_t timeout;
1793
1794 http_auth_type_t auth = section->request.auth;
1795
1796 CURLcode ret = CURLE_OK;
1797 char const *option;
1798
1799 char buffer[512];
1800
1801 fr_assert(candle);
1802
1803 buffer[(sizeof(buffer) - 1)] = '\0';
1804
1805 /*
1806 * Control which HTTP version we're going to use
1807 */
1808 if (inst->http_negotiation != CURL_HTTP_VERSION_NONE) FR_CURL_REQUEST_SET_OPTION(CURLOPT_HTTP_VERSION, inst->http_negotiation);
1809
1810 /*
1811 * Setup any header options and generic headers.
1812 */
1813 FR_CURL_REQUEST_SET_OPTION(CURLOPT_URL, uri);
1814#if CURL_AT_LEAST_VERSION(7,85,0)
1815 FR_CURL_REQUEST_SET_OPTION(CURLOPT_PROTOCOLS_STR, "http,https");
1816#else
1817 FR_CURL_REQUEST_SET_OPTION(CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
1818#endif
1819 if (section->request.proxy) {
1820 if (section->request.proxy == rest_no_proxy) {
1821 FR_CURL_REQUEST_SET_OPTION(CURLOPT_NOPROXY, "*");
1822 } else {
1823 FR_CURL_REQUEST_SET_OPTION(CURLOPT_PROXY, section->request.proxy);
1824 }
1825 }
1826 FR_CURL_REQUEST_SET_OPTION(CURLOPT_NOSIGNAL, 1L);
1827 FR_CURL_REQUEST_SET_OPTION(CURLOPT_USERAGENT, "FreeRADIUS " RADIUSD_VERSION_STRING);
1828
1829 timeout = inst->conn_config.connect_timeout;
1830 RDEBUG3("Connect timeout is %pVs, request timeout is %pVs",
1831 fr_box_time_delta(timeout), fr_box_time_delta(section->timeout));
1832 FR_CURL_REQUEST_SET_OPTION(CURLOPT_CONNECTTIMEOUT_MS, fr_time_delta_to_msec(timeout));
1833 FR_CURL_REQUEST_SET_OPTION(CURLOPT_TIMEOUT_MS, fr_time_delta_to_msec(section->timeout));
1834
1835 /*
1836 * FreeRADIUS custom headers
1837 */
1838 RDEBUG3("Adding custom headers:");
1839 snprintf(buffer, sizeof(buffer), "X-FreeRADIUS-Section: %s", section->name);
1840 if (unlikely(rest_request_config_add_header(request, randle, buffer, false) < 0)) return -1;
1841
1842 snprintf(buffer, sizeof(buffer), "X-FreeRADIUS-Server: %s", cf_section_name2(unlang_call_current(request)));
1843 if (unlikely(rest_request_config_add_header(request, randle, buffer, false) < 0)) return -1;
1844
1845 /*
1846 * Add in the section headers
1847 */
1848 if (call_env->request.header) {
1849 size_t len = talloc_array_length(call_env->request.header), i;
1850 for (i = 0; i < len; i++) {
1851 fr_value_box_list_foreach(&call_env->request.header[i], header) {
1852 if (unlikely(rest_request_config_add_header(request, randle, header->vb_strvalue, true) < 0)) return -1;
1853 }
1854 }
1855 }
1856
1857 /*
1858 * Add in dynamic headers from the request
1859 */
1860 {
1861 fr_pair_t *header;
1862 fr_dcursor_t header_cursor;
1863
1864 for (header = fr_pair_dcursor_by_da_init(&header_cursor, &request->control_pairs, attr_rest_http_header);
1865 header;
1866 header = fr_dcursor_current(&header_cursor)) {
1867 header = fr_dcursor_remove(&header_cursor);
1868 if (unlikely(rest_request_config_add_header(request, randle, header->vp_strvalue, true) < 0)) return -1;
1869
1870 talloc_free(header);
1871 }
1872 }
1873
1874 if (!rest_request_contains_header(randle, "Content-Type:")) {
1875 /*
1876 * HTTP/1.1 doesn't require a content type so only set it
1877 * if where body type requires it, and we haven't set one
1878 * already from attributes.
1879 */
1880 if (type != REST_HTTP_BODY_NONE) {
1881 char const *content_type = fr_table_str_by_value(http_content_type_table, type, section->request.body_str);
1882 snprintf(buffer, sizeof(buffer), "Content-Type: %s", content_type);
1883 if (unlikely(rest_request_config_add_header(request, randle, buffer, false) < 0)) return -1;
1884
1885 RDEBUG3("Request body content-type will be \"%s\"", content_type);
1886 }
1887 }
1888
1889 /*
1890 * Configure HTTP verb (GET, POST, PUT, PATCH, DELETE, other...)
1891 */
1892 switch (method) {
1894 FR_CURL_REQUEST_SET_OPTION(CURLOPT_HTTPGET, 1L);
1895 break;
1896
1898 FR_CURL_REQUEST_SET_OPTION(CURLOPT_POST, 1L);
1899 break;
1900
1902 /*
1903 * Do not set CURLOPT_PUT, this will cause libcurl
1904 * to ignore CURLOPT_POSTFIELDs and attempt to read
1905 * whatever was set with CURLOPT_READDATA, which by
1906 * default is stdin.
1907 *
1908 * This is many cases will cause the server to block,
1909 * indefinitely.
1910 */
1911 FR_CURL_REQUEST_SET_OPTION(CURLOPT_CUSTOMREQUEST, "PUT");
1912 break;
1913
1915 FR_CURL_REQUEST_SET_OPTION(CURLOPT_CUSTOMREQUEST, "PATCH");
1916 break;
1917
1919 FR_CURL_REQUEST_SET_OPTION(CURLOPT_CUSTOMREQUEST, "DELETE");
1920 break;
1921
1923 FR_CURL_REQUEST_SET_OPTION(CURLOPT_CUSTOMREQUEST, section->request.method_str);
1924 break;
1925
1926 default:
1927 fr_assert(0);
1928 break;
1929 }
1930
1931 /*
1932 * Set user based authentication parameters
1933 */
1934 if (auth > REST_HTTP_AUTH_NONE) {
1935
1936#define SET_AUTH_OPTION(_x, _y)\
1937do {\
1938 if ((ret = curl_easy_setopt(candle, _x, _y)) != CURLE_OK) {\
1939 option = STRINGIFY(_x);\
1940 REDEBUG("Failed setting curl option %s: %s (%i)", option, curl_easy_strerror(ret), ret); \
1941 goto error;\
1942 }\
1943} while (0)
1944 RDEBUG3("Configuring HTTP auth type %s, user \"%pV\", password \"%pV\"",
1945 fr_table_str_by_value(http_auth_table, auth, "<INVALID>"),
1946 call_env->request.username ? call_env->request.username : fr_box_strvalue("(none)"),
1947 call_env->request.password ? call_env->request.password : fr_box_strvalue("(none)"));
1948
1949 /*
1950 * FIXME - We probably want to escape \0s here...
1951 */
1952 if ((auth >= REST_HTTP_AUTH_BASIC) && (auth <= REST_HTTP_AUTH_ANY_SAFE)) {
1953 SET_AUTH_OPTION(CURLOPT_HTTPAUTH, http_curl_auth[auth]);
1954 if (call_env->request.username) SET_AUTH_OPTION(CURLOPT_USERNAME, call_env->request.username->vb_strvalue);
1955 if (call_env->request.password) SET_AUTH_OPTION(CURLOPT_PASSWORD, call_env->request.password->vb_strvalue);
1956 } else if (auth == REST_HTTP_AUTH_TLS_SRP) {
1957 SET_AUTH_OPTION(CURLOPT_TLSAUTH_TYPE, "SRP");
1958 if (call_env->request.username) SET_AUTH_OPTION(CURLOPT_TLSAUTH_USERNAME, call_env->request.username->vb_strvalue);
1959 if (call_env->request.password) SET_AUTH_OPTION(CURLOPT_TLSAUTH_PASSWORD, call_env->request.password->vb_strvalue);
1960 }
1961 }
1962
1963 /*
1964 * Set SSL/TLS authentication parameters
1965 */
1966 fr_curl_easy_tls_init(randle, &section->tls);
1967
1968 /*
1969 * Tell CURL how to get HTTP body content, and how to process incoming data.
1970 */
1971 rest_response_init(section, request, &ctx->response, type, call_env->response.header);
1972
1973 FR_CURL_REQUEST_SET_OPTION(CURLOPT_HEADERFUNCTION, rest_response_header);
1974 FR_CURL_REQUEST_SET_OPTION(CURLOPT_HEADERDATA, &ctx->response);
1975 FR_CURL_REQUEST_SET_OPTION(CURLOPT_WRITEFUNCTION, rest_response_body);
1976 FR_CURL_REQUEST_SET_OPTION(CURLOPT_WRITEDATA, &ctx->response);
1977
1978 /*
1979 * Force parsing the body text as a particular encoding.
1980 */
1981 ctx->response.force_to = section->response.force_to;
1982
1983 switch (method) {
1986 RDEBUG3("Using a HTTP method which does not require a body. Forcing request body type to \"none\"");
1987 goto finish;
1988
1993 if (section->request.chunk > 0) {
1994 ctx->request.chunk = section->request.chunk;
1995
1996 if (unlikely(rest_request_config_add_header(request, randle, "Transfer-Encoding: chunked", false) < 0)) return -1;
1997 }
1998
1999 break;
2000
2001 default:
2002 fr_assert(0);
2003 }
2004
2005 /*
2006 * Setup encoder specific options
2007 */
2008 switch (type) {
2010 if (rest_request_config_body(mctx, section, request, randle, NULL) < 0) return -1;
2011
2012 break;
2013
2015 {
2017
2018 data = talloc_zero(request, rest_custom_data_t);
2019 data->p = data->start = body_data;
2020 data->len = talloc_strlen(body_data);
2021
2022 /* Use the encoder specific pointer to store the data we need to encode */
2023 ctx->request.encoder = data;
2024 if (rest_request_config_body(mctx, section, request, randle, rest_encode_custom) < 0) {
2025 TALLOC_FREE(ctx->request.encoder);
2026 return -1;
2027 }
2028 }
2029 break;
2030
2031#ifdef HAVE_JSON
2033 {
2035
2036 data = talloc_zero(request, rest_custom_data_t);
2037 ctx->request.encoder = data;
2038
2039 rest_request_init(section, request, &ctx->request);
2040
2041 if (rest_request_config_body(mctx, section, request, randle, rest_encode_json) < 0) return -1;
2042 }
2043
2044 break;
2045#endif
2046
2048 rest_request_init(section, request, &ctx->request);
2049 fr_pair_dcursor_init(&(ctx->request.cursor), &request->request_pairs);
2050
2051 if (rest_request_config_body(mctx, section, request, randle, rest_encode_post) < 0) return -1;
2052
2053 break;
2054
2055 default:
2056 fr_assert(0);
2057 }
2058
2059
2060finish:
2061 FR_CURL_REQUEST_SET_OPTION(CURLOPT_HTTPHEADER, ctx->headers);
2062
2063 return 0;
2064
2065error:
2066 return -1;
2067}
2068
2069/** Sends the response to the correct decode function.
2070 *
2071 * Uses the Content-Type information written in rest_response_header to
2072 * determine the correct decode function to use. The decode function will
2073 * then convert the raw received data into fr_pair_ts.
2074 *
2075 * @param[in] instance configuration data.
2076 * @param[in] section configuration data.
2077 * @param[in] request Current request.
2078 * @param[in] randle to use.
2079 * @return
2080 * - 0 on success.
2081 * - -1 on failure.
2082 */
2083int rest_response_decode(rlm_rest_t const *instance, rlm_rest_section_t const *section,
2084 request_t *request, fr_curl_io_request_t *randle)
2085{
2086 rlm_rest_curl_context_t *ctx = talloc_get_type_abort(randle->uctx, rlm_rest_curl_context_t);
2087
2088 int ret = -1; /* -Wsometimes-uninitialized */
2089
2090 if (!ctx->response.buffer) {
2091 RDEBUG2("Skipping attribute processing, no valid body data received");
2092 return 0;
2093 }
2094
2095 switch (ctx->response.type) {
2097 return 0;
2098
2100 ret = rest_decode_plain(instance, section, request, randle, ctx->response.buffer, ctx->response.used);
2101 break;
2102
2104 ret = rest_decode_post(instance, section, request, randle, ctx->response.buffer, ctx->response.used);
2105 break;
2106
2107#ifdef HAVE_JSON
2109 ret = rest_decode_json(instance, section, request, randle, ctx->response.buffer, ctx->response.used);
2110 break;
2111#endif
2112
2116 return -1;
2117
2118 default:
2119 fr_assert(0);
2120 }
2121
2122 return ret;
2123}
2124
2125/** URL encodes a string.
2126 *
2127 * Encode special chars as per RFC 3986 section 4.
2128 *
2129 * @param[in] request Current request.
2130 * @param[out] out Where to write escaped string.
2131 * @param[in] outlen Size of out buffer.
2132 * @param[in] raw string to be urlencoded.
2133 * @param[in] arg pointer, gives context for escaping.
2134 * @return length of data written to out (excluding NULL).
2135 */
2136size_t rest_uri_escape(UNUSED request_t *request, char *out, size_t outlen, char const *raw, UNUSED void *arg)
2137{
2138 char *escaped;
2139
2140 escaped = curl_escape(raw, 0);
2141 strlcpy(out, escaped, outlen);
2142 curl_free(escaped);
2143
2144 return strlen(out);
2145}
2146
2147/** Unescapes the host portion of a URI string
2148 *
2149 * This is required because the xlat functions which operate on the input string
2150 * cannot distinguish between host and path components.
2151 *
2152 * @param[out] out Where to write the pointer to the new
2153 * buffer containing the escaped URI.
2154 * @param[in] inst of rlm_rest.
2155 * @param[in] request Current request
2156 * @param[in] randle to use.
2157 * @param[in] uri configuration data.
2158 * @return
2159 * - Length of data written to buffer (excluding NULL).
2160 * - < 0 if an error occurred.
2161 */
2163 fr_curl_io_request_t *randle, char const *uri)
2164{
2165 CURL *candle = randle->candle;
2166
2167 char const *p, *q;
2168
2169 char *scheme;
2170
2171 ssize_t len;
2172
2173 p = uri;
2174
2175 /*
2176 * All URLs must contain at least <scheme>://<server>/
2177 */
2178 p = strchr(p, ':');
2179 if (!p || (*++p != '/') || (*++p != '/')) {
2180 malformed:
2181 REDEBUG("URI \"%s\" is malformed, can't find start of path", uri);
2182 return -1;
2183 }
2184 p = strchr(p + 1, '/');
2185 if (!p) {
2186 goto malformed;
2187 }
2188
2189 len = (p - uri);
2190
2191 /*
2192 * Unescape any special sequences in the first part of the URI
2193 */
2194 scheme = curl_easy_unescape(candle, uri, len, NULL);
2195 if (!scheme) {
2196 REDEBUG("Error unescaping host");
2197 return -1;
2198 }
2199
2200 /*
2201 * URIs can't contain spaces, so anything after the space must
2202 * be something else.
2203 */
2204 q = strchr(p, ' ');
2205 *out = q ? talloc_typed_asprintf(request, "%s%.*s", scheme, (int)(q - p), p) :
2206 talloc_typed_asprintf(request, "%s%s", scheme, p);
2207
2208 MEM(*out);
2209 curl_free(scheme);
2210
2211 return talloc_array_length(*out) - 1; /* array_length includes \0 */
2212}
static int const char char buffer[256]
Definition acutest.h:576
#define RCSID(id)
Definition build.h:485
#define L(_str)
Helper for initialising arrays of string literals.
Definition build.h:209
#define unlikely(_x)
Definition build.h:383
#define UNUSED
Definition build.h:317
#define NUM_ELEMENTS(_t)
Definition build.h:339
CONF_SECTION * unlang_call_current(request_t *request)
Return the last virtual server that was called.
Definition call.c:225
char const * cf_section_name2(CONF_SECTION const *cs)
Return the second identifier of a CONF_SECTION.
Definition cf_util.c:1184
#define FR_CURL_REQUEST_SET_OPTION(_x, _y)
Definition base.h:67
fr_curl_io_request_t * fr_curl_io_request_alloc(TALLOC_CTX *ctx)
Allocate a new curl easy request and wrapper struct.
Definition io.c:544
void * uctx
Private data for the module using the API.
Definition base.h:105
CURL * candle
Request specific handle.
Definition base.h:102
Structure representing an individual request being passed to curl for processing.
Definition base.h:101
static void * fr_dcursor_next(fr_dcursor_t *cursor)
Advanced the cursor to the next item.
Definition dcursor.h:290
static void * fr_dcursor_remove(fr_dcursor_t *cursor)
Remove the current item.
Definition dcursor.h:482
static void * fr_dcursor_current(fr_dcursor_t *cursor)
Return the item the cursor current points to.
Definition dcursor.h:339
#define MEM(x)
Definition debug.h:36
#define RADIUSD_VERSION_STRING
Definition dependency.h:39
static fr_slen_t in
Definition dict.h:840
Test enumeration values.
Definition dict_test.h:92
char * fr_json_afrom_pair_list(TALLOC_CTX *ctx, fr_pair_list_t *vps, fr_json_format_t const *format)
Returns a JSON string of a list of value pairs.
Definition json.c:1237
int fr_curl_easy_tls_init(fr_curl_io_request_t *randle, fr_curl_tls_t const *conf)
Definition base.c:139
#define REXDENT()
Exdent (unindent) R* messages by one level.
Definition log.h:443
#define RWDEBUG(fmt,...)
Definition log.h:361
#define RDEBUG3(fmt,...)
Definition log.h:343
#define RERROR(fmt,...)
Definition log.h:298
#define RPWDEBUG(fmt,...)
Definition log.h:366
#define RINDENT()
Indent R* messages by one level.
Definition log.h:430
talloc_free(reap)
#define ROUND_UP(_num, _mul)
Round up - Works in all cases, but is slower.
Definition math.h:148
long int ssize_t
unsigned long int size_t
static size_t used
int strncasecmp(char *s1, char *s2, int n)
Definition missing.c:36
void * env_data
Per call environment data.
Definition module_ctx.h:44
module_instance_t const * mi
Instance of the module being instantiated.
Definition module_ctx.h:42
Temporary structure to hold arguments for module calls.
Definition module_ctx.h:41
int fr_pair_value_from_str(fr_pair_t *vp, char const *value, size_t inlen, fr_sbuff_unescape_rules_t const *uerules, UNUSED bool tainted)
Convert string value to native attribute value.
Definition pair.c:2599
int fr_pair_append(fr_pair_list_t *list, fr_pair_t *to_add)
Add a VP to the end of the list.
Definition pair.c:1351
fr_pair_t * fr_pair_afrom_da(TALLOC_CTX *ctx, fr_dict_attr_t const *da)
Dynamically allocate a new attribute and assign a fr_dict_attr_t.
Definition pair.c:287
void fr_pair_list_init(fr_pair_list_t *list)
Initialise a pair list header.
Definition pair.c:46
int fr_pair_value_bstrndup(fr_pair_t *vp, char const *src, size_t len, bool tainted)
Copy data into a "string" type value pair.
Definition pair.c:2795
void radius_pairmove(request_t *request, fr_pair_list_t *to, fr_pair_list_t *from)
Definition pairmove.c:44
#define fr_assert(_expr)
Definition rad_assert.h:38
static rc_request_t * current
#define pair_update_request(_attr, _da)
#define REDEBUG(fmt,...)
Definition radclient.h:52
#define RDEBUG2(fmt,...)
Definition radclient.h:54
fr_dict_attr_t const * request_attr_reply
Definition request.c:44
static int rest_decode_post(UNUSED rlm_rest_t const *instance, UNUSED rlm_rest_section_t const *section, request_t *request, fr_curl_io_request_t *randle, char *raw, size_t rawlen)
Converts POST response into fr_pair_ts and adds them to the request.
Definition rest.c:694
static int rest_decode_plain(UNUSED rlm_rest_t const *inst, UNUSED rlm_rest_section_t const *section, request_t *request, UNUSED fr_curl_io_request_t *randle, char *raw, size_t rawlen)
Converts plain response into a single fr_pair_t.
Definition rest.c:650
fr_table_num_sorted_t const http_auth_table[]
Definition rest.c:161
size_t len
Length of data.
Definition rest.c:209
char const * start
Start of the buffer.
Definition rest.c:207
#define CURLAUTH_DIGEST_IE
Definition rest.c:84
int rest_request_config(module_ctx_t const *mctx, rlm_rest_section_t const *section, request_t *request, fr_curl_io_request_t *randle, http_method_t method, http_body_type_t type, char const *uri, char const *body_data)
Configures request curlopts.
Definition rest.c:1783
ssize_t rest_uri_host_unescape(char **out, UNUSED rlm_rest_t const *inst, request_t *request, fr_curl_io_request_t *randle, char const *uri)
Unescapes the host portion of a URI string.
Definition rest.c:2162
int do_xlat
If true value will be expanded with xlat.
Definition rest.c:223
static size_t rest_encode_custom(void *out, size_t size, size_t nmemb, void *userdata)
Copies a pre-expanded xlat string to the output buffer.
Definition rest.c:292
fr_table_num_sorted_t const http_body_type_table[]
Conversion table for type config values.
Definition rest.c:146
static size_t rest_encode_json(void *out, size_t size, size_t nmemb, void *userdata)
Encodes fr_pair_t linked list in JSON format.
Definition rest.c:528
#define CURLOPT_TLSAUTH_SRP
Definition rest.c:75
fr_token_t op
The operator that determines how the new VP.
Definition rest.c:226
#define CURLAUTH_BASIC
Definition rest.c:78
fr_table_num_sorted_t const http_method_table[]
Conversion table for method config values.
Definition rest.c:127
void * rest_mod_conn_create(TALLOC_CTX *ctx, void *instance, UNUSED fr_time_delta_t timeout)
Creates a new connection handle for use by the FR connection API.
Definition rest.c:257
size_t rest_get_handle_data(char const **out, fr_curl_io_request_t *randle)
Extracts pointer to buffer containing response data.
Definition rest.c:1619
static bool rest_request_contains_header(fr_curl_io_request_t *randle, char const *header)
See if the list of headers already contains a header.
Definition rest.c:1738
static int json_pair_alloc(rlm_rest_t const *instance, rlm_rest_section_t const *section, request_t *request, json_object *object, UNUSED int level, int max)
Processes JSON response and converts it into multiple fr_pair_ts.
Definition rest.c:982
static void rest_request_init(rlm_rest_section_t const *section, request_t *request, rlm_rest_request_t *ctx)
(Re-)Initialises the data in a rlm_rest_request_t.
Definition rest.c:627
static ssize_t rest_request_encode_wrapper(char **out, UNUSED rlm_rest_t const *inst, rest_read_t func, size_t limit, void *userdata)
Emulates successive libcurl calls to an encoding function.
Definition rest.c:591
static int rest_decode_json(rlm_rest_t const *instance, rlm_rest_section_t const *section, request_t *request, UNUSED fr_curl_io_request_t *randle, char *raw, UNUSED size_t rawlen)
Converts JSON response into fr_pair_ts and adds them to the request.
Definition rest.c:1196
void rest_response_debug(request_t *request, fr_curl_io_request_t *handle)
Print out the response text.
Definition rest.c:1562
#define CURLAUTH_NTLM
Definition rest.c:90
static fr_pair_t * json_pair_alloc_leaf(UNUSED rlm_rest_t const *instance, UNUSED rlm_rest_section_t const *section, TALLOC_CTX *ctx, request_t *request, fr_dict_attr_t const *da, json_flags_t *flags, json_object *leaf)
Converts JSON "value" key into fr_pair_t.
Definition rest.c:846
fr_table_num_sorted_t const http_content_type_table[]
Conversion table for "Content-Type" header values.
Definition rest.c:189
#define SET_AUTH_OPTION(_x, _y)
int is_json
If true value will be inserted as raw JSON.
Definition rest.c:224
const unsigned long http_curl_auth[REST_HTTP_AUTH_NUM_ENTRIES]
Definition rest.c:101
#define CURLAUTH_NTLM_WB
Definition rest.c:93
const http_body_type_t http_body_type_supported[REST_HTTP_BODY_NUM_ENTRIES]
Table of encoder/decoder support.
Definition rest.c:52
#define CURLAUTH_GSSNEGOTIATE
Definition rest.c:87
size_t rest_uri_escape(UNUSED request_t *request, char *out, size_t outlen, char const *raw, UNUSED void *arg)
URL encodes a string.
Definition rest.c:2136
int rest_request_config_add_header(request_t *request, fr_curl_io_request_t *randle, char const *header, bool validate)
Adds an additional header to a handle to use in the next reques.
Definition rest.c:1703
void rest_response_error(request_t *request, fr_curl_io_request_t *handle)
Print out the response text as error lines.
Definition rest.c:1537
size_t http_body_type_table_len
Definition rest.c:159
static int rest_request_config_body(module_ctx_t const *mctx, rlm_rest_section_t const *section, request_t *request, fr_curl_io_request_t *randle, rest_read_t func)
Configures body specific curlopts.
Definition rest.c:1645
static int _mod_conn_free(fr_curl_io_request_t *randle)
Frees a libcurl handle, and any additional memory used by context data.
Definition rest.c:236
static void rest_response_init(rlm_rest_section_t const *section, request_t *request, rlm_rest_response_t *ctx, http_body_type_t type, tmpl_t *header)
(Re-)Initialises the data in a rlm_rest_response_t.
Definition rest.c:1597
static size_t rest_response_body(void *in, size_t size, size_t nmemb, void *userdata)
Processes incoming HTTP body data from libcurl.
Definition rest.c:1457
static size_t rest_encode_post(void *out, size_t size, size_t nmemb, void *userdata)
Encodes fr_pair_t linked list in POST format.
Definition rest.c:351
char const * p
how much text we've sent so far.
Definition rest.c:208
size_t http_auth_table_len
Definition rest.c:173
static size_t rest_response_header(void *in, size_t size, size_t nmemb, void *userdata)
Processes incoming HTTP header data from libcurl.
Definition rest.c:1244
size_t http_content_type_table_len
Definition rest.c:200
#define CURLAUTH_DIGEST
Definition rest.c:81
size_t http_method_table_len
Definition rest.c:135
int rest_response_decode(rlm_rest_t const *instance, rlm_rest_section_t const *section, request_t *request, fr_curl_io_request_t *randle)
Sends the response to the correct decode function.
Definition rest.c:2083
Flags to control the conversion of JSON values to fr_pair_ts.
Definition rest.c:222
Function prototypes and datatypes for the REST (HTTP) transport.
rlm_rest_t const * instance
This instance of rlm_rest.
Definition rest.h:229
read_state_t state
Encoder state.
Definition rest.h:215
HIDDEN fr_dict_attr_t const * attr_rest_http_header
Definition rlm_rest.c:285
http_auth_type_t auth
HTTP auth type.
Definition rest.h:119
struct curl_slist * headers
Any HTTP headers which will be sent with the request.
Definition rest.h:253
tmpl_t * header
Where to create pairs representing HTTP response headers.
Definition rest.h:243
request_t * request
Current request.
Definition rest.h:232
char * buffer
Raw incoming HTTP data.
Definition rest.h:235
int code
HTTP Status Code.
Definition rest.h:239
write_state_t state
Decoder state.
Definition rest.h:233
bool fail_header_decode
Force header decoding to fail for debugging purposes.
Definition rest.h:169
char const * proxy
Send request via this proxy.
Definition rest.h:109
size_t used
Space used in buffer.
Definition rest.h:237
struct rlm_rest_call_env_t::@185 request
http_body_type_t type
HTTP Content Type.
Definition rest.h:240
char * body
Pointer to the buffer which contains body data/ Only used when not performing chunked encoding.
Definition rest.h:256
fr_curl_tls_t tls
Definition rest.h:145
#define REST_BODY_MAX_ATTRS
Definition rest.h:41
bool fail_body_decode
Force body decoding to fail for debugging purposes.
Definition rest.h:170
http_body_type_t force_to
Override the Content-Type header in the response to force decoding as a particular type.
Definition rest.h:128
http_method_t
Definition rest.h:43
@ REST_HTTP_METHOD_PATCH
Definition rest.h:48
@ REST_HTTP_METHOD_DELETE
Definition rest.h:49
@ REST_HTTP_METHOD_PUT
Definition rest.h:47
@ REST_HTTP_METHOD_POST
Definition rest.h:46
@ REST_HTTP_METHOD_UNKNOWN
Definition rest.h:44
@ REST_HTTP_METHOD_CUSTOM
Must always come last, should not be in method table.
Definition rest.h:50
@ REST_HTTP_METHOD_GET
Definition rest.h:45
size_t max_body_in
Maximum size of incoming data.
Definition rest.h:131
fr_dcursor_t cursor
Cursor pointing to the start of the list to encode.
Definition rest.h:217
http_body_type_t force_to
Force decoding the body type as a particular encoding.
Definition rest.h:241
http_body_type_t
Definition rest.h:53
@ REST_HTTP_BODY_HTML
Definition rest.h:64
@ REST_HTTP_BODY_PLAIN
Definition rest.h:65
@ REST_HTTP_BODY_JSON
Definition rest.h:61
@ REST_HTTP_BODY_INVALID
Definition rest.h:57
@ REST_HTTP_BODY_XML
Definition rest.h:62
@ REST_HTTP_BODY_UNSUPPORTED
Definition rest.h:55
@ REST_HTTP_BODY_YAML
Definition rest.h:63
@ REST_HTTP_BODY_POST
Definition rest.h:60
@ REST_HTTP_BODY_CUSTOM
Definition rest.h:59
@ REST_HTTP_BODY_NUM_ENTRIES
Definition rest.h:66
@ REST_HTTP_BODY_UNKNOWN
Definition rest.h:54
@ REST_HTTP_BODY_NONE
Definition rest.h:58
@ REST_HTTP_BODY_UNAVAILABLE
Definition rest.h:56
char const * method_str
The string version of the HTTP method.
Definition rest.h:111
@ READ_STATE_ATTR_CONT
Definition rest.h:193
@ READ_STATE_ATTR_BEGIN
Definition rest.h:192
@ READ_STATE_END
Definition rest.h:194
@ READ_STATE_INIT
Definition rest.h:191
rlm_rest_section_t const * section
Section configuration.
Definition rest.h:230
char const * body_str
The string version of the encoding/content type.
Definition rest.h:114
#define REST_BODY_ALLOC_CHUNK
Definition rest.h:40
struct rlm_rest_call_env_t::@186 response
HIDDEN fr_dict_attr_t const * attr_rest_http_body
Definition rlm_rest.c:284
rlm_rest_section_request_t request
Request configuration.
Definition rest.h:142
rlm_rest_response_t response
Response context data.
Definition rest.h:260
size_t(* rest_read_t)(void *ptr, size_t size, size_t nmemb, void *userdata)
Definition rest.h:295
#define REST_BODY_MAX_LEN
Definition rest.h:39
rlm_rest_section_t const * section
Section configuration.
Definition rest.h:212
void * encoder
Encoder specific data.
Definition rest.h:221
rlm_rest_request_t request
Request context data.
Definition rest.h:259
rlm_rest_section_response_t response
Response configuration.
Definition rest.h:143
fr_time_delta_t timeout
Timeout timeval.
Definition rest.h:140
@ WRITE_STATE_INIT
Definition rest.h:201
@ WRITE_STATE_PARSE_HEADERS
Definition rest.h:202
@ WRITE_STATE_PARSE_CONTENT
Definition rest.h:203
char const * name
Section name.
Definition rest.h:138
http_auth_type_t
Definition rest.h:69
@ REST_HTTP_AUTH_NTLM_WB
Definition rest.h:78
@ REST_HTTP_AUTH_NUM_ENTRIES
Definition rest.h:81
@ REST_HTTP_AUTH_BASIC
Definition rest.h:73
@ REST_HTTP_AUTH_NTLM
Definition rest.h:77
@ REST_HTTP_AUTH_DIGEST
Definition rest.h:74
@ REST_HTTP_AUTH_TLS_SRP
Definition rest.h:72
@ REST_HTTP_AUTH_UNKNOWN
Definition rest.h:70
@ REST_HTTP_AUTH_GSSNEGOTIATE
Definition rest.h:76
@ REST_HTTP_AUTH_ANY
Definition rest.h:79
@ REST_HTTP_AUTH_NONE
Definition rest.h:71
@ REST_HTTP_AUTH_DIGEST_IE
Definition rest.h:75
@ REST_HTTP_AUTH_ANY_SAFE
Definition rest.h:80
size_t alloc
Space allocated for buffer.
Definition rest.h:236
request_t * request
Current request.
Definition rest.h:214
rlm_rest_t const * instance
This instance of rlm_rest.
Definition rest.h:211
char const * rest_no_proxy
Magic pointer value for determining if we should disable proxying.
Definition rlm_rest.c:95
uint32_t chunk
Max chunk-size (mainly for testing the encoders)
Definition rest.h:123
size_t chunk
Chunk size.
Definition rest.h:219
static char const * name
#define FR_SBUFF_OUT(_start, _len_or_end)
void * data
Module's instance data.
Definition module.h:272
static fr_dict_attr_t const * tmpl_list(tmpl_t const *vpt)
Definition tmpl.h:904
ssize_t tmpl_afrom_attr_str(TALLOC_CTX *ctx, tmpl_attr_error_t *err, tmpl_t **out, char const *name, tmpl_rules_t const *rules))
Parse a string into a TMPL_TYPE_ATTR_* type tmpl_t.
fr_pair_list_t * tmpl_list_head(request_t *request, fr_dict_attr_t const *list)
Resolve attribute fr_pair_list_t value to an attribute list.
Definition tmpl_eval.c:70
TALLOC_CTX * tmpl_list_ctx(request_t *request, fr_dict_attr_t const *list)
Return the correct TALLOC_CTX to alloc fr_pair_t in, for a list.
Definition tmpl_eval.c:110
int tmpl_request_ptr(request_t **request, FR_DLIST_HEAD(tmpl_request_list) const *rql)
Resolve a tmpl_request_ref_t to a request_t.
Definition tmpl_eval.c:163
static fr_dict_attr_t const * tmpl_attr_tail_da(tmpl_t const *vpt)
Return the last attribute reference da.
Definition tmpl.h:801
static char const * tmpl_list_name(fr_dict_attr_t const *list, char const *def)
Return the name of a tmpl list or def if list not provided.
Definition tmpl.h:915
Optional arguments passed to vp_tmpl functions.
Definition tmpl.h:332
static char buff[sizeof("18446744073709551615")+3]
Definition size_tests.c:41
#define fr_skip_whitespace(_p)
Skip whitespace ('\t', '\n', '\v', '\f', '\r', ' ')
Definition skip.h:37
PUBLIC int snprintf(char *string, size_t length, char *format, va_alist)
Definition snprintf.c:689
return count
Definition module.c:155
eap_aka_sim_process_conf_t * inst
fr_aka_sim_id_type_t type
fr_pair_t * vp
size_t strlcpy(char *dst, char const *src, size_t siz)
Definition strlcpy.c:34
Stores an attribute, a value and various bits of other data.
Definition pair.h:68
fr_dict_attr_t const *_CONST da
Dictionary attribute defines the attribute number, vendor and type of the pair.
Definition pair.h:69
#define fr_table_value_by_str(_table, _name, _def)
Convert a string to a value using a sorted or ordered table.
Definition table.h:653
#define fr_table_str_by_value(_table, _number, _def)
Convert an integer to a string.
Definition table.h:772
#define fr_table_value_by_substr(_table, _name, _name_len, _def)
Convert a partial string to a value using an ordered or sorted table.
Definition table.h:693
An element in a lexicographically sorted array of name to num mappings.
Definition table.h:49
char * talloc_bstr_realloc(TALLOC_CTX *ctx, char *in, size_t inlen)
Trim a bstr (char) buffer.
Definition talloc.c:650
char * talloc_typed_asprintf(TALLOC_CTX *ctx, char const *fmt,...)
Call talloc vasprintf, setting the type on the new chunk correctly.
Definition talloc.c:514
Functions which we wish were included in the standard talloc distribution.
#define talloc_get_type_abort_const
Definition talloc.h:287
static size_t talloc_strlen(char const *s)
Returns the length of a talloc array containing a string.
Definition talloc.h:294
Simple time functions.
static int64_t fr_time_delta_to_msec(fr_time_delta_t delta)
Definition time.h:637
A time delta, a difference in time measured in nanoseconds.
Definition time.h:80
fr_table_num_ordered_t const fr_tokens_table[]
Definition token.c:34
enum fr_token fr_token_t
@ T_BARE_WORD
Definition token.h:120
@ T_OP_EQ
Definition token.h:83
@ T_OP_SET
Definition token.h:84
@ T_OP_ADD_EQ
Definition token.h:69
ssize_t xlat_aeval(TALLOC_CTX *ctx, char **out, request_t *request, char const *fmt, xlat_escape_legacy_t escape, void const *escape_ctx))
Definition xlat_eval.c:1795
#define fr_pair_dcursor_by_da_init(_cursor, _list, _da)
Initialise a cursor that will return only attributes matching the specified fr_dict_attr_t.
Definition pair.h:628
ssize_t fr_pair_print_value_quoted(fr_sbuff_t *out, fr_pair_t const *vp, fr_token_t quote)
Print the value of an attribute to a string.
Definition pair_print.c:53
#define fr_pair_dcursor_init(_cursor, _list)
Initialises a special dcursor with callbacks that will maintain the attr sublists correctly.
Definition pair.h:591
static char const * fr_type_to_str(fr_type_t type)
Return a static string containing the type name.
Definition types.h:450
int fr_value_box_cast(TALLOC_CTX *ctx, fr_value_box_t *dst, fr_type_t dst_type, fr_dict_attr_t const *dst_enumv, fr_value_box_t const *src)
Convert one type of fr_value_box_t to another.
Definition value.c:3574
void fr_value_box_strdup_shallow(fr_value_box_t *dst, fr_dict_attr_t const *enumv, char const *src, bool tainted)
Assign a buffer containing a nul terminated string to a box, but don't copy it.
Definition value.c:4267
void fr_value_box_bstrndup_shallow(fr_value_box_t *dst, fr_dict_attr_t const *enumv, char const *src, size_t len, bool tainted)
Assign a string to to a fr_value_box_t.
Definition value.c:4463
static fr_slen_t data
Definition value.h:1288
#define FR_VALUE_BOX_INITIALISER_NULL(_vb)
A static initialiser for stack/globally allocated boxes.
Definition value.h:507
#define fr_box_strvalue_len(_val, _len)
Definition value.h:305
#define fr_value_box_init_null(_vb)
Initialise an empty/null box that will be filled later.
Definition value.h:612
#define fr_box_strvalue(_val)
Definition value.h:304
#define fr_box_time_delta(_val)
Definition value.h:362
#define fr_value_box(_box, _var, _tainted)
Automagically fill in a box, determining the value type from the type of the C variable.
Definition value.h:894
#define fr_value_box_list_foreach(_list_head, _iter)
Definition value.h:222
static size_t char ** out
Definition value.h:1020