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.
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.
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
18 * @brief Functions and datatypes for the REST (HTTP) transport.
22 * @copyright 2012-2013 Arran Cudbard-Bell <a.cudbard-bell@freeradius.org>
25 #include <freeradius-devel/ident.h>
33 #include <freeradius-devel/radiusd.h>
34 #include <freeradius-devel/libradius.h>
35 #include <freeradius-devel/connection.h>
39 /** Table of encoder/decoder support.
41 * Indexes in this table match the http_body_type_t enum, and should be
42 * updated if additional enum values are added.
44 * @see http_body_type_t
46 const http_body_type_t http_body_type_supported[HTTP_BODY_NUM_ENTRIES] = {
47 HTTP_BODY_UNSUPPORTED, // HTTP_BODY_UNKOWN
48 HTTP_BODY_UNSUPPORTED, // HTTP_BODY_UNSUPPORTED
49 HTTP_BODY_UNSUPPORTED, // HTTP_BODY_INVALID
50 HTTP_BODY_POST, // HTTP_BODY_POST
52 HTTP_BODY_JSON, // HTTP_BODY_JSON
54 HTTP_BODY_UNAVAILABLE,
56 HTTP_BODY_UNSUPPORTED, // HTTP_BODY_XML
57 HTTP_BODY_UNSUPPORTED, // HTTP_BODY_YAML
58 HTTP_BODY_INVALID, // HTTP_BODY_HTML
59 HTTP_BODY_INVALID // HTTP_BODY_PLAIN
63 * Lib CURL doesn't define symbols for unsupported auth methods
65 #ifndef CURLOPT_TLSAUTH_SRP
66 #define CURLOPT_TLSAUTH_SRP 0
68 #ifndef CURLAUTH_BASIC
69 #define CURLAUTH_BASIC 0
71 #ifndef CURLAUTH_DIGEST
72 #define CURLAUTH_DIGEST 0
74 #ifndef CURLAUTH_DIGEST_IE
75 #define CURLAUTH_DIGEST_IE 0
77 #ifndef CURLAUTH_GSSNEGOTIATE
78 #define CURLAUTH_GSSNEGOTIATE 0
81 #define CURLAUTH_NTLM 0
83 #ifndef CURLAUTH_NTLM_WB
84 #define CURLAUTH_NTLM_WB 0
87 const http_body_type_t http_curl_auth[HTTP_AUTH_NUM_ENTRIES] = {
88 0, // HTTP_AUTH_UNKNOWN
90 CURLOPT_TLSAUTH_SRP, // HTTP_AUTH_TLS_SRP
91 CURLAUTH_BASIC, // HTTP_AUTH_BASIC
92 CURLAUTH_DIGEST, // HTTP_AUTH_DIGEST
93 CURLAUTH_DIGEST_IE, // HTTP_AUTH_DIGEST_IE
94 CURLAUTH_GSSNEGOTIATE, // HTTP_AUTH_GSSNEGOTIATE
95 CURLAUTH_NTLM, // HTTP_AUTH_NTLM
96 CURLAUTH_NTLM_WB, // HTTP_AUTH_NTLM_WB
97 CURLAUTH_ANY, // HTTP_AUTH_ANY
98 CURLAUTH_ANYSAFE // HTTP_AUTH_ANY_SAFE
102 /** Conversion table for method config values.
104 * HTTP verb strings for http_method_t enum values. Used by libcurl in the
105 * status line of the outgoing HTTP header, by rest_write_header for decoding
106 * incoming HTTP responses, and by the configuration parser.
112 const FR_NAME_NUMBER http_method_table[] = {
113 { "GET", HTTP_METHOD_GET },
114 { "POST", HTTP_METHOD_POST },
115 { "PUT", HTTP_METHOD_PUT },
116 { "DELETE", HTTP_METHOD_DELETE },
121 /** Conversion table for type config values.
123 * Textual names for http_body_type_t enum values, used by the
124 * configuration parser.
126 * @see http_body_Type_t
130 const FR_NAME_NUMBER http_body_type_table[] = {
131 { "unknown", HTTP_BODY_UNKNOWN },
132 { "unsupported", HTTP_BODY_UNSUPPORTED },
133 { "unavailable", HTTP_BODY_UNAVAILABLE },
134 { "invalid", HTTP_BODY_INVALID },
135 { "post", HTTP_BODY_POST },
136 { "json", HTTP_BODY_JSON },
137 { "xml", HTTP_BODY_XML },
138 { "yaml", HTTP_BODY_YAML },
139 { "html", HTTP_BODY_HTML },
140 { "plain", HTTP_BODY_PLAIN },
145 const FR_NAME_NUMBER http_auth_table[] = {
146 { "none", HTTP_AUTH_NONE },
147 { "srp", HTTP_AUTH_TLS_SRP },
148 { "basic", HTTP_AUTH_BASIC },
149 { "digest", HTTP_AUTH_DIGEST },
150 { "digest-ie", HTTP_AUTH_DIGEST_IE },
151 { "gss-negotiate", HTTP_AUTH_GSSNEGOTIATE },
152 { "ntlm", HTTP_AUTH_NTLM },
153 { "ntlm-winbind", HTTP_AUTH_NTLM_WB },
154 { "any", HTTP_AUTH_ANY },
155 { "safe", HTTP_AUTH_ANY_SAFE },
160 /** Conversion table for "Content-Type" header values.
162 * Used by rest_write_header for parsing incoming headers.
164 * Values we expect to see in the 'Content-Type:' header of the incoming
167 * Some data types (like YAML) do no have standard MIME types defined,
168 * so multiple types, are listed here.
170 * @see http_body_Type_t
174 const FR_NAME_NUMBER http_content_type_table[] = {
175 { "application/x-www-form-urlencoded", HTTP_BODY_POST },
176 { "application/json", HTTP_BODY_JSON },
177 { "text/html", HTTP_BODY_HTML },
178 { "text/plain", HTTP_BODY_PLAIN },
179 { "text/xml", HTTP_BODY_XML },
180 { "text/yaml", HTTP_BODY_YAML },
181 { "text/x-yaml", HTTP_BODY_YAML },
182 { "application/yaml", HTTP_BODY_YAML },
183 { "application/x-yaml", HTTP_BODY_YAML },
188 /** Flags to control the conversion of JSON values to VALUE_PAIRs.
190 * These fields are set when parsing the expanded format for value pairs in
191 * JSON, and control how json_pairmake_leaf and json_pairmake convert the JSON
192 * value, and move the new VALUE_PAIR into an attribute list.
195 * @see json_pairmake_leaf
197 typedef struct json_flags {
198 boolean do_xlat; //!< If TRUE value will be expanded with xlat.
199 boolean is_json; //!< If TRUE value will be inserted as raw JSON
200 // (multiple values not supported).
201 FR_TOKEN operator; //!< The operator that determines how the new VP
202 // is processed. @see fr_tokens
206 /** Initialises libcurl.
208 * Allocates global variables and memory required for libcurl to fundtion.
209 * MUST only be called once per module instance.
211 * rest_cleanup must not be called if rest_init fails.
215 * @param[in] instance configuration data.
216 * @return TRUE if init succeeded FALSE if it failed.
218 int rest_init(rlm_rest_t *instance)
222 ret = curl_global_init(CURL_GLOBAL_ALL);
223 if (ret != CURLE_OK) {
225 "rlm_rest (%s): CURL init returned error: %i - %s",
227 ret, curl_easy_strerror(ret));
229 curl_global_cleanup();
233 radlog(L_DBG, "rlm_rest (%s): CURL library version: %s",
240 /** Cleans up after libcurl.
242 * Wrapper around curl_global_cleanup, frees any memory allocated by rest_init.
243 * Must only be called once per call of rest_init.
247 void rest_cleanup(void)
249 curl_global_cleanup();
252 /** Creates a new connection handle for use by the FR connection API.
254 * Matches the fr_connection_create_t function prototype, is passed to
255 * fr_connection_pool_init, and called when a new connection is required by the
256 * connection pool API.
258 * Creates an instances of rlm_rest_handle_t, and rlm_rest_curl_context_t
259 * which hold the context data required for generating requests and parsing
260 * responses. Calling rest_socket_delete will free this memory.
262 * If instance->connect_uri is not NULL libcurl will attempt to open a
263 * TCP socket to the server specified in the URI. This is done so that when the
264 * socket is first used, there will already be a cached TCP connection to the
265 * REST server associated with the curl handle.
267 * @see rest_socket_delete
268 * @see fr_connection_pool_init
269 * @see fr_connection_create_t
272 * @param[in] instance configuration data.
273 * @return connection handle or NULL if the connection failed or couldn't
276 void *rest_socket_create(void *instance)
278 rlm_rest_t *inst = instance;
280 rlm_rest_handle_t *randle;
281 rlm_rest_curl_context_t *ctx;
283 CURL *candle = curl_easy_init();
287 radlog(L_ERR, "rlm_rest (%s): Failed to create CURL handle",
292 if (!*inst->connect_uri) {
293 radlog(L_ERR, "rlm_rest (%s): Skipping pre-connect,"
294 " connect_uri not specified", inst->xlat_name);
299 * Pre-establish TCP connection to webserver. This would usually be
300 * done on the first request, but we do it here to minimise
303 ret = curl_easy_setopt(candle, CURLOPT_CONNECT_ONLY, 1);
304 if (ret != CURLE_OK) goto error;
306 ret = curl_easy_setopt(candle, CURLOPT_URL,
308 if (ret != CURLE_OK) goto error;
310 radlog(L_DBG, "rlm_rest (%s): Connecting to \"%s\"",
314 ret = curl_easy_perform(candle);
315 if (ret != CURLE_OK) {
316 radlog(L_ERR, "rlm_rest (%s): Connection failed: %i - %s",
318 ret, curl_easy_strerror(ret));
320 goto connection_error;
324 * Malloc memory for the connection handle abstraction.
326 randle = malloc(sizeof(*randle));
327 memset(randle, 0, sizeof(*randle));
329 ctx = malloc(sizeof(*ctx));
330 memset(ctx, 0, sizeof(*ctx));
332 ctx->headers = NULL; /* CURL needs this to be NULL */
333 ctx->read.instance = inst;
336 randle->handle = candle;
339 * Clear any previously configured options for the first request.
341 curl_easy_reset(candle);
346 * Cleanup for error conditions.
350 radlog(L_ERR, "rlm_rest (%s): Failed setting curl option: %i - %s",
352 ret, curl_easy_strerror(ret));
355 * So we don't leak CURL handles.
359 curl_easy_cleanup(candle);
364 /** Verifies that the last TCP socket associated with a handle is still active.
366 * Quieries libcurl to try and determine if the TCP socket associated with a
367 * connection handle is still viable.
369 * @param[in] instance configuration data.
370 * @param[in] handle to check.
371 * @returns FALSE if the last socket is dead, or if the socket state couldn't be
372 * determined, else TRUE.
374 int rest_socket_alive(void *instance, void *handle)
376 rlm_rest_t *inst = instance;
377 rlm_rest_handle_t *randle = handle;
378 CURL *candle = randle->handle;
383 curl_easy_getinfo(candle, CURLINFO_LASTSOCKET, &last_socket);
384 if (ret != CURLE_OK) {
386 "rlm_rest (%s): Couldn't determine socket"
387 " state: %i - %s", inst->xlat_name, ret,
388 curl_easy_strerror(ret));
393 if (last_socket == -1) {
400 /** Frees a libcurl handle, and any additional memory used by context data.
402 * @param[in] instance configuration data.
403 * @param[in] handle rlm_rest_handle_t to close and free.
404 * @return returns TRUE.
406 int rest_socket_delete(UNUSED void *instance, void *handle)
408 rlm_rest_handle_t *randle = handle;
409 CURL *candle = randle->handle;
411 curl_easy_cleanup(candle);
419 /** Encodes VALUE_PAIR linked list in POST format
421 * This is a stream function matching the rest_read_t prototype. Multiple
422 * successive calls will return additional encoded VALUE_PAIRs.
423 * Only complete attribute headers @verbatim '<name>=' @endverbatim and values
424 * will be written to the ptr buffer.
426 * POST request format is:
427 * @verbatim <attribute0>=<value0>&<attribute1>=<value1>&<attributeN>=<valueN>@endverbatim
429 * All attributes and values are url encoded. There is currently no support for
430 * nested attributes, or attribute qualifiers.
432 * Nested attributes may be added in the future using
433 * @verbatim <attribute-outer>:<attribute-inner>@endverbatim
434 * to denotate nesting.
436 * Requires libcurl for url encoding.
438 * @see rest_decode_post
440 * @param[out] ptr Char buffer to write encoded data to.
441 * @param[in] size Multiply by nmemb to get the length of ptr.
442 * @param[in] nmemb Multiply by size to get the length of ptr.
443 * @param[in] userdata rlm_rest_read_t to keep encoding state between calls.
444 * @return length of data (including NULL) written to ptr, or 0 if no more
447 static size_t rest_encode_post(void *ptr, size_t size, size_t nmemb,
450 rlm_rest_read_t *ctx = userdata;
451 REQUEST *request = ctx->request; /* Used by RDEBUG */
452 VALUE_PAIR **current = ctx->next;
454 char *p = ptr; /* Position in buffer */
455 char *f = ptr; /* Position in buffer of last fully encoded attribute or value */
456 char *escaped; /* Pointer to current URL escaped data */
459 ssize_t s = (size * nmemb) - 1;
461 /* Allow manual chunking */
462 if ((ctx->chunk) && (ctx->chunk <= s)) {
463 s = (ctx->chunk - 1);
466 if (ctx->state == READ_STATE_END) return FALSE;
468 /* Post data requires no headers */
469 if (ctx->state == READ_STATE_INIT) {
470 ctx->state = READ_STATE_ATTR_BEGIN;
475 ctx->state = READ_STATE_END;
480 RDEBUG2("Encoding attribute \"%s\"", current[0]->name);
482 if (ctx->state == READ_STATE_ATTR_BEGIN) {
483 escaped = curl_escape(current[0]->name,
484 strlen(current[0]->name));
485 len = strlen(escaped);
492 len = sprintf(p, "%s=", escaped);
500 * We wrote the attribute header, record progress.
503 ctx->state = READ_STATE_ATTR_CONT;
507 * Write out single attribute string.
509 len = vp_prints_value(p , s, current[0], 0);
510 escaped = curl_escape(p, len);
511 len = strlen(escaped);
518 len = strlcpy(p, escaped, len + 1);
522 RDEBUG("\tLength : %i", len);
523 RDEBUG("\tValue : %s", p);
529 if (!--s) goto no_space;
534 * We wrote one full attribute value pair, record progress.
538 ctx->state = READ_STATE_ATTR_BEGIN;
545 len = p - (char*)ptr;
547 RDEBUG2("POST Data: %s", (char*) ptr);
548 RDEBUG2("Returning %i bytes of POST data", len);
553 * Cleanup for error conditions
559 len = f - (char*)ptr;
561 RDEBUG2("POST Data: %s", (char*) ptr);
564 * The buffer wasn't big enough to encode a single attribute chunk.
567 radlog(L_ERR, "rlm_rest (%s): AVP exceeds buffer length"
568 " or chunk", ctx->instance->xlat_name);
570 RDEBUG2("Returning %i bytes of POST data"
571 " (buffer full or chunk exceeded)", len);
577 /** Encodes VALUE_PAIR linked list in JSON format
579 * This is a stream function matching the rest_read_t prototype. Multiple
580 * successive calls will return additional encoded VALUE_PAIRs.
582 * Only complete attribute headers
583 * @verbatim "<name>":{"type":"<type>","value":[' @endverbatim
584 * and complete attribute values will be written to ptr.
586 * If an attribute occurs multiple times in the request the attribute values
587 * will be concatenated into a single value array.
589 * JSON request format is:
594 "value":[<value0>,<value1>,<valueN>]
607 * @param[out] ptr Char buffer to write encoded data to.
608 * @param[in] size Multiply by nmemb to get the length of ptr.
609 * @param[in] nmemb Multiply by size to get the length of ptr.
610 * @param[in] userdata rlm_rest_read_t to keep encoding state between calls.
611 * @return length of data (including NULL) written to ptr, or 0 if no more
614 static size_t rest_encode_json(void *ptr, size_t size, size_t nmemb,
617 rlm_rest_read_t *ctx = userdata;
618 REQUEST *request = ctx->request; /* Used by RDEBUG */
619 VALUE_PAIR **current = ctx->next;
621 char *p = ptr; /* Position in buffer */
622 char *f = ptr; /* Position in buffer of last fully encoded attribute or value */
627 ssize_t s = (size * nmemb) - 1;
631 /* Allow manual chunking */
632 if ((ctx->chunk) && (ctx->chunk <= s)) {
633 s = (ctx->chunk - 1);
636 if (ctx->state == READ_STATE_END) return FALSE;
638 if (ctx->state == READ_STATE_INIT) {
639 ctx->state = READ_STATE_ATTR_BEGIN;
641 if (!--s) goto no_space;
647 ctx->state = READ_STATE_END;
649 if (!--s) goto no_space;
656 * New attribute, write name, type, and beginning of
659 RDEBUG2("Encoding attribute \"%s\"", current[0]->name);
660 if (ctx->state == READ_STATE_ATTR_BEGIN) {
661 type = fr_int2str(dict_attr_types, current[0]->type,
665 len += strlen(current[0]->name);
667 if (s < (23 + len)) goto no_space;
669 len = sprintf(p, "\"%s\":{\"type\":\"%s\",\"value\":[" ,
670 current[0]->name, type);
674 RDEBUG2("\tType : %s", type);
677 * We wrote the attribute header, record progress
680 ctx->state = READ_STATE_ATTR_CONT;
684 * Put all attribute values in an array for easier remote
685 * parsing whether they're multivalued or not.
688 len = vp_prints_value_json(p , s, current[0]);
689 assert((s - len) >= 0);
691 if (len < 0) goto no_space;
694 * Show actual value length minus quotes
696 RDEBUG2("\tLength : %i", (*p == '"') ? (len - 2) : len);
697 RDEBUG2("\tValue : %s", p);
703 * Multivalued attribute
706 ((current[0]->attribute == current[1]->attribute) &&
707 (current[0]->vendor == current[1]->vendor))) {
712 * We wrote one attribute value, record
722 if (!(s -= 2)) goto no_space;
727 if (!--s) goto no_space;
732 * We wrote one full attribute value pair, record progress.
736 ctx->state = READ_STATE_ATTR_BEGIN;
743 len = p - (char*)ptr;
745 RDEBUG2("JSON Data: %s", (char*) ptr);
746 RDEBUG2("Returning %i bytes of JSON data", len);
751 * Were out of buffer space
757 len = f - (char*)ptr;
759 RDEBUG2("JSON Data: %s", (char*) ptr);
762 * The buffer wasn't big enough to encode a single attribute chunk.
765 radlog(L_ERR, "rlm_rest (%s): AVP exceeds buffer length"
766 " or chunk", ctx->instance->xlat_name);
768 RDEBUG2("Returning %i bytes of JSON data"
769 " (buffer full or chunk exceeded)", len);
775 /** Emulates successive libcurl calls to an encoding function
777 * This function is used when the request will be sent to the HTTP server as one
778 * contiguous entity. A buffer of REST_BODY_INCR bytes is allocated and passed
779 * to the stream encoding function.
781 * If the stream function does not return 0, a new buffer is allocated which is
782 * the size of the previous buffer + REST_BODY_INCR bytes, the data from the
783 * previous buffer is copied, and freed, and another call is made to the stream
784 * function, passing a pointer into the new buffer at the end of the previously
787 * This process continues until the stream function signals (by returning 0)
788 * that it has no more data to write.
790 * @param[out] buffer where the pointer to the malloced buffer should
792 * @param[in] func Stream function.
793 * @param[in] limit Maximum buffer size to alloc.
794 * @param[in] userdata rlm_rest_read_t to keep encoding state between calls to
796 * @return the length of the data written to the buffer (excluding NULL) or -1
799 static ssize_t rest_read_wrapper(char **buffer, rest_read_t func,
800 size_t limit, void *userdata)
802 char *previous = NULL;
805 size_t alloc = REST_BODY_INCR; /* Size of buffer to malloc */
806 size_t used = 0; /* Size of data written */
809 while (alloc < limit) {
810 current = rad_malloc(alloc);
813 strlcpy(current, previous, used + 1);
817 len = func(current + used, REST_BODY_INCR, 1, userdata);
824 alloc += REST_BODY_INCR;
833 /** (Re-)Initialises the data in a rlm_rest_read_t.
835 * Resets the values of a rlm_rest_read_t to their defaults.
837 * Must be called between encoding sessions.
839 * As part of initialisation all VALUE_PAIR pointers in the REQUEST packet are
840 * written to an array.
842 * If sort is TRUE, this array of VALUE_PAIR pointers will be sorted by vendor
843 * and then by attribute. This is for stream encoders which may concatenate
844 * multiple attribute values together into an array.
846 * After the encoding session has completed this array must be freed by calling
847 * rest_read_ctx_free .
849 * @see rest_read_ctx_free
851 * @param[in] request Current request.
852 * @param[in] ctx to initialise.
853 * @param[in] sort If TRUE VALUE_PAIRs will be sorted within the VALUE_PAIR
856 static void rest_read_ctx_init(REQUEST *request,
857 rlm_rest_read_t *ctx,
860 unsigned short count = 0, i;
863 VALUE_PAIR **current, *tmp;
866 * Setup stream read data
868 ctx->request = request;
869 ctx->state = READ_STATE_INIT;
872 * Create sorted array of VP pointers
874 tmp = request->packet->vps;
875 while (tmp != NULL) {
880 ctx->first = current = rad_malloc((sizeof(tmp) * (count + 1)));
881 ctx->next = ctx->first;
883 tmp = request->packet->vps;
884 while (tmp != NULL) {
889 current = ctx->first;
891 if (!sort || (count < 2)) return;
893 /* TODO: Quicksort would be faster... */
895 for(i = 1; i < count; i++) {
896 assert(current[i-1]->attribute &&
897 current[i]->attribute);
900 if ((current[i-1]->vendor > current[i]->vendor) ||
901 ((current[i-1]->vendor == current[i]->vendor) &&
902 (current[i-1]->attribute > current[i]->attribute)
905 current[i] = current[i-1];
913 /** Frees the VALUE_PAIR array created by rest_read_ctx_init.
915 * Must be called between encoding sessions else module will leak VALUE_PAIR
918 * @see rest_read_ctx_init
920 * @param[in] ctx to free.
922 static void rest_read_ctx_free(rlm_rest_read_t *ctx)
924 if (ctx->first != NULL) {
929 /** Verify that value wasn't truncated when it was converted to a VALUE_PAIR
931 * Certain values may be truncated when they're converted into VALUE_PAIRs
932 * for example 64bit integers converted to 32bit integers. Warn the user
935 * @param[in] request Current request.
936 * @param[in] raw string from decoder.
937 * @param[in] vp containing parsed value.
939 static void rest_check_truncation(REQUEST *request, const char *raw,
944 vp_prints_value(cooked, sizeof(cooked), vp, 0);
945 if (strcmp(raw, cooked) != 0) {
946 RDEBUG("WARNING: Value-Pair does not match POST value, "
947 "truncation may have occurred");
948 RDEBUG("\tValue (pair) : \"%s\"", cooked);
949 RDEBUG("\tValue (post) : \"%s\"", raw);
953 /** Converts POST response into VALUE_PAIRs and adds them to the request
955 * Accepts VALUE_PAIRS in the same format as rest_encode_post, but with the
956 * addition of optional attribute list qualifiers as part of the attribute name
959 * If no qualifiers are specified, will default to the request list.
961 * POST response format is:
962 * @verbatim [outer.][<list>:]<attribute0>=<value0>&[outer.][<list>:]<attribute1>=<value1>&[outer.][<list>:]<attributeN>=<valueN> @endverbatim
964 * @see rest_encode_post
966 * @param[in] instance configuration data.
967 * @param[in] section configuration data.
968 * @param[in] handle rlm_rest_handle_t to use.
969 * @param[in] request Current request.
970 * @param[in] raw buffer containing POST data.
971 * @param[in] rawlen Length of data in raw buffer.
972 * @return the number of VALUE_PAIRs processed or -1 on unrecoverable error.
974 static int rest_decode_post(rlm_rest_t *instance,
975 UNUSED rlm_rest_section_t *section,
976 REQUEST *request, void *handle, char *raw,
977 UNUSED size_t rawlen)
979 rlm_rest_handle_t *randle = handle;
980 CURL *candle = randle->handle;
982 const char *p = raw, *q;
984 const char *attribute;
991 const DICT_ATTR **current, *processed[REST_BODY_MAX_ATTRS + 1];
994 pair_lists_t list_name;
995 request_refs_t request_name;
996 REQUEST *reference = request;
1000 int curl_len; /* Length from last curl_easy_unescape call */
1004 processed[0] = NULL;
1009 while (isspace(*p)) p++;
1010 if (*p == '\0') return FALSE;
1012 while (((q = strchr(p, '=')) != NULL) &&
1013 (count < REST_BODY_MAX_ATTRS)) {
1015 reference = request;
1017 name = curl_easy_unescape(candle, p, (q - p), &curl_len);
1020 RDEBUG("Decoding attribute \"%s\"", name);
1022 request_name = radius_request_name(&attribute, REQUEST_CURRENT);
1023 if (request_name == REQUEST_UNKNOWN) {
1024 RDEBUG("WARNING: Invalid request qualifier, skipping");
1031 if (!radius_request(&reference, request_name)) {
1032 RDEBUG("WARNING: Attribute name refers to outer request"
1033 " but not in a tunnel, skipping");
1040 list_name = radius_list_name(&attribute, PAIR_LIST_REPLY);
1041 if (list_name == PAIR_LIST_UNKNOWN) {
1042 RDEBUG("WARNING: Invalid list qualifier, skipping");
1049 da = dict_attrbyname(attribute);
1051 RDEBUG("WARNING: Attribute \"%s\" unknown, skipping",
1059 vps = radius_list(reference, list_name);
1063 RDEBUG2("\tType : %s", fr_int2str(dict_attr_types, da->type,
1067 len = (q == NULL) ? (rawlen - (p - raw)) : (unsigned)(q - p);
1069 value = curl_easy_unescape(candle, p, len, &curl_len);
1072 * If we found a delimiter we want to skip over it,
1073 * if we didn't we do *NOT* want to skip over the end
1076 p += (q == NULL) ? len : (len + 1);
1078 RDEBUG2("\tLength : %i", curl_len);
1079 RDEBUG2("\tValue : \"%s\"", value);
1081 vp = paircreate(da->attr, da->vendor, da->type);
1083 radlog(L_ERR, "rlm_rest (%s): Failed creating"
1084 " value-pair", instance->xlat_name);
1089 vp->operator = T_OP_SET;
1092 * Check to see if we've already processed an
1093 * attribute of the same type if we have, change the op
1094 * from T_OP_ADD to T_OP_SET.
1096 current = processed;
1097 while (*current++) {
1098 if ((current[0]->attr == da->attr) &&
1099 (current[0]->vendor == da->vendor)) {
1100 vp->operator = T_OP_ADD;
1105 if (vp->operator != T_OP_ADD) {
1110 tmp = pairparsevalue(vp, value);
1112 RDEBUG("Incompatible value assignment, skipping");
1118 rest_check_truncation(request, value, vp);
1120 vp->flags.do_xlat = 1;
1122 RDEBUG("Performing xlat expansion of response value", value);
1123 pairxlatmove(request, vps, &vp);
1125 if (++count == REST_BODY_MAX_ATTRS) {
1126 radlog(L_ERR, "rlm_rest (%s): At maximum"
1127 " attribute limit", instance->xlat_name);
1147 radlog(L_ERR, "rlm_rest (%s): Malformed POST data \"%s\"",
1148 instance->xlat_name, raw);
1156 /** Converts JSON "value" key into VALUE_PAIR.
1158 * If leaf is not in fact a leaf node, but contains JSON data, the data will
1159 * written to the attribute in JSON string format.
1161 * @param[in] instance configuration data.
1162 * @param[in] section configuration data.
1163 * @param[in] request Current request.
1164 * @param[in] da Attribute to create.
1165 * @param[in] flags containing the operator other flags controlling value
1167 * @param[in] leaf object containing the VALUE_PAIR value.
1168 * @return The VALUE_PAIR just created, or NULL on error.
1170 static VALUE_PAIR *json_pairmake_leaf(rlm_rest_t *instance,
1171 UNUSED rlm_rest_section_t *section,
1172 REQUEST *request, const DICT_ATTR *da,
1173 json_flags_t *flags, json_object *leaf)
1176 VALUE_PAIR *vp, *tmp;
1179 * Should encode any nested JSON structures into JSON strings.
1181 * "I knew you liked JSON so I put JSON in your JSON!"
1183 value = json_object_get_string(leaf);
1185 RDEBUG2("\tType : %s", fr_int2str(dict_attr_types, da->type,
1187 RDEBUG2("\tLength : %i", strlen(value));
1188 RDEBUG2("\tValue : \"%s\"", value);
1190 vp = paircreate(da->attr, da->vendor, da->type);
1192 radlog(L_ERR, "rlm_rest (%s): Failed creating value-pair",
1193 instance->xlat_name);
1197 vp->operator = flags->operator;
1199 tmp = pairparsevalue(vp, value);
1201 RDEBUG("Incompatible value assignment, skipping");
1207 rest_check_truncation(request, value, vp);
1209 if (flags->do_xlat) vp->flags.do_xlat = 1;
1214 /** Processes JSON response and converts it into multiple VALUE_PAIRs
1216 * Processes JSON attribute declarations in the format below. Will recurse when
1217 * processing nested attributes. When processing nested attributes flags and
1218 * operators from previous attributes are not inherited.
1220 * JSON response format is:
1227 "value":[<value0>,<value1>,<valueN>]
1231 "<nested-attribute0>":{
1237 "<attribute2>":"<value0>",
1238 "<attributeN>":"[<value0>,<value1>,<valueN>]"
1242 * JSON valuepair flags (bools):
1243 * - do_xlat (optional) Controls xlat expansion of values. Defaults to TRUE.
1244 * - is_json (optional) If TRUE, any nested JSON data will be copied to the
1245 * VALUE_PAIR in string form. Defaults to TRUE.
1246 * - op (optional) Controls how the attribute is inserted into
1247 * the target list. Defaults to ':=' (T_OP_SET).
1249 * If "op" is ':=' or '=', it will be automagically changed to '+=' for the
1250 * second and subsequent values in multivalued attributes. This does not work
1251 * between multiple attribute declarations.
1255 * @param[in] instance configuration data.
1256 * @param[in] section configuration data.
1257 * @param[in] request Current request.
1258 * @param[in] object containing root node, or parent node.
1259 * @param[in] level Current nesting level.
1260 * @param[in] max_attrs counter, decremented after each VALUE_PAIR is created,
1261 * when 0 no more attributes will be processed.
1262 * @return VALUE_PAIR or NULL on error.
1264 static VALUE_PAIR *json_pairmake(rlm_rest_t *instance,
1265 UNUSED rlm_rest_section_t *section,
1266 REQUEST *request, json_object *object,
1267 int level, int *max_attrs)
1272 const char *name, *attribute;
1274 struct json_object *value, *idx, *tmp;
1275 struct lh_entry *entry;
1278 const DICT_ATTR *da;
1281 request_refs_t request_name;
1282 pair_lists_t list_name;
1283 REQUEST *reference = request;
1288 if (!json_object_is_type(object, json_type_object)) {
1289 RDEBUG("Can't process VP container, expected JSON object,"
1290 " got \"%s\", skipping",
1291 json_object_get_type(object));
1296 * Process VP container
1298 entry = json_object_get_object(object)->head;
1300 flags.operator = T_OP_SET;
1304 name = (char*)entry->k;
1306 /* Fix the compiler warnings regarding const... */
1307 memcpy(&value, &entry->v, sizeof(value));
1309 entry = entry->next;
1312 * For people handcrafting JSON responses
1315 while ((p = q = strchr(p, '|'))) {
1321 reference = request;
1324 * Resolve attribute name to a dictionary entry and
1327 RDEBUG2("Decoding attribute \"%s\"", name);
1329 request_name = radius_request_name(&attribute, REQUEST_CURRENT);
1330 if (request_name == REQUEST_UNKNOWN) {
1331 RDEBUG("WARNING: Request qualifier, skipping");
1336 if (!radius_request(&reference, request_name)) {
1337 RDEBUG("WARNING: Attribute name refers to outer request"
1338 " but not in a tunnel, skipping");
1343 list_name = radius_list_name(&attribute, PAIR_LIST_REPLY);
1344 if (list_name == PAIR_LIST_UNKNOWN) {
1345 RDEBUG("WARNING: Invalid list qualifier, skipping");
1350 da = dict_attrbyname(attribute);
1352 RDEBUG("WARNING: Attribute \"%s\" unknown, skipping",
1358 vps = radius_list(reference, list_name);
1363 * Alternate JSON structure that allows operator,
1364 * and other flags to be specified.
1374 * - [] Multivalued array
1375 * - {} Nested Valuepair
1376 * - * Integer or string value
1378 if (json_object_is_type(value, json_type_object)) {
1380 * Process operator if present.
1382 tmp = json_object_object_get(value, "op");
1384 flags.operator = fr_str2int(fr_tokens,
1385 json_object_get_string(tmp), 0);
1387 if (!flags.operator) {
1388 RDEBUG("Invalid operator value \"%s\","
1395 * Process optional do_xlat bool.
1397 tmp = json_object_object_get(value, "do_xlat");
1399 flags.do_xlat = json_object_get_boolean(tmp);
1403 * Process optional is_json bool.
1405 tmp = json_object_object_get(value, "is_json");
1407 flags.is_json = json_object_get_boolean(tmp);
1411 * Value key must be present if were using
1412 * the expanded syntax.
1414 value = json_object_object_get(value, "value");
1416 RDEBUG("Value key missing, skipping", value);
1422 * Setup pairmake / recursion loop.
1424 if (!flags.is_json &&
1425 json_object_is_type(value, json_type_array)) {
1426 len = json_object_array_length(value);
1428 RDEBUG("Zero length value array, skipping", value);
1431 idx = json_object_array_get_idx(value, 0);
1439 if (!(*max_attrs)--) {
1440 radlog(L_ERR, "rlm_rest (%s): At maximum"
1441 " attribute limit", instance->xlat_name);
1446 * Automagically switch the op for multivalued
1449 if (((flags.operator == T_OP_SET) ||
1450 (flags.operator == T_OP_EQ)) && (len > 1)) {
1451 flags.operator = T_OP_ADD;
1454 if (!flags.is_json &&
1455 json_object_is_type(value, json_type_object)) {
1456 /* TODO: Insert nested VP into VP structure...*/
1457 RDEBUG("Found nested VP", value);
1458 vp = json_pairmake(instance, section,
1460 level + 1, max_attrs);
1462 vp = json_pairmake_leaf(instance, section,
1463 request, da, &flags,
1467 if (vp->flags.do_xlat) {
1468 RDEBUG("Performing xlat"
1469 " expansion of response"
1473 pairxlatmove(request, vps, &vp);
1476 } while ((++i < len) && (idx = json_object_array_get_idx(value, i)));
1482 /** Converts JSON response into VALUE_PAIRs and adds them to the request.
1484 * Converts the raw JSON string into a json-c object tree and passes it to
1485 * json_pairmake. After the tree has been parsed json_object_put is called
1486 * which decrements the reference count of the root node by one, and frees
1489 * @see rest_encode_json
1490 * @see json_pairmake
1492 * @param[in] instance configuration data.
1493 * @param[in] section configuration data.
1494 * @param[in,out] request Current request.
1495 * @param[in] handle REST handle.
1496 * @param[in] raw buffer containing JSON data.
1497 * @param[in] rawlen Length of data in raw buffer.
1498 * @return the number of VALUE_PAIRs processed or -1 on unrecoverable error.
1500 static int rest_decode_json(rlm_rest_t *instance,
1501 UNUSED rlm_rest_section_t *section,
1502 REQUEST *request, UNUSED void *handle,
1503 char *raw, UNUSED size_t rawlen)
1505 const char *p = raw;
1507 struct json_object *json;
1509 int max = REST_BODY_MAX_ATTRS;
1514 while (isspace(*p)) p++;
1515 if (*p == '\0') return FALSE;
1517 json = json_tokener_parse(p);
1519 radlog(L_ERR, "rlm_rest (%s): Malformed JSON data \"%s\"",
1520 instance->xlat_name, raw);
1524 json_pairmake(instance, section, request, json, 0, &max);
1527 * Decrement reference count for root object, should free entire
1530 json_object_put(json);
1532 return (REST_BODY_MAX_ATTRS - max);
1536 /** Processes incoming HTTP header data from libcurl.
1538 * Processes the status line, and Content-Type headers from the incoming HTTP
1541 * Matches prototype for CURLOPT_HEADERFUNCTION, and will be called directly
1544 * @param[in] ptr Char buffer where inbound header data is written.
1545 * @param[in] size Multiply by nmemb to get the length of ptr.
1546 * @param[in] nmemb Multiply by size to get the length of ptr.
1547 * @param[in] userdata rlm_rest_write_t to keep parsing state between calls.
1548 * @return Length of data processed, or 0 on error.
1550 static size_t rest_write_header(void *ptr, size_t size, size_t nmemb,
1553 rlm_rest_write_t *ctx = userdata;
1554 REQUEST *request = ctx->request; /* Used by RDEBUG */
1556 const char *p = ptr, *q;
1559 const size_t t = (size * nmemb);
1563 http_body_type_t type;
1564 http_body_type_t supp;
1568 case WRITE_STATE_INIT:
1569 RDEBUG("Processing header");
1572 * HTTP/<version> <reason_code>[ <reason_phrase>]\r\n
1574 * "HTTP/1.1 " (8) + "100 " (4) + "\r\n" (2) = 14
1576 if (s < 14) goto malformed;
1579 * Check start of header matches...
1581 if (strncasecmp("HTTP/", p, 5) != 0) goto malformed;
1587 * Skip the version field, next space should mark start
1590 q = memchr(p, ' ', s);
1591 if (q == NULL) goto malformed;
1597 * Process reason_code.
1599 * " 100" (4) + "\r\n" (2) = 6
1601 if (s < 6) goto malformed;
1605 /* Char after reason code must be a space, or \r */
1606 if (!((p[3] == ' ') || (p[3] == '\r'))) goto malformed;
1608 ctx->code = atoi(p);
1611 * Process reason_phrase (if present).
1617 q = memchr(p, '\r', s);
1618 if (q == NULL) goto malformed;
1622 tmp = rad_malloc(len + 1);
1623 strlcpy(tmp, p, len + 1);
1625 RDEBUG("\tStatus : %i (%s)", ctx->code, tmp);
1629 RDEBUG("\tStatus : %i", ctx->code);
1632 ctx->state = WRITE_STATE_PARSE_HEADERS;
1636 case WRITE_STATE_PARSE_HEADERS:
1638 (strncasecmp("Content-Type: ", p, 14) == 0)) {
1643 * Check to see if there's a parameter
1646 q = memchr(p, ';', s);
1649 * If there's not, find the end of this
1652 if (q == NULL) q = memchr(p, '\r', s);
1654 len = (q == NULL) ? s : (unsigned)(q - p);
1656 type = fr_substr2int(http_content_type_table,
1657 p, HTTP_BODY_UNKNOWN,
1660 supp = http_body_type_supported[type];
1662 tmp = rad_malloc(len + 1);
1663 strlcpy(tmp, p, len + 1);
1665 RDEBUG("\tType : %s (%s)",
1666 fr_int2str(http_body_type_table, type,
1667 "¿Unknown?"), tmp);
1671 if (type == HTTP_BODY_UNKNOWN) {
1672 RDEBUG("Couldn't determine type, using"
1673 " request type \"%s\".",
1674 fr_int2str(http_body_type_table,
1678 } else if (supp == HTTP_BODY_UNSUPPORTED) {
1679 RDEBUG("Type \"%s\" is currently"
1681 fr_int2str(http_body_type_table,
1682 type, "¿Unknown?"));
1683 ctx->type = HTTP_BODY_UNSUPPORTED;
1684 } else if (supp == HTTP_BODY_UNAVAILABLE) {
1685 RDEBUG("Type \"%s\" is currently"
1686 " unavailable, please rebuild"
1687 " this module with the required"
1689 fr_int2str(http_body_type_table,
1690 type, "¿Unknown?"));
1691 ctx->type = HTTP_BODY_UNSUPPORTED;
1693 } else if (supp == HTTP_BODY_INVALID) {
1694 RDEBUG("Type \"%s\" is not a valid web"
1695 " API data markup format",
1696 fr_int2str(http_body_type_table,
1697 type, "¿Unknown?"));
1699 ctx->type = HTTP_BODY_INVALID;
1701 } else if (type != ctx->type) {
1714 RDEBUG("Incoming header was malformed");
1720 /** Processes incoming HTTP body data from libcurl.
1722 * Writes incoming body data to an intermediary buffer for later parsing by
1723 * one of the decode functions.
1725 * @param[in] ptr Char buffer where inbound header data is written
1726 * @param[in] size Multiply by nmemb to get the length of ptr.
1727 * @param[in] nmemb Multiply by size to get the length of ptr.
1728 * @param[in] userdata rlm_rest_write_t to keep parsing state between calls.
1729 * @return length of data processed, or 0 on error.
1731 static size_t rest_write_body(void *ptr, size_t size, size_t nmemb,
1734 rlm_rest_write_t *ctx = userdata;
1735 REQUEST *request = ctx->request; /* Used by RDEBUG */
1737 const char *p = ptr;
1740 const size_t t = (size * nmemb);
1743 * Any post processing of headers should go here...
1745 if (ctx->state == WRITE_STATE_PARSE_HEADERS) {
1746 ctx->state = WRITE_STATE_PARSE_CONTENT;
1751 case HTTP_BODY_UNSUPPORTED:
1754 case HTTP_BODY_INVALID:
1755 tmp = rad_malloc(t + 1);
1756 strlcpy(tmp, p, t + 1);
1765 if (t > (ctx->alloc - ctx->used)) {
1766 ctx->alloc += ((t + 1) > REST_BODY_INCR) ?
1767 t + 1 : REST_BODY_INCR;
1771 ctx->buffer = rad_malloc(ctx->alloc);
1773 /* If data has been written previously */
1775 strlcpy(ctx->buffer, tmp,
1780 strlcpy(ctx->buffer + ctx->used, p, t + 1);
1789 /** (Re-)Initialises the data in a rlm_rest_write_t.
1791 * This resets the values of the a rlm_rest_write_t to their defaults.
1792 * Must be called between encoding sessions.
1794 * @see rest_write_body
1795 * @see rest_write_header
1797 * @param[in] request Current request.
1798 * @param[in] ctx data to initialise.
1799 * @param[in] type Default http_body_type to use when decoding raw data, may be
1800 * overwritten by rest_write_header.
1802 static void rest_write_ctx_init(REQUEST *request, rlm_rest_write_t *ctx,
1803 http_body_type_t type)
1805 ctx->request = request;
1807 ctx->state = WRITE_STATE_INIT;
1813 /** Frees the intermediary buffer created by rest_write.
1815 * @param[in] ctx data to be freed.
1817 static void rest_write_free(rlm_rest_write_t *ctx)
1819 if (ctx->buffer != NULL) {
1824 /** Configures body specific curlopts.
1826 * Configures libcurl handle to use either chunked mode, where the request
1827 * data will be sent using multiple HTTP requests, or contiguous mode where
1828 * the request data will be sent in a single HTTP request.
1830 * @param[in] instance configuration data.
1831 * @param[in] section configuration data.
1832 * @param[in] handle rlm_rest_handle_t to configure.
1833 * @param[in] func to pass to libcurl for chunked.
1834 * transfers (NULL if not using chunked mode).
1835 * @return TRUE on success FALSE on error.
1837 static int rest_request_config_body(rlm_rest_t *instance,
1838 rlm_rest_section_t *section,
1839 rlm_rest_handle_t *handle,
1842 rlm_rest_curl_context_t *ctx = handle->ctx;
1843 CURL *candle = handle->handle;
1848 if (section->chunk > 0) {
1849 ret = curl_easy_setopt(candle, CURLOPT_READDATA,
1851 if (ret != CURLE_OK) goto error;
1853 ret = curl_easy_setopt(candle, CURLOPT_READFUNCTION,
1855 if (ret != CURLE_OK) goto error;
1857 len = rest_read_wrapper(&ctx->body, func,
1858 REST_BODY_MAX_LEN , &ctx->read);
1860 radlog(L_ERR, "rlm_rest (%s): Failed creating HTTP"
1861 " body content", instance->xlat_name);
1865 ret = curl_easy_setopt(candle, CURLOPT_POSTFIELDS,
1867 if (ret != CURLE_OK) goto error;
1869 ret = curl_easy_setopt(candle, CURLOPT_POSTFIELDSIZE,
1871 if (ret != CURLE_OK) goto error;
1877 radlog(L_ERR, "rlm_rest (%s): Failed setting curl option: %i - %s",
1878 instance->xlat_name, ret, curl_easy_strerror(ret));
1883 /** Configures request curlopts.
1885 * Configures libcurl handle setting various curlopts for things like local
1886 * client time, Content-Type, and other FreeRADIUS custom headers.
1888 * Current FreeRADIUS custom headers are:
1889 * - X-FreeRADIUS-Section The module section being processed.
1890 * - X-FreeRADIUS-Server The current virtual server the REQUEST is
1893 * Sets up callbacks for all response processing (buffers and body data).
1895 * @param[in] instance configuration data.
1896 * @param[in] section configuration data.
1897 * @param[in] handle to configure.
1898 * @param[in] request Current request.
1899 * @param[in] method to use (HTTP verbs PUT, POST, DELETE etc...).
1900 * @param[in] type Content-Type for request encoding, also sets the default
1902 * @param[in] uri buffer containing the expanded URI to send the request to.
1903 * @return TRUE on success (all opts configured) FALSE on error.
1905 int rest_request_config(rlm_rest_t *instance, rlm_rest_section_t *section,
1906 REQUEST *request, void *handle, http_method_t method,
1907 http_body_type_t type, char *uri)
1909 rlm_rest_handle_t *randle = handle;
1910 rlm_rest_curl_context_t *ctx = randle->ctx;
1911 CURL *candle = randle->handle;
1913 http_auth_type_t auth = section->auth;
1920 buffer[(sizeof(buffer) - 1)] = '\0';
1923 * Setup any header options and generic headers.
1925 ret = curl_easy_setopt(candle, CURLOPT_URL, uri);
1926 if (ret != CURLE_OK) goto error;
1928 ret = curl_easy_setopt(candle, CURLOPT_USERAGENT, "FreeRADIUS");
1929 if (ret != CURLE_OK) goto error;
1931 snprintf(buffer, (sizeof(buffer) - 1), "Content-Type: %s",
1932 fr_int2str(http_content_type_table, type, "¿Unknown?"));
1933 ctx->headers = curl_slist_append(ctx->headers, buffer);
1934 if (!ctx->headers) goto error_header;
1936 if (section->timeout) {
1937 ret = curl_easy_setopt(candle, CURLOPT_TIMEOUT,
1939 if (ret != CURLE_OK) goto error;
1942 ret = curl_easy_setopt(candle, CURLOPT_PROTOCOLS,
1943 (CURLPROTO_HTTP | CURLPROTO_HTTPS));
1944 if (ret != CURLE_OK) goto error;
1947 * FreeRADIUS custom headers
1949 snprintf(buffer, (sizeof(buffer) - 1), "X-FreeRADIUS-Section: %s",
1951 ctx->headers = curl_slist_append(ctx->headers, buffer);
1952 if (!ctx->headers) goto error_header;
1954 snprintf(buffer, (sizeof(buffer) - 1), "X-FreeRADIUS-Server: %s",
1956 ctx->headers = curl_slist_append(ctx->headers, buffer);
1957 if (!ctx->headers) goto error_header;
1960 * Configure HTTP verb (GET, POST, PUT, DELETE, other...)
1964 case HTTP_METHOD_GET :
1965 ret = curl_easy_setopt(candle, CURLOPT_HTTPGET,
1967 if (ret != CURLE_OK) goto error;
1971 case HTTP_METHOD_POST :
1972 ret = curl_easy_setopt(candle, CURLOPT_POST,
1974 if (ret != CURLE_OK) goto error;
1978 case HTTP_METHOD_PUT :
1979 ret = curl_easy_setopt(candle, CURLOPT_PUT,
1981 if (ret != CURLE_OK) goto error;
1985 case HTTP_METHOD_DELETE :
1986 ret = curl_easy_setopt(candle, CURLOPT_HTTPGET,
1988 if (ret != CURLE_OK) goto error;
1990 ret = curl_easy_setopt(candle,
1991 CURLOPT_CUSTOMREQUEST, "DELETE");
1992 if (ret != CURLE_OK) goto error;
1996 case HTTP_METHOD_CUSTOM :
1997 ret = curl_easy_setopt(candle, CURLOPT_HTTPGET,
1999 if (ret != CURLE_OK) goto error;
2001 ret = curl_easy_setopt(candle,
2002 CURLOPT_CUSTOMREQUEST,
2004 if (ret != CURLE_OK) goto error;
2012 * Set user based authentication parameters
2015 if ((auth >= HTTP_AUTH_BASIC) &&
2016 (auth <= HTTP_AUTH_ANY_SAFE)) {
2017 ret = curl_easy_setopt(candle, CURLOPT_HTTPAUTH,
2018 http_curl_auth[auth]);
2019 if (ret != CURLE_OK) goto error;
2021 if (section->username) {
2022 radius_xlat(buffer, sizeof(buffer),
2023 section->username, request, NULL, NULL);
2025 ret = curl_easy_setopt(candle, CURLOPT_USERNAME,
2027 if (ret != CURLE_OK) goto error;
2029 if (section->password) {
2030 radius_xlat(buffer, sizeof(buffer),
2031 section->password, request, NULL, NULL);
2033 ret = curl_easy_setopt(candle, CURLOPT_PASSWORD,
2035 if (ret != CURLE_OK) goto error;
2038 #ifdef CURLOPT_TLSAUTH_USERNAME
2039 } else if (type == HTTP_AUTH_TLS_SRP) {
2040 ret = curl_easy_setopt(candle, CURLOPT_TLSAUTH_TYPE,
2041 http_curl_auth[auth]);
2043 if (section->username) {
2044 radius_xlat(buffer, sizeof(buffer),
2045 section->username, request, NULL, NULL);
2047 ret = curl_easy_setopt(candle,
2048 CURLOPT_TLSAUTH_USERNAME,
2050 if (ret != CURLE_OK) goto error;
2052 if (section->password) {
2053 radius_xlat(buffer, sizeof(buffer),
2054 section->password, request, NULL, NULL);
2056 ret = curl_easy_setopt(candle,
2057 CURLOPT_TLSAUTH_PASSWORD,
2059 if (ret != CURLE_OK) goto error;
2066 * Set SSL/TLS authentication parameters
2068 if (section->tls_certfile) {
2069 ret = curl_easy_setopt(candle,
2071 section->tls_certfile);
2072 if (ret != CURLE_OK) goto error;
2075 if (section->tls_keyfile) {
2076 ret = curl_easy_setopt(candle,
2078 section->tls_keyfile);
2079 if (ret != CURLE_OK) goto error;
2082 if (section->tls_keypassword) {
2083 ret = curl_easy_setopt(candle,
2085 section->tls_keypassword);
2086 if (ret != CURLE_OK) goto error;
2089 if (section->tls_cacertfile) {
2090 ret = curl_easy_setopt(candle,
2092 section->tls_cacertfile);
2093 if (ret != CURLE_OK) goto error;
2096 if (section->tls_cacertdir) {
2097 ret = curl_easy_setopt(candle,
2099 section->tls_cacertdir);
2100 if (ret != CURLE_OK) goto error;
2103 if (section->tls_randfile) {
2104 ret = curl_easy_setopt(candle,
2105 CURLOPT_RANDOM_FILE,
2106 section->tls_randfile);
2107 if (ret != CURLE_OK) goto error;
2110 if (section->tls_verify_cert) {
2111 ret = curl_easy_setopt(candle,
2112 CURLOPT_SSL_VERIFYHOST,
2113 (section->tls_verify_cert_cn == TRUE) ?
2115 if (ret != CURLE_OK) goto error;
2117 ret = curl_easy_setopt(candle,
2118 CURLOPT_SSL_VERIFYPEER,
2120 if (ret != CURLE_OK) goto error;
2124 * Tell CURL how to get HTTP body content, and how to process
2127 rest_write_ctx_init(request, &ctx->write, type);
2129 ret = curl_easy_setopt(candle, CURLOPT_HEADERFUNCTION,
2131 if (ret != CURLE_OK) goto error;
2133 ret = curl_easy_setopt(candle, CURLOPT_HEADERDATA,
2135 if (ret != CURLE_OK) goto error;
2137 ret = curl_easy_setopt(candle, CURLOPT_WRITEFUNCTION,
2139 if (ret != CURLE_OK) goto error;
2141 ret = curl_easy_setopt(candle, CURLOPT_WRITEDATA,
2143 if (ret != CURLE_OK) goto error;
2147 case HTTP_METHOD_GET :
2148 case HTTP_METHOD_DELETE :
2152 case HTTP_METHOD_POST :
2153 case HTTP_METHOD_PUT :
2154 case HTTP_METHOD_CUSTOM :
2155 if (section->chunk > 0) {
2156 ctx->read.chunk = section->chunk;
2158 ctx->headers = curl_slist_append(ctx->headers,
2160 if (!ctx->headers) goto error_header;
2162 ctx->headers = curl_slist_append(ctx->headers,
2163 "Transfer-Encoding: chunked");
2164 if (!ctx->headers) goto error_header;
2170 case HTTP_BODY_JSON:
2171 rest_read_ctx_init(request,
2174 ret = rest_request_config_body(instance,
2178 if (!ret) return -1;
2183 case HTTP_BODY_POST:
2184 rest_read_ctx_init(request,
2187 ret = rest_request_config_body(instance,
2191 if (!ret) return -1;
2199 ret = curl_easy_setopt(candle, CURLOPT_HTTPHEADER,
2201 if (ret != CURLE_OK) goto error;
2212 radlog(L_ERR, "rlm_rest (%s): Failed setting curl option: %i - %s",
2213 instance->xlat_name, ret, curl_easy_strerror(ret));
2217 radlog(L_ERR, "rlm_rest (%s): Failed creating header",
2218 instance->xlat_name);
2222 /** Sends a REST (HTTP) request.
2224 * Send the actual REST request to the server. The response will be handled by
2225 * the numerous callbacks configured in rest_request_config.
2227 * @param[in] instance configuration data.
2228 * @param[in] section configuration data.
2229 * @param[in] handle to use.
2230 * @return TRUE on success or FALSE on error.
2232 int rest_request_perform(rlm_rest_t *instance,
2233 UNUSED rlm_rest_section_t *section, void *handle)
2235 rlm_rest_handle_t *randle = handle;
2236 CURL *candle = randle->handle;
2239 ret = curl_easy_perform(candle);
2240 if (ret != CURLE_OK) {
2241 radlog(L_ERR, "rlm_rest (%s): Request failed: %i - %s",
2242 instance->xlat_name, ret, curl_easy_strerror(ret));
2249 /** Sends the response to the correct decode function.
2251 * Uses the Content-Type information written in rest_write_header to
2252 * determine the correct decode function to use. The decode function will
2253 * then convert the raw received data into VALUE_PAIRs.
2255 * @param[in] instance configuration data.
2256 * @param[in] section configuration data.
2257 * @param[in] request Current request.
2258 * @param[in] handle to use.
2259 * @return TRUE on success or FALSE on error.
2261 int rest_request_decode(rlm_rest_t *instance,
2262 UNUSED rlm_rest_section_t *section,
2263 REQUEST *request, void *handle)
2265 rlm_rest_handle_t *randle = handle;
2266 rlm_rest_curl_context_t *ctx = randle->ctx;
2270 if (ctx->write.buffer == NULL) {
2271 RDEBUG("Skipping attribute processing, no body data received");
2275 RDEBUG("Processing body", ret);
2277 switch (ctx->write.type)
2279 case HTTP_BODY_POST:
2280 ret = rest_decode_post(instance, section, request,
2281 handle, ctx->write.buffer,
2285 case HTTP_BODY_JSON:
2286 ret = rest_decode_json(instance, section, request,
2287 handle, ctx->write.buffer,
2291 case HTTP_BODY_UNSUPPORTED:
2292 case HTTP_BODY_UNAVAILABLE:
2293 case HTTP_BODY_INVALID:
2303 /** Cleans up after a REST request.
2305 * Resets all options associated with a CURL handle, and frees any headers
2306 * associated with it.
2308 * Calls rest_read_ctx_free and rest_write_free to free any memory used by
2311 * @param[in] instance configuration data.
2312 * @param[in] section configuration data.
2313 * @param[in] handle to cleanup.
2314 * @return TRUE on success or FALSE on error.
2316 void rest_request_cleanup(UNUSED rlm_rest_t *instance,
2317 UNUSED rlm_rest_section_t *section, void *handle)
2319 rlm_rest_handle_t *randle = handle;
2320 rlm_rest_curl_context_t *ctx = randle->ctx;
2321 CURL *candle = randle->handle;
2324 * Clear any previously configured options
2326 curl_easy_reset(candle);
2331 if (ctx->headers != NULL) {
2332 curl_slist_free_all(ctx->headers);
2333 ctx->headers = NULL;
2337 * Free body data (only used if chunking is disabled)
2339 if (ctx->body != NULL) free(ctx->body);
2342 * Free other context info
2344 rest_read_ctx_free(&ctx->read);
2345 rest_write_free(&ctx->write);
2348 /** URL encodes a string.
2350 * Encode special chars as per RFC 3986 section 4.
2352 * @param[in] request Current request.
2353 * @param[out] out Where to write escaped string.
2354 * @param[in] outlen Size of out buffer.
2355 * @param[in] raw string to be urlencoded.
2356 * @param[in] arg pointer, gives context for escaping.
2357 * @return length of data written to out (excluding NULL).
2359 static size_t rest_uri_escape(UNUSED REQUEST *request, char *out, size_t outlen,
2360 const char *raw, UNUSED void *arg)
2364 escaped = curl_escape(raw, strlen(raw));
2365 strlcpy(out, escaped, outlen);
2371 /** Builds URI; performs XLAT expansions and encoding.
2373 * Splits the URI into "http://example.org" and "/%{xlat}/query/?bar=foo"
2374 * Both components are expanded, but values expanded for the second component
2375 * are also url encoded.
2377 * @param[in] instance configuration data.
2378 * @param[in] section configuration data.
2379 * @param[in] request Current request
2380 * @param[out] buffer to write expanded URI to.
2381 * @param[in] bufsize Size of buffer.
2382 * @return length of data written to buffer (excluding NULL) or < 0 if an error
2385 ssize_t rest_uri_build(rlm_rest_t *instance, rlm_rest_section_t *section,
2386 REQUEST *request, char *buffer, size_t bufsize)
2393 unsigned short count = 0;
2400 * All URLs must contain at least <scheme>://<server>/
2402 while ((q = strchr(p, '/'))) {
2411 radlog(L_ERR, "rlm_rest (%s): Error URI is malformed,"
2412 " can't find start of path", instance->xlat_name);
2418 scheme = rad_malloc(len + 1);
2419 strlcpy(scheme, section->uri, len + 1);
2424 out += radius_xlat(out, bufsize, scheme, request, NULL, NULL);
2428 out += radius_xlat(out, (bufsize - (buffer - out)), path, request,
2429 rest_uri_escape, NULL);
2431 return (buffer - out);