Fix a typo in a comment
[libisds.git] / src / soap.c
blobb78ab688cd0b536012248da7ab976c76a1e2d2e1
1 #include "isds_priv.h"
2 #include "soap.h"
3 #include "utils.h"
4 #include <stdlib.h>
5 #include <string.h>
6 #include <strings.h> /* strncasecmp(3) */
7 #include "system.h"
9 /* Private structure for write_body() call back */
10 struct soap_body {
11 void *data;
12 size_t length;
15 /* Private structure for write_header() call back */
16 struct auth_headers {
17 _Bool is_complete; /* Response has finished, next iteration is new
18 response, values become obsolete. */
19 char *last_header; /* Temporary storage for previous unfinished header */
20 char *method; /* WWW-Authenticate value */
21 char *code; /* X-Response-message-code value */
22 isds_otp_resolution resolution; /* Decoded .code member */
23 char *message; /* X-Response-message-text value */
24 char *redirect; /* Redirect URL */
28 /* Deallocate content of struct auth_headers */
29 static void auth_headers_free(struct auth_headers *headers) {
30 zfree(headers->last_header);
31 zfree(headers->method);
32 zfree(headers->code);
33 zfree(headers->message);
34 zfree(headers->redirect);
38 /* If given @line is HTTP header of @name,
39 * return pointer to the header value. Otherwise return NULL.
40 * @name is header name without name---value separator, terminated with 0. */
41 static const char *header_value(const char *line, const char *name) {
42 const char *value;
43 if (line == NULL || name == NULL) return NULL;
45 for (value = line; ; value++, name++) {
46 if (*value == '\0') return NULL; /* Line too short */
47 if (*name == '\0') break; /* Name matches */
48 if (*name != *value) return NULL; /* Name does not match */
51 /* Check separator. RFC2616, section 4.2 requires collon only. */
52 if (*value++ != ':') return NULL;
54 return value;
58 /* Try to decode header value per RFC 2047.
59 * @prepend_space is true if a space should be inserted before decoded word
60 * into @output in case the word has been decoded successfully.
61 * @input is zero terminated input, it's updated to point all consumed
62 * input - 1.
63 * @output is buffer to store decoded value, it's updated to point after last
64 * written character. The buffer must be preallocated.
65 * @return 0 if input has been successfully decoded, then @input and @output
66 * poineres will be updated. Otherwise return non-zero value and keeps
67 * argument pointers and memory unchanged. */
68 static int try_rfc2047_decode(_Bool prepend_space, const char **input,
69 char **output) {
70 const char *encoded;
71 const char *charset_start, *encoding, *end;
72 size_t charset_length;
73 char *charset = NULL;
74 /* ISDS prescribes B encoding only, but RFC 2047 requires to support Q
75 * encoding too. ISDS prescribes UTF-8 charset only, RFC requiers to
76 * support any MIME charset. */
77 if (input == NULL || *input == NULL || output == NULL || *output == NULL)
78 return -1;
80 /* Start is "=?" */
81 encoded = *input;
82 if (encoded[0] != '=' || encoded[1] != '?')
83 return -1;
85 /* Then is "CHARSET?" */
86 charset_start = (encoded += 2);
87 while (*encoded != '?') {
88 if (*encoded == '\0')
89 return -1;
90 if (*encoded == ' ' || *encoded == '\t' || *encoded == '\r' || *encoded == '\n')
91 return -1;
92 encoded++;
94 encoded++;
96 /* Then is "ENCODING?", where ENCODING is /[BbQq]/ */
97 if (*encoded == '\0') return -1;
98 encoding = encoded++;
99 if (*encoded != '?')
100 return -1;
101 encoded++;
103 /* Then is "ENCODED_TEXT?=" */
104 while (*encoded != '?') {
105 if (*encoded == '\0')
106 return -1;
107 if (*encoded == ' ' || *encoded == '\t' || *encoded == '\r' || *encoded == '\n')
108 return -1;
109 encoded++;
111 end = encoded;
112 if (*(++encoded) != '=') return -1;
114 /* Now pointers are:
115 * "=?CHARSET?E?ENCODED_TEXT?="
116 * | | | ||
117 * | | | |\- encoded
118 * | | | \- end
119 * | | \- encoding
120 * | \- charset_start
121 * \- *input
124 charset_length = encoding - charset_start - 1;
125 if (charset_length < 1)
126 return -1;
127 charset = strndup(charset_start, charset_length);
128 if (charset == NULL)
129 return -1;
131 /* Decode encoding */
132 char *bit_stream = NULL;
133 size_t bit_length = 0;
134 size_t encoding_length = end - encoding - 2;
136 if (*encoding == 'B') {
137 /* Decode Base-64 */
138 char *b64_stream = NULL;
139 if (NULL == (b64_stream =
140 malloc((encoding_length + 1) * sizeof(*encoding)))) {
141 free(charset);
142 return -1;
144 memcpy(b64_stream, encoding + 2, encoding_length);
145 b64_stream[encoding_length] = '\0';
146 bit_length = _isds_b64decode(b64_stream, (void **)&bit_stream);
147 free(b64_stream);
148 if (bit_length == (size_t) -1) {
149 free(charset);
150 return -1;
152 } else if (*encoding == 'Q') {
153 /* Decode Quoted-printable-like */
154 if (NULL == (bit_stream =
155 malloc((encoding_length) * sizeof(*encoding)))) {
156 free(charset);
157 return -1;
159 for (size_t q = 2; q < encoding_length + 2; q++) {
160 if (encoding[q] == '_') {
161 bit_stream[bit_length] = '\x20';
162 } else if (encoding[q] == '=') {
163 int ordinar;
164 /* Validate "=HH", where H is hexadecimal digit */
165 if (q + 2 >= encoding_length + 2 ) {
166 free(bit_stream);
167 free(charset);
168 return -1;
170 /* Convert =HH */
171 if ((ordinar = _isds_hex2i(encoding[++q])) < 0) {
172 free(bit_stream);
173 free(charset);
174 return -1;
176 bit_stream[bit_length] = (ordinar << 4);
177 if ((ordinar = _isds_hex2i(encoding[++q])) < 0) {
178 free(bit_stream);
179 free(charset);
180 return -1;
182 bit_stream[bit_length] += ordinar;
183 } else {
184 bit_stream[bit_length] = encoding[q];
186 bit_length++;
188 } else {
189 /* Unknown encoding */
190 free(charset);
191 return -1;
194 /* Convert to UTF-8 */
195 char *utf_stream = NULL;
196 size_t utf_length;
197 utf_length = _isds_any2any(charset, "UTF-8", bit_stream, bit_length,
198 (void **)&utf_stream);
199 free(bit_stream);
200 free(charset);
201 if (utf_length == (size_t) -1) {
202 return -1;
205 /* Copy UTF-8 stream to output buffer */
206 if (prepend_space) {
207 **output = ' ';
208 (*output)++;
210 memcpy(*output, utf_stream, utf_length);
211 free(utf_stream);
212 *output += utf_length;
214 *input = encoded;
215 return 0;
219 /* Decode HTTP header value per RFC 2047.
220 * @encoded_value is encoded HTTP header value terminated with NUL. It can
221 * contain HTTP LWS separators that will be replaced with a space.
222 * @return newly allocated decoded value without EOL, or return NULL. */
223 static char *decode_header_value(const char *encoded_value) {
224 char *decoded = NULL, *decoded_cursor;
225 size_t content_length;
226 _Bool text_started = 0, lws_seen = 0, encoded_word_seen = 0;
228 if (encoded_value == NULL) return NULL;
229 content_length = strlen(encoded_value);
231 /* A character can occupy up to 6 bytes in UTF-8 */
232 decoded = malloc(content_length * 6 + 1);
233 if (decoded == NULL) {
234 /* ENOMEM */
235 return NULL;
238 /* Decode */
239 /* RFC 2616, section 4.2: Remove surrounding LWS, replace inner ones with
240 * a space. */
241 /* RFC 2047, section 6.2: LWS between adjacent encoded words is ignored.
242 * */
243 for (decoded_cursor = decoded; *encoded_value; encoded_value++) {
244 if (*encoded_value == '\r' || *encoded_value == '\n' ||
245 *encoded_value == '\t' || *encoded_value == ' ') {
246 lws_seen = 1;
247 continue;
249 if (*encoded_value == '=' &&
250 !try_rfc2047_decode(
251 lws_seen && text_started && !encoded_word_seen,
252 &encoded_value, &decoded_cursor)) {
253 encoded_word_seen = 1;
254 } else {
255 if (lws_seen && text_started)
256 *(decoded_cursor++) = ' ';
257 *(decoded_cursor++) = *encoded_value;
258 encoded_word_seen = 0;
260 lws_seen = 0;
261 text_started = 1;
263 *decoded_cursor = '\0';
265 return decoded;
269 /* Return true, if server requests OTP authorization method that client
270 * requested. Otherwise return false.
271 * @client_method is method client requested
272 * @server_method is value of WWW-Authenticate header */
273 /*static _Bool otp_method_matches(const isds_otp_method client_method,
274 const char *server_method) {
275 char *method_name = NULL;
277 switch (client_method) {
278 case OTP_HMAC: method_name = "hotp"; break;
279 case OTP_TIME: method_name = "totp"; break;
280 default: return 0;
283 if (!strncmp(server_method, method_name, 4) && (
284 server_method[4] == '\0' || server_method[4] == ' ' ||
285 server_method[4] == '\t'))
286 return 1;
287 return 0;
291 /* Convert UTF-8 @string to HTTP OTP resolution enum type.
292 * @Return corresponding value or OTP_RESOLUTION_UNKNOWN if @string is not
293 * defined or unknown value. */
294 static isds_otp_resolution string2isds_otp_resolution(const char *string) {
295 if (string == NULL)
296 return OTP_RESOLUTION_UNKNOWN;
297 else if (!strcmp(string, "authentication.info.totpSended"))
298 return OTP_RESOLUTION_TOTP_SENT;
299 else if (!strcmp(string, "authentication.error.userIsNotAuthenticated"))
300 return OTP_RESOLUTION_BAD_AUTHENTICATION;
301 else if (!strcmp(string, "authentication.error.intruderDetected"))
302 return OTP_RESOLUTION_ACCESS_BLOCKED;
303 else if (!strcmp(string, "authentication.error.paswordExpired"))
304 return OTP_RESOLUTION_PASSWORD_EXPIRED;
305 else if (!strcmp(string, "authentication.info.cannotSendQuickly"))
306 return OTP_RESOLUTION_TO_FAST;
307 else if (!strcmp(string, "authentication.error.badRole"))
308 return OTP_RESOLUTION_UNAUTHORIZED;
309 else if (!strcmp(string, "authentication.info.totpNotSended"))
310 return OTP_RESOLUTION_TOTP_NOT_SENT;
311 else
312 return OTP_RESOLUTION_UNKNOWN;
316 /* Close connection to server and destroy CURL handle associated
317 * with @context */
318 _hidden isds_error _isds_close_connection(struct isds_ctx *context) {
319 if (!context) return IE_INVALID_CONTEXT;
321 if (context->curl) {
322 curl_easy_cleanup(context->curl);
323 context->curl = NULL;
324 isds_log(ILF_HTTP, ILL_DEBUG, _("Connection to server %s closed\n"),
325 context->url);
326 return IE_SUCCESS;
327 } else {
328 return IE_CONNECTION_CLOSED;
333 /* Remove username and password from context CURL handle. */
334 static isds_error unset_http_authorization(struct isds_ctx *context) {
335 isds_error error = IE_SUCCESS;
337 if (context == NULL) return IE_INVALID_CONTEXT;
338 if (context->curl == NULL) return IE_CONNECTION_CLOSED;
340 #if HAVE_DECL_CURLOPT_USERNAME /* Since curl-7.19.1 */
341 if (curl_easy_setopt(context->curl, CURLOPT_USERNAME, NULL))
342 error = IE_ERROR;
343 if (curl_easy_setopt(context->curl, CURLOPT_PASSWORD, NULL))
344 error = IE_ERROR;
345 #else
346 if (curl_easy_setopt(context->curl, CURLOPT_USERPWD, NULL))
347 error = IE_ERROR;
348 #endif /* not HAVE_DECL_CURLOPT_USERNAME */
350 if (error)
351 isds_log(ILF_HTTP, ILL_ERR, _("Error while unsetting user name and "
352 "password from CURL handle for connection to server %s.\n"),
353 context->url);
354 else
355 isds_log(ILF_HTTP, ILL_DEBUG, _("User name and password for server %s "
356 "have been unset from CURL handle.\n"), context->url);
357 return error;
361 /* CURL call back function called when chunk of HTTP response body is available.
362 * @buffer points to new data
363 * @size * @nmemb is length of the chunk in bytes. Zero means empty body.
364 * @userp is private structure.
365 * Must return the length of the chunk, otherwise CURL will signal
366 * CURL_WRITE_ERROR. */
367 static size_t write_body(void *buffer, size_t size, size_t nmemb, void *userp) {
368 struct soap_body *body = (struct soap_body *) userp;
369 void *new_data;
371 /* FIXME: Check for (size * nmemb + body->lengt) !> SIZE_T_MAX.
372 * Precompute the product then. */
374 if (!body) return 0; /* This should never happen */
375 if (0 == (size * nmemb)) return 0; /* Empty body */
377 new_data = realloc(body->data, body->length + size * nmemb);
378 if (!new_data) return 0;
380 memcpy(new_data + body->length, buffer, size * nmemb);
382 body->data = new_data;
383 body->length += size * nmemb;
385 return (size * nmemb);
389 /* CURL call back function called when a HTTP response header is available.
390 * This is called for each header even if reply consists of more responses.
391 * @buffer points to new header (no zero terminator, but HTTP EOL is included)
392 * @size * @nmemb is length of the header in bytes
393 * @userp is private structure.
394 * Must return the length of the header, otherwise CURL will signal
395 * CURL_WRITE_ERROR. */
396 static size_t write_header(void *buffer, size_t size, size_t nmemb, void *userp) {
397 struct auth_headers *headers = (struct auth_headers *) userp;
398 size_t length;
399 const char *value;
401 /* FIXME: Check for (size * nmemb) !> SIZE_T_MAX.
402 * Precompute the product then. */
403 length = size * nmemb;
405 if (NULL == headers) return 0; /* This should never happen */
406 if (0 == length) {
407 /* ??? Is this the empty line delimiter? */
408 return 0; /* Empty headers */
411 /* New response, invalide authentication headers. */
412 /* XXX: Chunked encoding trailer is not supported */
413 if (headers->is_complete) auth_headers_free(headers);
415 /* Append continuation to multi-line header */
416 if (*(char *)buffer == ' ' || *(char *)buffer == '\t') {
417 if (headers->last_header != NULL) {
418 size_t old_length = strlen(headers->last_header);
419 char *longer_header = realloc(headers->last_header, old_length + length);
420 if (longer_header == NULL) {
421 /* ENOMEM */
422 return 0;
424 strncpy(longer_header + old_length, (char*)buffer + 1, length - 1);
425 longer_header[old_length + length - 1] = '\0';
426 headers->last_header = longer_header;
427 } else {
428 /* Invalid continuation without starting header will be skipped. */
429 isds_log(ILF_HTTP, ILL_WARNING,
430 _("HTTP header continuation without starting header has "
431 "been encountered. Skipping invalid HTTP response "
432 "line.\n"));
434 goto leave;
437 /* Decode last header */
438 value = header_value(headers->last_header, "WWW-Authenticate");
439 if (value != NULL) {
440 free(headers->method);
441 if (NULL == (headers->method = decode_header_value(value))) {
442 /* TODO: Set IE_NOMEM to context */
443 return 0;
445 goto store;
448 value = header_value(headers->last_header, "X-Response-message-code");
449 if (value != NULL) {
450 free(headers->code);
451 if (NULL == (headers->code = decode_header_value(value))) {
452 /* TODO: Set IE_NOMEM to context */
453 return 0;
455 goto store;
458 value = header_value(headers->last_header, "X-Response-message-text");
459 if (value != NULL) {
460 free(headers->message);
461 if (NULL == (headers->message = decode_header_value(value))) {
462 /* TODO: Set IE_NOMEM to context */
463 return 0;
465 goto store;
468 store:
469 /* Last header decoded, free it */
470 zfree(headers->last_header);
472 if (!strncmp(buffer, "\r\n", length)) {
473 /* Current line is header---body separator */
474 headers->is_complete = 1;
475 goto leave;
476 } else {
477 /* Current line is new header, store it */
478 headers->last_header = malloc(length + 1);
479 if (headers->last_header == NULL) {
480 /* TODO: Set IE_NOMEM to context */
481 return 0;
483 memcpy(headers->last_header, buffer, length);
484 headers->last_header[length] = '\0';
487 leave:
488 return (length);
492 /* CURL progress callback proxy to rearrange arguments.
493 * @curl_data is session context */
494 static int progress_proxy(void *curl_data, double download_total,
495 double download_current, double upload_total, double upload_current) {
496 struct isds_ctx *context = (struct isds_ctx *) curl_data;
497 int abort = 0;
499 if (context && context->progress_callback) {
500 abort = context->progress_callback(
501 upload_total, upload_current,
502 download_total, download_current,
503 context->progress_callback_data);
504 if (abort) {
505 isds_log(ILF_HTTP, ILL_INFO,
506 _("Application aborted HTTP transfer"));
510 return abort;
514 /* CURL call back function called when curl has something to log.
515 * @curl is cURL context
516 * @type is cURL log facility
517 * @buffer points to log data, XXX: not zero-terminated
518 * @size is length of log data
519 * @userp is private structure.
520 * Must return 0. */
521 static int log_curl(CURL *curl, curl_infotype type, char *buffer, size_t size,
522 void *userp) {
523 if (!buffer || 0 == size) return 0;
524 if (type == CURLINFO_TEXT || type == CURLINFO_HEADER_IN ||
525 type == CURLINFO_HEADER_OUT)
526 isds_log(ILF_HTTP, ILL_DEBUG, "%*s", size, buffer);
527 return 0;
531 /* Do HTTP request.
532 * @context holds the base URL,
533 * @url is a (CGI) file of SOAP URL,
534 * @use_get is a false to do a POST request, true to do a GET request.
535 * @request is body for POST request
536 * @request_length is length of @request in bytes
537 * @reponse is automatically reallocated() buffer to fit HTTP response with
538 * @response_length (does not need to match allocated memory exactly). You must
539 * free() the @response.
540 * @mime_type is automatically allocated MIME type send by server (*NULL if not
541 * sent). Set NULL if you don't care.
542 * @charset is charset of the body signaled by server. The same constrains
543 * like on @mime_type apply.
544 * @http_code is final HTTP code returned by server. This can be 200, 401, 500
545 * or any other one. Pass NULL if you don't interest.
546 * In case of error, the response memory, MIME type, charset and length will be
547 * deallocated and zeroed automatically. Thus be sure they are preallocated or
548 * they points to NULL.
549 * @response_otp_headers is pre-allocated structure for OTP authentication
550 * headers sent by server. Members must be valid pointers or NULLs.
551 * Pass NULL if you don't interest.
552 * Be ware that successful return value does not mean the HTTP request has
553 * been accepted by the server. You must consult @http_code. OTOH, failure
554 * return value means the request could not been sent (e.g. SSL error).
555 * Side effect: message buffer */
556 static isds_error http(struct isds_ctx *context,
557 const char *url, _Bool use_get,
558 const void *request, const size_t request_length,
559 void **response, size_t *response_length,
560 char **mime_type, char **charset, long *http_code,
561 struct auth_headers *response_otp_headers) {
563 CURLcode curl_err;
564 isds_error err = IE_SUCCESS;
565 struct soap_body body;
566 char *content_type;
567 struct curl_slist *headers = NULL;
570 if (!context) return IE_INVALID_CONTEXT;
571 if (!url) return IE_INVAL;
572 if (request_length > 0 && !request) return IE_INVAL;
573 if (!response || !response_length) return IE_INVAL;
575 /* Clean authentication headers */
577 /* Set the body here to allow deallocation in leave block */
578 body.data = *response;
579 body.length = 0;
581 /* Set Request-URI */
582 curl_err = curl_easy_setopt(context->curl, CURLOPT_URL, url);
584 /* Set TLS options */
585 if (!curl_err && context->tls_verify_server) {
586 if (!*context->tls_verify_server)
587 isds_log(ILF_SEC, ILL_WARNING,
588 _("Disabling server identity verification. "
589 "That was your decision.\n"));
590 curl_err = curl_easy_setopt(context->curl, CURLOPT_SSL_VERIFYPEER,
591 (*context->tls_verify_server)? 1L : 0L);
592 if (!curl_err) {
593 curl_err = curl_easy_setopt(context->curl, CURLOPT_SSL_VERIFYHOST,
594 (*context->tls_verify_server)? 2L : 0L);
597 if (!curl_err && context->tls_ca_file) {
598 isds_log(ILF_SEC, ILL_INFO,
599 _("CA certificates will be searched in `%s' file since now\n"),
600 context->tls_ca_file);
601 curl_err = curl_easy_setopt(context->curl, CURLOPT_CAINFO,
602 context->tls_ca_file);
604 if (!curl_err && context->tls_ca_dir) {
605 isds_log(ILF_SEC, ILL_INFO,
606 _("CA certificates will be searched in `%s' directory "
607 "since now\n"), context->tls_ca_dir);
608 curl_err = curl_easy_setopt(context->curl, CURLOPT_CAPATH,
609 context->tls_ca_dir);
611 if (!curl_err && context->tls_crl_file) {
612 #if HAVE_DECL_CURLOPT_CRLFILE /* Since curl-7.19.0 */
613 isds_log(ILF_SEC, ILL_INFO,
614 _("CRLs will be searched in `%s' file since now\n"),
615 context->tls_crl_file);
616 curl_err = curl_easy_setopt(context->curl, CURLOPT_CRLFILE,
617 context->tls_crl_file);
618 #else
619 isds_log(ILF_SEC, ILL_WARNING,
620 _("Your curl library cannot pass certificate revocation "
621 "list to cryptographic library.\n"
622 "Make sure cryptographic library default setting "
623 "delivers proper CRLs,\n"
624 "or upgrade curl.\n"));
625 #endif /* not HAVE_DECL_CURLOPT_CRLFILE */
629 /* Set credentials */
630 #if HAVE_DECL_CURLOPT_USERNAME /* Since curl-7.19.1 */
631 if (!curl_err && context->username) {
632 curl_err = curl_easy_setopt(context->curl, CURLOPT_USERNAME,
633 context->username);
635 if (!curl_err && context->password) {
636 curl_err = curl_easy_setopt(context->curl, CURLOPT_PASSWORD,
637 context->password);
639 #else
640 if (!curl_err && (context->username || context->password)) {
641 char *userpwd =
642 _isds_astrcat3(context->username, ":", context->password);
643 if (!userpwd) {
644 isds_log_message(context, _("Could not pass credentials to CURL"));
645 err = IE_NOMEM;
646 goto leave;
648 curl_err = curl_easy_setopt(context->curl, CURLOPT_USERPWD, userpwd);
649 free(userpwd);
651 #endif /* not HAVE_DECL_CURLOPT_USERNAME */
653 /* Set PKI credentials */
654 if (!curl_err && (context->pki_credentials)) {
655 if (context->pki_credentials->engine) {
656 /* Select SSL engine */
657 isds_log(ILF_SEC, ILL_INFO,
658 _("Cryptographic engine `%s' will be used for "
659 "key or certificate\n"),
660 context->pki_credentials->engine);
661 curl_err = curl_easy_setopt(context->curl, CURLOPT_SSLENGINE,
662 context->pki_credentials->engine);
665 if (!curl_err) {
666 /* Select certificate format */
667 #if HAVE_DECL_CURLOPT_SSLCERTTYPE /* since curl-7.9.3 */
668 if (context->pki_credentials->certificate_format ==
669 PKI_FORMAT_ENG) {
670 /* XXX: It's valid to have certificate in engine without name.
671 * Engines can select certificate according private key and
672 * vice versa. */
673 if (context->pki_credentials->certificate)
674 isds_log(ILF_SEC, ILL_INFO, _("Client `%s' certificate "
675 "will be read from `%s' engine\n"),
676 context->pki_credentials->certificate,
677 context->pki_credentials->engine);
678 else
679 isds_log(ILF_SEC, ILL_INFO, _("Client certificate "
680 "will be read from `%s' engine\n"),
681 context->pki_credentials->engine);
682 curl_err = curl_easy_setopt(context->curl, CURLOPT_SSLCERTTYPE,
683 "ENG");
684 } else if (context->pki_credentials->certificate) {
685 isds_log(ILF_SEC, ILL_INFO, _("Client %s certificate "
686 "will be read from `%s' file\n"),
687 (context->pki_credentials->certificate_format ==
688 PKI_FORMAT_DER) ? _("DER") : _("PEM"),
689 context->pki_credentials->certificate);
690 curl_err = curl_easy_setopt(context->curl, CURLOPT_SSLCERTTYPE,
691 (context->pki_credentials->certificate_format ==
692 PKI_FORMAT_DER) ? "DER" : "PEM");
694 #else
695 if ((context->pki_credentials->certificate_format ==
696 PKI_FORMAT_ENG ||
697 context->pki_credentials->certificate))
698 isds_log(ILF_SEC, ILL_WARNING,
699 _("Your curl library cannot distinguish certificate "
700 "formats. Make sure your cryptographic library\n"
701 "understands your certificate file by default, "
702 "or upgrade curl.\n"));
703 #endif /* not HAVE_DECL_CURLOPT_SSLCERTTYPE */
706 if (!curl_err && context->pki_credentials->certificate) {
707 /* Select certificate */
708 if (!curl_err)
709 curl_err = curl_easy_setopt(context->curl, CURLOPT_SSLCERT,
710 context->pki_credentials->certificate);
713 if (!curl_err) {
714 /* Select key format */
715 if (context->pki_credentials->key_format == PKI_FORMAT_ENG) {
716 if (context->pki_credentials->key)
717 isds_log(ILF_SEC, ILL_INFO, _("Client private key `%s' "
718 "from `%s' engine will be used\n"),
719 context->pki_credentials->key,
720 context->pki_credentials->engine);
721 else
722 isds_log(ILF_SEC, ILL_INFO, _("Client private key "
723 "from `%s' engine will be used\n"),
724 context->pki_credentials->engine);
725 curl_err = curl_easy_setopt(context->curl, CURLOPT_SSLKEYTYPE,
726 "ENG");
727 } else if (context->pki_credentials->key) {
728 isds_log(ILF_SEC, ILL_INFO, _("Client %s private key will be "
729 "read from `%s' file\n"),
730 (context->pki_credentials->key_format ==
731 PKI_FORMAT_DER) ? _("DER") : _("PEM"),
732 context->pki_credentials->key);
733 curl_err = curl_easy_setopt(context->curl, CURLOPT_SSLKEYTYPE,
734 (context->pki_credentials->key_format ==
735 PKI_FORMAT_DER) ? "DER" : "PEM");
738 if (!curl_err)
739 /* Select key */
740 curl_err = curl_easy_setopt(context->curl, CURLOPT_SSLKEY,
741 context->pki_credentials->key);
743 if (!curl_err) {
744 /* Pass key pass-phrase */
745 #if HAVE_DECL_CURLOPT_KEYPASSWD /* since curl-7.16.5 */
746 curl_err = curl_easy_setopt(context->curl,
747 CURLOPT_KEYPASSWD,
748 context->pki_credentials->passphrase);
749 #elif HAVE_DECL_CURLOPT_SSLKEYPASSWD /* up to curl-7.16.4 */
750 curl_err = curl_easy_setopt(context->curl,
751 CURLOPT_SSLKEYPASSWD,
752 context->pki_credentials->passphrase);
753 #else /* up to curl-7.9.2 */
754 curl_err = curl_easy_setopt(context->curl,
755 CURLOPT_SSLCERTPASSWD,
756 context->pki_credentials->passphrase);
757 #endif
762 /* Set authorization cookie for OTP session */
763 if (!curl_err && context->otp) {
764 isds_log(ILF_SEC, ILL_INFO,
765 _("Cookies will be stored and sent "
766 "because context has been authorized by OTP.\n"));
767 curl_err = curl_easy_setopt(context->curl, CURLOPT_COOKIEFILE, "");
770 /* Set timeout */
771 if (!curl_err) {
772 curl_err = curl_easy_setopt(context->curl, CURLOPT_NOSIGNAL, 1);
774 if (!curl_err && context->timeout) {
775 #if HAVE_DECL_CURLOPT_TIMEOUT_MS /* Since curl-7.16.2 */
776 curl_err = curl_easy_setopt(context->curl, CURLOPT_TIMEOUT_MS,
777 context->timeout);
778 #else
779 curl_err = curl_easy_setopt(context->curl, CURLOPT_TIMEOUT,
780 context->timeout / 1000);
781 #endif /* not HAVE_DECL_CURLOPT_TIMEOUT_MS */
784 /* Register callback */
785 if (context->progress_callback) {
786 if (!curl_err) {
787 curl_err = curl_easy_setopt(context->curl, CURLOPT_NOPROGRESS, 0);
789 if (!curl_err) {
790 curl_err = curl_easy_setopt(context->curl,
791 CURLOPT_PROGRESSFUNCTION, progress_proxy);
793 if (!curl_err) {
794 curl_err = curl_easy_setopt(context->curl, CURLOPT_PROGRESSDATA,
795 context);
799 /* Set other CURL features */
800 if (!curl_err) {
801 curl_err = curl_easy_setopt(context->curl, CURLOPT_FAILONERROR, 0);
804 /* Set get-response function */
805 if (!curl_err) {
806 curl_err = curl_easy_setopt(context->curl, CURLOPT_WRITEFUNCTION,
807 write_body);
809 if (!curl_err) {
810 curl_err = curl_easy_setopt(context->curl, CURLOPT_WRITEDATA, &body);
813 /* Set get-response-headers function if needed.
814 * XXX: Both CURLOPT_HEADERFUNCTION and CURLOPT_WRITEHEADER must be set or
815 * unset at the same time (see curl_easy_setopt(3)) ASAP, otherwise old
816 * invalid CURLOPT_WRITEHEADER value could be derefenced. */
817 if (!curl_err) {
818 curl_err = curl_easy_setopt(context->curl, CURLOPT_HEADERFUNCTION,
819 (response_otp_headers == NULL) ? NULL: write_header);
821 if (!curl_err) {
822 curl_err = curl_easy_setopt(context->curl, CURLOPT_WRITEHEADER,
823 response_otp_headers);
826 /* Set MIME types and headers requires by SOAP 1.1.
827 * SOAP 1.1 requires text/xml, SOAP 1.2 requires application/soap+xml */
828 if (!curl_err) {
829 headers = curl_slist_append(headers,
830 "Accept: application/soap+xml,application/xml,text/xml");
831 if (!headers) {
832 err = IE_NOMEM;
833 goto leave;
835 headers = curl_slist_append(headers, "Content-Type: text/xml");
836 if (!headers) {
837 err = IE_NOMEM;
838 goto leave;
840 headers = curl_slist_append(headers, "SOAPAction: ");
841 if (!headers) {
842 err = IE_NOMEM;
843 goto leave;
845 curl_err = curl_easy_setopt(context->curl, CURLOPT_HTTPHEADER, headers);
847 if (!curl_err) {
848 /* Set user agent identification */
849 curl_err = curl_easy_setopt(context->curl, CURLOPT_USERAGENT,
850 "libisds/" PACKAGE_VERSION);
853 if (use_get) {
854 /* Set GET request */
855 if (!curl_err) {
856 curl_err = curl_easy_setopt(context->curl, CURLOPT_HTTPGET, 1);
858 } else {
859 /* Set POST request body */
860 if (!curl_err) {
861 curl_err = curl_easy_setopt(context->curl, CURLOPT_POST, 1);
863 if (!curl_err) {
864 curl_err = curl_easy_setopt(context->curl, CURLOPT_POSTFIELDS, request);
866 if (!curl_err) {
867 curl_err = curl_easy_setopt(context->curl, CURLOPT_POSTFIELDSIZE,
868 request_length);
873 /* Debug cURL if requested */
874 _Bool debug_curl =
875 ((log_facilities & ILF_HTTP) && (log_level >= ILL_DEBUG));
876 if (!curl_err) {
877 curl_err = curl_easy_setopt(context->curl, CURLOPT_VERBOSE,
878 (debug_curl) ? 1 : 0);
880 if (!curl_err) {
881 curl_err = curl_easy_setopt(context->curl, CURLOPT_DEBUGFUNCTION,
882 (debug_curl) ? log_curl : NULL);
886 /* Check for errors so far */
887 if (curl_err) {
888 isds_log_message(context, curl_easy_strerror(curl_err));
889 err = IE_NETWORK;
890 goto leave;
893 isds_log(ILF_HTTP, ILL_DEBUG, _("Sending %s request to <%s>\n"),
894 use_get ? "GET" : "POST", url);
895 if (!use_get) {
896 isds_log(ILF_HTTP, ILL_DEBUG,
897 _("POST body length: %zu, content follows:\n"), request_length);
898 isds_log(ILF_HTTP, ILL_DEBUG, "%.*s\n", request_length, request);
899 isds_log(ILF_HTTP, ILL_DEBUG, _("End of POST body\n"));
903 /* Do the request */
904 curl_err = curl_easy_perform(context->curl);
906 if (!curl_err)
907 curl_err = curl_easy_getinfo(context->curl, CURLINFO_CONTENT_TYPE,
908 &content_type);
910 if (curl_err) {
911 /* TODO: Use curl_easy_setopt(CURLOPT_ERRORBUFFER) to obtain detailed
912 * error message. */
913 /* TODO: CURL is not internationalized yet. Collect CURL messages for
914 * I18N. */
915 isds_printf_message(context,
916 _("%s: %s"), url, _(curl_easy_strerror(curl_err)));
917 if (curl_err == CURLE_ABORTED_BY_CALLBACK)
918 err = IE_ABORTED;
919 else if (
920 curl_err == CURLE_SSL_CONNECT_ERROR ||
921 curl_err == CURLE_SSL_ENGINE_NOTFOUND ||
922 curl_err == CURLE_SSL_ENGINE_SETFAILED ||
923 curl_err == CURLE_SSL_CERTPROBLEM ||
924 curl_err == CURLE_SSL_CIPHER ||
925 curl_err == CURLE_SSL_CACERT ||
926 curl_err == CURLE_USE_SSL_FAILED ||
927 curl_err == CURLE_SSL_ENGINE_INITFAILED ||
928 curl_err == CURLE_SSL_CACERT_BADFILE ||
929 curl_err == CURLE_SSL_SHUTDOWN_FAILED ||
930 curl_err == CURLE_SSL_CRL_BADFILE ||
931 curl_err == CURLE_SSL_ISSUER_ERROR
933 err = IE_SECURITY;
934 else
935 err = IE_NETWORK;
936 goto leave;
939 isds_log(ILF_HTTP, ILL_DEBUG, _("Final response to %s received\n"), url);
940 isds_log(ILF_HTTP, ILL_DEBUG,
941 _("Response body length: %zu, content follows:\n"),
942 body.length);
943 isds_log(ILF_HTTP, ILL_DEBUG, "%.*s\n", body.length, body.data);
944 isds_log(ILF_HTTP, ILL_DEBUG, _("End of response body\n"));
947 /* Extract MIME type and charset */
948 if (content_type) {
949 char *sep;
950 size_t offset;
952 sep = strchr(content_type, ';');
953 if (sep) offset = (size_t) (sep - content_type);
954 else offset = strlen(content_type);
956 if (mime_type) {
957 *mime_type = malloc(offset + 1);
958 if (!*mime_type) {
959 err = IE_NOMEM;
960 goto leave;
962 memcpy(*mime_type, content_type, offset);
963 (*mime_type)[offset] = '\0';
966 if (charset) {
967 if (!sep) {
968 *charset = NULL;
969 } else {
970 sep = strstr(sep, "charset=");
971 if (!sep) {
972 *charset = NULL;
973 } else {
974 *charset = strdup(sep + 8);
975 if (!*charset) {
976 err = IE_NOMEM;
977 goto leave;
984 /* Get HTTP response code */
985 if (http_code) {
986 curl_err = curl_easy_getinfo(context->curl,
987 CURLINFO_RESPONSE_CODE, http_code);
988 if (curl_err) {
989 err = IE_ERROR;
990 goto leave;
994 /* Store OTP authentication results */
995 if (response_otp_headers && response_otp_headers->is_complete) {
996 isds_log(ILF_SEC, ILL_DEBUG,
997 _("OTP authentication headers received: "
998 "method=%s, code=%s, message=%s\n"),
999 response_otp_headers->method, response_otp_headers->code,
1000 response_otp_headers->message);
1002 /* XXX: Don't make unknown code fatal. Missing code can be succcess if
1003 * HTTP code is 302. This is checked in _isds_soap(). */
1004 response_otp_headers->resolution =
1005 string2isds_otp_resolution(response_otp_headers->code);
1007 if (response_otp_headers->message != NULL) {
1008 char *message_locale = _isds_utf82locale(response_otp_headers->message);
1009 /* _isds_utf82locale() return NULL on inconverable string. Do not
1010 * panic on it.
1011 * TODO: Escape such characters.
1012 * if (message_locale == NULL) {
1013 err = IE_NOMEM;
1014 goto leave;
1016 isds_printf_message(context,
1017 _("Server returned OTP authentication message: %s"),
1018 message_locale);
1019 free(message_locale);
1022 char *next_url = NULL; /* Weak pointer managed by cURL */
1023 curl_err = curl_easy_getinfo(context->curl, CURLINFO_REDIRECT_URL,
1024 &next_url);
1025 if (curl_err) {
1026 err = IE_ERROR;
1027 goto leave;
1029 if (next_url != NULL) {
1030 isds_log(ILF_SEC, ILL_DEBUG,
1031 _("OTP authentication headers redirect to: <%s>\n"),
1032 next_url);
1033 free(response_otp_headers->redirect);
1034 response_otp_headers->redirect = strdup(next_url);
1035 if (response_otp_headers->redirect == NULL) {
1036 err = IE_NOMEM;
1037 goto leave;
1041 leave:
1042 curl_slist_free_all(headers);
1044 if (err) {
1045 free(body.data);
1046 body.data = NULL;
1047 body.length = 0;
1049 if (mime_type) {
1050 free(*mime_type);
1051 *mime_type = NULL;
1053 if (charset) {
1054 free(*charset);
1055 *charset = NULL;
1058 if (err != IE_ABORTED) _isds_close_connection(context);
1061 *response = body.data;
1062 *response_length = body.length;
1064 return err;
1068 /* Do SOAP request.
1069 * @context holds the base URL,
1070 * @file is a (CGI) file of SOAP URL,
1071 * @request is XML node set with SOAP request body.
1072 * @file must be NULL, @request should be NULL rather than empty, if they should
1073 * not be signaled in the SOAP request.
1074 * @reponse is automatically allocated() node set with SOAP response body.
1075 * You must xmlFreeNodeList() it. This is literal body, empty (NULL), one node
1076 * or more nodes can be returned.
1077 * @raw_response is automatically allocated bit stream with response body. Use
1078 * NULL if you don't care
1079 * @raw_response_length is size of @raw_response in bytes
1080 * In case of error the response will be deallocated automatically.
1081 * Side effect: message buffer */
1082 _hidden isds_error _isds_soap(struct isds_ctx *context, const char *file,
1083 const xmlNodePtr request, xmlNodePtr *response,
1084 void **raw_response, size_t *raw_response_length) {
1086 isds_error err = IE_SUCCESS;
1087 char *url = NULL;
1088 char *mime_type = NULL;
1089 long http_code = 0;
1090 struct auth_headers response_otp_headers;
1091 xmlBufferPtr http_request = NULL;
1092 xmlSaveCtxtPtr save_ctx = NULL;
1093 xmlDocPtr request_soap_doc = NULL;
1094 xmlNodePtr request_soap_envelope = NULL, request_soap_body = NULL;
1095 xmlNsPtr soap_ns = NULL;
1096 void *http_response = NULL;
1097 size_t response_length = 0;
1098 xmlDocPtr response_soap_doc = NULL;
1099 xmlNodePtr response_root = NULL;
1100 xmlXPathContextPtr xpath_ctx = NULL;
1101 xmlXPathObjectPtr response_soap_headers = NULL, response_soap_body = NULL,
1102 response_soap_fault = NULL;
1105 if (!context) return IE_INVALID_CONTEXT;
1106 if (!response) return IE_INVAL;
1107 if (!raw_response_length && raw_response) return IE_INVAL;
1109 xmlFreeNodeList(*response);
1110 *response = NULL;
1111 if (raw_response) *raw_response = NULL;
1113 url = _isds_astrcat(context->url, file);
1114 if (!url) return IE_NOMEM;
1116 /* Build SOAP request envelope */
1117 request_soap_doc = xmlNewDoc(BAD_CAST "1.0");
1118 if (!request_soap_doc) {
1119 isds_log_message(context, _("Could not build SOAP request document"));
1120 err = IE_ERROR;
1121 goto leave;
1123 request_soap_envelope = xmlNewNode(NULL, BAD_CAST "Envelope");
1124 if (!request_soap_envelope) {
1125 isds_log_message(context, _("Could not build SOAP request envelope"));
1126 err = IE_ERROR;
1127 goto leave;
1129 xmlDocSetRootElement(request_soap_doc, request_soap_envelope);
1130 /* Only this way we get namespace definition as @xmlns:soap,
1131 * otherwise we get namespace prefix without definition */
1132 soap_ns = xmlNewNs(request_soap_envelope, BAD_CAST SOAP_NS, NULL);
1133 if(!soap_ns) {
1134 isds_log_message(context, _("Could not create SOAP name space"));
1135 err = IE_ERROR;
1136 goto leave;
1138 xmlSetNs(request_soap_envelope, soap_ns);
1139 request_soap_body = xmlNewChild(request_soap_envelope, NULL,
1140 BAD_CAST "Body", NULL);
1141 if (!request_soap_body) {
1142 isds_log_message(context,
1143 _("Could not add Body to SOAP request envelope"));
1144 err = IE_ERROR;
1145 goto leave;
1148 /* Append request XML node set to SOAP body if request is not empty */
1149 /* XXX: Copy of request must be used, otherwise xmlFreeDoc(request_soap_doc)
1150 * would destroy this outer structure. */
1151 if (request) {
1152 xmlNodePtr request_copy = xmlCopyNodeList(request);
1153 if (!request_copy) {
1154 isds_log_message(context,
1155 _("Could not copy request content"));
1156 err = IE_ERROR;
1157 goto leave;
1159 if (!xmlAddChildList(request_soap_body, request_copy)) {
1160 xmlFreeNodeList(request_copy);
1161 isds_log_message(context,
1162 _("Could not add request content to SOAP "
1163 "request envelope"));
1164 err = IE_ERROR;
1165 goto leave;
1170 /* Serialize the SOAP request into HTTP request body */
1171 http_request = xmlBufferCreate();
1172 if (!http_request) {
1173 isds_log_message(context,
1174 _("Could not create xmlBuffer for HTTP request body"));
1175 err = IE_ERROR;
1176 goto leave;
1178 /* Last argument 1 means format the XML tree. This is pretty but it breaks
1179 * XML document transport as it adds text nodes (indentiation) between
1180 * elements. */
1181 save_ctx = xmlSaveToBuffer(http_request, "UTF-8", 0);
1182 if (!save_ctx) {
1183 isds_log_message(context,
1184 _("Could not create XML serializer"));
1185 err = IE_ERROR;
1186 goto leave;
1188 /* XXX: According LibXML documentation, this function does not return
1189 * meaningful value yet */
1190 xmlSaveDoc(save_ctx, request_soap_doc);
1191 if (-1 == xmlSaveFlush(save_ctx)) {
1192 isds_log_message(context,
1193 _("Could not serialize SOAP request to HTTP request body"));
1194 err = IE_ERROR;
1195 goto leave;
1198 if (context->otp_credentials != NULL)
1199 memset(&response_otp_headers, 0, sizeof(response_otp_headers));
1200 redirect:
1201 if (context->otp_credentials != NULL)
1202 auth_headers_free(&response_otp_headers);
1203 isds_log(ILF_SOAP, ILL_DEBUG,
1204 _("SOAP request to sent to %s:\n%.*s\nEnd of SOAP request\n"),
1205 url, http_request->use, http_request->content);
1207 err = http(context, url, 0, http_request->content, http_request->use,
1208 &http_response, &response_length,
1209 &mime_type, NULL, &http_code,
1210 (context->otp_credentials == NULL) ? NULL: &response_otp_headers);
1212 /* TODO: HTTP binding for SOAP prescribes non-200 HTTP return codes
1213 * to be processed too. */
1215 if (err) {
1216 goto leave;
1219 if (NULL != context->otp_credentials)
1220 context->otp_credentials->resolution = response_otp_headers.resolution;
1222 /* Check for HTTP return code */
1223 isds_log(ILF_SOAP, ILL_DEBUG, _("Server returned %ld HTTP code\n"),
1224 http_code);
1225 switch (http_code) {
1226 /* XXX: We must see which code is used for not permitted ISDS
1227 * operation like downloading message without proper user
1228 * permissions. In that case we should keep connection opened. */
1229 case 200:
1230 if (NULL != context->otp_credentials) {
1231 if (context->otp_credentials->resolution ==
1232 OTP_RESOLUTION_UNKNOWN)
1233 context->otp_credentials->resolution =
1234 OTP_RESOLUTION_SUCCESS;
1236 break;
1237 case 302:
1238 if (NULL != context->otp_credentials) {
1239 if (context->otp_credentials->resolution ==
1240 OTP_RESOLUTION_UNKNOWN)
1241 context->otp_credentials->resolution =
1242 OTP_RESOLUTION_SUCCESS;
1243 err = IE_PARTIAL_SUCCESS;
1244 isds_printf_message(context,
1245 _("Server redirects on <%s> because OTP authentication "
1246 "succeeded."),
1247 url);
1248 if (context->otp_credentials->otp_code != NULL &&
1249 response_otp_headers.redirect != NULL) {
1250 /* XXX: If OTP code is known, this must be second OTP phase, so
1251 * send final POST request and unset Basic authentication
1252 * from cURL context as cookie is used instead. */
1253 free(url);
1254 url = response_otp_headers.redirect;
1255 response_otp_headers.redirect = NULL;
1256 _isds_discard_credentials(context, 0);
1257 err = unset_http_authorization(context);
1258 if (err) {
1259 isds_log_message(context, _("Could not remove "
1260 "credentials from CURL handle."));
1261 goto leave;
1263 goto redirect;
1264 } else {
1265 /* XXX: Otherwise bail out to ask application for OTP code. */
1266 goto leave;
1268 } else {
1269 err = IE_HTTP;
1270 isds_printf_message(context,
1271 _("Code 302: Server redirects on <%s> request. "
1272 "Redirection is forbidden in stateless mode."),
1273 url);
1274 goto leave;
1276 break;
1277 case 401: /* ISDS server returns 401 even if Authorization
1278 presents. */
1279 case 403: /* HTTP/1.0 prescribes 403 if Authorization presents. */
1280 err = IE_NOT_LOGGED_IN;
1281 isds_log_message(context, _("Authentication failed"));
1282 goto leave;
1283 break;
1284 case 404:
1285 err = IE_HTTP;
1286 isds_printf_message(context,
1287 _("Code 404: Document (%s) not found on server"), url);
1288 goto leave;
1289 break;
1290 /* 500 should return standard SOAP message */
1293 /* Check for Content-Type: text/xml.
1294 * Do it after HTTP code check because 401 Unauthorized returns HTML web
1295 * page for browsers. */
1296 if (mime_type && strcmp(mime_type, "text/xml")
1297 && strcmp(mime_type, "application/soap+xml")
1298 && strcmp(mime_type, "application/xml")) {
1299 char *mime_type_locale = _isds_utf82locale(mime_type);
1300 isds_printf_message(context,
1301 _("%s: bad MIME type sent by server: %s"), url,
1302 mime_type_locale);
1303 free(mime_type_locale);
1304 err = IE_SOAP;
1305 goto leave;
1308 /* TODO: Convert returned body into XML default encoding */
1310 /* Parse the HTTP body as XML */
1311 response_soap_doc = xmlParseMemory(http_response, response_length);
1312 if (!response_soap_doc) {
1313 err = IE_XML;
1314 goto leave;
1317 xpath_ctx = xmlXPathNewContext(response_soap_doc);
1318 if (!xpath_ctx) {
1319 err = IE_ERROR;
1320 goto leave;
1323 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
1324 err = IE_ERROR;
1325 goto leave;
1328 isds_log(ILF_SOAP, ILL_DEBUG,
1329 _("SOAP response received:\n%.*s\nEnd of SOAP response\n"),
1330 response_length, http_response);
1333 /* Check for SOAP version */
1334 response_root = xmlDocGetRootElement(response_soap_doc);
1335 if (!response_root) {
1336 isds_log_message(context, "SOAP response has no root element");
1337 err = IE_SOAP;
1338 goto leave;
1340 if (xmlStrcmp(response_root->name, BAD_CAST "Envelope") ||
1341 xmlStrcmp(response_root->ns->href, BAD_CAST SOAP_NS)) {
1342 isds_log_message(context, "SOAP response is not SOAP 1.1 document");
1343 err = IE_SOAP;
1344 goto leave;
1347 /* Check for SOAP Headers */
1348 response_soap_headers = xmlXPathEvalExpression(
1349 BAD_CAST "/soap:Envelope/soap:Header/"
1350 "*[@soap:mustUnderstand/text() = true()]", xpath_ctx);
1351 if (!response_soap_headers) {
1352 err = IE_ERROR;
1353 goto leave;
1355 if (!xmlXPathNodeSetIsEmpty(response_soap_headers->nodesetval)) {
1356 isds_log_message(context,
1357 _("SOAP response requires unsupported feature"));
1358 /* TODO: log the headers
1359 * xmlChar *fragment = NULL;
1360 * fragment = xmlXPathCastNodeSetToSting(response_soap_headers->nodesetval);*/
1361 err = IE_NOTSUP;
1362 goto leave;
1365 /* Get SOAP Body */
1366 response_soap_body = xmlXPathEvalExpression(
1367 BAD_CAST "/soap:Envelope/soap:Body", xpath_ctx);
1368 if (!response_soap_body) {
1369 err = IE_ERROR;
1370 goto leave;
1372 if (xmlXPathNodeSetIsEmpty(response_soap_body->nodesetval)) {
1373 isds_log_message(context,
1374 _("SOAP response does not contain SOAP Body element"));
1375 err = IE_SOAP;
1376 goto leave;
1378 if (response_soap_body->nodesetval->nodeNr > 1) {
1379 isds_log_message(context,
1380 _("SOAP response has more than one Body element"));
1381 err = IE_SOAP;
1382 goto leave;
1385 /* Check for SOAP Fault */
1386 response_soap_fault = xmlXPathEvalExpression(
1387 BAD_CAST "/soap:Envelope/soap:Body/soap:Fault", xpath_ctx);
1388 if (!response_soap_fault) {
1389 err = IE_ERROR;
1390 goto leave;
1392 if (!xmlXPathNodeSetIsEmpty(response_soap_fault->nodesetval)) {
1393 /* Server signals Fault. Gather error message and croak. */
1394 /* XXX: Only first message is passed */
1395 char *message = NULL, *message_locale = NULL;
1396 xpath_ctx->node = response_soap_fault->nodesetval->nodeTab[0];
1397 xmlXPathFreeObject(response_soap_fault);
1398 /* XXX: faultstring and faultcode are in no name space according
1399 * ISDS specification */
1400 /* First more verbose faultstring */
1401 response_soap_fault = xmlXPathEvalExpression(
1402 BAD_CAST "faultstring[1]/text()", xpath_ctx);
1403 if (response_soap_fault &&
1404 !xmlXPathNodeSetIsEmpty(response_soap_fault->nodesetval)) {
1405 message = (char *)
1406 xmlXPathCastNodeSetToString(response_soap_fault->nodesetval);
1407 message_locale = _isds_utf82locale(message);
1409 /* If not available, try shorter faultcode */
1410 if (!message_locale) {
1411 free(message);
1412 xmlXPathFreeObject(response_soap_fault);
1413 response_soap_fault = xmlXPathEvalExpression(
1414 BAD_CAST "faultcode[1]/text()", xpath_ctx);
1415 if (response_soap_fault &&
1416 !xmlXPathNodeSetIsEmpty(response_soap_fault->nodesetval)) {
1417 message = (char *)
1418 xmlXPathCastNodeSetToString(
1419 response_soap_fault->nodesetval);
1420 message_locale = _isds_utf82locale(message);
1424 /* Croak */
1425 if (message_locale)
1426 isds_printf_message(context, _("SOAP response signals Fault: %s"),
1427 message_locale);
1428 else
1429 isds_log_message(context, _("SOAP response signals Fault"));
1431 free(message_locale);
1432 free(message);
1434 err = IE_SOAP;
1435 goto leave;
1439 /* Extract XML Tree with ISDS response from SOAP envelope and return it.
1440 * XXX: response_soap_body is Body, we need children which may not exist
1441 * (i.e. empty Body). */
1442 /* TODO: Destroy SOAP response but Body children. This is more memory
1443 * friendly than copying (potentially) fat body */
1444 if (response_soap_body->nodesetval->nodeTab[0]->children) {
1445 *response = xmlDocCopyNodeList(response_soap_doc,
1446 response_soap_body->nodesetval->nodeTab[0]->children);
1447 if (!*response) {
1448 err = IE_NOMEM;
1449 goto leave;
1451 } else *response = NULL;
1453 /* Save raw response */
1454 if (raw_response) {
1455 *raw_response = http_response;
1456 *raw_response_length = response_length;
1457 http_response = NULL;
1461 leave:
1462 if (err) {
1463 xmlFreeNodeList(*response);
1464 *response = NULL;
1467 xmlXPathFreeObject(response_soap_fault);
1468 xmlXPathFreeObject(response_soap_body);
1469 xmlXPathFreeObject(response_soap_headers);
1470 xmlXPathFreeContext(xpath_ctx);
1471 xmlFreeDoc(response_soap_doc);
1472 if (context->otp_credentials != NULL)
1473 auth_headers_free(&response_otp_headers);
1474 free(mime_type);
1475 free(http_response);
1476 xmlSaveClose(save_ctx);
1477 xmlBufferFree(http_request);
1478 xmlFreeDoc(request_soap_doc); /* recursive, frees request_body, soap_ns*/
1479 free(url);
1481 return err;
1485 /* Build new URL from current @context and template.
1486 * @context is context carrying an URL
1487 * @template is printf(3) format string. First argument is string of base URL
1488 * found in @context, second argument is length of the base URL.
1489 * @new_url is newly allocated URL built from @template. Caller must free it.
1490 * Return IE_SUCCESS, or corresponding error code and @new_url will not be
1491 * allocated.
1492 * */
1493 _hidden isds_error _isds_build_url_from_context(struct isds_ctx *context,
1494 const char *template, char **new_url) {
1495 int length, slashes;
1497 if (NULL != new_url) *new_url = NULL;
1498 if (NULL == context) return IE_INVALID_CONTEXT;
1499 if (NULL == template) return IE_INVAL;
1500 if (NULL == new_url) return IE_INVAL;
1502 /* Find length of base URL from context URL */
1503 if (NULL == context->url) {
1504 isds_log_message(context, _("Base URL could not have been determined "
1505 "from context URL because there was no URL set in the "
1506 "context"));
1507 return IE_ERROR;
1509 for (length = 0, slashes = 0; context->url[length] != '\0'; length++) {
1510 if (context->url[length] == '/') slashes++;
1511 if (slashes == 3) break;
1513 if (slashes != 3) {
1514 isds_log_message(context, _("Base URL could not have been determined "
1515 "from context URL"));
1516 return IE_ERROR;
1518 length++;
1520 /* Build new URL */
1521 if (-1 == isds_asprintf(new_url, template, context->url, length))
1522 return IE_NOMEM;
1524 return IE_SUCCESS;
1528 /* Invalidate session cookie for otp authenticated @context */
1529 _hidden isds_error _isds_invalidate_otp_cookie(struct isds_ctx *context) {
1530 isds_error err;
1531 char *url = NULL;
1532 long http_code;
1533 void *response = NULL;
1534 size_t response_length;
1536 if (context == NULL || !context->otp) return IE_INVALID_CONTEXT;
1537 if (context->curl == NULL) return IE_CONNECTION_CLOSED;
1539 /* Build logout URL */
1540 /*"https://DOMAINNAME/as/processLogout?uri=https://DOMAINNAME/apps/DS/WEB_SERVICE_ENDPOINT"*/
1541 err = _isds_build_url_from_context(context,
1542 "%1$.*2$sas/processLogout?uri=%1$sDS/dz", &url);
1543 if (err) return err;
1545 /* Invalidate the cookie by GET request */
1546 err = http(context,
1547 url, 1,
1548 NULL, 0,
1549 &response, &response_length,
1550 NULL, NULL, &http_code,
1551 NULL);
1552 free(response);
1553 free(url);
1554 if (err) {
1555 /* long message set by http() */
1556 } else if (http_code != 200) {
1557 /* TODO: Specification does not define response for this request.
1558 * Especially it does not state whether direct 200 or 302 redirect is
1559 * sent. We need to check real implementation. */
1560 err = IE_ISDS;
1561 isds_printf_message(context, _("Cookie for OTP authenticated "
1562 "connection to <%s> could not been invalidated"),
1563 context->url);
1564 } else {
1565 isds_log(ILF_SEC, ILL_DEBUG, _("Cookie for OTP authenticated "
1566 "connection to <%s> has been invalidated.\n"),
1567 context->url);
1569 return err;
1573 /* LibXML functions:
1575 * void xmlInitParser(void)
1576 * Initialization function for the XML parser. This is not reentrant. Call
1577 * once before processing in case of use in multithreaded programs.
1579 * int xmlInitParserCtxt(xmlParserCtxtPtr ctxt)
1580 * Initialize a parser context
1582 * xmlDocPtr xmlCtxtReadDoc(xmlParserCtxtPtr ctxt, const xmlChar * cur,
1583 * const * char URL, const char * encoding, int options);
1584 * Parse in-memory NULL-terminated document @cur.
1586 * xmlDocPtr xmlParseMemory(const char * buffer, int size)
1587 * Parse an XML in-memory block and build a tree.
1589 * xmlParserCtxtPtr xmlCreateMemoryParserCtxt(const char * buffer, int
1590 * size);
1591 * Create a parser context for an XML in-memory document.
1593 * xmlParserCtxtPtr xmlCreateDocParserCtxt(const xmlChar * cur)
1594 * Creates a parser context for an XML in-memory document.
1596 * xmlDocPtr xmlCtxtReadMemory(xmlParserCtxtPtr ctxt,
1597 * const char * buffer, int size, const char * URL, const char * encoding,
1598 * int options)
1599 * Parse an XML in-memory document and build a tree. This reuses the existing
1600 * @ctxt parser context.
1602 * void xmlCleanupParser(void)
1603 * Cleanup function for the XML library. It tries to reclaim all parsing
1604 * related glob document related memory. Calling this function should not
1605 * prevent reusing the libr finished using the library or XML document built
1606 * with it.
1608 * void xmlClearParserCtxt(xmlParserCtxtPtr ctxt)
1609 * Clear (release owned resources) and reinitialize a parser context.
1611 * void xmlCtxtReset(xmlParserCtxtPtr ctxt)
1612 * Reset a parser context
1614 * void xmlFreeParserCtxt(xmlParserCtxtPtr ctxt)
1615 * Free all the memory used by a parser context. However the parsed document
1616 * in ctxt->myDoc is not freed.
1618 * void xmlFreeDoc(xmlDocPtr cur)
1619 * Free up all the structures used by a document, tree included.