-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
rest.c
2396 lines (1993 loc) · 57.3 KB
/
rest.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
/*
* $Id$
*
* @brief Functions and datatypes for the REST (HTTP) transport.
* @file rest.c
*
* @copyright 2012-2013 Arran Cudbard-Bell <a.cudbard-bell@freeradius.org>
*/
#include <freeradius-devel/ident.h>
RCSID("$Id$")
#include <assert.h>
#include <ctype.h>
#include <string.h>
#include <time.h>
#include <freeradius-devel/radiusd.h>
#include <freeradius-devel/libradius.h>
#include <freeradius-devel/connection.h>
#include "rest.h"
/** Table of encoder/decoder support.
*
* Indexes in this table match the http_body_type_t enum, and should be
* updated if additional enum values are added.
*
* @see http_body_type_t
*/
const http_body_type_t http_body_type_supported[HTTP_BODY_NUM_ENTRIES] = {
HTTP_BODY_UNSUPPORTED, // HTTP_BODY_UNKOWN
HTTP_BODY_UNSUPPORTED, // HTTP_BODY_UNSUPPORTED
HTTP_BODY_UNSUPPORTED, // HTTP_BODY_INVALID
HTTP_BODY_POST, // HTTP_BODY_POST
#ifdef HAVE_JSON
HTTP_BODY_JSON, // HTTP_BODY_JSON
#else
HTTP_BODY_UNAVAILABLE,
#endif
HTTP_BODY_UNSUPPORTED, // HTTP_BODY_XML
HTTP_BODY_UNSUPPORTED, // HTTP_BODY_YAML
HTTP_BODY_INVALID, // HTTP_BODY_HTML
HTTP_BODY_INVALID // HTTP_BODY_PLAIN
};
/*
* Lib CURL doesn't define symbols for unsupported auth methods
*/
#ifndef CURLOPT_TLSAUTH_SRP
#define CURLOPT_TLSAUTH_SRP 0
#endif
#ifndef CURLAUTH_BASIC
#define CURLAUTH_BASIC 0
#endif
#ifndef CURLAUTH_DIGEST
#define CURLAUTH_DIGEST 0
#endif
#ifndef CURLAUTH_DIGEST_IE
#define CURLAUTH_DIGEST_IE 0
#endif
#ifndef CURLAUTH_GSSNEGOTIATE
#define CURLAUTH_GSSNEGOTIATE 0
#endif
#ifndef CURLAUTH_NTLM
#define CURLAUTH_NTLM 0
#endif
#ifndef CURLAUTH_NTLM_WB
#define CURLAUTH_NTLM_WB 0
#endif
const http_body_type_t http_curl_auth[HTTP_AUTH_NUM_ENTRIES] = {
0, // HTTP_AUTH_UNKNOWN
0, // HTTP_AUTH_NONE
CURLOPT_TLSAUTH_SRP, // HTTP_AUTH_TLS_SRP
CURLAUTH_BASIC, // HTTP_AUTH_BASIC
CURLAUTH_DIGEST, // HTTP_AUTH_DIGEST
CURLAUTH_DIGEST_IE, // HTTP_AUTH_DIGEST_IE
CURLAUTH_GSSNEGOTIATE, // HTTP_AUTH_GSSNEGOTIATE
CURLAUTH_NTLM, // HTTP_AUTH_NTLM
CURLAUTH_NTLM_WB, // HTTP_AUTH_NTLM_WB
CURLAUTH_ANY, // HTTP_AUTH_ANY
CURLAUTH_ANYSAFE // HTTP_AUTH_ANY_SAFE
};
/** Conversion table for method config values.
*
* HTTP verb strings for http_method_t enum values. Used by libcurl in the
* status line of the outgoing HTTP header, by rest_write_header for decoding
* incoming HTTP responses, and by the configuration parser.
*
* @see http_method_t
* @see fr_str2int
* @see fr_int2str
*/
const FR_NAME_NUMBER http_method_table[] = {
{ "GET", HTTP_METHOD_GET },
{ "POST", HTTP_METHOD_POST },
{ "PUT", HTTP_METHOD_PUT },
{ "DELETE", HTTP_METHOD_DELETE },
{ NULL , -1 }
};
/** Conversion table for type config values.
*
* Textual names for http_body_type_t enum values, used by the
* configuration parser.
*
* @see http_body_Type_t
* @see fr_str2int
* @see fr_int2str
*/
const FR_NAME_NUMBER http_body_type_table[] = {
{ "unknown", HTTP_BODY_UNKNOWN },
{ "unsupported", HTTP_BODY_UNSUPPORTED },
{ "unavailable", HTTP_BODY_UNAVAILABLE },
{ "invalid", HTTP_BODY_INVALID },
{ "post", HTTP_BODY_POST },
{ "json", HTTP_BODY_JSON },
{ "xml", HTTP_BODY_XML },
{ "yaml", HTTP_BODY_YAML },
{ "html", HTTP_BODY_HTML },
{ "plain", HTTP_BODY_PLAIN },
{ NULL , -1 }
};
const FR_NAME_NUMBER http_auth_table[] = {
{ "none", HTTP_AUTH_NONE },
{ "srp", HTTP_AUTH_TLS_SRP },
{ "basic", HTTP_AUTH_BASIC },
{ "digest", HTTP_AUTH_DIGEST },
{ "digest-ie", HTTP_AUTH_DIGEST_IE },
{ "gss-negotiate", HTTP_AUTH_GSSNEGOTIATE },
{ "ntlm", HTTP_AUTH_NTLM },
{ "ntlm-winbind", HTTP_AUTH_NTLM_WB },
{ "any", HTTP_AUTH_ANY },
{ "safe", HTTP_AUTH_ANY_SAFE },
{ NULL , -1 }
};
/** Conversion table for "Content-Type" header values.
*
* Used by rest_write_header for parsing incoming headers.
*
* Values we expect to see in the 'Content-Type:' header of the incoming
* response.
*
* Some data types (like YAML) do no have standard MIME types defined,
* so multiple types, are listed here.
*
* @see http_body_Type_t
* @see fr_str2int
* @see fr_int2str
*/
const FR_NAME_NUMBER http_content_type_table[] = {
{ "application/x-www-form-urlencoded", HTTP_BODY_POST },
{ "application/json", HTTP_BODY_JSON },
{ "text/html", HTTP_BODY_HTML },
{ "text/plain", HTTP_BODY_PLAIN },
{ "text/xml", HTTP_BODY_XML },
{ "text/yaml", HTTP_BODY_YAML },
{ "text/x-yaml", HTTP_BODY_YAML },
{ "application/yaml", HTTP_BODY_YAML },
{ "application/x-yaml", HTTP_BODY_YAML },
{ NULL , -1 }
};
#ifdef HAVE_JSON
/** Flags to control the conversion of JSON values to VALUE_PAIRs.
*
* These fields are set when parsing the expanded format for value pairs in
* JSON, and control how json_pairmake_leaf and json_pairmake convert the JSON
* value, and move the new VALUE_PAIR into an attribute list.
*
* @see json_pairmake
* @see json_pairmake_leaf
*/
typedef struct json_flags {
int do_xlat; //!< If TRUE value will be expanded with xlat.
int is_json; //!< If TRUE value will be inserted as raw JSON
// (multiple values not supported).
FR_TOKEN op; //!< The operator that determines how the new VP
// is processed. @see fr_tokens
} json_flags_t;
#endif
/** Initialises libcurl.
*
* Allocates global variables and memory required for libcurl to fundtion.
* MUST only be called once per module instance.
*
* rest_cleanup must not be called if rest_init fails.
*
* @see rest_cleanup
*
* @param[in] instance configuration data.
* @return TRUE if init succeeded FALSE if it failed.
*/
int rest_init(rlm_rest_t *instance)
{
CURLcode ret;
ret = curl_global_init(CURL_GLOBAL_ALL);
if (ret != CURLE_OK) {
radlog(L_ERR,
"rlm_rest (%s): CURL init returned error: %i - %s",
instance->xlat_name,
ret, curl_easy_strerror(ret));
curl_global_cleanup();
return FALSE;
}
radlog(L_DBG, "rlm_rest (%s): CURL library version: %s",
instance->xlat_name,
curl_version());
return TRUE;
}
/** Cleans up after libcurl.
*
* Wrapper around curl_global_cleanup, frees any memory allocated by rest_init.
* Must only be called once per call of rest_init.
*
* @see rest_init
*/
void rest_cleanup(void)
{
curl_global_cleanup();
}
/** Creates a new connection handle for use by the FR connection API.
*
* Matches the fr_connection_create_t function prototype, is passed to
* fr_connection_pool_init, and called when a new connection is required by the
* connection pool API.
*
* Creates an instances of rlm_rest_handle_t, and rlm_rest_curl_context_t
* which hold the context data required for generating requests and parsing
* responses. Calling rest_socket_delete will free this memory.
*
* If instance->connect_uri is not NULL libcurl will attempt to open a
* TCP socket to the server specified in the URI. This is done so that when the
* socket is first used, there will already be a cached TCP connection to the
* REST server associated with the curl handle.
*
* @see rest_socket_delete
* @see fr_connection_pool_init
* @see fr_connection_create_t
* @see connection.c
*
* @param[in] instance configuration data.
* @return connection handle or NULL if the connection failed or couldn't
* be initialised.
*/
void *rest_socket_create(void *instance)
{
rlm_rest_t *inst = instance;
rlm_rest_handle_t *randle = NULL;
rlm_rest_curl_context_t *ctx = NULL;
CURL *candle = curl_easy_init();
CURLcode ret;
if (!candle) {
radlog(L_ERR, "rlm_rest (%s): Failed to create CURL handle",
inst->xlat_name);
return NULL;
}
if (!*inst->connect_uri) {
radlog(L_ERR, "rlm_rest (%s): Skipping pre-connect,"
" connect_uri not specified", inst->xlat_name);
return candle;
}
/*
* Pre-establish TCP connection to webserver. This would usually be
* done on the first request, but we do it here to minimise
* latency.
*/
ret = curl_easy_setopt(candle, CURLOPT_CONNECT_ONLY, 1);
if (ret != CURLE_OK) goto error;
ret = curl_easy_setopt(candle, CURLOPT_URL,
inst->connect_uri);
if (ret != CURLE_OK) goto error;
radlog(L_DBG, "rlm_rest (%s): Connecting to \"%s\"",
inst->xlat_name,
inst->connect_uri);
ret = curl_easy_perform(candle);
if (ret != CURLE_OK) {
radlog(L_ERR, "rlm_rest (%s): Connection failed: %i - %s",
inst->xlat_name,
ret, curl_easy_strerror(ret));
goto connection_error;
}
/*
* Allocate memory for the connection handle abstraction.
*/
randle = talloc_zero(inst, rlm_rest_handle_t);
ctx = talloc_zero(randle, rlm_rest_curl_context_t);
ctx->headers = NULL; /* CURL needs this to be NULL */
ctx->read.instance = inst;
randle->ctx = ctx;
randle->handle = candle;
/*
* Clear any previously configured options for the first request.
*/
curl_easy_reset(candle);
return randle;
/*
* Cleanup for error conditions.
*/
error:
radlog(L_ERR, "rlm_rest (%s): Failed setting curl option: %i - %s",
inst->xlat_name,
ret, curl_easy_strerror(ret));
/*
* So we don't leak CURL handles.
*/
connection_error:
curl_easy_cleanup(candle);
if (randle) talloc_free(randle);
return NULL;
}
/** Verifies that the last TCP socket associated with a handle is still active.
*
* Quieries libcurl to try and determine if the TCP socket associated with a
* connection handle is still viable.
*
* @param[in] instance configuration data.
* @param[in] handle to check.
* @returns FALSE if the last socket is dead, or if the socket state couldn't be
* determined, else TRUE.
*/
int rest_socket_alive(void *instance, void *handle)
{
rlm_rest_t *inst = instance;
rlm_rest_handle_t *randle = handle;
CURL *candle = randle->handle;
long last_socket;
CURLcode ret;
ret = curl_easy_getinfo(candle, CURLINFO_LASTSOCKET, &last_socket);
if (ret != CURLE_OK) {
radlog(L_ERR,
"rlm_rest (%s): Couldn't determine socket"
" state: %i - %s", inst->xlat_name, ret,
curl_easy_strerror(ret));
return FALSE;
}
if (last_socket == -1) {
return FALSE;
}
return TRUE;
}
/** Frees a libcurl handle, and any additional memory used by context data.
*
* @param[in] instance configuration data.
* @param[in] handle rlm_rest_handle_t to close and free.
* @return returns TRUE.
*/
int rest_socket_delete(UNUSED void *instance, void *handle)
{
rlm_rest_handle_t *randle = handle;
CURL *candle = randle->handle;
curl_easy_cleanup(candle);
talloc_free(randle);
return TRUE;
}
/** Encodes VALUE_PAIR linked list in POST format
*
* This is a stream function matching the rest_read_t prototype. Multiple
* successive calls will return additional encoded VALUE_PAIRs.
* Only complete attribute headers @verbatim '<name>=' @endverbatim and values
* will be written to the ptr buffer.
*
* POST request format is:
* @verbatim <attribute0>=<value0>&<attribute1>=<value1>&<attributeN>=<valueN>@endverbatim
*
* All attributes and values are url encoded. There is currently no support for
* nested attributes, or attribute qualifiers.
*
* Nested attributes may be added in the future using
* @verbatim <attribute-outer>:<attribute-inner>@endverbatim
* to denotate nesting.
*
* Requires libcurl for url encoding.
*
* @see rest_decode_post
*
* @param[out] ptr Char buffer to write encoded data to.
* @param[in] size Multiply by nmemb to get the length of ptr.
* @param[in] nmemb Multiply by size to get the length of ptr.
* @param[in] userdata rlm_rest_read_t to keep encoding state between calls.
* @return length of data (including NULL) written to ptr, or 0 if no more
* data to write.
*/
static size_t rest_encode_post(void *ptr, size_t size, size_t nmemb,
void *userdata)
{
rlm_rest_read_t *ctx = userdata;
REQUEST *request = ctx->request; /* Used by RDEBUG */
VALUE_PAIR **current = ctx->next;
char *p = ptr; /* Position in buffer */
char *f = ptr; /* Position in buffer of last fully encoded attribute or value */
char *escaped; /* Pointer to current URL escaped data */
ssize_t len = 0;
ssize_t s = (size * nmemb) - 1;
/* Allow manual chunking */
if ((ctx->chunk) && (ctx->chunk <= s)) {
s = (ctx->chunk - 1);
}
if (ctx->state == READ_STATE_END) return FALSE;
/* Post data requires no headers */
if (ctx->state == READ_STATE_INIT) {
ctx->state = READ_STATE_ATTR_BEGIN;
}
while (s > 0) {
if (!*current) {
ctx->state = READ_STATE_END;
goto end_chunk;
}
RDEBUG2("Encoding attribute \"%s\"", current[0]->da->name);
if (ctx->state == READ_STATE_ATTR_BEGIN) {
escaped = curl_escape(current[0]->da->name,
strlen(current[0]->da->name));
len = strlen(escaped);
if (s < (1 + len)) {
curl_free(escaped);
goto no_space;
}
len = sprintf(p, "%s=", escaped);
curl_free(escaped);
p += len;
s -= len;
/*
* We wrote the attribute header, record progress.
*/
f = p;
ctx->state = READ_STATE_ATTR_CONT;
}
/*
* Write out single attribute string.
*/
len = vp_prints_value(p , s, current[0], 0);
escaped = curl_escape(p, len);
len = strlen(escaped);
if (s < len) {
curl_free(escaped);
goto no_space;
}
len = strlcpy(p, escaped, len + 1);
curl_free(escaped);
RDEBUG("\tLength : %i", len);
RDEBUG("\tValue : %s", p);
p += len;
s -= len;
if (*++current) {
if (!--s) goto no_space;
*p++ = '&';
}
/*
* We wrote one full attribute value pair, record progress.
*/
f = p;
ctx->next = current;
ctx->state = READ_STATE_ATTR_BEGIN;
}
end_chunk:
*p = '\0';
len = p - (char*)ptr;
RDEBUG2("POST Data: %s", (char*) ptr);
RDEBUG2("Returning %i bytes of POST data", len);
return len;
/*
* Cleanup for error conditions
*/
no_space:
*f = '\0';
len = f - (char*)ptr;
RDEBUG2("POST Data: %s", (char*) ptr);
/*
* The buffer wasn't big enough to encode a single attribute chunk.
*/
if (!len) {
radlog(L_ERR, "rlm_rest (%s): AVP exceeds buffer length"
" or chunk", ctx->instance->xlat_name);
} else {
RDEBUG2("Returning %i bytes of POST data"
" (buffer full or chunk exceeded)", len);
}
return len;
}
/** Encodes VALUE_PAIR linked list in JSON format
*
* This is a stream function matching the rest_read_t prototype. Multiple
* successive calls will return additional encoded VALUE_PAIRs.
*
* Only complete attribute headers
* @verbatim "<name>":{"type":"<type>","value":[' @endverbatim
* and complete attribute values will be written to ptr.
*
* If an attribute occurs multiple times in the request the attribute values
* will be concatenated into a single value array.
*
* JSON request format is:
@verbatim
{
"<attribute0>":{
"type":"<type0>",
"value":[<value0>,<value1>,<valueN>]
},
"<attribute1>":{
"type":"<type1>",
"value":[...]
},
"<attributeN>":{
"type":"<typeN>",
"value":[...]
},
}
@endverbatim
*
* @param[out] ptr Char buffer to write encoded data to.
* @param[in] size Multiply by nmemb to get the length of ptr.
* @param[in] nmemb Multiply by size to get the length of ptr.
* @param[in] userdata rlm_rest_read_t to keep encoding state between calls.
* @return length of data (including NULL) written to ptr, or 0 if no more
* data to write.
*/
static size_t rest_encode_json(void *ptr, size_t size, size_t nmemb,
void *userdata)
{
rlm_rest_read_t *ctx = userdata;
REQUEST *request = ctx->request; /* Used by RDEBUG */
VALUE_PAIR **current = ctx->next;
char *p = ptr; /* Position in buffer */
char *f = ptr; /* Position in buffer of last fully encoded attribute or value */
const char *type;
ssize_t len = 0;
ssize_t s = (size * nmemb) - 1;
assert(s > 0);
/* Allow manual chunking */
if ((ctx->chunk) && (ctx->chunk <= s)) {
s = (ctx->chunk - 1);
}
if (ctx->state == READ_STATE_END) return FALSE;
if (ctx->state == READ_STATE_INIT) {
ctx->state = READ_STATE_ATTR_BEGIN;
if (!--s) goto no_space;
*p++ = '{';
}
while (s > 0) {
if (!*current) {
ctx->state = READ_STATE_END;
if (!--s) goto no_space;
*p++ = '}';
goto end_chunk;
}
/*
* New attribute, write name, type, and beginning of
* value array.
*/
RDEBUG2("Encoding attribute \"%s\"", current[0]->da->name);
if (ctx->state == READ_STATE_ATTR_BEGIN) {
type = fr_int2str(dict_attr_types, current[0]->da->type,
"¿Unknown?");
len = strlen(type);
len += strlen(current[0]->da->name);
if (s < (23 + len)) goto no_space;
len = sprintf(p, "\"%s\":{\"type\":\"%s\",\"value\":[" ,
current[0]->da->name, type);
p += len;
s -= len;
RDEBUG2("\tType : %s", type);
/*
* We wrote the attribute header, record progress
*/
f = p;
ctx->state = READ_STATE_ATTR_CONT;
}
/*
* Put all attribute values in an array for easier remote
* parsing whether they're multivalued or not.
*/
while (TRUE) {
len = vp_prints_value_json(p , s, current[0]);
assert((s - len) >= 0);
if (len < 0) goto no_space;
/*
* Show actual value length minus quotes
*/
RDEBUG2("\tLength : %i", (*p == '"') ? (len - 2) : len);
RDEBUG2("\tValue : %s", p);
p += len;
s -= len;
/*
* Multivalued attribute
*/
if (current[1] &&
(current[0]->da == current[1]->da)) {
*p++ = ',';
current++;
/*
* We wrote one attribute value, record
* progress.
*/
f = p;
ctx->next = current;
} else {
break;
}
}
if (!(s -= 2)) goto no_space;
*p++ = ']';
*p++ = '}';
if (*++current) {
if (!--s) goto no_space;
*p++ = ',';
}
/*
* We wrote one full attribute value pair, record progress.
*/
f = p;
ctx->next = current;
ctx->state = READ_STATE_ATTR_BEGIN;
}
end_chunk:
*p = '\0';
len = p - (char*)ptr;
RDEBUG2("JSON Data: %s", (char*) ptr);
RDEBUG2("Returning %i bytes of JSON data", len);
return len;
/*
* Were out of buffer space
*/
no_space:
*f = '\0';
len = f - (char*)ptr;
RDEBUG2("JSON Data: %s", (char*) ptr);
/*
* The buffer wasn't big enough to encode a single attribute chunk.
*/
if (!len) {
radlog(L_ERR, "rlm_rest (%s): AVP exceeds buffer length"
" or chunk", ctx->instance->xlat_name);
} else {
RDEBUG2("Returning %i bytes of JSON data"
" (buffer full or chunk exceeded)", len);
}
return len;
}
/** Emulates successive libcurl calls to an encoding function
*
* This function is used when the request will be sent to the HTTP server as one
* contiguous entity. A buffer of REST_BODY_INCR bytes is allocated and passed
* to the stream encoding function.
*
* If the stream function does not return 0, a new buffer is allocated which is
* the size of the previous buffer + REST_BODY_INCR bytes, the data from the
* previous buffer is copied, and freed, and another call is made to the stream
* function, passing a pointer into the new buffer at the end of the previously
* written data.
*
* This process continues until the stream function signals (by returning 0)
* that it has no more data to write.
*
* @param[out] buffer where the pointer to the malloced buffer should
* be written.
* @param[in] func Stream function.
* @param[in] limit Maximum buffer size to alloc.
* @param[in] userdata rlm_rest_read_t to keep encoding state between calls to
* stream function.
* @return the length of the data written to the buffer (excluding NULL) or -1
* if alloc >= limit.
*/
static ssize_t rest_read_wrapper(char **buffer, rest_read_t func,
size_t limit, void *userdata)
{
char *previous = NULL;
char *current;
size_t alloc = REST_BODY_INCR; /* Size of buffer to malloc */
size_t used = 0; /* Size of data written */
size_t len = 0;
while (alloc < limit) {
current = rad_malloc(alloc);
if (previous) {
strlcpy(current, previous, used + 1);
free(previous);
}
len = func(current + used, REST_BODY_INCR, 1, userdata);
used += len;
if (!len) {
*buffer = current;
return used;
}
alloc += REST_BODY_INCR;
previous = current;
};
free(current);
return -1;
}
/** (Re-)Initialises the data in a rlm_rest_read_t.
*
* Resets the values of a rlm_rest_read_t to their defaults.
*
* Must be called between encoding sessions.
*
* As part of initialisation all VALUE_PAIR pointers in the REQUEST packet are
* written to an array.
*
* If sort is TRUE, this array of VALUE_PAIR pointers will be sorted by vendor
* and then by attribute. This is for stream encoders which may concatenate
* multiple attribute values together into an array.
*
* After the encoding session has completed this array must be freed by calling
* rest_read_ctx_free .
*
* @see rest_read_ctx_free
*
* @param[in] request Current request.
* @param[in] ctx to initialise.
* @param[in] sort If TRUE VALUE_PAIRs will be sorted within the VALUE_PAIR
* pointer array.
*/
static void rest_read_ctx_init(REQUEST *request,
rlm_rest_read_t *ctx,
int sort)
{
unsigned short count = 0, i;
unsigned short swap;
VALUE_PAIR **current, *tmp;
/*
* Setup stream read data
*/
ctx->request = request;
ctx->state = READ_STATE_INIT;
/*
* Create sorted array of VP pointers
*/
tmp = request->packet->vps;
while (tmp != NULL) {
tmp = tmp->next;
count++;
}
ctx->first = current = rad_malloc((sizeof(tmp) * (count + 1)));
ctx->next = ctx->first;
tmp = request->packet->vps;
while (tmp != NULL) {
*current++ = tmp;
tmp = tmp->next;
}
current[0] = NULL;
current = ctx->first;
if (!sort || (count < 2)) return;
/* TODO: Quicksort would be faster... */
do {
for(i = 1; i < count; i++) {
swap = 0;
if (current[i-1]->da > current[i]->da) {
tmp = current[i];
current[i] = current[i-1];
current[i-1] = tmp;
swap = 1;
}
}
} while (swap);
}
/** Frees the VALUE_PAIR array created by rest_read_ctx_init.
*
* Must be called between encoding sessions else module will leak VALUE_PAIR
* pointers.
*
* @see rest_read_ctx_init
*
* @param[in] ctx to free.
*/
static void rest_read_ctx_free(rlm_rest_read_t *ctx)
{
if (ctx->first != NULL) {
free(ctx->first);
}
}
/** Converts POST response into VALUE_PAIRs and adds them to the request
*
* Accepts VALUE_PAIRS in the same format as rest_encode_post, but with the
* addition of optional attribute list qualifiers as part of the attribute name
* string.
*
* If no qualifiers are specified, will default to the request list.
*
* POST response format is:
* @verbatim [outer.][<list>:]<attribute0>=<value0>&[outer.][<list>:]<attribute1>=<value1>&[outer.][<list>:]<attributeN>=<valueN> @endverbatim
*
* @see rest_encode_post
*
* @param[in] instance configuration data.
* @param[in] section configuration data.
* @param[in] handle rlm_rest_handle_t to use.
* @param[in] request Current request.
* @param[in] raw buffer containing POST data.
* @param[in] rawlen Length of data in raw buffer.
* @return the number of VALUE_PAIRs processed or -1 on unrecoverable error.
*/
static int rest_decode_post(rlm_rest_t *instance,
UNUSED rlm_rest_section_t *section,
REQUEST *request, void *handle, char *raw,
UNUSED size_t rawlen)
{
rlm_rest_handle_t *randle = handle;
CURL *candle = randle->handle;
const char *p = raw, *q;
const char *attribute;
char *name = NULL;
char *value = NULL;
char buffer[1024];
const DICT_ATTR *da;
VALUE_PAIR *vp;
const DICT_ATTR **current, *processed[REST_BODY_MAX_ATTRS + 1];
pair_lists_t list_name;
request_refs_t request_name;
REQUEST *reference = request;
VALUE_PAIR **vps;
size_t len;
int curl_len; /* Length from last curl_easy_unescape call */
int count = 0;
processed[0] = NULL;
/*
* Empty response?
*/
while (isspace(*p)) p++;
if (*p == '\0') return FALSE;
while (((q = strchr(p, '=')) != NULL) &&
(count < REST_BODY_MAX_ATTRS)) {
attribute = name;
reference = request;
name = curl_easy_unescape(candle, p, (q - p), &curl_len);
p = (q + 1);
RDEBUG("Decoding attribute \"%s\"", name);
request_name = radius_request_name(&attribute, REQUEST_CURRENT);
if (request_name == REQUEST_UNKNOWN) {
RDEBUGW("Invalid request qualifier, skipping");
curl_free(name);
continue;
}
if (!radius_request(&reference, request_name)) {
RDEBUGW("Attribute name refers to outer request"