Do not process DataBoxCreditInfo response on server error
[libisds.git] / src / isds.c
blob18c2e0d7e7466aed57a432a224aa00afec7b980f
1 #include "isds_priv.h"
2 #include <stdlib.h>
3 #include <string.h>
4 #include <stdio.h>
5 #include <stdarg.h>
6 #include <ctype.h>
7 #include <stdint.h>
8 #include <limits.h> /* Because of LONG_{MIN,MAX} constants */
9 #include "utils.h"
10 #if HAVE_LIBCURL
11 #include "soap.h"
12 #endif
13 #include "validator.h"
14 #include "crypto.h"
15 #include <gpg-error.h> /* Because of ksba or gpgme */
16 #include "physxml.h"
17 #include "system.h"
19 /* Locators */
20 /* Base URL of production ISDS instance */
21 const char isds_locator[] = "https://ws1.mojedatovaschranka.cz/";
22 const char isds_cert_locator[] = "https://ws1c.mojedatovaschranka.cz/";
23 const char isds_otp_locator[] = "https://www.mojedatovaschranka.cz/";
25 /* Base URL of production ISDS instance */
26 const char isds_testing_locator[] = "https://ws1.czebox.cz/";
27 const char isds_cert_testing_locator[] = "https://ws1c.czebox.cz/";
28 const char isds_otp_testing_locator[] = "https://www.czebox.cz/";
30 /* Extension to MIME type map */
31 static const xmlChar *extension_map_mime[] = {
32 BAD_CAST "cer", BAD_CAST "application/x-x509-ca-cert",
33 BAD_CAST "crt", BAD_CAST "application/x-x509-ca-cert",
34 BAD_CAST "der", BAD_CAST "application/x-x509-ca-cert",
35 BAD_CAST "doc", BAD_CAST "application/msword",
36 BAD_CAST "docx", BAD_CAST "application/vnd.openxmlformats-officedocument."
37 "wordprocessingml.document",
38 BAD_CAST "dbf", BAD_CAST "application/octet-stream",
39 BAD_CAST "prj", BAD_CAST "application/octet-stream",
40 BAD_CAST "qix", BAD_CAST "application/octet-stream",
41 BAD_CAST "sbn", BAD_CAST "application/octet-stream",
42 BAD_CAST "sbx", BAD_CAST "application/octet-stream",
43 BAD_CAST "shp", BAD_CAST "application/octet-stream",
44 BAD_CAST "shx", BAD_CAST "application/octet-stream",
45 BAD_CAST "dgn", BAD_CAST "application/octet-stream",
46 BAD_CAST "dwg", BAD_CAST "image/vnd.dwg",
47 BAD_CAST "edi", BAD_CAST "application/edifact",
48 BAD_CAST "fo", BAD_CAST "application/vnd.software602.filler.form+xml",
49 BAD_CAST "gfs", BAD_CAST "application/xml",
50 BAD_CAST "gml", BAD_CAST "application/xml",
51 BAD_CAST "gif", BAD_CAST "image/gif",
52 BAD_CAST "htm", BAD_CAST "text/html",
53 BAD_CAST "html", BAD_CAST "text/html",
54 BAD_CAST "isdoc", BAD_CAST "text/isdoc",
55 BAD_CAST "isdocx", BAD_CAST "text/isdocx",
56 BAD_CAST "jfif", BAD_CAST "image/jpeg",
57 BAD_CAST "jpg", BAD_CAST "image/jpeg",
58 BAD_CAST "jpeg", BAD_CAST "image/jpeg",
59 BAD_CAST "mpeg", BAD_CAST "video/mpeg",
60 BAD_CAST "mpeg1", BAD_CAST "video/mpeg",
61 BAD_CAST "mpeg2", BAD_CAST "video/mpeg",
62 BAD_CAST "mpg", BAD_CAST "video/mpeg",
63 BAD_CAST "mp2", BAD_CAST "audio/mpeg",
64 BAD_CAST "mp3", BAD_CAST "audio/mpeg",
65 BAD_CAST "odp", BAD_CAST "application/vnd.oasis.opendocument.presentation",
66 BAD_CAST "ods", BAD_CAST "application/vnd.oasis.opendocument.spreadsheet",
67 BAD_CAST "odt", BAD_CAST "application/vnd.oasis.opendocument.text",
68 BAD_CAST "pdf", BAD_CAST "application/pdf",
69 BAD_CAST "p7b", BAD_CAST "application/pkcs7-certificates",
70 BAD_CAST "p7c", BAD_CAST "application/pkcs7-mime",
71 BAD_CAST "p7m", BAD_CAST "application/pkcs7-mime",
72 BAD_CAST "p7f", BAD_CAST "application/pkcs7-signature",
73 BAD_CAST "p7s", BAD_CAST "application/pkcs7-signature",
74 BAD_CAST "pk7", BAD_CAST "application/pkcs7-mime",
75 BAD_CAST "png", BAD_CAST "image/png",
76 BAD_CAST "ppt", BAD_CAST "application/vnd.ms-powerpoint",
77 BAD_CAST "pptx", BAD_CAST "application/vnd.openxmlformats-officedocument."
78 "presentationml.presentation",
79 BAD_CAST "rtf", BAD_CAST "application/rtf",
80 BAD_CAST "tif", BAD_CAST "image/tiff",
81 BAD_CAST "tiff", BAD_CAST "image/tiff",
82 BAD_CAST "tsr", BAD_CAST "application/timestamp-reply",
83 BAD_CAST "tst", BAD_CAST "application/timestamp-reply",
84 BAD_CAST "txt", BAD_CAST "text/plain",
85 BAD_CAST "wav", BAD_CAST "audio/wav",
86 BAD_CAST "xls", BAD_CAST "application/vnd.ms-excel",
87 BAD_CAST "xlsx", BAD_CAST "application/vnd.openxmlformats-officedocument."
88 "spreadsheetml.sheet",
89 BAD_CAST "xml", BAD_CAST "application/xml",
90 BAD_CAST "xsd", BAD_CAST "application/xml",
91 BAD_CAST "zfo", BAD_CAST "application/vnd.software602.filler.form-xml-zip"
94 /* Structure type to hold conversion table from status code to isds_error and
95 * long message */
96 struct code_map_isds_error {
97 const xmlChar **codes; /* NULL terminated array of status codes */
98 const char **meanings; /* Mapping to non-localized long messages */
99 const isds_error *errors; /* Mapping to isds_error code */
102 /* Deallocate structure isds_pki_credentials and NULL it.
103 * Pass-phrase is discarded.
104 * @pki credentials to to free */
105 void isds_pki_credentials_free(struct isds_pki_credentials **pki) {
106 if(!pki || !*pki) return;
108 free((*pki)->engine);
109 free((*pki)->certificate);
110 free((*pki)->key);
112 if ((*pki)->passphrase) {
113 memset((*pki)->passphrase, 0, strlen((*pki)->passphrase));
114 free((*pki)->passphrase);
117 zfree((*pki));
121 /* Free isds_list with all member data.
122 * @list list to free, on return will be NULL */
123 void isds_list_free(struct isds_list **list) {
124 struct isds_list *item, *next_item;
126 if (!list || !*list) return;
128 for(item = *list; item; item = next_item) {
129 if (item->destructor) (item->destructor)(&(item->data));
130 next_item = item->next;
131 free(item);
134 *list = NULL;
138 /* Deallocate structure isds_hash and NULL it.
139 * @hash hash to to free */
140 void isds_hash_free(struct isds_hash **hash) {
141 if(!hash || !*hash) return;
142 free((*hash)->value);
143 zfree((*hash));
147 /* Deallocate structure isds_PersonName recursively and NULL it */
148 static void isds_PersonName_free(struct isds_PersonName **person_name) {
149 if (!person_name || !*person_name) return;
151 free((*person_name)->pnFirstName);
152 free((*person_name)->pnMiddleName);
153 free((*person_name)->pnLastName);
154 free((*person_name)->pnLastNameAtBirth);
156 free(*person_name);
157 *person_name = NULL;
161 /* Deallocate structure isds_BirthInfo recursively and NULL it */
162 static void isds_BirthInfo_free(struct isds_BirthInfo **birth_info) {
163 if (!birth_info || !*birth_info) return;
165 free((*birth_info)->biDate);
166 free((*birth_info)->biCity);
167 free((*birth_info)->biCounty);
168 free((*birth_info)->biState);
170 free(*birth_info);
171 *birth_info = NULL;
175 /* Deallocate structure isds_Address recursively and NULL it */
176 static void isds_Address_free(struct isds_Address **address) {
177 if (!address || !*address) return;
179 free((*address)->adCity);
180 free((*address)->adStreet);
181 free((*address)->adNumberInStreet);
182 free((*address)->adNumberInMunicipality);
183 free((*address)->adZipCode);
184 free((*address)->adState);
186 free(*address);
187 *address = NULL;
191 /* Deallocate structure isds_DbOwnerInfo recursively and NULL it */
192 void isds_DbOwnerInfo_free(struct isds_DbOwnerInfo **db_owner_info) {
193 if (!db_owner_info || !*db_owner_info) return;
195 free((*db_owner_info)->dbID);
196 free((*db_owner_info)->dbType);
197 free((*db_owner_info)->ic);
198 isds_PersonName_free(&((*db_owner_info)->personName));
199 free((*db_owner_info)->firmName);
200 isds_BirthInfo_free(&((*db_owner_info)->birthInfo));
201 isds_Address_free(&((*db_owner_info)->address));
202 free((*db_owner_info)->nationality);
203 free((*db_owner_info)->email);
204 free((*db_owner_info)->telNumber);
205 free((*db_owner_info)->identifier);
206 free((*db_owner_info)->registryCode);
207 free((*db_owner_info)->dbState);
208 free((*db_owner_info)->dbEffectiveOVM);
210 free(*db_owner_info);
211 *db_owner_info = NULL;
214 /* Deallocate structure isds_DbUserInfo recursively and NULL it */
215 void isds_DbUserInfo_free(struct isds_DbUserInfo **db_user_info) {
216 if (!db_user_info || !*db_user_info) return;
218 free((*db_user_info)->userID);
219 free((*db_user_info)->userType);
220 free((*db_user_info)->userPrivils);
221 isds_PersonName_free(&((*db_user_info)->personName));
222 isds_Address_free(&((*db_user_info)->address));
223 free((*db_user_info)->biDate);
224 free((*db_user_info)->ic);
225 free((*db_user_info)->firmName);
226 free((*db_user_info)->caStreet);
227 free((*db_user_info)->caCity);
228 free((*db_user_info)->caZipCode);
229 free((*db_user_info)->caState);
231 zfree(*db_user_info);
235 /* Deallocate struct isds_event recursively and NULL it */
236 void isds_event_free(struct isds_event **event) {
237 if (!event || !*event) return;
239 free((*event)->time);
240 free((*event)->type);
241 free((*event)->description);
242 zfree(*event);
246 /* Deallocate struct isds_envelope recursively and NULL it */
247 void isds_envelope_free(struct isds_envelope **envelope) {
248 if (!envelope || !*envelope) return;
250 free((*envelope)->dmID);
251 free((*envelope)->dbIDSender);
252 free((*envelope)->dmSender);
253 free((*envelope)->dmSenderAddress);
254 free((*envelope)->dmSenderType);
255 free((*envelope)->dmRecipient);
256 free((*envelope)->dmRecipientAddress);
257 free((*envelope)->dmAmbiguousRecipient);
258 free((*envelope)->dmType);
260 free((*envelope)->dmOrdinal);
261 free((*envelope)->dmMessageStatus);
262 free((*envelope)->dmDeliveryTime);
263 free((*envelope)->dmAcceptanceTime);
264 isds_hash_free(&(*envelope)->hash);
265 free((*envelope)->timestamp);
266 isds_list_free(&(*envelope)->events);
268 free((*envelope)->dmSenderOrgUnit);
269 free((*envelope)->dmSenderOrgUnitNum);
270 free((*envelope)->dbIDRecipient);
271 free((*envelope)->dmRecipientOrgUnit);
272 free((*envelope)->dmRecipientOrgUnitNum);
273 free((*envelope)->dmToHands);
274 free((*envelope)->dmAnnotation);
275 free((*envelope)->dmRecipientRefNumber);
276 free((*envelope)->dmSenderRefNumber);
277 free((*envelope)->dmRecipientIdent);
278 free((*envelope)->dmSenderIdent);
280 free((*envelope)->dmLegalTitleLaw);
281 free((*envelope)->dmLegalTitleYear);
282 free((*envelope)->dmLegalTitleSect);
283 free((*envelope)->dmLegalTitlePar);
284 free((*envelope)->dmLegalTitlePoint);
286 free((*envelope)->dmPersonalDelivery);
287 free((*envelope)->dmAllowSubstDelivery);
289 free((*envelope)->dmOVM);
290 free((*envelope)->dmPublishOwnID);
292 free(*envelope);
293 *envelope = NULL;
297 /* Deallocate struct isds_message recursively and NULL it */
298 void isds_message_free(struct isds_message **message) {
299 if (!message || !*message) return;
301 free((*message)->raw);
302 isds_envelope_free(&((*message)->envelope));
303 isds_list_free(&((*message)->documents));
304 xmlFreeDoc((*message)->xml); (*message)->xml = NULL;
306 free(*message);
307 *message = NULL;
311 /* Deallocate struct isds_document recursively and NULL it */
312 void isds_document_free(struct isds_document **document) {
313 if (!document || !*document) return;
315 if (!(*document)->is_xml) {
316 free((*document)->data);
318 free((*document)->dmMimeType);
319 free((*document)->dmFileGuid);
320 free((*document)->dmUpFileGuid);
321 free((*document)->dmFileDescr);
322 free((*document)->dmFormat);
324 free(*document);
325 *document = NULL;
329 /* Deallocate struct isds_message_copy recursively and NULL it */
330 void isds_message_copy_free(struct isds_message_copy **copy) {
331 if (!copy || !*copy) return;
333 free((*copy)->dbIDRecipient);
334 free((*copy)->dmRecipientOrgUnit);
335 free((*copy)->dmRecipientOrgUnitNum);
336 free((*copy)->dmToHands);
338 free((*copy)->dmStatus);
339 free((*copy)->dmID);
341 zfree(*copy);
345 /* Deallocate struct isds_message_status_change recursively and NULL it */
346 void isds_message_status_change_free(
347 struct isds_message_status_change **message_status_change) {
348 if (!message_status_change || !*message_status_change) return;
350 free((*message_status_change)->dmID);
351 free((*message_status_change)->time);
352 free((*message_status_change)->dmMessageStatus);
354 zfree(*message_status_change);
358 /* Deallocate struct isds_approval recursively and NULL it */
359 void isds_approval_free(struct isds_approval **approval) {
360 if (!approval || !*approval) return;
362 free((*approval)->refference);
364 zfree(*approval);
368 /* Deallocate struct isds_credentials_delivery recursively and NULL it.
369 * The email string is deallocated too. */
370 void isds_credentials_delivery_free(
371 struct isds_credentials_delivery **credentials_delivery) {
372 if (!credentials_delivery || !*credentials_delivery) return;
374 free((*credentials_delivery)->email);
375 free((*credentials_delivery)->token);
376 free((*credentials_delivery)->new_user_name);
378 zfree(*credentials_delivery);
382 /* Deallocate struct isds_commercial_permission recursively and NULL it */
383 void isds_commercial_permission_free(
384 struct isds_commercial_permission **permission) {
385 if (NULL == permission || NULL == *permission) return;
387 free((*permission)->recipient);
388 free((*permission)->payer);
389 free((*permission)->expiration);
390 free((*permission)->count);
391 free((*permission)->reply_identifier);
393 zfree(*permission);
397 /* Deallocate struct isds_credit_event recursively and NULL it */
398 void isds_credit_event_free(struct isds_credit_event **event) {
399 if (NULL == event || NULL == *event) return;
401 free((*event)->time);
402 switch ((*event)->type) {
403 case ISDS_CREDIT_CHARGED:
404 free((*event)->details.charged.transaction);
405 break;
406 case ISDS_CREDIT_DISCHARGED:
407 free((*event)->details.discharged.transaction);
408 break;
409 case ISDS_CREDIT_MESSAGE_SENT:
410 free((*event)->details.message_sent.recipient);
411 free((*event)->details.message_sent.message_id);
412 break;
413 case ISDS_CREDIT_STORAGE_SET:
414 free((*event)->details.storage_set.new_valid_from);
415 free((*event)->details.storage_set.new_valid_to);
416 free((*event)->details.storage_set.old_capacity);
417 free((*event)->details.storage_set.old_valid_from);
418 free((*event)->details.storage_set.old_valid_to);
419 free((*event)->details.storage_set.initiator);
420 break;
421 case ISDS_CREDIT_EXPIRED:
422 break;
425 zfree(*event);
429 /* *DUP_OR_ERROR macros needs error label */
430 #define STRDUP_OR_ERROR(new, template) { \
431 if (!template) { \
432 (new) = NULL; \
433 } else { \
434 (new) = strdup(template); \
435 if (!new) goto error; \
439 #define FLATDUP_OR_ERROR(new, template) { \
440 if (!template) { \
441 (new) = NULL; \
442 } else { \
443 (new) = malloc(sizeof(*(new))); \
444 if (!new) goto error; \
445 memcpy((new), (template), sizeof(*(template))); \
449 /* Copy structure isds_pki_credentials recursively. */
450 struct isds_pki_credentials *isds_pki_credentials_duplicate(
451 const struct isds_pki_credentials *template) {
452 struct isds_pki_credentials *new = NULL;
454 if(!template) return NULL;
456 new = calloc(1, sizeof(*new));
457 if (!new) return NULL;
459 STRDUP_OR_ERROR(new->engine, template->engine);
460 new->certificate_format = template->certificate_format;
461 STRDUP_OR_ERROR(new->certificate, template->certificate);
462 new->key_format = template->key_format;
463 STRDUP_OR_ERROR(new->key, template->key);
464 STRDUP_OR_ERROR(new->passphrase, template->passphrase);
466 return new;
468 error:
469 isds_pki_credentials_free(&new);
470 return NULL;
474 /* Copy structure isds_PersonName recursively */
475 struct isds_PersonName *isds_PersonName_duplicate(
476 const struct isds_PersonName *template) {
477 struct isds_PersonName *new = NULL;
479 if (!template) return NULL;
481 new = calloc(1, sizeof(*new));
482 if (!new) return NULL;
484 STRDUP_OR_ERROR(new->pnFirstName, template->pnFirstName);
485 STRDUP_OR_ERROR(new->pnMiddleName, template->pnMiddleName);
486 STRDUP_OR_ERROR(new->pnLastName, template->pnLastName);
487 STRDUP_OR_ERROR(new->pnLastNameAtBirth, template->pnLastNameAtBirth);
489 return new;
491 error:
492 isds_PersonName_free(&new);
493 return NULL;
497 /* Copy structure isds_BirthInfo recursively */
498 static struct isds_BirthInfo *isds_BirthInfo_duplicate(
499 const struct isds_BirthInfo *template) {
500 struct isds_BirthInfo *new = NULL;
502 if (!template) return NULL;
504 new = calloc(1, sizeof(*new));
505 if (!new) return NULL;
507 FLATDUP_OR_ERROR(new->biDate, template->biDate);
508 STRDUP_OR_ERROR(new->biCity, template->biCity);
509 STRDUP_OR_ERROR(new->biCounty, template->biCounty);
510 STRDUP_OR_ERROR(new->biState, template->biState);
512 return new;
514 error:
515 isds_BirthInfo_free(&new);
516 return NULL;
520 /* Copy structure isds_Address recursively */
521 struct isds_Address *isds_Address_duplicate(
522 const struct isds_Address *template) {
523 struct isds_Address *new = NULL;
525 if (!template) return NULL;
527 new = calloc(1, sizeof(*new));
528 if (!new) return NULL;
530 STRDUP_OR_ERROR(new->adCity, template->adCity);
531 STRDUP_OR_ERROR(new->adStreet, template->adStreet);
532 STRDUP_OR_ERROR(new->adNumberInStreet, template->adNumberInStreet);
533 STRDUP_OR_ERROR(new->adNumberInMunicipality,
534 template->adNumberInMunicipality);
535 STRDUP_OR_ERROR(new->adZipCode, template->adZipCode);
536 STRDUP_OR_ERROR(new->adState, template->adState);
538 return new;
540 error:
541 isds_Address_free(&new);
542 return NULL;
546 /* Copy structure isds_DbOwnerInfo recursively */
547 struct isds_DbOwnerInfo *isds_DbOwnerInfo_duplicate(
548 const struct isds_DbOwnerInfo *template) {
549 struct isds_DbOwnerInfo *new = NULL;
550 if (!template) return NULL;
552 new = calloc(1, sizeof(*new));
553 if (!new) return NULL;
555 STRDUP_OR_ERROR(new->dbID, template->dbID);
556 FLATDUP_OR_ERROR(new->dbType, template->dbType);
557 STRDUP_OR_ERROR(new->ic, template->ic);
559 if (template->personName) {
560 if (!(new->personName =
561 isds_PersonName_duplicate(template->personName)))
562 goto error;
565 STRDUP_OR_ERROR(new->firmName, template->firmName);
567 if (template->birthInfo) {
568 if (!(new->birthInfo =
569 isds_BirthInfo_duplicate(template->birthInfo)))
570 goto error;
573 if (template->address) {
574 if (!(new->address = isds_Address_duplicate(template->address)))
575 goto error;
578 STRDUP_OR_ERROR(new->nationality, template->nationality);
579 STRDUP_OR_ERROR(new->email, template->email);
580 STRDUP_OR_ERROR(new->telNumber, template->telNumber);
581 STRDUP_OR_ERROR(new->identifier, template->identifier);
582 STRDUP_OR_ERROR(new->registryCode, template->registryCode);
583 FLATDUP_OR_ERROR(new->dbState, template->dbState);
584 FLATDUP_OR_ERROR(new->dbEffectiveOVM, template->dbEffectiveOVM);
585 FLATDUP_OR_ERROR(new->dbOpenAddressing, template->dbOpenAddressing);
587 return new;
589 error:
590 isds_DbOwnerInfo_free(&new);
591 return NULL;
595 /* Copy structure isds_DbUserInfo recursively */
596 struct isds_DbUserInfo *isds_DbUserInfo_duplicate(
597 const struct isds_DbUserInfo *template) {
598 struct isds_DbUserInfo *new = NULL;
599 if (!template) return NULL;
601 new = calloc(1, sizeof(*new));
602 if (!new) return NULL;
604 STRDUP_OR_ERROR(new->userID, template->userID);
605 FLATDUP_OR_ERROR(new->userType, template->userType);
606 FLATDUP_OR_ERROR(new->userPrivils, template->userPrivils);
608 if (template->personName) {
609 if (!(new->personName =
610 isds_PersonName_duplicate(template->personName)))
611 goto error;
614 if (template->address) {
615 if (!(new->address = isds_Address_duplicate(template->address)))
616 goto error;
619 FLATDUP_OR_ERROR(new->biDate, template->biDate);
620 STRDUP_OR_ERROR(new->ic, template->ic);
621 STRDUP_OR_ERROR(new->firmName, template->firmName);
622 STRDUP_OR_ERROR(new->caStreet, template->caStreet);
623 STRDUP_OR_ERROR(new->caCity, template->caCity);
624 STRDUP_OR_ERROR(new->caZipCode, template->caZipCode);
625 STRDUP_OR_ERROR(new->caState, template->caState);
627 return new;
629 error:
630 isds_DbUserInfo_free(&new);
631 return NULL;
634 #undef FLATDUP_OR_ERROR
635 #undef STRDUP_OR_ERROR
638 /* Logs libxml2 errors. Should be registered to libxml2 library.
639 * @ctx is unused currently
640 * @msg is printf-like formated message from libxml2 (UTF-8?)
641 * @... are variadic arguments for @msg */
642 static void log_xml(void *ctx, const char *msg, ...) {
643 va_list ap;
644 char *text = NULL;
646 if (!msg) return;
648 va_start(ap, msg);
649 isds_vasprintf(&text, msg, ap);
650 va_end(ap);
652 if (text)
653 isds_log(ILF_XML, ILL_ERR, "%s", text);
654 free(text);
658 /* Initialize ISDS library.
659 * Global function, must be called before other functions.
660 * If it fails you can not use ISDS library and must call isds_cleanup() to
661 * free partially initialized global variables. */
662 isds_error isds_init(void) {
663 /* NULL global variables */
664 log_facilities = ILF_ALL;
665 log_level = ILL_WARNING;
666 log_callback = NULL;
667 log_callback_data = NULL;
669 #if ENABLE_NLS
670 /* Initialize gettext */
671 bindtextdomain(PACKAGE, LOCALEDIR);
672 #endif
674 #if HAVE_LIBCURL
675 /* Initialize CURL */
676 if (curl_global_init(CURL_GLOBAL_ALL)) {
677 isds_log(ILF_ISDS, ILL_CRIT, _("CURL library initialization failed\n"));
678 return IE_ERROR;
680 #endif /* HAVE_LIBCURL */
682 /* Initialize gpg-error because of gpgme and ksba */
683 if (gpg_err_init()) {
684 isds_log(ILF_ISDS, ILL_CRIT,
685 _("gpg-error library initialization failed\n"));
686 return IE_ERROR;
689 /* Initialize GPGME */
690 if (_isds_init_gpgme(&version_gpgme)) {
691 isds_log(ILF_ISDS, ILL_CRIT,
692 _("GPGME library initialization failed\n"));
693 return IE_ERROR;
696 /* Initialize gcrypt */
697 if (_isds_init_gcrypt(&version_gcrypt)) {
698 isds_log(ILF_ISDS, ILL_CRIT,
699 _("gcrypt library initialization failed\n"));
700 return IE_ERROR;
703 /* This can _exit() current program. Find not so assertive check. */
704 LIBXML_TEST_VERSION;
705 xmlSetGenericErrorFunc(NULL, log_xml);
707 /* Check expat */
708 if (_isds_init_expat(&version_expat)) {
709 isds_log(ILF_ISDS, ILL_CRIT,
710 _("expat library initialization failed\n"));
711 return IE_ERROR;
714 /* Allocate global variables */
717 return IE_SUCCESS;
721 /* Deinitialize ISDS library.
722 * Global function, must be called as last library function. */
723 isds_error isds_cleanup(void) {
724 /* XML */
725 xmlCleanupParser();
727 #if HAVE_LIBCURL
728 /* Curl */
729 curl_global_cleanup();
730 #endif
732 return IE_SUCCESS;
736 /* Return version string of this library. Version of dependencies can be
737 * embedded. Do no try to parse it. You must free it. */
738 char *isds_version(void) {
739 char *buffer = NULL;
741 isds_asprintf(&buffer,
742 #if HAVE_LIBCURL
743 _("%s (%s, GPGME %s, gcrypt %s, %s, libxml2 %s)"),
744 #else
745 _("%s (GPGME %s, gcrypt %s, %s, libxml2 %s)"),
746 #endif
747 PACKAGE_VERSION,
748 #if HAVE_LIBCURL
749 curl_version(),
750 #endif
751 version_gpgme, version_gcrypt,
752 version_expat, xmlParserVersion);
753 return buffer;
757 /* Return text description of ISDS error */
758 const char *isds_strerror(const isds_error error) {
759 switch (error) {
760 case IE_SUCCESS:
761 return(_("Success")); break;
762 case IE_ERROR:
763 return(_("Unspecified error")); break;
764 case IE_NOTSUP:
765 return(_("Not supported")); break;
766 case IE_INVAL:
767 return(_("Invalid value")); break;
768 case IE_INVALID_CONTEXT:
769 return(_("Invalid context")); break;
770 case IE_NOT_LOGGED_IN:
771 return(_("Not logged in")); break;
772 case IE_CONNECTION_CLOSED:
773 return(_("Connection closed")); break;
774 case IE_TIMED_OUT:
775 return(_("Timed out")); break;
776 case IE_NOEXIST:
777 return(_("Not exist")); break;
778 case IE_NOMEM:
779 return(_("Out of memory")); break;
780 case IE_NETWORK:
781 return(_("Network problem")); break;
782 case IE_HTTP:
783 return(_("HTTP problem")); break;
784 case IE_SOAP:
785 return(_("SOAP problem")); break;
786 case IE_XML:
787 return(_("XML problem")); break;
788 case IE_ISDS:
789 return(_("ISDS server problem")); break;
790 case IE_ENUM:
791 return(_("Invalid enum value")); break;
792 case IE_DATE:
793 return(_("Invalid date value")); break;
794 case IE_2BIG:
795 return(_("Too big")); break;
796 case IE_2SMALL:
797 return(_("Too small")); break;
798 case IE_NOTUNIQ:
799 return(_("Value not unique")); break;
800 case IE_NOTEQUAL:
801 return(_("Values not equal")); break;
802 case IE_PARTIAL_SUCCESS:
803 return(_("Some suboperations failed")); break;
804 case IE_ABORTED:
805 return(_("Operation aborted")); break;
806 case IE_SECURITY:
807 return(_("Security problem")); break;
808 default:
809 return(_("Unknown error"));
814 /* Create ISDS context.
815 * Each context can be used for different sessions to (possibly) different
816 * ISDS server with different credentials. */
817 struct isds_ctx *isds_ctx_create(void) {
818 struct isds_ctx *context;
819 context = malloc(sizeof(*context));
820 if (context) memset(context, 0, sizeof(*context));
821 return context;
824 #if HAVE_LIBCURL
825 /* Close possibly opened connection to Czech POINT document deposit without
826 * resetting long_message buffer.
827 * XXX: Do not use czp_close_connection() if you do not want to destroy log
828 * message.
829 * @context is Czech POINT session context. */
830 static isds_error czp_do_close_connection(struct isds_ctx *context) {
831 if (!context) return IE_INVALID_CONTEXT;
832 _isds_close_connection(context);
833 return IE_SUCCESS;
837 /* Discard credentials.
838 * @context is ISDS context
839 * @discard_saved_username is true for removing saved username, false for
840 * keeping it.
841 * Only that. It does not cause log out, connection close or similar. */
842 _hidden isds_error _isds_discard_credentials(struct isds_ctx *context,
843 _Bool discard_saved_username) {
844 if(!context) return IE_INVALID_CONTEXT;
846 if (context->username) {
847 memset(context->username, 0, strlen(context->username));
848 zfree(context->username);
850 if (context->password) {
851 memset(context->password, 0, strlen(context->password));
852 zfree(context->password);
854 isds_pki_credentials_free(&context->pki_credentials);
855 if (discard_saved_username && context->saved_username) {
856 memset(context->saved_username, 0, strlen(context->saved_username));
857 zfree(context->saved_username);
860 return IE_SUCCESS;
862 #endif /* HAVE_LIBCURL */
865 /* Destroy ISDS context and free memory.
866 * @context will be NULLed on success. */
867 isds_error isds_ctx_free(struct isds_ctx **context) {
868 if (!context || !*context) {
869 return IE_INVALID_CONTEXT;
872 #if HAVE_LIBCURL
873 /* Discard credentials and close connection */
874 switch ((*context)->type) {
875 case CTX_TYPE_NONE: break;
876 case CTX_TYPE_ISDS: isds_logout(*context); break;
877 case CTX_TYPE_CZP:
878 case CTX_TYPE_TESTING_REQUEST_COLLECTOR:
879 czp_do_close_connection(*context); break;
882 /* For sure */
883 _isds_discard_credentials(*context, 1);
885 /* Free other structures */
886 free((*context)->tls_verify_server);
887 free((*context)->tls_ca_file);
888 free((*context)->tls_ca_dir);
889 free((*context)->tls_crl_file);
890 #endif /* HAVE_LIBCURL */
891 free((*context)->long_message);
893 free(*context);
894 *context = NULL;
895 return IE_SUCCESS;
899 /* Return long message text produced by library function, e.g. detailed error
900 * message. Returned pointer is only valid until new library function is
901 * called for the same context. Could be NULL, especially if NULL context is
902 * supplied. Return string is locale encoded. */
903 char *isds_long_message(const struct isds_ctx *context) {
904 if (!context) return NULL;
905 return context->long_message;
909 /* Stores message into context' long_message buffer.
910 * Application can pick the message up using isds_long_message().
911 * NULL @message truncates the buffer but does not deallocate it.
912 * @message is coded in locale encoding */
913 _hidden isds_error isds_log_message(struct isds_ctx *context,
914 const char *message) {
915 char *buffer;
916 size_t length;
918 if (!context) return IE_INVALID_CONTEXT;
920 /* FIXME: Check for integer overflow */
921 length = 1 + ((message) ? strlen(message) : 0);
922 buffer = realloc(context->long_message, length);
923 if (!buffer) return IE_NOMEM;
925 if (message)
926 strcpy(buffer, message);
927 else
928 *buffer = '\0';
930 context->long_message = buffer;
931 return IE_SUCCESS;
935 /* Appends message into context' long_message buffer.
936 * Application can pick the message up using isds_long_message().
937 * NULL message has void effect. */
938 _hidden isds_error isds_append_message(struct isds_ctx *context,
939 const char *message) {
940 char *buffer;
941 size_t old_length, length;
943 if (!context) return IE_INVALID_CONTEXT;
944 if (!message) return IE_SUCCESS;
945 if (!context->long_message)
946 return isds_log_message(context, message);
948 old_length = strlen(context->long_message);
949 /* FIXME: Check for integer overflow */
950 length = 1 + old_length + strlen(message);
951 buffer = realloc(context->long_message, length);
952 if (!buffer) return IE_NOMEM;
954 strcpy(buffer + old_length, message);
956 context->long_message = buffer;
957 return IE_SUCCESS;
961 /* Stores formatted message into context' long_message buffer.
962 * Application can pick the message up using isds_long_message(). */
963 _hidden isds_error isds_printf_message(struct isds_ctx *context,
964 const char *format, ...) {
965 va_list ap;
966 int length;
968 if (!context) return IE_INVALID_CONTEXT;
969 va_start(ap, format);
970 length = isds_vasprintf(&(context->long_message), format, ap);
971 va_end(ap);
973 return (length < 0) ? IE_ERROR: IE_SUCCESS;
977 /* Set logging up.
978 * @facilities is bit mask of isds_log_facility values,
979 * @level is verbosity level. */
980 void isds_set_logging(const unsigned int facilities,
981 const isds_log_level level) {
982 log_facilities = facilities;
983 log_level = level;
987 /* Register callback function libisds calls when new global log message is
988 * produced by library. Library logs to stderr by default.
989 * @callback is function provided by application libisds will call. See type
990 * definition for @callback argument explanation. Pass NULL to revert logging to
991 * default behaviour.
992 * @data is application specific data @callback gets as last argument */
993 void isds_set_log_callback(isds_log_callback callback, void *data) {
994 log_callback = callback;
995 log_callback_data = data;
999 /* Log @message in class @facility with log @level into global log. @message
1000 * is printf(3) formatting string, variadic arguments may be necessary.
1001 * For debugging purposes. */
1002 _hidden isds_error isds_log(const isds_log_facility facility,
1003 const isds_log_level level, const char *message, ...) {
1004 va_list ap;
1005 char *buffer = NULL;
1006 int length;
1008 if (level > log_level) return IE_SUCCESS;
1009 if (!(log_facilities & facility)) return IE_SUCCESS;
1010 if (!message) return IE_INVAL;
1012 if (log_callback) {
1013 /* Pass message to application supplied callback function */
1014 va_start(ap, message);
1015 length = isds_vasprintf(&buffer, message, ap);
1016 va_end(ap);
1018 if (length == -1) {
1019 return IE_ERROR;
1021 if (length > 0) {
1022 log_callback(facility, level, buffer, length, log_callback_data);
1024 free(buffer);
1025 } else {
1026 /* Default: Log it to stderr */
1027 va_start(ap, message);
1028 vfprintf(stderr, message, ap);
1029 va_end(ap);
1030 /* Line buffered printf is default.
1031 * fflush(stderr);*/
1034 return IE_SUCCESS;
1038 /* Set timeout in milliseconds for each network job like connecting to server
1039 * or sending message. Use 0 to disable timeout limits. */
1040 isds_error isds_set_timeout(struct isds_ctx *context,
1041 const unsigned int timeout) {
1042 if (!context) return IE_INVALID_CONTEXT;
1043 zfree(context->long_message);
1045 #if HAVE_LIBCURL
1046 context->timeout = timeout;
1048 if (context->curl) {
1049 CURLcode curl_err;
1051 curl_err = curl_easy_setopt(context->curl, CURLOPT_NOSIGNAL, 1);
1052 if (!curl_err)
1053 #if HAVE_DECL_CURLOPT_TIMEOUT_MS /* Since curl-7.16.2 */
1054 curl_err = curl_easy_setopt(context->curl, CURLOPT_TIMEOUT_MS,
1055 context->timeout);
1056 #else
1057 curl_err = curl_easy_setopt(context->curl, CURLOPT_TIMEOUT,
1058 context->timeout / 1000);
1059 #endif /* not HAVE_DECL_CURLOPT_TIMEOUT_MS */
1060 if (curl_err) return IE_ERROR;
1063 return IE_SUCCESS;
1064 #else /* not HAVE_LIBCURL */
1065 return IE_NOTSUP;
1066 #endif
1070 /* Register callback function libisds calls periodically during HTTP data
1071 * transfer.
1072 * @context is session context
1073 * @callback is function provided by application libisds will call. See type
1074 * definition for @callback argument explanation.
1075 * @data is application specific data @callback gets as last argument */
1076 isds_error isds_set_progress_callback(struct isds_ctx *context,
1077 isds_progress_callback callback, void *data) {
1078 if (!context) return IE_INVALID_CONTEXT;
1079 zfree(context->long_message);
1081 #if HAVE_LIBCURL
1082 context->progress_callback = callback;
1083 context->progress_callback_data = data;
1085 return IE_SUCCESS;
1086 #else /* not HAVE_LIBCURL */
1087 return IE_NOTSUP;
1088 #endif
1092 /* Change context settings.
1093 * @context is context which setting will be applied to
1094 * @option is name of option. It determines the type of last argument. See
1095 * isds_option definition for more info.
1096 * @... is value of new setting. Type is determined by @option
1097 * */
1098 isds_error isds_set_opt(struct isds_ctx *context, const isds_option option,
1099 ...) {
1100 isds_error err = IE_SUCCESS;
1101 va_list ap;
1102 #if HAVE_LIBCURL
1103 char *pointer, *string;
1104 #endif
1106 if (!context) return IE_INVALID_CONTEXT;
1107 zfree(context->long_message);
1109 va_start(ap, option);
1111 #define REPLACE_VA_BOOLEAN(destination) { \
1112 if (!(destination)) { \
1113 (destination) = malloc(sizeof(*(destination))); \
1114 if (!(destination)) { \
1115 err = IE_NOMEM; goto leave; \
1118 *(destination) = (_Bool) !!va_arg(ap, int); \
1121 #define REPLACE_VA_STRING(destination) { \
1122 string = va_arg(ap, char *); \
1123 if (string) { \
1124 pointer = realloc((destination), 1 + strlen(string)); \
1125 if (!pointer) { err = IE_NOMEM; goto leave; } \
1126 strcpy(pointer, string); \
1127 (destination) = pointer; \
1128 } else { \
1129 free(destination); \
1130 (destination) = NULL; \
1134 switch (option) {
1135 case IOPT_TLS_VERIFY_SERVER:
1136 #if HAVE_LIBCURL
1137 REPLACE_VA_BOOLEAN(context->tls_verify_server);
1138 #else
1139 err = IE_NOTSUP; goto leave;
1140 #endif
1141 break;
1142 case IOPT_TLS_CA_FILE:
1143 #if HAVE_LIBCURL
1144 REPLACE_VA_STRING(context->tls_ca_file);
1145 #else
1146 err = IE_NOTSUP; goto leave;
1147 #endif
1148 break;
1149 case IOPT_TLS_CA_DIRECTORY:
1150 #if HAVE_LIBCURL
1151 REPLACE_VA_STRING(context->tls_ca_dir);
1152 #else
1153 err = IE_NOTSUP; goto leave;
1154 #endif
1155 break;
1156 case IOPT_TLS_CRL_FILE:
1157 #if HAVE_LIBCURL
1158 #if HAVE_DECL_CURLOPT_CRLFILE /* Since curl-7.19.0 */
1159 REPLACE_VA_STRING(context->tls_crl_file);
1160 #else
1161 isds_log_message(context,
1162 _("Curl library does not support CRL definition"));
1163 err = IE_NOTSUP;
1164 #endif /* not HAVE_DECL_CURLOPT_CRLFILE */
1165 #else
1166 err = IE_NOTSUP; goto leave;
1167 #endif /* not HAVE_LIBCURL */
1168 break;
1169 case IOPT_NORMALIZE_MIME_TYPE:
1170 context->normalize_mime_type = (_Bool) !!va_arg(ap, int);
1171 break;
1173 default:
1174 err = IE_ENUM; goto leave;
1177 #undef REPLACE_VA_STRING
1178 #undef REPLACE_VA_BOOLEAN
1180 leave:
1181 va_end(ap);
1182 return err;
1186 #if HAVE_LIBCURL
1187 /* Copy credentials into context. Any non-NULL argument will be duplicated.
1188 * Destination for NULL argument will not be touched.
1189 * Destination pointers must be freed before calling this function.
1190 * If @username is @context->saved_username, the saved_username will not be
1191 * replaced. The saved_username is clobbered only if context has set otp
1192 * member.
1193 * Return IE_SUCCESS on success. */
1194 static isds_error _isds_store_credentials(struct isds_ctx *context,
1195 const char *username, const char *password,
1196 const struct isds_pki_credentials *pki_credentials) {
1197 if (NULL == context) return IE_INVALID_CONTEXT;
1199 /* FIXME: mlock password
1200 * (I have a library) */
1202 if (username) {
1203 context->username = strdup(username);
1204 if (context->otp && context->saved_username != username)
1205 context->saved_username = strdup(username);
1207 if (password) {
1208 if (NULL == context->otp_credentials)
1209 context->password = strdup(password);
1210 else
1211 context->password = _isds_astrcat(password,
1212 context->otp_credentials->otp_code);
1214 context->pki_credentials = isds_pki_credentials_duplicate(pki_credentials);
1216 if ((NULL != username && NULL == context->username) ||
1217 (NULL != password && NULL == context->password) ||
1218 (NULL != pki_credentials && NULL == context->pki_credentials) ||
1219 (context->otp && NULL != context->username &&
1220 NULL == context->saved_username)) {
1221 return IE_NOMEM;
1224 return IE_SUCCESS;
1226 #endif
1229 /* Connect and log into ISDS server.
1230 * All required arguments will be copied, you do not have to keep them after
1231 * that.
1232 * ISDS supports six different authentication methods. Exact method is
1233 * selected on @username, @password, @pki_credentials, and @otp arguments:
1234 * - If @pki_credentials == NULL, @username and @password must be supplied
1235 * and then
1236 * - If @otp == NULL, simple authentication by username and password will
1237 * be proceeded.
1238 * - If @otp != NULL, authentication by username and password and OTP
1239 * will be used.
1240 * - If @pki_credentials != NULL, then
1241 * - If @username == NULL, only certificate will be used
1242 * - If @username != NULL, then
1243 * - If @password == NULL, then certificate will be used and
1244 * @username shifts meaning to box ID. This is used for hosted
1245 * services.
1246 * - Otherwise all three arguments will be used.
1247 * Please note, that different cases require different certificate type
1248 * (system qualified one or commercial non qualified one). This library
1249 * does not check such political issues. Please see ISDS Specification
1250 * for more details.
1251 * @url is base address of ISDS web service. Pass extern isds_locator
1252 * variable to use production ISDS instance without client certificate
1253 * authentication (or extern isds_cert_locator with client certificate
1254 * authentication or extern isds_otp_locators with OTP authentication).
1255 * Passing NULL has the same effect, autoselection between isds_locator,
1256 * isds_cert_locator, and isds_otp_locator is performed in addition. You can
1257 * pass extern isds_testing_locator (or isds_cert_testing_locator or
1258 * isds_otp_testing_locator) variable to select testing instance.
1259 * @username is user name of ISDS user or box ID
1260 * @password is user's secret password
1261 * @pki_credentials defines public key cryptographic material to use in client
1262 * authentication.
1263 * @otp selects one-time password authentication method to use, defines OTP
1264 * code (if known) and returns fine grade resolution of OTP procedure.
1265 * @return:
1266 * IE_SUCCESS if authentication succeeds
1267 * IE_NOT_LOGGED_IN if authentication fails. If OTP authentication has been
1268 * requested, fine grade reason will be set into @otp->resolution. Error
1269 * message from server can be obtained by isds_long_message() call.
1270 * IE_PARTIAL_SUCCESS if time-based OTP authentication has been requested and
1271 * server has sent OTP code through side channel. Application is expected to
1272 * fill the code into @otp->otp_code, keep other arguments unchanged, and retry
1273 * this call to complete second phase of TOTP authentication;
1274 * or other appropriate error. */
1275 isds_error isds_login(struct isds_ctx *context, const char *url,
1276 const char *username, const char *password,
1277 const struct isds_pki_credentials *pki_credentials,
1278 struct isds_otp *otp) {
1279 #if HAVE_LIBCURL
1280 isds_error err = IE_NOT_LOGGED_IN;
1281 isds_error soap_err;
1282 xmlNsPtr isds_ns = NULL;
1283 xmlNodePtr request = NULL;
1284 xmlNodePtr response = NULL;
1285 #endif /* HAVE_LIBCURL */
1287 if (!context) return IE_INVALID_CONTEXT;
1288 zfree(context->long_message);
1290 #if HAVE_LIBCURL
1291 /* Close connection if already logged in */
1292 if (context->curl) {
1293 _isds_close_connection(context);
1296 /* Store configuration */
1297 context->type = CTX_TYPE_ISDS;
1298 zfree(context->url);
1300 /* Mangle base URI according to requested authentication method */
1301 if (NULL == pki_credentials) {
1302 isds_log(ILF_SEC, ILL_INFO,
1303 _("Selected authentication method: no certificate, "
1304 "username and password\n"));
1305 if (!username || !password) {
1306 isds_log_message(context,
1307 _("Both username and password must be supplied"));
1308 return IE_INVAL;
1310 context->otp_credentials = otp;
1311 context->otp = (NULL != context->otp_credentials);
1313 if (!context->otp) {
1314 /* Default locator is official system (without certificate or
1315 * OTP) */
1316 context->url = strdup((NULL != url) ? url : isds_locator);
1317 } else {
1318 const char *authenticator_uri = NULL;
1319 if (!url) url = isds_otp_locator;
1320 otp->resolution = OTP_RESOLUTION_UNKNOWN;
1321 switch (context->otp_credentials->method) {
1322 case OTP_HMAC:
1323 isds_log(ILF_SEC, ILL_INFO,
1324 _("Selected authentication method: "
1325 "HMAC-based one-time password\n"));
1326 authenticator_uri =
1327 "%1$sas/processLogin?type=hotp&uri=%1$sapps/";
1328 break;
1329 case OTP_TIME:
1330 isds_log(ILF_SEC, ILL_INFO,
1331 _("Selected authentication method: "
1332 "Time-based one-time password\n"));
1333 if (context->otp_credentials->otp_code == NULL) {
1334 isds_log(ILF_SEC, ILL_INFO,
1335 _("OTP code has not been provided by "
1336 "application, requesting server for "
1337 "new one.\n"));
1338 authenticator_uri =
1339 "%1$sas/processLogin?type=totp&sendSms=true&"
1340 "uri=%1$sapps/";
1341 } else {
1342 isds_log(ILF_SEC, ILL_INFO,
1343 _("OTP code has been provided by "
1344 "application, not requesting server "
1345 "for new one.\n"));
1346 authenticator_uri =
1347 "%1$sas/processLogin?type=totp&"
1348 "uri=%1$sapps/";
1350 break;
1351 default:
1352 isds_log_message(context,
1353 _("Unknown one-time password authentication "
1354 "method requested by application"));
1355 return IE_ENUM;
1357 if (-1 == isds_asprintf(&context->url, authenticator_uri, url))
1358 return IE_NOMEM;
1360 } else {
1361 /* Default locator is official system (with client certificate) */
1362 context->otp = 0;
1363 context->otp_credentials = NULL;
1364 if (!url) url = isds_cert_locator;
1366 if (!username) {
1367 isds_log(ILF_SEC, ILL_INFO,
1368 _("Selected authentication method: system certificate, "
1369 "no username and no password\n"));
1370 password = NULL;
1371 context->url = _isds_astrcat(url, "cert/");
1372 } else {
1373 if (!password) {
1374 isds_log(ILF_SEC, ILL_INFO,
1375 _("Selected authentication method: system certificate, "
1376 "box ID and no password\n"));
1377 context->url = _isds_astrcat(url, "hspis/");
1378 } else {
1379 isds_log(ILF_SEC, ILL_INFO,
1380 _("Selected authentication method: commercial "
1381 "certificate, username and password\n"));
1382 context->url = _isds_astrcat(url, "certds/");
1386 if (!(context->url))
1387 return IE_NOMEM;
1389 /* Prepare CURL handle */
1390 context->curl = curl_easy_init();
1391 if (!(context->curl))
1392 return IE_ERROR;
1394 /* Build log-in request */
1395 request = xmlNewNode(NULL, BAD_CAST "DummyOperation");
1396 if (!request) {
1397 isds_log_message(context, _("Could not build ISDS log-in request"));
1398 return IE_ERROR;
1400 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
1401 if(!isds_ns) {
1402 isds_log_message(context, _("Could not create ISDS name space"));
1403 xmlFreeNode(request);
1404 return IE_ERROR;
1406 xmlSetNs(request, isds_ns);
1408 /* Store credentials */
1409 _isds_discard_credentials(context, 1);
1410 if (_isds_store_credentials(context, username, password, pki_credentials)) {
1411 _isds_discard_credentials(context, 1);
1412 xmlFreeNode(request);
1413 return IE_NOMEM;
1416 isds_log(ILF_ISDS, ILL_DEBUG, _("Logging user %s into server %s\n"),
1417 username, url);
1419 /* Send log-in request */
1420 soap_err = _isds_soap(context, "DS/dz", request, &response, NULL, NULL);
1422 if (context->otp) {
1423 /* Revert context URL from OTP authentication service URL to OTP web
1424 * service base URL for subsequent calls. Potenial isds_login() retry
1425 * will re-set context URL again. */
1426 zfree(context->url);
1427 context->url = _isds_astrcat(url, "apps/");
1428 if (context->url == NULL) {
1429 soap_err = IE_NOMEM;
1431 /* Detach pointer to OTP credentials from context */
1432 context->otp_credentials = NULL;
1435 /* Remove credentials */
1436 _isds_discard_credentials(context, 0);
1438 /* Destroy log-in request */
1439 xmlFreeNode(request);
1441 if (soap_err) {
1442 xmlFreeNodeList(response);
1443 _isds_close_connection(context);
1444 return soap_err;
1447 /* XXX: Until we don't propagate HTTP code 500 or 4xx, we can be sure
1448 * authentication succeeded if soap_err == IE_SUCCESS */
1449 err = IE_SUCCESS;
1451 xmlFreeNodeList(response);
1453 if (!err)
1454 isds_log(ILF_ISDS, ILL_DEBUG,
1455 _("User %s has been logged into server %s successfully\n"),
1456 username, url);
1457 return err;
1458 #else /* not HAVE_LIBCURL */
1459 return IE_NOTSUP;
1460 #endif
1464 /* Log out from ISDS server discards credentials and connection configuration. */
1465 isds_error isds_logout(struct isds_ctx *context) {
1466 if (!context) return IE_INVALID_CONTEXT;
1467 zfree(context->long_message);
1469 #if HAVE_LIBCURL
1470 if (context->curl) {
1471 if (context->otp) {
1472 isds_error err = _isds_invalidate_otp_cookie(context);
1473 if (err) return err;
1476 /* Close connection */
1477 _isds_close_connection(context);
1479 /* Discard credentials for sure. They should not survive isds_login(),
1480 * even successful .*/
1481 _isds_discard_credentials(context, 1);
1482 zfree(context->url);
1484 isds_log(ILF_ISDS, ILL_DEBUG, _("Logged out from ISDS server\n"));
1485 } else {
1486 _isds_discard_credentials(context, 1);
1488 return IE_SUCCESS;
1489 #else /* not HAVE_LIBCURL */
1490 return IE_NOTSUP;
1491 #endif
1495 /* Verify connection to ISDS is alive and server is responding.
1496 * Send dummy request to ISDS and expect dummy response. */
1497 isds_error isds_ping(struct isds_ctx *context) {
1498 #if HAVE_LIBCURL
1499 isds_error soap_err;
1500 xmlNsPtr isds_ns = NULL;
1501 xmlNodePtr request = NULL;
1502 xmlNodePtr response = NULL;
1503 #endif /* HAVE_LIBCURL */
1505 if (!context) return IE_INVALID_CONTEXT;
1506 zfree(context->long_message);
1508 #if HAVE_LIBCURL
1509 /* Check if connection is established */
1510 if (!context->curl) return IE_CONNECTION_CLOSED;
1513 /* Build dummy request */
1514 request = xmlNewNode(NULL, BAD_CAST "DummyOperation");
1515 if (!request) {
1516 isds_log_message(context, _("Could build ISDS dummy request"));
1517 return IE_ERROR;
1519 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
1520 if(!isds_ns) {
1521 isds_log_message(context, _("Could not create ISDS name space"));
1522 xmlFreeNode(request);
1523 return IE_ERROR;
1525 xmlSetNs(request, isds_ns);
1527 isds_log(ILF_ISDS, ILL_DEBUG, _("Pinging ISDS server\n"));
1529 /* Sent dummy request */
1530 soap_err = _isds_soap(context, "DS/dz", request, &response, NULL, NULL);
1532 /* Destroy log-in request */
1533 xmlFreeNode(request);
1535 if (soap_err) {
1536 isds_log(ILF_ISDS, ILL_DEBUG,
1537 _("ISDS server could not be contacted\n"));
1538 xmlFreeNodeList(response);
1539 return soap_err;
1542 /* XXX: Until we don't propagate HTTP code 500 or 4xx, we can be sure
1543 * authentication succeeded if soap_err == IE_SUCCESS */
1544 /* TODO: ISDS documentation does not specify response body.
1545 * However real server sends back DummyOperationResponse */
1548 xmlFreeNodeList(response);
1550 isds_log(ILF_ISDS, ILL_DEBUG, _("ISDS server alive\n"));
1552 return IE_SUCCESS;
1553 #else /* not HAVE_LIBCURL */
1554 return IE_NOTSUP;
1555 #endif
1559 /* Send bogus request to ISDS.
1560 * Just for test purposes */
1561 isds_error isds_bogus_request(struct isds_ctx *context) {
1562 #if HAVE_LIBCURL
1563 isds_error err;
1564 xmlNsPtr isds_ns = NULL;
1565 xmlNodePtr request = NULL;
1566 xmlDocPtr response = NULL;
1567 xmlChar *code = NULL, *message = NULL;
1568 #endif
1570 if (!context) return IE_INVALID_CONTEXT;
1571 zfree(context->long_message);
1573 #if HAVE_LIBCURL
1574 /* Check if connection is established */
1575 if (!context->curl) {
1576 /* Testing printf message */
1577 isds_printf_message(context, "%s", _("I said connection closed"));
1578 return IE_CONNECTION_CLOSED;
1582 /* Build dummy request */
1583 request = xmlNewNode(NULL, BAD_CAST "X-BogusOperation");
1584 if (!request) {
1585 isds_log_message(context, _("Could build ISDS bogus request"));
1586 return IE_ERROR;
1588 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
1589 if(!isds_ns) {
1590 isds_log_message(context, _("Could not create ISDS name space"));
1591 xmlFreeNode(request);
1592 return IE_ERROR;
1594 xmlSetNs(request, isds_ns);
1596 isds_log(ILF_ISDS, ILL_DEBUG, _("Sending bogus request to ISDS\n"));
1598 /* Sent bogus request */
1599 err = isds(context, SERVICE_DM_OPERATIONS, request, &response, NULL, NULL);
1601 /* Destroy request */
1602 xmlFreeNode(request);
1604 if (err) {
1605 isds_log(ILF_ISDS, ILL_DEBUG,
1606 _("Processing ISDS response on bogus request failed\n"));
1607 xmlFreeDoc(response);
1608 return err;
1611 /* Check for response status */
1612 err = isds_response_status(context, SERVICE_DM_OPERATIONS, response,
1613 &code, &message, NULL);
1614 if (err) {
1615 isds_log(ILF_ISDS, ILL_DEBUG,
1616 _("ISDS response on bogus request is missing status\n"));
1617 free(code);
1618 free(message);
1619 xmlFreeDoc(response);
1620 return err;
1622 if (xmlStrcmp(code, BAD_CAST "0000")) {
1623 char *code_locale = _isds_utf82locale((char*)code);
1624 char *message_locale = _isds_utf82locale((char*)message);
1625 isds_log(ILF_ISDS, ILL_DEBUG,
1626 _("Server refused bogus request (code=%s, message=%s)\n"),
1627 code_locale, message_locale);
1628 /* XXX: Literal error messages from ISDS are Czech messages
1629 * (English sometimes) in UTF-8. It's hard to catch them for
1630 * translation. Successfully gettextized would return in locale
1631 * encoding, unsuccessfully translated would pass in UTF-8. */
1632 isds_log_message(context, message_locale);
1633 free(code_locale);
1634 free(message_locale);
1635 free(code);
1636 free(message);
1637 xmlFreeDoc(response);
1638 return IE_ISDS;
1642 free(code);
1643 free(message);
1644 xmlFreeDoc(response);
1646 isds_log(ILF_ISDS, ILL_DEBUG,
1647 _("Bogus message accepted by server. This should not happen.\n"));
1649 return IE_SUCCESS;
1650 #else /* not HAVE_LIBCURL */
1651 return IE_NOTSUP;
1652 #endif
1656 #if HAVE_LIBCURL
1657 /* Serialize XML subtree to buffer preserving XML indentation.
1658 * @context is session context
1659 * @subtree is XML element to be serialized (with children)
1660 * @buffer is automatically reallocated buffer where serialize to
1661 * @length is size of serialized stream in bytes
1662 * @return standard error code, free @buffer in case of error */
1663 static isds_error serialize_subtree(struct isds_ctx *context,
1664 xmlNodePtr subtree, void **buffer, size_t *length) {
1665 isds_error err = IE_SUCCESS;
1666 xmlBufferPtr xml_buffer = NULL;
1667 xmlSaveCtxtPtr save_ctx = NULL;
1668 xmlDocPtr subtree_doc = NULL;
1669 xmlNodePtr subtree_copy;
1670 xmlNsPtr isds_ns;
1671 void *new_buffer;
1673 if (!context) return IE_INVALID_CONTEXT;
1674 if (!buffer) return IE_INVAL;
1675 zfree(*buffer);
1676 if (!subtree || !length) return IE_INVAL;
1678 /* Make temporary XML document with @subtree root element */
1679 /* XXX: We can not use xmlNodeDump() because it dumps the subtree as is.
1680 * It can result in not well-formed on invalid XML tree (e.g. name space
1681 * prefix definition can miss. */
1682 /*FIXME */
1684 subtree_doc = xmlNewDoc(BAD_CAST "1.0");
1685 if (!subtree_doc) {
1686 isds_log_message(context, _("Could not build temporary document"));
1687 err = IE_ERROR;
1688 goto leave;
1691 /* XXX: Copy subtree and attach the copy to document.
1692 * One node can not bee attached into more document at the same time.
1693 * XXX: Check xmlDOMWrapRemoveNode(). It could solve NS references
1694 * automatically.
1695 * XXX: Check xmlSaveTree() too. */
1696 subtree_copy = xmlCopyNodeList(subtree);
1697 if (!subtree_copy) {
1698 isds_log_message(context, _("Could not copy subtree"));
1699 err = IE_ERROR;
1700 goto leave;
1702 xmlDocSetRootElement(subtree_doc, subtree_copy);
1704 /* Only this way we get namespace definition as @xmlns:isds,
1705 * otherwise we get namespace prefix without definition */
1706 /* FIXME: Don't overwrite original default namespace */
1707 isds_ns = xmlNewNs(subtree_copy, BAD_CAST ISDS_NS, NULL);
1708 if(!isds_ns) {
1709 isds_log_message(context, _("Could not create ISDS name space"));
1710 err = IE_ERROR;
1711 goto leave;
1713 xmlSetNs(subtree_copy, isds_ns);
1716 /* Serialize the document into buffer */
1717 xml_buffer = xmlBufferCreate();
1718 if (!xml_buffer) {
1719 isds_log_message(context, _("Could not create xmlBuffer"));
1720 err = IE_ERROR;
1721 goto leave;
1723 /* Last argument 0 means to not format the XML tree */
1724 save_ctx = xmlSaveToBuffer(xml_buffer, "UTF-8", 0);
1725 if (!save_ctx) {
1726 isds_log_message(context, _("Could not create XML serializer"));
1727 err = IE_ERROR;
1728 goto leave;
1730 /* XXX: According LibXML documentation, this function does not return
1731 * meaningful value yet */
1732 xmlSaveDoc(save_ctx, subtree_doc);
1733 if (-1 == xmlSaveFlush(save_ctx)) {
1734 isds_log_message(context,
1735 _("Could not serialize XML subtree"));
1736 err = IE_ERROR;
1737 goto leave;
1739 /* XXX: libxml-2.7.4 complains when xmlSaveClose() on immutable buffer
1740 * even after xmlSaveFlush(). Thus close it here */
1741 xmlSaveClose(save_ctx); save_ctx = NULL;
1744 /* Store and detach buffer from xml_buffer */
1745 *buffer = xml_buffer->content;
1746 *length = xml_buffer->use;
1747 xmlBufferSetAllocationScheme(xml_buffer, XML_BUFFER_ALLOC_IMMUTABLE);
1749 /* Shrink buffer */
1750 new_buffer = realloc(*buffer, *length);
1751 if (new_buffer) *buffer = new_buffer;
1753 leave:
1754 if (err) {
1755 zfree(*buffer);
1756 *length = 0;
1759 xmlSaveClose(save_ctx);
1760 xmlBufferFree(xml_buffer);
1761 xmlFreeDoc(subtree_doc); /* Frees subtree_copy, isds_ns etc. */
1762 return err;
1764 #endif /* HAVE_LIBCURL */
1767 #if 0
1768 /* Dump XML subtree to buffer as literal string, not valid XML possibly.
1769 * @context is session context
1770 * @document is original document where @nodeset points to
1771 * @nodeset is XPath node set to dump (recursively)
1772 * @buffer is automatically reallocated buffer where serialize to
1773 * @length is size of serialized stream in bytes
1774 * @return standard error code, free @buffer in case of error */
1775 static isds_error dump_nodeset(struct isds_ctx *context,
1776 const xmlDocPtr document, const xmlNodeSetPtr nodeset,
1777 void **buffer, size_t *length) {
1778 isds_error err = IE_SUCCESS;
1779 xmlBufferPtr xml_buffer = NULL;
1780 void *new_buffer;
1782 if (!context) return IE_INVALID_CONTEXT;
1783 if (!buffer) return IE_INVAL;
1784 zfree(*buffer);
1785 if (!document || !nodeset || !length) return IE_INVAL;
1786 *length = 0;
1788 /* Empty node set results into NULL buffer */
1789 if (xmlXPathNodeSetIsEmpty(nodeset)) {
1790 goto leave;
1793 /* Resulting the document into buffer */
1794 xml_buffer = xmlBufferCreate();
1795 if (!xml_buffer) {
1796 isds_log_message(context, _("Could not create xmlBuffer"));
1797 err = IE_ERROR;
1798 goto leave;
1801 /* Iterate over all nodes */
1802 for (int i = 0; i < nodeset->nodeNr; i++) {
1803 /* Serialize node.
1804 * XXX: xmlNodeDump() appends to xml_buffer. */
1805 if (-1 ==
1806 xmlNodeDump(xml_buffer, document, nodeset->nodeTab[i], 0, 0)) {
1807 isds_log_message(context, _("Could not dump XML node"));
1808 err = IE_ERROR;
1809 goto leave;
1813 /* Store and detach buffer from xml_buffer */
1814 *buffer = xml_buffer->content;
1815 *length = xml_buffer->use;
1816 xmlBufferSetAllocationScheme(xml_buffer, XML_BUFFER_ALLOC_IMMUTABLE);
1818 /* Shrink buffer */
1819 new_buffer = realloc(*buffer, *length);
1820 if (new_buffer) *buffer = new_buffer;
1823 leave:
1824 if (err) {
1825 zfree(*buffer);
1826 *length = 0;
1829 xmlBufferFree(xml_buffer);
1830 return err;
1832 #endif
1834 #if 0
1835 /* Dump XML subtree to buffer as literal string, not valid XML possibly.
1836 * @context is session context
1837 * @document is original document where @nodeset points to
1838 * @nodeset is XPath node set to dump (recursively)
1839 * @buffer is automatically reallocated buffer where serialize to
1840 * @length is size of serialized stream in bytes
1841 * @return standard error code, free @buffer in case of error */
1842 static isds_error dump_nodeset(struct isds_ctx *context,
1843 const xmlDocPtr document, const xmlNodeSetPtr nodeset,
1844 void **buffer, size_t *length) {
1845 isds_error err = IE_SUCCESS;
1846 xmlBufferPtr xml_buffer = NULL;
1847 xmlSaveCtxtPtr save_ctx = NULL;
1848 void *new_buffer;
1850 if (!context) return IE_INVALID_CONTEXT;
1851 if (!buffer) return IE_INVAL;
1852 zfree(*buffer);
1853 if (!document || !nodeset || !length) return IE_INVAL;
1854 *length = 0;
1856 /* Empty node set results into NULL buffer */
1857 if (xmlXPathNodeSetIsEmpty(nodeset)) {
1858 goto leave;
1861 /* Resulting the document into buffer */
1862 xml_buffer = xmlBufferCreate();
1863 if (!xml_buffer) {
1864 isds_log_message(context, _("Could not create xmlBuffer"));
1865 err = IE_ERROR;
1866 goto leave;
1868 if (xmlSubstituteEntitiesDefault(1)) {
1869 isds_log_message(context, _("Could not disable attribute escaping"));
1870 err = IE_ERROR;
1871 goto leave;
1873 /* Last argument means:
1874 * 0 to not format the XML tree
1875 * XML_SAVE_NO_EMPTY ISDS does not produce shorten tags */
1876 save_ctx = xmlSaveToBuffer(xml_buffer, "UTF-8",
1877 XML_SAVE_NO_DECL|XML_SAVE_NO_EMPTY|XML_SAVE_NO_XHTML);
1878 if (!save_ctx) {
1879 isds_log_message(context, _("Could not create XML serializer"));
1880 err = IE_ERROR;
1881 goto leave;
1883 /*if (xmlSaveSetAttrEscape(save_ctx, NULL)) {
1884 isds_log_message(context, _("Could not disable attribute escaping"));
1885 err = IE_ERROR;
1886 goto leave;
1890 /* Iterate over all nodes */
1891 for (int i = 0; i < nodeset->nodeNr; i++) {
1892 /* Serialize node.
1893 * XXX: xmlNodeDump() appends to xml_buffer. */
1894 /*if (-1 ==
1895 xmlNodeDump(xml_buffer, document, nodeset->nodeTab[i], 0, 0)) {
1897 /* XXX: According LibXML documentation, this function does not return
1898 * meaningful value yet */
1899 xmlSaveTree(save_ctx, nodeset->nodeTab[i]);
1900 if (-1 == xmlSaveFlush(save_ctx)) {
1901 isds_log_message(context,
1902 _("Could not serialize XML subtree"));
1903 err = IE_ERROR;
1904 goto leave;
1908 /* XXX: libxml-2.7.4 complains when xmlSaveClose() on immutable buffer
1909 * even after xmlSaveFlush(). Thus close it here */
1910 xmlSaveClose(save_ctx); save_ctx = NULL;
1912 /* Store and detach buffer from xml_buffer */
1913 *buffer = xml_buffer->content;
1914 *length = xml_buffer->use;
1915 xmlBufferSetAllocationScheme(xml_buffer, XML_BUFFER_ALLOC_IMMUTABLE);
1917 /* Shrink buffer */
1918 new_buffer = realloc(*buffer, *length);
1919 if (new_buffer) *buffer = new_buffer;
1921 leave:
1922 if (err) {
1923 zfree(*buffer);
1924 *length = 0;
1927 xmlSaveClose(save_ctx);
1928 xmlBufferFree(xml_buffer);
1929 return err;
1931 #endif
1934 #if HAVE_LIBCURL
1935 /* Convert UTF-8 @string representation of ISDS dbType to enum @type */
1936 static isds_error string2isds_DbType(xmlChar *string, isds_DbType *type) {
1937 if (!string || !type) return IE_INVAL;
1939 if (!xmlStrcmp(string, BAD_CAST "FO"))
1940 *type = DBTYPE_FO;
1941 else if (!xmlStrcmp(string, BAD_CAST "PFO"))
1942 *type = DBTYPE_PFO;
1943 else if (!xmlStrcmp(string, BAD_CAST "PFO_ADVOK"))
1944 *type = DBTYPE_PFO_ADVOK;
1945 else if (!xmlStrcmp(string, BAD_CAST "PFO_DANPOR"))
1946 *type = DBTYPE_PFO_DANPOR;
1947 else if (!xmlStrcmp(string, BAD_CAST "PFO_INSSPR"))
1948 *type = DBTYPE_PFO_INSSPR;
1949 else if (!xmlStrcmp(string, BAD_CAST "PO"))
1950 *type = DBTYPE_PO;
1951 else if (!xmlStrcmp(string, BAD_CAST "PO_ZAK"))
1952 *type = DBTYPE_PO_ZAK;
1953 else if (!xmlStrcmp(string, BAD_CAST "PO_REQ"))
1954 *type = DBTYPE_PO_REQ;
1955 else if (!xmlStrcmp(string, BAD_CAST "OVM"))
1956 *type = DBTYPE_OVM;
1957 else if (!xmlStrcmp(string, BAD_CAST "OVM_NOTAR"))
1958 *type = DBTYPE_OVM_NOTAR;
1959 else if (!xmlStrcmp(string, BAD_CAST "OVM_EXEKUT"))
1960 *type = DBTYPE_OVM_EXEKUT;
1961 else if (!xmlStrcmp(string, BAD_CAST "OVM_REQ"))
1962 *type = DBTYPE_OVM_REQ;
1963 else
1964 return IE_ENUM;
1965 return IE_SUCCESS;
1969 /* Convert ISDS dbType enum @type to UTF-8 string.
1970 * @Return pointer to static string, or NULL if unknown enum value */
1971 static const xmlChar *isds_DbType2string(const isds_DbType type) {
1972 switch(type) {
1973 /* DBTYPE_SYSTEM is invalid value from point of view of public
1974 * SOAP interface. */
1975 case DBTYPE_FO: return(BAD_CAST "FO"); break;
1976 case DBTYPE_PFO: return(BAD_CAST "PFO"); break;
1977 case DBTYPE_PFO_ADVOK: return(BAD_CAST "PFO_ADVOK"); break;
1978 case DBTYPE_PFO_DANPOR: return(BAD_CAST "PFO_DANPOR"); break;
1979 case DBTYPE_PFO_INSSPR: return(BAD_CAST "PFO_INSSPR"); break;
1980 case DBTYPE_PO: return(BAD_CAST "PO"); break;
1981 case DBTYPE_PO_ZAK: return(BAD_CAST "PO_ZAK"); break;
1982 case DBTYPE_PO_REQ: return(BAD_CAST "PO_REQ"); break;
1983 case DBTYPE_OVM: return(BAD_CAST "OVM"); break;
1984 case DBTYPE_OVM_NOTAR: return(BAD_CAST "OVM_NOTAR"); break;
1985 case DBTYPE_OVM_EXEKUT: return(BAD_CAST "OVM_EXEKUT"); break;
1986 case DBTYPE_OVM_REQ: return(BAD_CAST "OVM_REQ"); break;
1987 default: return NULL; break;
1992 /* Convert UTF-8 @string representation of ISDS userType to enum @type */
1993 static isds_error string2isds_UserType(xmlChar *string, isds_UserType *type) {
1994 if (!string || !type) return IE_INVAL;
1996 if (!xmlStrcmp(string, BAD_CAST "PRIMARY_USER"))
1997 *type = USERTYPE_PRIMARY;
1998 else if (!xmlStrcmp(string, BAD_CAST "ENTRUSTED_USER"))
1999 *type = USERTYPE_ENTRUSTED;
2000 else if (!xmlStrcmp(string, BAD_CAST "ADMINISTRATOR"))
2001 *type = USERTYPE_ADMINISTRATOR;
2002 else if (!xmlStrcmp(string, BAD_CAST "OFFICIAL"))
2003 *type = USERTYPE_OFFICIAL;
2004 else if (!xmlStrcmp(string, BAD_CAST "OFFICIAL_CERT"))
2005 *type = USERTYPE_OFFICIAL_CERT;
2006 else if (!xmlStrcmp(string, BAD_CAST "LIQUIDATOR"))
2007 *type = USERTYPE_LIQUIDATOR;
2008 else
2009 return IE_ENUM;
2010 return IE_SUCCESS;
2014 /* Convert ISDS userType enum @type to UTF-8 string.
2015 * @Return pointer to static string, or NULL if unknown enum value */
2016 static const xmlChar *isds_UserType2string(const isds_UserType type) {
2017 switch(type) {
2018 case USERTYPE_PRIMARY: return(BAD_CAST "PRIMARY_USER"); break;
2019 case USERTYPE_ENTRUSTED: return(BAD_CAST "ENTRUSTED_USER"); break;
2020 case USERTYPE_ADMINISTRATOR: return(BAD_CAST "ADMINISTRATOR"); break;
2021 case USERTYPE_OFFICIAL: return(BAD_CAST "OFFICIAL"); break;
2022 case USERTYPE_OFFICIAL_CERT: return(BAD_CAST "OFFICIAL_CERT"); break;
2023 case USERTYPE_LIQUIDATOR: return(BAD_CAST "LIQUIDATOR"); break;
2024 default: return NULL; break;
2029 /* Convert UTF-8 @string representation of ISDS sender type to enum @type */
2030 static isds_error string2isds_sender_type(const xmlChar *string,
2031 isds_sender_type *type) {
2032 if (!string || !type) return IE_INVAL;
2034 if (!xmlStrcmp(string, BAD_CAST "PRIMARY_USER"))
2035 *type = SENDERTYPE_PRIMARY;
2036 else if (!xmlStrcmp(string, BAD_CAST "ENTRUSTED_USER"))
2037 *type = SENDERTYPE_ENTRUSTED;
2038 else if (!xmlStrcmp(string, BAD_CAST "ADMINISTRATOR"))
2039 *type = SENDERTYPE_ADMINISTRATOR;
2040 else if (!xmlStrcmp(string, BAD_CAST "OFFICIAL"))
2041 *type = SENDERTYPE_OFFICIAL;
2042 else if (!xmlStrcmp(string, BAD_CAST "VIRTUAL"))
2043 *type = SENDERTYPE_VIRTUAL;
2044 else if (!xmlStrcmp(string, BAD_CAST "OFFICIAL_CERT"))
2045 *type = SENDERTYPE_OFFICIAL_CERT;
2046 else if (!xmlStrcmp(string, BAD_CAST "LIQUIDATOR"))
2047 *type = SENDERTYPE_LIQUIDATOR;
2048 else
2049 return IE_ENUM;
2050 return IE_SUCCESS;
2054 /* Convert UTF-8 @string representation of ISDS PDZType to enum @type */
2055 static isds_error string2isds_payment_type(const xmlChar *string,
2056 isds_payment_type *type) {
2057 if (!string || !type) return IE_INVAL;
2059 if (!xmlStrcmp(string, BAD_CAST "K"))
2060 *type = PAYMENT_SENDER;
2061 else if (!xmlStrcmp(string, BAD_CAST "O"))
2062 *type = PAYMENT_RESPONSE;
2063 else if (!xmlStrcmp(string, BAD_CAST "G"))
2064 *type = PAYMENT_SPONSOR;
2065 else if (!xmlStrcmp(string, BAD_CAST "Z"))
2066 *type = PAYMENT_SPONSOR_LIMITED;
2067 else if (!xmlStrcmp(string, BAD_CAST "D"))
2068 *type = PAYMENT_SPONSOR_EXTERNAL;
2069 else if (!xmlStrcmp(string, BAD_CAST "E"))
2070 *type = PAYMENT_STAMP;
2071 else
2072 return IE_ENUM;
2073 return IE_SUCCESS;
2077 /* Convert UTF-8 @string representation of ISDS ciEventType to enum @type.
2078 * ciEventType is integer but we convert it from string representation
2079 * directly. */
2080 static isds_error string2isds_credit_event_type(const xmlChar *string,
2081 isds_credit_event_type *type) {
2082 if (!string || !type) return IE_INVAL;
2084 if (!xmlStrcmp(string, BAD_CAST "1"))
2085 *type = ISDS_CREDIT_CHARGED;
2086 else if (!xmlStrcmp(string, BAD_CAST "2"))
2087 *type = ISDS_CREDIT_DISCHARGED;
2088 else if (!xmlStrcmp(string, BAD_CAST "3"))
2089 *type = ISDS_CREDIT_MESSAGE_SENT;
2090 else if (!xmlStrcmp(string, BAD_CAST "4"))
2091 *type = ISDS_CREDIT_STORAGE_SET;
2092 else if (!xmlStrcmp(string, BAD_CAST "5"))
2093 *type = ISDS_CREDIT_EXPIRED;
2094 else
2095 return IE_ENUM;
2096 return IE_SUCCESS;
2100 /* Convert ISDS dmFileMetaType enum @type to UTF-8 string.
2101 * @Return pointer to static string, or NULL if unknown enum value */
2102 static const xmlChar *isds_FileMetaType2string(const isds_FileMetaType type) {
2103 switch(type) {
2104 case FILEMETATYPE_MAIN: return(BAD_CAST "main"); break;
2105 case FILEMETATYPE_ENCLOSURE: return(BAD_CAST "enclosure"); break;
2106 case FILEMETATYPE_SIGNATURE: return(BAD_CAST "signature"); break;
2107 case FILEMETATYPE_META: return(BAD_CAST "meta"); break;
2108 default: return NULL; break;
2111 #endif /* HAVE_LIBCURL */
2114 /* Convert UTF-8 @string to ISDS dmFileMetaType enum @type.
2115 * @Return IE_ENUM if @string is not valid enum member */
2116 static isds_error string2isds_FileMetaType(const xmlChar *string,
2117 isds_FileMetaType *type) {
2118 if (!string || !type) return IE_INVAL;
2120 if (!xmlStrcmp(string, BAD_CAST "main"))
2121 *type = FILEMETATYPE_MAIN;
2122 else if (!xmlStrcmp(string, BAD_CAST "enclosure"))
2123 *type = FILEMETATYPE_ENCLOSURE;
2124 else if (!xmlStrcmp(string, BAD_CAST "signature"))
2125 *type = FILEMETATYPE_SIGNATURE;
2126 else if (!xmlStrcmp(string, BAD_CAST "meta"))
2127 *type = FILEMETATYPE_META;
2128 else
2129 return IE_ENUM;
2130 return IE_SUCCESS;
2134 /* Convert UTF-8 @string to ISDS hash @algorithm.
2135 * @Return IE_ENUM if @string is not valid enum member */
2136 static isds_error string2isds_hash_algorithm(const xmlChar *string,
2137 isds_hash_algorithm *algorithm) {
2138 if (!string || !algorithm) return IE_INVAL;
2140 if (!xmlStrcmp(string, BAD_CAST "MD5"))
2141 *algorithm = HASH_ALGORITHM_MD5;
2142 else if (!xmlStrcmp(string, BAD_CAST "SHA-1"))
2143 *algorithm = HASH_ALGORITHM_SHA_1;
2144 else if (!xmlStrcmp(string, BAD_CAST "SHA-224"))
2145 *algorithm = HASH_ALGORITHM_SHA_224;
2146 else if (!xmlStrcmp(string, BAD_CAST "SHA-256"))
2147 *algorithm = HASH_ALGORITHM_SHA_256;
2148 else if (!xmlStrcmp(string, BAD_CAST "SHA-384"))
2149 *algorithm = HASH_ALGORITHM_SHA_384;
2150 else if (!xmlStrcmp(string, BAD_CAST "SHA-512"))
2151 *algorithm = HASH_ALGORITHM_SHA_512;
2152 else
2153 return IE_ENUM;
2154 return IE_SUCCESS;
2158 #if HAVE_LIBCURL
2159 /* Convert struct tm *@time to UTF-8 ISO 8601 date @string. */
2160 static isds_error tm2datestring(const struct tm *time, xmlChar **string) {
2161 if (!time || !string) return IE_INVAL;
2163 if (-1 == isds_asprintf((char **) string, "%d-%02d-%02d",
2164 time->tm_year + 1900, time->tm_mon + 1, time->tm_mday))
2165 return IE_ERROR;
2167 return IE_SUCCESS;
2171 /* Convert struct timeval * @time to UTF-8 ISO 8601 date-time @string. It
2172 * respects the @time microseconds too. */
2173 static isds_error timeval2timestring(const struct timeval *time,
2174 xmlChar **string) {
2175 struct tm broken;
2177 if (!time || !string) return IE_INVAL;
2179 if (!gmtime_r(&time->tv_sec, &broken)) return IE_DATE;
2180 if (time->tv_usec < 0 || time->tv_usec > 999999) return IE_DATE;
2182 /* TODO: small negative year should be formatted as "-0012". This is not
2183 * true for glibc "%04d". We should implement it.
2184 * TODO: What's type of time->tv_usec exactly? Unsigned? Absolute?
2185 * See <http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/#dateTime> */
2186 if (-1 == isds_asprintf((char **) string,
2187 "%04d-%02d-%02dT%02d:%02d:%02d.%06ld",
2188 broken.tm_year + 1900, broken.tm_mon + 1, broken.tm_mday,
2189 broken.tm_hour, broken.tm_min, broken.tm_sec,
2190 time->tv_usec))
2191 return IE_ERROR;
2193 return IE_SUCCESS;
2195 #endif /* HAVE_LIBCURL */
2198 /* Convert UTF-8 ISO 8601 date-time @string to struct timeval.
2199 * It respects microseconds too.
2200 * In case of error, @time will be freed. */
2201 static isds_error timestring2timeval(const xmlChar *string,
2202 struct timeval **time) {
2203 struct tm broken;
2204 char *offset, *delim, *endptr;
2205 char subseconds[7];
2206 int offset_hours, offset_minutes;
2207 int i;
2208 #ifdef _WIN32
2209 int tmp;
2210 #endif
2212 if (!time) return IE_INVAL;
2213 if (!string) {
2214 zfree(*time);
2215 return IE_INVAL;
2218 memset(&broken, 0, sizeof(broken));
2220 if (!*time) {
2221 *time = calloc(1, sizeof(**time));
2222 if (!*time) return IE_NOMEM;
2223 } else {
2224 memset(*time, 0, sizeof(**time));
2228 /* xsd:date is ISO 8601 string, thus ASCII */
2229 /*TODO: negative year */
2231 #ifdef _WIN32
2232 i = 0;
2233 if ((tmp = sscanf((const char*)string, "%d-%d-%dT%d:%d:%d%n",
2234 &broken.tm_year, &broken.tm_mon, &broken.tm_mday,
2235 &broken.tm_hour, &broken.tm_min, &broken.tm_sec,
2236 &i)) < 6) {
2237 zfree(*time);
2238 return IE_DATE;
2241 broken.tm_year -= 1900;
2242 broken.tm_mon--;
2243 offset = (char*)string + i;
2244 #else
2245 /* Parse date and time without subseconds and offset */
2246 offset = strptime((char*)string, "%Y-%m-%dT%T", &broken);
2247 if (!offset) {
2248 zfree(*time);
2249 return IE_DATE;
2251 #endif
2253 /* Get subseconds */
2254 if (*offset == '.' ) {
2255 offset++;
2257 /* Copy first 6 digits, pad it with zeros.
2258 * XXX: It truncates longer number, no round.
2259 * Current server implementation uses only millisecond resolution. */
2260 /* TODO: isdigit() is locale sensitive */
2261 for (i = 0;
2262 i < sizeof(subseconds)/sizeof(char) - 1 && isdigit(*offset);
2263 i++, offset++) {
2264 subseconds[i] = *offset;
2266 for (; i < sizeof(subseconds)/sizeof(char) - 1; i++) {
2267 subseconds[i] = '0';
2269 subseconds[6] = '\0';
2271 /* Convert it into integer */
2272 (*time)->tv_usec = strtol(subseconds, &endptr, 10);
2273 if (*endptr != '\0' || (*time)->tv_usec == LONG_MIN ||
2274 (*time)->tv_usec == LONG_MAX) {
2275 zfree(*time);
2276 return IE_DATE;
2279 /* move to the zone offset delimiter or signal NULL*/
2280 delim = strchr(offset, '-');
2281 if (!delim)
2282 delim = strchr(offset, '+');
2283 if (!delim)
2284 delim = strchr(offset, 'Z');
2285 offset = delim;
2288 /* Get zone offset */
2289 /* ISO allows zone offset string only: "" | "Z" | ("+"|"-" "<HH>:<MM>")
2290 * "" equals to "Z" and it means UTC zone. */
2291 /* One can not use strptime(, "%z",) becase it's RFC E-MAIL format without
2292 * colon separator */
2293 if (offset && (*offset == '-' || *offset == '+')) {
2294 if (2 != sscanf(offset + 1, "%2d:%2d", &offset_hours, &offset_minutes)) {
2295 zfree(*time);
2296 return IE_DATE;
2298 if (*offset == '+') {
2299 broken.tm_hour -= offset_hours;
2300 broken.tm_min -= offset_minutes;
2301 } else {
2302 broken.tm_hour += offset_hours;
2303 broken.tm_min += offset_minutes;
2307 /* Convert to time_t */
2308 (*time)->tv_sec = _isds_timegm(&broken);
2309 if ((*time)->tv_sec == (time_t) -1) {
2310 zfree(*time);
2311 return IE_DATE;
2314 return IE_SUCCESS;
2318 /* Convert unsigned int into isds_message_status.
2319 * @context is session context
2320 * @number is pointer to number value. NULL will be treated as invalid value.
2321 * @status is automatically reallocated status
2322 * @return IE_SUCCESS, or error code and free status */
2323 static isds_error uint2isds_message_status(struct isds_ctx *context,
2324 const unsigned long int *number, isds_message_status **status) {
2325 if (!context) return IE_INVALID_CONTEXT;
2326 if (!status) return IE_INVAL;
2328 free(*status); *status = NULL;
2329 if (!number) return IE_INVAL;
2331 if (*number < 1 || *number > 10) {
2332 isds_printf_message(context, _("Invalid message status value: %lu"),
2333 *number);
2334 return IE_ENUM;
2337 *status = malloc(sizeof(**status));
2338 if (!*status) return IE_NOMEM;
2340 **status = 1 << *number;
2341 return IE_SUCCESS;
2345 /* Convert event description string into isds_event members type and
2346 * description
2347 * @string is raw event description starting with event prefix
2348 * @event is structure where to store type and stripped description to
2349 * @return standard error code, unknown prefix is not classified as an error.
2350 * */
2351 static isds_error eventstring2event(const xmlChar *string,
2352 struct isds_event* event) {
2353 const xmlChar *known_prefixes[] = {
2354 BAD_CAST "EV0:",
2355 BAD_CAST "EV1:",
2356 BAD_CAST "EV2:",
2357 BAD_CAST "EV3:",
2358 BAD_CAST "EV4:",
2359 BAD_CAST "EV5:",
2360 BAD_CAST "EV11:",
2361 BAD_CAST "EV12:",
2362 BAD_CAST "EV13:"
2364 const isds_event_type types[] = {
2365 EVENT_ENTERED_SYSTEM,
2366 EVENT_ACCEPTED_BY_RECIPIENT,
2367 EVENT_ACCEPTED_BY_FICTION,
2368 EVENT_UNDELIVERABLE,
2369 EVENT_COMMERCIAL_ACCEPTED,
2370 EVENT_DELIVERED,
2371 EVENT_PRIMARY_LOGIN,
2372 EVENT_ENTRUSTED_LOGIN,
2373 EVENT_SYSCERT_LOGIN
2375 unsigned int index;
2376 size_t length;
2378 if (!string || !event) return IE_INVAL;
2380 if (!event->type) {
2381 event->type = malloc(sizeof(*event->type));
2382 if (!(event->type)) return IE_NOMEM;
2384 zfree(event->description);
2386 for (index = 0; index < sizeof(known_prefixes)/sizeof(known_prefixes[0]);
2387 index++) {
2388 length = xmlUTF8Strlen(known_prefixes[index]);
2390 if (!xmlStrncmp(string, known_prefixes[index], length)) {
2391 /* Prefix is known */
2392 *event->type = types[index];
2394 /* Strip prefix from description and spaces */
2395 /* TODO: Recognize all white spaces from UCS blank class and
2396 * operate on UTF-8 chars. */
2397 for (; string[length] != '\0' && string[length] == ' '; length++);
2398 event->description = strdup((char *) (string + length));
2399 if (!(event->description)) return IE_NOMEM;
2401 return IE_SUCCESS;
2405 /* Unknown event prefix.
2406 * XSD allows any string */
2407 char *string_locale = _isds_utf82locale((char *) string);
2408 isds_log(ILF_ISDS, ILL_WARNING,
2409 _("Unknown delivery info event prefix: %s\n"), string_locale);
2410 free(string_locale);
2412 *event->type = EVENT_UKNOWN;
2413 event->description = strdup((char *) string);
2414 if (!(event->description)) return IE_NOMEM;
2416 return IE_SUCCESS;
2420 /* Following EXTRACT_* macros expect @result, @xpath_ctx, @err, @context
2421 * and leave label */
2422 #define EXTRACT_STRING(element, string) { \
2423 xmlXPathFreeObject(result); \
2424 result = xmlXPathEvalExpression(BAD_CAST element "/text()", xpath_ctx); \
2425 if (NULL == (result)) { \
2426 err = IE_ERROR; \
2427 goto leave; \
2429 if (!xmlXPathNodeSetIsEmpty(result->nodesetval)) { \
2430 if (result->nodesetval->nodeNr > 1) { \
2431 isds_printf_message(context, _("Multiple %s element"), element); \
2432 err = IE_ERROR; \
2433 goto leave; \
2435 (string) = (char *) \
2436 xmlXPathCastNodeSetToString(result->nodesetval); \
2437 if (NULL == (string)) { \
2438 err = IE_ERROR; \
2439 goto leave; \
2444 #define EXTRACT_BOOLEAN(element, booleanPtr) \
2446 char *string = NULL; \
2447 EXTRACT_STRING(element, string); \
2449 if (string) { \
2450 (booleanPtr) = calloc(1, sizeof(*(booleanPtr))); \
2451 if (!(booleanPtr)) { \
2452 free(string); \
2453 err = IE_NOMEM; \
2454 goto leave; \
2457 if (!xmlStrcmp((xmlChar *)string, BAD_CAST "true") || \
2458 !xmlStrcmp((xmlChar *)string, BAD_CAST "1")) \
2459 *(booleanPtr) = 1; \
2460 else if (!xmlStrcmp((xmlChar *)string, BAD_CAST "false") || \
2461 !xmlStrcmp((xmlChar *)string, BAD_CAST "0")) \
2462 *(booleanPtr) = 0; \
2463 else { \
2464 char *string_locale = _isds_utf82locale((char*)string); \
2465 isds_printf_message(context, \
2466 _("%s value is not valid boolean: %s"), \
2467 element, string_locale); \
2468 free(string_locale); \
2469 free(string); \
2470 err = IE_ERROR; \
2471 goto leave; \
2474 free(string); \
2478 #define EXTRACT_LONGINT(element, longintPtr, preallocated) \
2480 char *string = NULL; \
2481 EXTRACT_STRING(element, string); \
2482 if (string) { \
2483 long int number; \
2484 char *endptr; \
2486 number = strtol((char*)string, &endptr, 10); \
2488 if (*endptr != '\0') { \
2489 char *string_locale = _isds_utf82locale((char *)string); \
2490 isds_printf_message(context, \
2491 _("%s is not valid integer: %s"), \
2492 element, string_locale); \
2493 free(string_locale); \
2494 free(string); \
2495 err = IE_ISDS; \
2496 goto leave; \
2499 if (number == LONG_MIN || number == LONG_MAX) { \
2500 char *string_locale = _isds_utf82locale((char *)string); \
2501 isds_printf_message(context, \
2502 _("%s value out of range of long int: %s"), \
2503 element, string_locale); \
2504 free(string_locale); \
2505 free(string); \
2506 err = IE_ERROR; \
2507 goto leave; \
2510 free(string); string = NULL; \
2512 if (!(preallocated)) { \
2513 (longintPtr) = calloc(1, sizeof(*(longintPtr))); \
2514 if (!(longintPtr)) { \
2515 err = IE_NOMEM; \
2516 goto leave; \
2519 *(longintPtr) = number; \
2523 #define EXTRACT_ULONGINT(element, ulongintPtr, preallocated) \
2525 char *string = NULL; \
2526 EXTRACT_STRING(element, string); \
2527 if (string) { \
2528 long int number; \
2529 char *endptr; \
2531 number = strtol((char*)string, &endptr, 10); \
2533 if (*endptr != '\0') { \
2534 char *string_locale = _isds_utf82locale((char *)string); \
2535 isds_printf_message(context, \
2536 _("%s is not valid integer: %s"), \
2537 element, string_locale); \
2538 free(string_locale); \
2539 free(string); \
2540 err = IE_ISDS; \
2541 goto leave; \
2544 if (number == LONG_MIN || number == LONG_MAX) { \
2545 char *string_locale = _isds_utf82locale((char *)string); \
2546 isds_printf_message(context, \
2547 _("%s value out of range of long int: %s"), \
2548 element, string_locale); \
2549 free(string_locale); \
2550 free(string); \
2551 err = IE_ERROR; \
2552 goto leave; \
2555 free(string); string = NULL; \
2556 if (number < 0) { \
2557 isds_printf_message(context, \
2558 _("%s value is negative: %ld"), element, number); \
2559 err = IE_ERROR; \
2560 goto leave; \
2563 if (!(preallocated)) { \
2564 (ulongintPtr) = calloc(1, sizeof(*(ulongintPtr))); \
2565 if (!(ulongintPtr)) { \
2566 err = IE_NOMEM; \
2567 goto leave; \
2570 *(ulongintPtr) = number; \
2574 #define EXTRACT_DATE(element, tmPtr) { \
2575 char *string = NULL; \
2576 EXTRACT_STRING(element, string); \
2577 if (NULL != string) { \
2578 (tmPtr) = calloc(1, sizeof(*(tmPtr))); \
2579 if (NULL == (tmPtr)) { \
2580 free(string); \
2581 err = IE_NOMEM; \
2582 goto leave; \
2584 err = _isds_datestring2tm((xmlChar *)string, (tmPtr)); \
2585 if (err) { \
2586 if (err == IE_NOTSUP) { \
2587 err = IE_ISDS; \
2588 char *string_locale = _isds_utf82locale(string); \
2589 char *element_locale = _isds_utf82locale(element); \
2590 isds_printf_message(context, _("Invalid %s value: %s"), \
2591 element_locale, string_locale); \
2592 free(string_locale); \
2593 free(element_locale); \
2595 free(string); \
2596 goto leave; \
2598 free(string); \
2602 #define EXTRACT_STRING_ATTRIBUTE(attribute, string, required) { \
2603 (string) = (char *) xmlGetNsProp(xpath_ctx->node, ( BAD_CAST attribute), \
2604 NULL); \
2605 if ((required) && (!string)) { \
2606 char *attribute_locale = _isds_utf82locale(attribute); \
2607 char *element_locale = \
2608 _isds_utf82locale((char *)xpath_ctx->node->name); \
2609 isds_printf_message(context, \
2610 _("Could not extract required %s attribute value from " \
2611 "%s element"), attribute_locale, element_locale); \
2612 free(element_locale); \
2613 free(attribute_locale); \
2614 err = IE_ERROR; \
2615 goto leave; \
2620 #define INSERT_STRING_WITH_NS(parent, ns, element, string) \
2622 node = xmlNewTextChild(parent, ns, BAD_CAST (element), \
2623 (xmlChar *) (string)); \
2624 if (!node) { \
2625 isds_printf_message(context, \
2626 _("Could not add %s child to %s element"), \
2627 element, (parent)->name); \
2628 err = IE_ERROR; \
2629 goto leave; \
2633 #define INSERT_STRING(parent, element, string) \
2634 { INSERT_STRING_WITH_NS(parent, NULL, element, string) }
2636 #define INSERT_SCALAR_BOOLEAN(parent, element, boolean) \
2638 if (boolean) { INSERT_STRING(parent, element, "true"); } \
2639 else { INSERT_STRING(parent, element, "false"); } \
2642 #define INSERT_BOOLEAN(parent, element, booleanPtr) \
2644 if (booleanPtr) { \
2645 INSERT_SCALAR_BOOLEAN(parent, element, (*(booleanPtr))); \
2646 } else { \
2647 INSERT_STRING(parent, element, NULL); \
2651 #define INSERT_LONGINT(parent, element, longintPtr, buffer) { \
2652 if ((longintPtr)) { \
2653 /* FIXME: locale sensitive */ \
2654 if (-1 == isds_asprintf((char **)&(buffer), "%ld", *(longintPtr))) { \
2655 err = IE_NOMEM; \
2656 goto leave; \
2658 INSERT_STRING(parent, element, buffer) \
2659 free(buffer); (buffer) = NULL; \
2660 } else { INSERT_STRING(parent, element, NULL) } \
2663 #define INSERT_ULONGINT(parent, element, ulongintPtr, buffer) { \
2664 if ((ulongintPtr)) { \
2665 /* FIXME: locale sensitive */ \
2666 if (-1 == isds_asprintf((char **)&(buffer), "%lu", *(ulongintPtr))) { \
2667 err = IE_NOMEM; \
2668 goto leave; \
2670 INSERT_STRING(parent, element, buffer) \
2671 free(buffer); (buffer) = NULL; \
2672 } else { INSERT_STRING(parent, element, NULL) } \
2675 #define INSERT_ULONGINTNOPTR(parent, element, ulongint, buffer) \
2677 /* FIXME: locale sensitive */ \
2678 if (-1 == isds_asprintf((char **)&(buffer), "%lu", ulongint)) { \
2679 err = IE_NOMEM; \
2680 goto leave; \
2682 INSERT_STRING(parent, element, buffer) \
2683 free(buffer); (buffer) = NULL; \
2686 /* Requires attribute_node variable, do not free it. Can be used to reffer to
2687 * new attribute. */
2688 #define INSERT_STRING_ATTRIBUTE(parent, attribute, string) \
2690 attribute_node = xmlNewProp((parent), BAD_CAST (attribute), \
2691 (xmlChar *) (string)); \
2692 if (!attribute_node) { \
2693 isds_printf_message(context, _("Could not add %s " \
2694 "attribute to %s element"), \
2695 (attribute), (parent)->name); \
2696 err = IE_ERROR; \
2697 goto leave; \
2701 #define CHECK_FOR_STRING_LENGTH(string, minimum, maximum, name) { \
2702 if (string) { \
2703 int length = xmlUTF8Strlen((xmlChar *) (string)); \
2704 if (length > (maximum)) { \
2705 isds_printf_message(context, \
2706 ngettext("%s has more than %d characters", \
2707 "%s has more than %d characters", (maximum)), \
2708 (name), (maximum)); \
2709 err = IE_2BIG; \
2710 goto leave; \
2712 if (length < (minimum)) { \
2713 isds_printf_message(context, \
2714 ngettext("%s has less than %d characters", \
2715 "%s has less than %d characters", (minimum)), \
2716 (name), (minimum)); \
2717 err = IE_2SMALL; \
2718 goto leave; \
2723 #define INSERT_ELEMENT(child, parent, element) \
2725 (child) = xmlNewChild((parent), NULL, BAD_CAST (element), NULL); \
2726 if (!(child)) { \
2727 isds_printf_message(context, \
2728 _("Could not add %s child to %s element"), \
2729 (element), (parent)->name); \
2730 err = IE_ERROR; \
2731 goto leave; \
2736 /* Find child element by name in given XPath context and switch context onto
2737 * it. The child must be uniq and must exist. Otherwise fails.
2738 * @context is ISDS context
2739 * @child is child element name
2740 * @xpath_ctx is XPath context. In success, the @xpath_ctx will be changed
2741 * into it child. In error case, the @xpath_ctx keeps original value. */
2742 static isds_error move_xpathctx_to_child(struct isds_ctx *context,
2743 const xmlChar *child, xmlXPathContextPtr xpath_ctx) {
2744 isds_error err = IE_SUCCESS;
2745 xmlXPathObjectPtr result = NULL;
2747 if (!context) return IE_INVALID_CONTEXT;
2748 if (!child || !xpath_ctx) return IE_INVAL;
2750 /* Find child */
2751 result = xmlXPathEvalExpression(child, xpath_ctx);
2752 if (!result) {
2753 err = IE_XML;
2754 goto leave;
2757 /* No match */
2758 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
2759 char *parent_locale = _isds_utf82locale((char*) xpath_ctx->node->name);
2760 char *child_locale = _isds_utf82locale((char*) child);
2761 isds_printf_message(context,
2762 _("%s element does not contain %s child"),
2763 parent_locale, child_locale);
2764 free(child_locale);
2765 free(parent_locale);
2766 err = IE_NOEXIST;
2767 goto leave;
2770 /* More matches */
2771 if (result->nodesetval->nodeNr > 1) {
2772 char *parent_locale = _isds_utf82locale((char*) xpath_ctx->node->name);
2773 char *child_locale = _isds_utf82locale((char*) child);
2774 isds_printf_message(context,
2775 _("%s element contains multiple %s children"),
2776 parent_locale, child_locale);
2777 free(child_locale);
2778 free(parent_locale);
2779 err = IE_NOTUNIQ;
2780 goto leave;
2783 /* Switch context */
2784 xpath_ctx->node = result->nodesetval->nodeTab[0];
2786 leave:
2787 xmlXPathFreeObject(result);
2788 return err;
2793 #if HAVE_LIBCURL
2794 /* Find and convert XSD:gPersonName group in current node into structure
2795 * @context is ISDS context
2796 * @personName is automatically reallocated person name structure. If no member
2797 * value is found, will be freed.
2798 * @xpath_ctx is XPath context with current node as parent for XSD:gPersonName
2799 * elements
2800 * In case of error @personName will be freed. */
2801 static isds_error extract_gPersonName(struct isds_ctx *context,
2802 struct isds_PersonName **personName, xmlXPathContextPtr xpath_ctx) {
2803 isds_error err = IE_SUCCESS;
2804 xmlXPathObjectPtr result = NULL;
2806 if (!context) return IE_INVALID_CONTEXT;
2807 if (!personName) return IE_INVAL;
2808 isds_PersonName_free(personName);
2809 if (!xpath_ctx) return IE_INVAL;
2812 *personName = calloc(1, sizeof(**personName));
2813 if (!*personName) {
2814 err = IE_NOMEM;
2815 goto leave;
2818 EXTRACT_STRING("isds:pnFirstName", (*personName)->pnFirstName);
2819 EXTRACT_STRING("isds:pnMiddleName", (*personName)->pnMiddleName);
2820 EXTRACT_STRING("isds:pnLastName", (*personName)->pnLastName);
2821 EXTRACT_STRING("isds:pnLastNameAtBirth", (*personName)->pnLastNameAtBirth);
2823 if (!(*personName)->pnFirstName && !(*personName)->pnMiddleName &&
2824 !(*personName)->pnLastName && !(*personName)->pnLastNameAtBirth)
2825 isds_PersonName_free(personName);
2827 leave:
2828 if (err) isds_PersonName_free(personName);
2829 xmlXPathFreeObject(result);
2830 return err;
2834 /* Find and convert XSD:gAddress group in current node into structure
2835 * @context is ISDS context
2836 * @address is automatically reallocated address structure. If no member
2837 * value is found, will be freed.
2838 * @xpath_ctx is XPath context with current node as parent for XSD:gAddress
2839 * elements
2840 * In case of error @address will be freed. */
2841 static isds_error extract_gAddress(struct isds_ctx *context,
2842 struct isds_Address **address, xmlXPathContextPtr xpath_ctx) {
2843 isds_error err = IE_SUCCESS;
2844 xmlXPathObjectPtr result = NULL;
2846 if (!context) return IE_INVALID_CONTEXT;
2847 if (!address) return IE_INVAL;
2848 isds_Address_free(address);
2849 if (!xpath_ctx) return IE_INVAL;
2852 *address = calloc(1, sizeof(**address));
2853 if (!*address) {
2854 err = IE_NOMEM;
2855 goto leave;
2858 EXTRACT_STRING("isds:adCity", (*address)->adCity);
2859 EXTRACT_STRING("isds:adStreet", (*address)->adStreet);
2860 EXTRACT_STRING("isds:adNumberInStreet", (*address)->adNumberInStreet);
2861 EXTRACT_STRING("isds:adNumberInMunicipality",
2862 (*address)->adNumberInMunicipality);
2863 EXTRACT_STRING("isds:adZipCode", (*address)->adZipCode);
2864 EXTRACT_STRING("isds:adState", (*address)->adState);
2866 if (!(*address)->adCity && !(*address)->adStreet &&
2867 !(*address)->adNumberInStreet &&
2868 !(*address)->adNumberInMunicipality &&
2869 !(*address)->adZipCode && !(*address)->adState)
2870 isds_Address_free(address);
2872 leave:
2873 if (err) isds_Address_free(address);
2874 xmlXPathFreeObject(result);
2875 return err;
2879 /* Find and convert isds:biDate element in current node into structure
2880 * @context is ISDS context
2881 * @biDate is automatically reallocated birth date structure. If no member
2882 * value is found, will be freed.
2883 * @xpath_ctx is XPath context with current node as parent for isds:biDate
2884 * element
2885 * In case of error @biDate will be freed. */
2886 static isds_error extract_BiDate(struct isds_ctx *context,
2887 struct tm **biDate, xmlXPathContextPtr xpath_ctx) {
2888 isds_error err = IE_SUCCESS;
2889 xmlXPathObjectPtr result = NULL;
2890 char *string = NULL;
2892 if (!context) return IE_INVALID_CONTEXT;
2893 if (!biDate) return IE_INVAL;
2894 zfree(*biDate);
2895 if (!xpath_ctx) return IE_INVAL;
2897 EXTRACT_STRING("isds:biDate", string);
2898 if (string) {
2899 *biDate = calloc(1, sizeof(**biDate));
2900 if (!*biDate) {
2901 err = IE_NOMEM;
2902 goto leave;
2904 err = _isds_datestring2tm((xmlChar *)string, *biDate);
2905 if (err) {
2906 if (err == IE_NOTSUP) {
2907 err = IE_ISDS;
2908 char *string_locale = _isds_utf82locale(string);
2909 isds_printf_message(context,
2910 _("Invalid isds:biDate value: %s"), string_locale);
2911 free(string_locale);
2913 goto leave;
2917 leave:
2918 if (err) zfree(*biDate);
2919 free(string);
2920 xmlXPathFreeObject(result);
2921 return err;
2925 /* Convert isds:dBOwnerInfo XML tree into structure
2926 * @context is ISDS context
2927 * @db_owner_info is automatically reallocated box owner info structure
2928 * @xpath_ctx is XPath context with current node as isds:dBOwnerInfo element
2929 * In case of error @db_owner_info will be freed. */
2930 static isds_error extract_DbOwnerInfo(struct isds_ctx *context,
2931 struct isds_DbOwnerInfo **db_owner_info,
2932 xmlXPathContextPtr xpath_ctx) {
2933 isds_error err = IE_SUCCESS;
2934 xmlXPathObjectPtr result = NULL;
2935 char *string = NULL;
2937 if (!context) return IE_INVALID_CONTEXT;
2938 if (!db_owner_info) return IE_INVAL;
2939 isds_DbOwnerInfo_free(db_owner_info);
2940 if (!xpath_ctx) return IE_INVAL;
2943 *db_owner_info = calloc(1, sizeof(**db_owner_info));
2944 if (!*db_owner_info) {
2945 err = IE_NOMEM;
2946 goto leave;
2949 EXTRACT_STRING("isds:dbID", (*db_owner_info)->dbID);
2951 EXTRACT_STRING("isds:dbType", string);
2952 if (string) {
2953 (*db_owner_info)->dbType =
2954 calloc(1, sizeof(*((*db_owner_info)->dbType)));
2955 if (!(*db_owner_info)->dbType) {
2956 err = IE_NOMEM;
2957 goto leave;
2959 err = string2isds_DbType((xmlChar *)string, (*db_owner_info)->dbType);
2960 if (err) {
2961 zfree((*db_owner_info)->dbType);
2962 if (err == IE_ENUM) {
2963 err = IE_ISDS;
2964 char *string_locale = _isds_utf82locale(string);
2965 isds_printf_message(context, _("Unknown isds:dbType: %s"),
2966 string_locale);
2967 free(string_locale);
2969 goto leave;
2971 zfree(string);
2974 EXTRACT_STRING("isds:ic", (*db_owner_info)->ic);
2976 err = extract_gPersonName(context, &(*db_owner_info)->personName,
2977 xpath_ctx);
2978 if (err) goto leave;
2980 EXTRACT_STRING("isds:firmName", (*db_owner_info)->firmName);
2982 (*db_owner_info)->birthInfo =
2983 calloc(1, sizeof(*((*db_owner_info)->birthInfo)));
2984 if (!(*db_owner_info)->birthInfo) {
2985 err = IE_NOMEM;
2986 goto leave;
2988 err = extract_BiDate(context, &(*db_owner_info)->birthInfo->biDate,
2989 xpath_ctx);
2990 if (err) goto leave;
2991 EXTRACT_STRING("isds:biCity", (*db_owner_info)->birthInfo->biCity);
2992 EXTRACT_STRING("isds:biCounty", (*db_owner_info)->birthInfo->biCounty);
2993 EXTRACT_STRING("isds:biState", (*db_owner_info)->birthInfo->biState);
2994 if (!(*db_owner_info)->birthInfo->biDate &&
2995 !(*db_owner_info)->birthInfo->biCity &&
2996 !(*db_owner_info)->birthInfo->biCounty &&
2997 !(*db_owner_info)->birthInfo->biState)
2998 isds_BirthInfo_free(&(*db_owner_info)->birthInfo);
3000 err = extract_gAddress(context, &(*db_owner_info)->address, xpath_ctx);
3001 if (err) goto leave;
3003 EXTRACT_STRING("isds:nationality", (*db_owner_info)->nationality);
3004 EXTRACT_STRING("isds:email", (*db_owner_info)->email);
3005 EXTRACT_STRING("isds:telNumber", (*db_owner_info)->telNumber);
3006 EXTRACT_STRING("isds:identifier", (*db_owner_info)->identifier);
3007 EXTRACT_STRING("isds:registryCode", (*db_owner_info)->registryCode);
3009 EXTRACT_LONGINT("isds:dbState", (*db_owner_info)->dbState, 0);
3011 EXTRACT_BOOLEAN("isds:dbEffectiveOVM", (*db_owner_info)->dbEffectiveOVM);
3012 EXTRACT_BOOLEAN("isds:dbOpenAddressing",
3013 (*db_owner_info)->dbOpenAddressing);
3015 leave:
3016 if (err) isds_DbOwnerInfo_free(db_owner_info);
3017 free(string);
3018 xmlXPathFreeObject(result);
3019 return err;
3023 /* Insert struct isds_DbOwnerInfo data (box description) into XML tree
3024 * @context is session context
3025 * @owner is libisds structure with box description
3026 * @db_owner_info is XML element of XSD:tDbOwnerInfo */
3027 static isds_error insert_DbOwnerInfo(struct isds_ctx *context,
3028 const struct isds_DbOwnerInfo *owner, xmlNodePtr db_owner_info) {
3030 isds_error err = IE_SUCCESS;
3031 xmlNodePtr node;
3032 xmlChar *string = NULL;
3034 if (!context) return IE_INVALID_CONTEXT;
3035 if (!owner || !db_owner_info) return IE_INVAL;
3038 /* Build XSD:tDbOwnerInfo */
3039 CHECK_FOR_STRING_LENGTH(owner->dbID, 0, 7, "dbID")
3040 INSERT_STRING(db_owner_info, "dbID", owner->dbID);
3042 /* dbType */
3043 if (owner->dbType) {
3044 const xmlChar *type_string = isds_DbType2string(*(owner->dbType));
3045 if (!type_string) {
3046 isds_printf_message(context, _("Invalid dbType value: %d"),
3047 *(owner->dbType));
3048 err = IE_ENUM;
3049 goto leave;
3051 INSERT_STRING(db_owner_info, "dbType", type_string);
3053 INSERT_STRING(db_owner_info, "ic", owner->ic);
3054 if (owner->personName) {
3055 INSERT_STRING(db_owner_info, "pnFirstName",
3056 owner->personName->pnFirstName);
3057 INSERT_STRING(db_owner_info, "pnMiddleName",
3058 owner->personName->pnMiddleName);
3059 INSERT_STRING(db_owner_info, "pnLastName",
3060 owner->personName->pnLastName);
3061 INSERT_STRING(db_owner_info, "pnLastNameAtBirth",
3062 owner->personName->pnLastNameAtBirth);
3064 INSERT_STRING(db_owner_info, "firmName", owner->firmName);
3065 if (owner->birthInfo) {
3066 if (owner->birthInfo->biDate) {
3067 if (!tm2datestring(owner->birthInfo->biDate, &string))
3068 INSERT_STRING(db_owner_info, "biDate", string);
3069 free(string); string = NULL;
3071 INSERT_STRING(db_owner_info, "biCity", owner->birthInfo->biCity);
3072 INSERT_STRING(db_owner_info, "biCounty", owner->birthInfo->biCounty);
3073 INSERT_STRING(db_owner_info, "biState", owner->birthInfo->biState);
3075 if (owner->address) {
3076 INSERT_STRING(db_owner_info, "adCity", owner->address->adCity);
3077 INSERT_STRING(db_owner_info, "adStreet", owner->address->adStreet);
3078 INSERT_STRING(db_owner_info, "adNumberInStreet",
3079 owner->address->adNumberInStreet);
3080 INSERT_STRING(db_owner_info, "adNumberInMunicipality",
3081 owner->address->adNumberInMunicipality);
3082 INSERT_STRING(db_owner_info, "adZipCode", owner->address->adZipCode);
3083 INSERT_STRING(db_owner_info, "adState", owner->address->adState);
3085 INSERT_STRING(db_owner_info, "nationality", owner->nationality);
3086 INSERT_STRING(db_owner_info, "email", owner->email);
3087 INSERT_STRING(db_owner_info, "telNumber", owner->telNumber);
3089 CHECK_FOR_STRING_LENGTH(owner->identifier, 0, 20, "identifier")
3090 INSERT_STRING(db_owner_info, "identifier", owner->identifier);
3092 CHECK_FOR_STRING_LENGTH(owner->registryCode, 0, 5, "registryCode")
3093 INSERT_STRING(db_owner_info, "registryCode", owner->registryCode);
3095 INSERT_LONGINT(db_owner_info, "dbState", owner->dbState, string);
3097 INSERT_BOOLEAN(db_owner_info, "dbEffectiveOVM", owner->dbEffectiveOVM);
3098 INSERT_BOOLEAN(db_owner_info, "dbOpenAddressing",
3099 owner->dbOpenAddressing);
3101 leave:
3102 free(string);
3103 return err;
3107 /* Convert XSD:tDbUserInfo XML tree into structure
3108 * @context is ISDS context
3109 * @db_user_info is automatically reallocated user info structure
3110 * @xpath_ctx is XPath context with current node as XSD:tDbUserInfo element
3111 * In case of error @db_user_info will be freed. */
3112 static isds_error extract_DbUserInfo(struct isds_ctx *context,
3113 struct isds_DbUserInfo **db_user_info, xmlXPathContextPtr xpath_ctx) {
3114 isds_error err = IE_SUCCESS;
3115 xmlXPathObjectPtr result = NULL;
3116 char *string = NULL;
3118 if (!context) return IE_INVALID_CONTEXT;
3119 if (!db_user_info) return IE_INVAL;
3120 isds_DbUserInfo_free(db_user_info);
3121 if (!xpath_ctx) return IE_INVAL;
3124 *db_user_info = calloc(1, sizeof(**db_user_info));
3125 if (!*db_user_info) {
3126 err = IE_NOMEM;
3127 goto leave;
3130 EXTRACT_STRING("isds:userID", (*db_user_info)->userID);
3132 EXTRACT_STRING("isds:userType", string);
3133 if (string) {
3134 (*db_user_info)->userType =
3135 calloc(1, sizeof(*((*db_user_info)->userType)));
3136 if (!(*db_user_info)->userType) {
3137 err = IE_NOMEM;
3138 goto leave;
3140 err = string2isds_UserType((xmlChar *)string,
3141 (*db_user_info)->userType);
3142 if (err) {
3143 zfree((*db_user_info)->userType);
3144 if (err == IE_ENUM) {
3145 err = IE_ISDS;
3146 char *string_locale = _isds_utf82locale(string);
3147 isds_printf_message(context,
3148 _("Unknown isds:userType value: %s"), string_locale);
3149 free(string_locale);
3151 goto leave;
3153 zfree(string);
3156 EXTRACT_LONGINT("isds:userPrivils", (*db_user_info)->userPrivils, 0);
3158 (*db_user_info)->personName =
3159 calloc(1, sizeof(*((*db_user_info)->personName)));
3160 if (!(*db_user_info)->personName) {
3161 err = IE_NOMEM;
3162 goto leave;
3165 err = extract_gPersonName(context, &(*db_user_info)->personName,
3166 xpath_ctx);
3167 if (err) goto leave;
3169 err = extract_gAddress(context, &(*db_user_info)->address, xpath_ctx);
3170 if (err) goto leave;
3172 err = extract_BiDate(context, &(*db_user_info)->biDate, xpath_ctx);
3173 if (err) goto leave;
3175 EXTRACT_STRING("isds:ic", (*db_user_info)->ic);
3176 EXTRACT_STRING("isds:firmName", (*db_user_info)->firmName);
3178 EXTRACT_STRING("isds:caStreet", (*db_user_info)->caStreet);
3179 EXTRACT_STRING("isds:caCity", (*db_user_info)->caCity);
3180 EXTRACT_STRING("isds:caZipCode", (*db_user_info)->caZipCode);
3182 /* ???: Default value is "CZ" according specification. Should we provide
3183 * it? */
3184 EXTRACT_STRING("isds:caState", (*db_user_info)->caState);
3186 leave:
3187 if (err) isds_DbUserInfo_free(db_user_info);
3188 free(string);
3189 xmlXPathFreeObject(result);
3190 return err;
3194 /* Insert struct isds_DbUserInfo data (user description) into XML tree
3195 * @context is session context
3196 * @user is libisds structure with user description
3197 * @db_user_info is XML element of XSD:tDbUserInfo */
3198 static isds_error insert_DbUserInfo(struct isds_ctx *context,
3199 const struct isds_DbUserInfo *user, xmlNodePtr db_user_info) {
3201 isds_error err = IE_SUCCESS;
3202 xmlNodePtr node;
3203 xmlChar *string = NULL;
3205 if (!context) return IE_INVALID_CONTEXT;
3206 if (!user || !db_user_info) return IE_INVAL;
3208 /* Build XSD:tDbUserInfo */
3209 if (user->personName) {
3210 INSERT_STRING(db_user_info, "pnFirstName",
3211 user->personName->pnFirstName);
3212 INSERT_STRING(db_user_info, "pnMiddleName",
3213 user->personName->pnMiddleName);
3214 INSERT_STRING(db_user_info, "pnLastName",
3215 user->personName->pnLastName);
3216 INSERT_STRING(db_user_info, "pnLastNameAtBirth",
3217 user->personName->pnLastNameAtBirth);
3219 if (user->address) {
3220 INSERT_STRING(db_user_info, "adCity", user->address->adCity);
3221 INSERT_STRING(db_user_info, "adStreet", user->address->adStreet);
3222 INSERT_STRING(db_user_info, "adNumberInStreet",
3223 user->address->adNumberInStreet);
3224 INSERT_STRING(db_user_info, "adNumberInMunicipality",
3225 user->address->adNumberInMunicipality);
3226 INSERT_STRING(db_user_info, "adZipCode", user->address->adZipCode);
3227 INSERT_STRING(db_user_info, "adState", user->address->adState);
3229 if (user->biDate) {
3230 if (!tm2datestring(user->biDate, &string))
3231 INSERT_STRING(db_user_info, "biDate", string);
3232 zfree(string);
3234 CHECK_FOR_STRING_LENGTH(user->userID, 6, 12, "userID");
3235 INSERT_STRING(db_user_info, "userID", user->userID);
3237 /* userType */
3238 if (user->userType) {
3239 const xmlChar *type_string = isds_UserType2string(*(user->userType));
3240 if (!type_string) {
3241 isds_printf_message(context, _("Invalid userType value: %d"),
3242 *(user->userType));
3243 err = IE_ENUM;
3244 goto leave;
3246 INSERT_STRING(db_user_info, "userType", type_string);
3249 INSERT_LONGINT(db_user_info, "userPrivils", user->userPrivils, string);
3250 CHECK_FOR_STRING_LENGTH(user->ic, 0, 8, "ic")
3251 INSERT_STRING(db_user_info, "ic", user->ic);
3252 CHECK_FOR_STRING_LENGTH(user->firmName, 0, 100, "firmName")
3253 INSERT_STRING(db_user_info, "firmName", user->firmName);
3254 INSERT_STRING(db_user_info, "caStreet", user->caStreet);
3255 INSERT_STRING(db_user_info, "caCity", user->caCity);
3256 INSERT_STRING(db_user_info, "caZipCode", user->caZipCode);
3257 INSERT_STRING(db_user_info, "caState", user->caState);
3259 leave:
3260 free(string);
3261 return err;
3265 /* Convert XSD:tPDZRec XML tree into structure
3266 * @context is ISDS context
3267 * @permission is automatically reallocated commercial permission structure
3268 * @xpath_ctx is XPath context with current node as XSD:tPDZRec element
3269 * In case of error @permission will be freed. */
3270 static isds_error extract_DbPDZRecord(struct isds_ctx *context,
3271 struct isds_commercial_permission **permission,
3272 xmlXPathContextPtr xpath_ctx) {
3273 isds_error err = IE_SUCCESS;
3274 xmlXPathObjectPtr result = NULL;
3275 char *string = NULL;
3277 if (!context) return IE_INVALID_CONTEXT;
3278 if (!permission) return IE_INVAL;
3279 isds_commercial_permission_free(permission);
3280 if (!xpath_ctx) return IE_INVAL;
3283 *permission = calloc(1, sizeof(**permission));
3284 if (!*permission) {
3285 err = IE_NOMEM;
3286 goto leave;
3289 EXTRACT_STRING("isds:PDZType", string);
3290 if (string) {
3291 err = string2isds_payment_type((xmlChar *)string,
3292 &(*permission)->type);
3293 if (err) {
3294 if (err == IE_ENUM) {
3295 err = IE_ISDS;
3296 char *string_locale = _isds_utf82locale(string);
3297 isds_printf_message(context,
3298 _("Unknown isds:PDZType value: %s"), string_locale);
3299 free(string_locale);
3301 goto leave;
3303 zfree(string);
3306 EXTRACT_STRING("isds:PDZRecip", (*permission)->recipient);
3307 EXTRACT_STRING("isds:PDZPayer", (*permission)->payer);
3309 EXTRACT_STRING("isds:PDZExpire", string);
3310 if (string) {
3311 err = timestring2timeval((xmlChar *) string,
3312 &((*permission)->expiration));
3313 if (err) {
3314 char *string_locale = _isds_utf82locale(string);
3315 if (err == IE_DATE) err = IE_ISDS;
3316 isds_printf_message(context,
3317 _("Could not convert PDZExpire as ISO time: %s"),
3318 string_locale);
3319 free(string_locale);
3320 goto leave;
3322 zfree(string);
3325 EXTRACT_ULONGINT("isds:PDZCnt", (*permission)->count, 0);
3326 EXTRACT_STRING("isds:ODZIdent", (*permission)->reply_identifier);
3328 leave:
3329 if (err) isds_commercial_permission_free(permission);
3330 free(string);
3331 xmlXPathFreeObject(result);
3332 return err;
3336 /* Convert XSD:tCiRecord XML tree into structure
3337 * @context is ISDS context
3338 * @event is automatically reallocated commercial credit event structure
3339 * @xpath_ctx is XPath context with current node as XSD:tCiRecord element
3340 * In case of error @event will be freed. */
3341 static isds_error extract_CiRecord(struct isds_ctx *context,
3342 struct isds_credit_event **event,
3343 xmlXPathContextPtr xpath_ctx) {
3344 isds_error err = IE_SUCCESS;
3345 xmlXPathObjectPtr result = NULL;
3346 char *string = NULL;
3347 long int *number_ptr;
3349 if (!context) return IE_INVALID_CONTEXT;
3350 if (!event) return IE_INVAL;
3351 isds_credit_event_free(event);
3352 if (!xpath_ctx) return IE_INVAL;
3355 *event = calloc(1, sizeof(**event));
3356 if (!*event) {
3357 err = IE_NOMEM;
3358 goto leave;
3361 EXTRACT_STRING("isds:ciEventTime", string);
3362 if (string) {
3363 err = timestring2timeval((xmlChar *) string,
3364 &(*event)->time);
3365 if (err) {
3366 char *string_locale = _isds_utf82locale(string);
3367 if (err == IE_DATE) err = IE_ISDS;
3368 isds_printf_message(context,
3369 _("Could not convert ciEventTime as ISO time: %s"),
3370 string_locale);
3371 free(string_locale);
3372 goto leave;
3374 zfree(string);
3377 EXTRACT_STRING("isds:ciEventType", string);
3378 if (string) {
3379 err = string2isds_credit_event_type((xmlChar *)string,
3380 &(*event)->type);
3381 if (err) {
3382 if (err == IE_ENUM) {
3383 err = IE_ISDS;
3384 char *string_locale = _isds_utf82locale(string);
3385 isds_printf_message(context,
3386 _("Unknown isds:ciEventType value: %s"), string_locale);
3387 free(string_locale);
3389 goto leave;
3391 zfree(string);
3394 number_ptr = &((*event)->credit_change);
3395 EXTRACT_LONGINT("isds:ciCreditChange", number_ptr, 1);
3396 number_ptr = &(*event)->new_credit;
3397 EXTRACT_LONGINT("isds:ciCreditAfter", number_ptr, 1);
3399 switch((*event)->type) {
3400 case ISDS_CREDIT_CHARGED:
3401 EXTRACT_STRING("isds:ciTransID",
3402 (*event)->details.charged.transaction);
3403 break;
3404 case ISDS_CREDIT_DISCHARGED:
3405 EXTRACT_STRING("isds:ciTransID",
3406 (*event)->details.discharged.transaction);
3407 break;
3408 case ISDS_CREDIT_MESSAGE_SENT:
3409 EXTRACT_STRING("isds:ciRecipientID",
3410 (*event)->details.message_sent.recipient);
3411 EXTRACT_STRING("isds:ciPDZID",
3412 (*event)->details.message_sent.message_id);
3413 break;
3414 case ISDS_CREDIT_STORAGE_SET:
3415 number_ptr = &((*event)->details.storage_set.new_capacity);
3416 EXTRACT_LONGINT("isds:ciNewCapacity", number_ptr, 1);
3417 EXTRACT_DATE("isds:ciNewFrom",
3418 (*event)->details.storage_set.new_valid_from);
3419 EXTRACT_DATE("isds:ciNewTo",
3420 (*event)->details.storage_set.new_valid_to);
3421 EXTRACT_LONGINT("isds:ciOldCapacity",
3422 (*event)->details.storage_set.old_capacity, 0);
3423 EXTRACT_DATE("isds:ciOldFrom",
3424 (*event)->details.storage_set.old_valid_from);
3425 EXTRACT_DATE("isds:ciOldTo",
3426 (*event)->details.storage_set.old_valid_to);
3427 EXTRACT_STRING("isds:ciDoneBy",
3428 (*event)->details.storage_set.initiator);
3429 break;
3430 case ISDS_CREDIT_EXPIRED:
3431 break;
3434 leave:
3435 if (err) isds_credit_event_free(event);
3436 free(string);
3437 xmlXPathFreeObject(result);
3438 return err;
3442 #endif /* HAVE_LIBCURL */
3445 /* Convert XSD gMessageEnvelopeSub group of elements from XML tree into
3446 * isds_envelope structure. The envelope is automatically allocated but not
3447 * reallocated. The date are just appended into envelope structure.
3448 * @context is ISDS context
3449 * @envelope is automatically allocated message envelope structure
3450 * @xpath_ctx is XPath context with current node as gMessageEnvelope parent
3451 * In case of error @envelope will be freed. */
3452 static isds_error append_GMessageEnvelopeSub(struct isds_ctx *context,
3453 struct isds_envelope **envelope, xmlXPathContextPtr xpath_ctx) {
3454 isds_error err = IE_SUCCESS;
3455 xmlXPathObjectPtr result = NULL;
3457 if (!context) return IE_INVALID_CONTEXT;
3458 if (!envelope) return IE_INVAL;
3459 if (!xpath_ctx) return IE_INVAL;
3462 if (!*envelope) {
3463 /* Allocate envelope */
3464 *envelope = calloc(1, sizeof(**envelope));
3465 if (!*envelope) {
3466 err = IE_NOMEM;
3467 goto leave;
3469 } else {
3470 /* Else free former data */
3471 zfree((*envelope)->dmSenderOrgUnit);
3472 zfree((*envelope)->dmSenderOrgUnitNum);
3473 zfree((*envelope)->dbIDRecipient);
3474 zfree((*envelope)->dmRecipientOrgUnit);
3475 zfree((*envelope)->dmRecipientOrgUnitNum);
3476 zfree((*envelope)->dmToHands);
3477 zfree((*envelope)->dmAnnotation);
3478 zfree((*envelope)->dmRecipientRefNumber);
3479 zfree((*envelope)->dmSenderRefNumber);
3480 zfree((*envelope)->dmRecipientIdent);
3481 zfree((*envelope)->dmSenderIdent);
3482 zfree((*envelope)->dmLegalTitleLaw);
3483 zfree((*envelope)->dmLegalTitleYear);
3484 zfree((*envelope)->dmLegalTitleSect);
3485 zfree((*envelope)->dmLegalTitlePar);
3486 zfree((*envelope)->dmLegalTitlePoint);
3487 zfree((*envelope)->dmPersonalDelivery);
3488 zfree((*envelope)->dmAllowSubstDelivery);
3491 /* Extract envelope elements added by sender or ISDS
3492 * (XSD: gMessageEnvelopeSub type) */
3493 EXTRACT_STRING("isds:dmSenderOrgUnit", (*envelope)->dmSenderOrgUnit);
3494 EXTRACT_LONGINT("isds:dmSenderOrgUnitNum",
3495 (*envelope)->dmSenderOrgUnitNum, 0);
3496 EXTRACT_STRING("isds:dbIDRecipient", (*envelope)->dbIDRecipient);
3497 EXTRACT_STRING("isds:dmRecipientOrgUnit", (*envelope)->dmRecipientOrgUnit);
3498 EXTRACT_LONGINT("isds:dmRecipientOrgUnitNum",
3499 (*envelope)->dmRecipientOrgUnitNum, 0);
3500 EXTRACT_STRING("isds:dmToHands", (*envelope)->dmToHands);
3501 EXTRACT_STRING("isds:dmAnnotation", (*envelope)->dmAnnotation);
3502 EXTRACT_STRING("isds:dmRecipientRefNumber",
3503 (*envelope)->dmRecipientRefNumber);
3504 EXTRACT_STRING("isds:dmSenderRefNumber", (*envelope)->dmSenderRefNumber);
3505 EXTRACT_STRING("isds:dmRecipientIdent", (*envelope)->dmRecipientIdent);
3506 EXTRACT_STRING("isds:dmSenderIdent", (*envelope)->dmSenderIdent);
3508 /* Extract envelope elements regarding law reference */
3509 EXTRACT_LONGINT("isds:dmLegalTitleLaw", (*envelope)->dmLegalTitleLaw, 0);
3510 EXTRACT_LONGINT("isds:dmLegalTitleYear", (*envelope)->dmLegalTitleYear, 0);
3511 EXTRACT_STRING("isds:dmLegalTitleSect", (*envelope)->dmLegalTitleSect);
3512 EXTRACT_STRING("isds:dmLegalTitlePar", (*envelope)->dmLegalTitlePar);
3513 EXTRACT_STRING("isds:dmLegalTitlePoint", (*envelope)->dmLegalTitlePoint);
3515 /* Extract envelope other elements */
3516 EXTRACT_BOOLEAN("isds:dmPersonalDelivery", (*envelope)->dmPersonalDelivery);
3517 EXTRACT_BOOLEAN("isds:dmAllowSubstDelivery",
3518 (*envelope)->dmAllowSubstDelivery);
3520 leave:
3521 if (err) isds_envelope_free(envelope);
3522 xmlXPathFreeObject(result);
3523 return err;
3528 /* Convert XSD gMessageEnvelope group of elements from XML tree into
3529 * isds_envelope structure. The envelope is automatically allocated but not
3530 * reallocated. The date are just appended into envelope structure.
3531 * @context is ISDS context
3532 * @envelope is automatically allocated message envelope structure
3533 * @xpath_ctx is XPath context with current node as gMessageEnvelope parent
3534 * In case of error @envelope will be freed. */
3535 static isds_error append_GMessageEnvelope(struct isds_ctx *context,
3536 struct isds_envelope **envelope, xmlXPathContextPtr xpath_ctx) {
3537 isds_error err = IE_SUCCESS;
3538 xmlXPathObjectPtr result = NULL;
3540 if (!context) return IE_INVALID_CONTEXT;
3541 if (!envelope) return IE_INVAL;
3542 if (!xpath_ctx) return IE_INVAL;
3545 if (!*envelope) {
3546 /* Allocate envelope */
3547 *envelope = calloc(1, sizeof(**envelope));
3548 if (!*envelope) {
3549 err = IE_NOMEM;
3550 goto leave;
3552 } else {
3553 /* Else free former data */
3554 zfree((*envelope)->dmID);
3555 zfree((*envelope)->dbIDSender);
3556 zfree((*envelope)->dmSender);
3557 zfree((*envelope)->dmSenderAddress);
3558 zfree((*envelope)->dmSenderType);
3559 zfree((*envelope)->dmRecipient);
3560 zfree((*envelope)->dmRecipientAddress);
3561 zfree((*envelope)->dmAmbiguousRecipient);
3564 /* Extract envelope elements added by ISDS
3565 * (XSD: gMessageEnvelope type) */
3566 EXTRACT_STRING("isds:dmID", (*envelope)->dmID);
3567 EXTRACT_STRING("isds:dbIDSender", (*envelope)->dbIDSender);
3568 EXTRACT_STRING("isds:dmSender", (*envelope)->dmSender);
3569 EXTRACT_STRING("isds:dmSenderAddress", (*envelope)->dmSenderAddress);
3570 /* XML Schema does not guarantee enumeration. It's plain xs:int. */
3571 EXTRACT_LONGINT("isds:dmSenderType", (*envelope)->dmSenderType, 0);
3572 EXTRACT_STRING("isds:dmRecipient", (*envelope)->dmRecipient);
3573 EXTRACT_STRING("isds:dmRecipientAddress", (*envelope)->dmRecipientAddress);
3574 EXTRACT_BOOLEAN("isds:dmAmbiguousRecipient",
3575 (*envelope)->dmAmbiguousRecipient);
3577 /* Extract envelope elements added by sender and ISDS
3578 * (XSD: gMessageEnvelope type) */
3579 err = append_GMessageEnvelopeSub(context, envelope, xpath_ctx);
3580 if (err) goto leave;
3582 leave:
3583 if (err) isds_envelope_free(envelope);
3584 xmlXPathFreeObject(result);
3585 return err;
3589 /* Convert other envelope elements from XML tree into isds_envelope structure:
3590 * dmMessageStatus, dmAttachmentSize, dmDeliveryTime, dmAcceptanceTime.
3591 * The envelope is automatically allocated but not reallocated.
3592 * The data are just appended into envelope structure.
3593 * @context is ISDS context
3594 * @envelope is automatically allocated message envelope structure
3595 * @xpath_ctx is XPath context with current node as parent desired elements
3596 * In case of error @envelope will be freed. */
3597 static isds_error append_status_size_times(struct isds_ctx *context,
3598 struct isds_envelope **envelope, xmlXPathContextPtr xpath_ctx) {
3599 isds_error err = IE_SUCCESS;
3600 xmlXPathObjectPtr result = NULL;
3601 char *string = NULL;
3602 unsigned long int *unumber = NULL;
3604 if (!context) return IE_INVALID_CONTEXT;
3605 if (!envelope) return IE_INVAL;
3606 if (!xpath_ctx) return IE_INVAL;
3609 if (!*envelope) {
3610 /* Allocate new */
3611 *envelope = calloc(1, sizeof(**envelope));
3612 if (!*envelope) {
3613 err = IE_NOMEM;
3614 goto leave;
3616 } else {
3617 /* Free old data */
3618 zfree((*envelope)->dmMessageStatus);
3619 zfree((*envelope)->dmAttachmentSize);
3620 zfree((*envelope)->dmDeliveryTime);
3621 zfree((*envelope)->dmAcceptanceTime);
3625 /* dmMessageStatus element is mandatory */
3626 EXTRACT_ULONGINT("sisds:dmMessageStatus", unumber, 0);
3627 if (!unumber) {
3628 isds_log_message(context,
3629 _("Missing mandatory sisds:dmMessageStatus integer"));
3630 err = IE_ISDS;
3631 goto leave;
3633 err = uint2isds_message_status(context, unumber,
3634 &((*envelope)->dmMessageStatus));
3635 if (err) {
3636 if (err == IE_ENUM) err = IE_ISDS;
3637 goto leave;
3639 free(unumber); unumber = NULL;
3641 EXTRACT_ULONGINT("sisds:dmAttachmentSize", (*envelope)->dmAttachmentSize,
3644 EXTRACT_STRING("sisds:dmDeliveryTime", string);
3645 if (string) {
3646 err = timestring2timeval((xmlChar *) string,
3647 &((*envelope)->dmDeliveryTime));
3648 if (err) {
3649 char *string_locale = _isds_utf82locale(string);
3650 if (err == IE_DATE) err = IE_ISDS;
3651 isds_printf_message(context,
3652 _("Could not convert dmDeliveryTime as ISO time: %s"),
3653 string_locale);
3654 free(string_locale);
3655 goto leave;
3657 zfree(string);
3660 EXTRACT_STRING("sisds:dmAcceptanceTime", string);
3661 if (string) {
3662 err = timestring2timeval((xmlChar *) string,
3663 &((*envelope)->dmAcceptanceTime));
3664 if (err) {
3665 char *string_locale = _isds_utf82locale(string);
3666 if (err == IE_DATE) err = IE_ISDS;
3667 isds_printf_message(context,
3668 _("Could not convert dmAcceptanceTime as ISO time: %s"),
3669 string_locale);
3670 free(string_locale);
3671 goto leave;
3673 zfree(string);
3676 leave:
3677 if (err) isds_envelope_free(envelope);
3678 free(unumber);
3679 free(string);
3680 xmlXPathFreeObject(result);
3681 return err;
3685 /* Convert message type attribute of current element into isds_envelope
3686 * structure.
3687 * TODO: This function can be incorporated into append_status_size_times() as
3688 * they are called always together.
3689 * The envelope is automatically allocated but not reallocated.
3690 * The data are just appended into envelope structure.
3691 * @context is ISDS context
3692 * @envelope is automatically allocated message envelope structure
3693 * @xpath_ctx is XPath context with current node as parent of attribute
3694 * carrying message type
3695 * In case of error @envelope will be freed. */
3696 static isds_error append_message_type(struct isds_ctx *context,
3697 struct isds_envelope **envelope, xmlXPathContextPtr xpath_ctx) {
3698 isds_error err = IE_SUCCESS;
3700 if (!context) return IE_INVALID_CONTEXT;
3701 if (!envelope) return IE_INVAL;
3702 if (!xpath_ctx) return IE_INVAL;
3705 if (!*envelope) {
3706 /* Allocate new */
3707 *envelope = calloc(1, sizeof(**envelope));
3708 if (!*envelope) {
3709 err = IE_NOMEM;
3710 goto leave;
3712 } else {
3713 /* Free old data */
3714 zfree((*envelope)->dmType);
3718 EXTRACT_STRING_ATTRIBUTE("dmType", (*envelope)->dmType, 0);
3720 if (!(*envelope)->dmType) {
3721 /* Use default value */
3722 (*envelope)->dmType = strdup("V");
3723 if (!(*envelope)->dmType) {
3724 err = IE_NOMEM;
3725 goto leave;
3727 } else if (1 != xmlUTF8Strlen((xmlChar *) (*envelope)->dmType)) {
3728 char *type_locale = _isds_utf82locale((*envelope)->dmType);
3729 isds_printf_message(context,
3730 _("Message type in dmType attribute is not 1 character long: "
3731 "%s"),
3732 type_locale);
3733 free(type_locale);
3734 err = IE_ISDS;
3735 goto leave;
3738 leave:
3739 if (err) isds_envelope_free(envelope);
3740 return err;
3744 #if HAVE_LIBCURL
3745 /* Convert dmType isds_envelope member into XML attribute and append it to
3746 * current node.
3747 * @context is ISDS context
3748 * @type is UTF-8 encoded string one multibyte long exactly or NULL to omit
3749 * @dm_envelope is XML element the resulting attribute will be appended to.
3750 * @return error code, in case of error context' message is filled. */
3751 static isds_error insert_message_type(struct isds_ctx *context,
3752 const char *type, xmlNodePtr dm_envelope) {
3753 isds_error err = IE_SUCCESS;
3754 xmlAttrPtr attribute_node;
3756 if (!context) return IE_INVALID_CONTEXT;
3757 if (!dm_envelope) return IE_INVAL;
3759 /* Insert optional message type */
3760 if (type) {
3761 if (1 != xmlUTF8Strlen((xmlChar *) type)) {
3762 char *type_locale = _isds_utf82locale(type);
3763 isds_printf_message(context,
3764 _("Message type in envelope is not 1 character long: %s"),
3765 type_locale);
3766 free(type_locale);
3767 err = IE_INVAL;
3768 goto leave;
3770 INSERT_STRING_ATTRIBUTE(dm_envelope, "dmType", type);
3773 leave:
3774 return err;
3776 #endif /* HAVE_LIBCURL */
3779 /* Extract message document into reallocated document structure
3780 * @context is ISDS context
3781 * @document is automatically reallocated message documents structure
3782 * @xpath_ctx is XPath context with current node as isds:dmFile
3783 * In case of error @document will be freed. */
3784 static isds_error extract_document(struct isds_ctx *context,
3785 struct isds_document **document, xmlXPathContextPtr xpath_ctx) {
3786 isds_error err = IE_SUCCESS;
3787 xmlXPathObjectPtr result = NULL;
3788 xmlNodePtr file_node = xpath_ctx->node;
3789 char *string = NULL;
3791 if (!context) return IE_INVALID_CONTEXT;
3792 if (!document) return IE_INVAL;
3793 isds_document_free(document);
3794 if (!xpath_ctx) return IE_INVAL;
3796 *document = calloc(1, sizeof(**document));
3797 if (!*document) {
3798 err = IE_NOMEM;
3799 goto leave;
3802 /* Extract document meta data */
3803 EXTRACT_STRING_ATTRIBUTE("dmMimeType", (*document)->dmMimeType, 1)
3804 if (context->normalize_mime_type) {
3805 const char *normalized_type =
3806 isds_normalize_mime_type((*document)->dmMimeType);
3807 if (NULL != normalized_type &&
3808 normalized_type != (*document)->dmMimeType) {
3809 char *new_type = strdup(normalized_type);
3810 if (NULL == new_type) {
3811 isds_printf_message(context,
3812 _("Not enough memory to normalize document MIME type"));
3813 err = IE_NOMEM;
3814 goto leave;
3816 free((*document)->dmMimeType);
3817 (*document)->dmMimeType = new_type;
3821 EXTRACT_STRING_ATTRIBUTE("dmFileMetaType", string, 1)
3822 err = string2isds_FileMetaType((xmlChar*)string,
3823 &((*document)->dmFileMetaType));
3824 if (err) {
3825 char *meta_type_locale = _isds_utf82locale(string);
3826 isds_printf_message(context,
3827 _("Document has invalid dmFileMetaType attribute value: %s"),
3828 meta_type_locale);
3829 free(meta_type_locale);
3830 err = IE_ISDS;
3831 goto leave;
3833 zfree(string);
3835 EXTRACT_STRING_ATTRIBUTE("dmFileGuid", (*document)->dmFileGuid, 0)
3836 EXTRACT_STRING_ATTRIBUTE("dmUpFileGuid", (*document)->dmUpFileGuid, 0)
3837 EXTRACT_STRING_ATTRIBUTE("dmFileDescr", (*document)->dmFileDescr, 0)
3838 EXTRACT_STRING_ATTRIBUTE("dmFormat", (*document)->dmFormat, 0)
3841 /* Extract document data.
3842 * Base64 encoded blob or XML subtree must be presented. */
3844 /* Check for dmEncodedContent */
3845 result = xmlXPathEvalExpression(BAD_CAST "isds:dmEncodedContent",
3846 xpath_ctx);
3847 if (!result) {
3848 err = IE_XML;
3849 goto leave;
3852 if (!xmlXPathNodeSetIsEmpty(result->nodesetval)) {
3853 /* Here we have Base64 blob */
3854 (*document)->is_xml = 0;
3856 if (result->nodesetval->nodeNr > 1) {
3857 isds_printf_message(context,
3858 _("Document has more dmEncodedContent elements"));
3859 err = IE_ISDS;
3860 goto leave;
3863 xmlXPathFreeObject(result); result = NULL;
3864 EXTRACT_STRING("isds:dmEncodedContent", string);
3866 /* Decode non-empty document */
3867 if (string && string[0] != '\0') {
3868 (*document)->data_length =
3869 _isds_b64decode(string, &((*document)->data));
3870 if ((*document)->data_length == (size_t) -1) {
3871 isds_printf_message(context,
3872 _("Error while Base64-decoding document content"));
3873 err = IE_ERROR;
3874 goto leave;
3877 } else {
3878 /* No Base64 blob, try XML document */
3879 xmlXPathFreeObject(result); result = NULL;
3880 result = xmlXPathEvalExpression(BAD_CAST "isds:dmXMLContent",
3881 xpath_ctx);
3882 if (!result) {
3883 err = IE_XML;
3884 goto leave;
3887 if (!xmlXPathNodeSetIsEmpty(result->nodesetval)) {
3888 /* Here we have XML document */
3889 (*document)->is_xml = 1;
3891 if (result->nodesetval->nodeNr > 1) {
3892 isds_printf_message(context,
3893 _("Document has more dmXMLContent elements"));
3894 err = IE_ISDS;
3895 goto leave;
3898 /* XXX: We cannot serialize the content simply because:
3899 * - XML document may point out of its scope (e.g. to message
3900 * envelope)
3901 * - isds:dmXMLContent can contain more elements, no element,
3902 * a text node only
3903 * - it's not the XML way
3904 * Thus we provide the only right solution: XML DOM. Let's
3905 * application to cope with this hot potato :) */
3906 (*document)->xml_node_list =
3907 result->nodesetval->nodeTab[0]->children;
3908 } else {
3909 /* No base64 blob, nor XML document */
3910 isds_printf_message(context,
3911 _("Document has no dmEncodedContent, nor dmXMLContent "
3912 "element"));
3913 err = IE_ISDS;
3914 goto leave;
3919 leave:
3920 if (err) isds_document_free(document);
3921 free(string);
3922 xmlXPathFreeObject(result);
3923 xpath_ctx->node = file_node;
3924 return err;
3929 /* Extract message documents into reallocated list of documents
3930 * @context is ISDS context
3931 * @documents is automatically reallocated message documents list structure
3932 * @xpath_ctx is XPath context with current node as XSD tFilesArray
3933 * In case of error @documents will be freed. */
3934 static isds_error extract_documents(struct isds_ctx *context,
3935 struct isds_list **documents, xmlXPathContextPtr xpath_ctx) {
3936 isds_error err = IE_SUCCESS;
3937 xmlXPathObjectPtr result = NULL;
3938 xmlNodePtr files_node = xpath_ctx->node;
3939 struct isds_list *document, *prev_document = NULL;
3941 if (!context) return IE_INVALID_CONTEXT;
3942 if (!documents) return IE_INVAL;
3943 isds_list_free(documents);
3944 if (!xpath_ctx) return IE_INVAL;
3946 /* Find documents */
3947 result = xmlXPathEvalExpression(BAD_CAST "isds:dmFile", xpath_ctx);
3948 if (!result) {
3949 err = IE_XML;
3950 goto leave;
3953 /* No match */
3954 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
3955 isds_printf_message(context,
3956 _("Message does not contain any document"));
3957 err = IE_ISDS;
3958 goto leave;
3962 /* Iterate over documents */
3963 for (int i = 0; i < result->nodesetval->nodeNr; i++) {
3965 /* Allocate and append list item */
3966 document = calloc(1, sizeof(*document));
3967 if (!document) {
3968 err = IE_NOMEM;
3969 goto leave;
3971 document->destructor = (void (*)(void **))isds_document_free;
3972 if (i == 0) *documents = document;
3973 else prev_document->next = document;
3974 prev_document = document;
3976 /* Extract document */
3977 xpath_ctx->node = result->nodesetval->nodeTab[i];
3978 err = extract_document(context,
3979 (struct isds_document **) &(document->data), xpath_ctx);
3980 if (err) goto leave;
3984 leave:
3985 if (err) isds_list_free(documents);
3986 xmlXPathFreeObject(result);
3987 xpath_ctx->node = files_node;
3988 return err;
3992 #if HAVE_LIBCURL
3993 /* Convert isds:dmRecord XML tree into structure
3994 * @context is ISDS context
3995 * @envelope is automatically reallocated message envelope structure
3996 * @xpath_ctx is XPath context with current node as isds:dmRecord element
3997 * In case of error @envelope will be freed. */
3998 static isds_error extract_DmRecord(struct isds_ctx *context,
3999 struct isds_envelope **envelope, xmlXPathContextPtr xpath_ctx) {
4000 isds_error err = IE_SUCCESS;
4001 xmlXPathObjectPtr result = NULL;
4003 if (!context) return IE_INVALID_CONTEXT;
4004 if (!envelope) return IE_INVAL;
4005 isds_envelope_free(envelope);
4006 if (!xpath_ctx) return IE_INVAL;
4009 *envelope = calloc(1, sizeof(**envelope));
4010 if (!*envelope) {
4011 err = IE_NOMEM;
4012 goto leave;
4016 /* Extract tRecord data */
4017 EXTRACT_ULONGINT("isds:dmOrdinal", (*envelope)->dmOrdinal, 0);
4019 /* Get dmMessageStatus, dmAttachmentSize, dmDeliveryTime,
4020 * dmAcceptanceTime. */
4021 err = append_status_size_times(context, envelope, xpath_ctx);
4022 if (err) goto leave;
4024 /* Extract envelope elements added by sender and ISDS
4025 * (XSD: gMessageEnvelope type) */
4026 err = append_GMessageEnvelope(context, envelope, xpath_ctx);
4027 if (err) goto leave;
4029 /* Get message type */
4030 err = append_message_type(context, envelope, xpath_ctx);
4031 if (err) goto leave;
4034 leave:
4035 if (err) isds_envelope_free(envelope);
4036 xmlXPathFreeObject(result);
4037 return err;
4041 /* Convert XSD:tStateChangesRecord type XML tree into structure
4042 * @context is ISDS context
4043 * @changed_status is automatically reallocated message state change structure
4044 * @xpath_ctx is XPath context with current node as element of
4045 * XSD:tStateChangesRecord type
4046 * In case of error @changed_status will be freed. */
4047 static isds_error extract_StateChangesRecord(struct isds_ctx *context,
4048 struct isds_message_status_change **changed_status,
4049 xmlXPathContextPtr xpath_ctx) {
4050 isds_error err = IE_SUCCESS;
4051 xmlXPathObjectPtr result = NULL;
4052 unsigned long int *unumber = NULL;
4053 char *string = NULL;
4055 if (!context) return IE_INVALID_CONTEXT;
4056 if (!changed_status) return IE_INVAL;
4057 isds_message_status_change_free(changed_status);
4058 if (!xpath_ctx) return IE_INVAL;
4061 *changed_status = calloc(1, sizeof(**changed_status));
4062 if (!*changed_status) {
4063 err = IE_NOMEM;
4064 goto leave;
4068 /* Extract tGetStateChangesInput data */
4069 EXTRACT_STRING("isds:dmID", (*changed_status)->dmID);
4071 /* dmEventTime is mandatory */
4072 EXTRACT_STRING("isds:dmEventTime", string);
4073 if (string) {
4074 err = timestring2timeval((xmlChar *) string,
4075 &((*changed_status)->time));
4076 if (err) {
4077 char *string_locale = _isds_utf82locale(string);
4078 if (err == IE_DATE) err = IE_ISDS;
4079 isds_printf_message(context,
4080 _("Could not convert dmEventTime as ISO time: %s"),
4081 string_locale);
4082 free(string_locale);
4083 goto leave;
4085 zfree(string);
4088 /* dmMessageStatus element is mandatory */
4089 EXTRACT_ULONGINT("isds:dmMessageStatus", unumber, 0);
4090 if (!unumber) {
4091 isds_log_message(context,
4092 _("Missing mandatory isds:dmMessageStatus integer"));
4093 err = IE_ISDS;
4094 goto leave;
4096 err = uint2isds_message_status(context, unumber,
4097 &((*changed_status)->dmMessageStatus));
4098 if (err) {
4099 if (err == IE_ENUM) err = IE_ISDS;
4100 goto leave;
4102 zfree(unumber);
4105 leave:
4106 free(unumber);
4107 free(string);
4108 if (err) isds_message_status_change_free(changed_status);
4109 xmlXPathFreeObject(result);
4110 return err;
4112 #endif /* HAVE_LIBCURL */
4115 /* Find and convert isds:dmHash XML tree into structure
4116 * @context is ISDS context
4117 * @envelope is automatically reallocated message hash structure
4118 * @xpath_ctx is XPath context with current node containing isds:dmHash child
4119 * In case of error @hash will be freed. */
4120 static isds_error find_and_extract_DmHash(struct isds_ctx *context,
4121 struct isds_hash **hash, xmlXPathContextPtr xpath_ctx) {
4122 isds_error err = IE_SUCCESS;
4123 xmlNodePtr old_ctx_node;
4124 xmlXPathObjectPtr result = NULL;
4125 char *string = NULL;
4127 if (!context) return IE_INVALID_CONTEXT;
4128 if (!hash) return IE_INVAL;
4129 isds_hash_free(hash);
4130 if (!xpath_ctx) return IE_INVAL;
4132 old_ctx_node = xpath_ctx->node;
4134 *hash = calloc(1, sizeof(**hash));
4135 if (!*hash) {
4136 err = IE_NOMEM;
4137 goto leave;
4140 /* Locate dmHash */
4141 err = move_xpathctx_to_child(context, BAD_CAST "sisds:dmHash", xpath_ctx);
4142 if (err == IE_NOEXIST || err == IE_NOTUNIQ) {
4143 err = IE_ISDS;
4144 goto leave;
4146 if (err) {
4147 err = IE_ERROR;
4148 goto leave;
4151 /* Get hash algorithm */
4152 EXTRACT_STRING_ATTRIBUTE("algorithm", string, 1);
4153 err = string2isds_hash_algorithm((xmlChar*) string, &(*hash)->algorithm);
4154 if (err) {
4155 if (err == IE_ENUM) {
4156 char *string_locale = _isds_utf82locale(string);
4157 isds_printf_message(context, _("Unsupported hash algorithm: %s"),
4158 string_locale);
4159 free(string_locale);
4161 goto leave;
4163 zfree(string);
4165 /* Get hash value */
4166 EXTRACT_STRING(".", string);
4167 if (!string) {
4168 isds_printf_message(context,
4169 _("sisds:dmHash element is missing hash value"));
4170 err = IE_ISDS;
4171 goto leave;
4173 (*hash)->length = _isds_b64decode(string, &((*hash)->value));
4174 if ((*hash)->length == (size_t) -1) {
4175 isds_printf_message(context,
4176 _("Error while Base64-decoding hash value"));
4177 err = IE_ERROR;
4178 goto leave;
4181 leave:
4182 if (err) isds_hash_free(hash);
4183 free(string);
4184 xmlXPathFreeObject(result);
4185 xpath_ctx->node = old_ctx_node;
4186 return err;
4190 /* Find and append isds:dmQTimestamp XML tree into envelope.
4191 * Because one service is allowed to miss time-stamp content, and we think
4192 * other could too (flaw in specification), this function is deliberated and
4193 * will not fail (i.e. will return IE_SUCCESS), if time-stamp is missing.
4194 * @context is ISDS context
4195 * @envelope is automatically allocated envelope structure
4196 * @xpath_ctx is XPath context with current node containing isds:dmQTimestamp
4197 * child
4198 * In case of error @envelope will be freed. */
4199 static isds_error find_and_append_DmQTimestamp(struct isds_ctx *context,
4200 struct isds_envelope **envelope, xmlXPathContextPtr xpath_ctx) {
4201 isds_error err = IE_SUCCESS;
4202 xmlXPathObjectPtr result = NULL;
4203 char *string = NULL;
4205 if (!context) return IE_INVALID_CONTEXT;
4206 if (!envelope) return IE_INVAL;
4207 if (!xpath_ctx) {
4208 isds_envelope_free(envelope);
4209 return IE_INVAL;
4212 if (!*envelope) {
4213 *envelope = calloc(1, sizeof(**envelope));
4214 if (!*envelope) {
4215 err = IE_NOMEM;
4216 goto leave;
4218 } else {
4219 zfree((*envelope)->timestamp);
4220 (*envelope)->timestamp_length = 0;
4223 /* Get dmQTimestamp */
4224 EXTRACT_STRING("sisds:dmQTimestamp", string);
4225 if (!string) {
4226 isds_log(ILF_ISDS, ILL_INFO, _("Missing dmQTimestamp element content\n"));
4227 goto leave;
4229 (*envelope)->timestamp_length =
4230 _isds_b64decode(string, &((*envelope)->timestamp));
4231 if ((*envelope)->timestamp_length == (size_t) -1) {
4232 isds_printf_message(context,
4233 _("Error while Base64-decoding time stamp value"));
4234 err = IE_ERROR;
4235 goto leave;
4238 leave:
4239 if (err) isds_envelope_free(envelope);
4240 free(string);
4241 xmlXPathFreeObject(result);
4242 return err;
4246 /* Convert XSD tReturnedMessage XML tree into message structure.
4247 * It does not store serialized XML tree into message->raw.
4248 * It does store (pointer to) parsed XML tree into message->xml if needed.
4249 * @context is ISDS context
4250 * @include_documents Use true if documents must be extracted
4251 * (tReturnedMessage XSD type), use false if documents shall be omitted
4252 * (tReturnedMessageEnvelope).
4253 * @message is automatically reallocated message structure
4254 * @xpath_ctx is XPath context with current node as tReturnedMessage element
4255 * type
4256 * In case of error @message will be freed. */
4257 static isds_error extract_TReturnedMessage(struct isds_ctx *context,
4258 const _Bool include_documents, struct isds_message **message,
4259 xmlXPathContextPtr xpath_ctx) {
4260 isds_error err = IE_SUCCESS;
4261 xmlNodePtr message_node;
4263 if (!context) return IE_INVALID_CONTEXT;
4264 if (!message) return IE_INVAL;
4265 isds_message_free(message);
4266 if (!xpath_ctx) return IE_INVAL;
4269 *message = calloc(1, sizeof(**message));
4270 if (!*message) {
4271 err = IE_NOMEM;
4272 goto leave;
4275 /* Save message XPATH context node */
4276 message_node = xpath_ctx->node;
4279 /* Extract dmDM */
4280 err = move_xpathctx_to_child(context, BAD_CAST "isds:dmDm", xpath_ctx);
4281 if (err == IE_NOEXIST || err == IE_NOTUNIQ) { err = IE_ISDS; goto leave; }
4282 if (err) { err = IE_ERROR; goto leave; }
4283 err = append_GMessageEnvelope(context, &((*message)->envelope), xpath_ctx);
4284 if (err) goto leave;
4286 if (include_documents) {
4287 struct isds_list *item;
4289 /* Extract dmFiles */
4290 err = move_xpathctx_to_child(context, BAD_CAST "isds:dmFiles",
4291 xpath_ctx);
4292 if (err == IE_NOEXIST || err == IE_NOTUNIQ) {
4293 err = IE_ISDS; goto leave;
4295 if (err) { err = IE_ERROR; goto leave; }
4296 err = extract_documents(context, &((*message)->documents), xpath_ctx);
4297 if (err) goto leave;
4299 /* Store xmlDoc of this message if needed */
4300 /* Only if we got a XML document in all the documents. */
4301 for (item = (*message)->documents; item; item = item->next) {
4302 if (item->data && ((struct isds_document *)item->data)->is_xml) {
4303 (*message)->xml = xpath_ctx->doc;
4304 break;
4310 /* Restore context to message */
4311 xpath_ctx->node = message_node;
4313 /* Extract dmHash */
4314 err = find_and_extract_DmHash(context, &(*message)->envelope->hash,
4315 xpath_ctx);
4316 if (err) goto leave;
4318 /* Extract dmQTimestamp, */
4319 err = find_and_append_DmQTimestamp(context, &(*message)->envelope,
4320 xpath_ctx);
4321 if (err) goto leave;
4323 /* Get dmMessageStatus, dmAttachmentSize, dmDeliveryTime,
4324 * dmAcceptanceTime. */
4325 err = append_status_size_times(context, &((*message)->envelope), xpath_ctx);
4326 if (err) goto leave;
4328 /* Get message type */
4329 err = append_message_type(context, &((*message)->envelope), xpath_ctx);
4330 if (err) goto leave;
4332 leave:
4333 if (err) isds_message_free(message);
4334 return err;
4338 /* Extract message event into reallocated isds_event structure
4339 * @context is ISDS context
4340 * @event is automatically reallocated message event structure
4341 * @xpath_ctx is XPath context with current node as isds:dmEvent
4342 * In case of error @event will be freed. */
4343 static isds_error extract_event(struct isds_ctx *context,
4344 struct isds_event **event, xmlXPathContextPtr xpath_ctx) {
4345 isds_error err = IE_SUCCESS;
4346 xmlXPathObjectPtr result = NULL;
4347 xmlNodePtr event_node = xpath_ctx->node;
4348 char *string = NULL;
4350 if (!context) return IE_INVALID_CONTEXT;
4351 if (!event) return IE_INVAL;
4352 isds_event_free(event);
4353 if (!xpath_ctx) return IE_INVAL;
4355 *event = calloc(1, sizeof(**event));
4356 if (!*event) {
4357 err = IE_NOMEM;
4358 goto leave;
4361 /* Extract event data.
4362 * All elements are optional according XSD. That's funny. */
4363 EXTRACT_STRING("sisds:dmEventTime", string);
4364 if (string) {
4365 err = timestring2timeval((xmlChar *) string, &((*event)->time));
4366 if (err) {
4367 char *string_locale = _isds_utf82locale(string);
4368 if (err == IE_DATE) err = IE_ISDS;
4369 isds_printf_message(context,
4370 _("Could not convert dmEventTime as ISO time: %s"),
4371 string_locale);
4372 free(string_locale);
4373 goto leave;
4375 zfree(string);
4378 /* dmEventDescr element has prefix and the rest */
4379 EXTRACT_STRING("sisds:dmEventDescr", string);
4380 if (string) {
4381 err = eventstring2event((xmlChar *) string, *event);
4382 if (err) goto leave;
4383 zfree(string);
4386 leave:
4387 if (err) isds_event_free(event);
4388 free(string);
4389 xmlXPathFreeObject(result);
4390 xpath_ctx->node = event_node;
4391 return err;
4395 /* Convert element of XSD tEventsArray type from XML tree into
4396 * isds_list of isds_event's structure. The list is automatically reallocated.
4397 * @context is ISDS context
4398 * @events is automatically reallocated list of event structures
4399 * @xpath_ctx is XPath context with current node as tEventsArray
4400 * In case of error @events will be freed. */
4401 static isds_error extract_events(struct isds_ctx *context,
4402 struct isds_list **events, xmlXPathContextPtr xpath_ctx) {
4403 isds_error err = IE_SUCCESS;
4404 xmlXPathObjectPtr result = NULL;
4405 xmlNodePtr events_node = xpath_ctx->node;
4406 struct isds_list *event, *prev_event = NULL;
4408 if (!context) return IE_INVALID_CONTEXT;
4409 if (!events) return IE_INVAL;
4410 if (!xpath_ctx) return IE_INVAL;
4412 /* Free old list */
4413 isds_list_free(events);
4415 /* Find events */
4416 result = xmlXPathEvalExpression(BAD_CAST "sisds:dmEvent", xpath_ctx);
4417 if (!result) {
4418 err = IE_XML;
4419 goto leave;
4422 /* No match */
4423 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
4424 isds_printf_message(context,
4425 _("Delivery info does not contain any event"));
4426 err = IE_ISDS;
4427 goto leave;
4431 /* Iterate over events */
4432 for (int i = 0; i < result->nodesetval->nodeNr; i++) {
4434 /* Allocate and append list item */
4435 event = calloc(1, sizeof(*event));
4436 if (!event) {
4437 err = IE_NOMEM;
4438 goto leave;
4440 event->destructor = (void (*)(void **))isds_event_free;
4441 if (i == 0) *events = event;
4442 else prev_event->next = event;
4443 prev_event = event;
4445 /* Extract event */
4446 xpath_ctx->node = result->nodesetval->nodeTab[i];
4447 err = extract_event(context,
4448 (struct isds_event **) &(event->data), xpath_ctx);
4449 if (err) goto leave;
4453 leave:
4454 if (err) isds_list_free(events);
4455 xmlXPathFreeObject(result);
4456 xpath_ctx->node = events_node;
4457 return err;
4461 #if HAVE_LIBCURL
4462 /* Insert Base64 encoded data as element with text child.
4463 * @context is session context
4464 * @parent is XML node to append @element with @data as child
4465 * @ns is XML namespace of @element, use NULL to inherit from @parent
4466 * @element is UTF-8 encoded name of new element
4467 * @data is bit stream to encode into @element
4468 * @length is size of @data in bytes
4469 * @return standard error code and fill long error message if needed */
4470 static isds_error insert_base64_encoded_string(struct isds_ctx *context,
4471 xmlNodePtr parent, const xmlNsPtr ns, const char *element,
4472 const void *data, size_t length) {
4473 isds_error err = IE_SUCCESS;
4474 xmlNodePtr node;
4476 if (!context) return IE_INVALID_CONTEXT;
4477 if (!data && length > 0) return IE_INVAL;
4478 if (!parent || !element) return IE_INVAL;
4480 xmlChar *base64data = NULL;
4481 base64data = (xmlChar *) _isds_b64encode(data, length);
4482 if (!base64data) {
4483 isds_printf_message(context,
4484 ngettext("Not enough memory to encode %zd byte into Base64",
4485 "Not enough memory to encode %zd bytes into Base64",
4486 length),
4487 length);
4488 err = IE_NOMEM;
4489 goto leave;
4491 INSERT_STRING_WITH_NS(parent, ns, element, base64data);
4493 leave:
4494 free(base64data);
4495 return err;
4499 /* Convert isds_document structure into XML tree and append to dmFiles node.
4500 * @context is session context
4501 * @document is ISDS document
4502 * @dm_files is XML element the resulting tree will be appended to as a child.
4503 * @return error code, in case of error context' message is filled. */
4504 static isds_error insert_document(struct isds_ctx *context,
4505 struct isds_document *document, xmlNodePtr dm_files) {
4506 isds_error err = IE_SUCCESS;
4507 xmlNodePtr new_file = NULL, file = NULL, node;
4508 xmlAttrPtr attribute_node;
4510 if (!context) return IE_INVALID_CONTEXT;
4511 if (!document || !dm_files) return IE_INVAL;
4513 /* Allocate new dmFile */
4514 new_file = xmlNewNode(dm_files->ns, BAD_CAST "dmFile");
4515 if (!new_file) {
4516 isds_printf_message(context, _("Could not allocate main dmFile"));
4517 err = IE_ERROR;
4518 goto leave;
4520 /* Append the new dmFile.
4521 * XXX: Main document must go first */
4522 if (document->dmFileMetaType == FILEMETATYPE_MAIN && dm_files->children)
4523 file = xmlAddPrevSibling(dm_files->children, new_file);
4524 else
4525 file = xmlAddChild(dm_files, new_file);
4527 if (!file) {
4528 xmlFreeNode(new_file); new_file = NULL;
4529 isds_printf_message(context, _("Could not add dmFile child to "
4530 "%s element"), dm_files->name);
4531 err = IE_ERROR;
4532 goto leave;
4535 /* @dmMimeType is required */
4536 if (!document->dmMimeType) {
4537 isds_log_message(context,
4538 _("Document is missing mandatory MIME type definition"));
4539 err = IE_INVAL;
4540 goto leave;
4542 INSERT_STRING_ATTRIBUTE(file, "dmMimeType", document->dmMimeType);
4544 const xmlChar *string = isds_FileMetaType2string(document->dmFileMetaType);
4545 if (!string) {
4546 isds_printf_message(context,
4547 _("Document has unknown dmFileMetaType: %ld"),
4548 document->dmFileMetaType);
4549 err = IE_ENUM;
4550 goto leave;
4552 INSERT_STRING_ATTRIBUTE(file, "dmFileMetaType", string);
4554 if (document->dmFileGuid) {
4555 INSERT_STRING_ATTRIBUTE(file, "dmFileGuid", document->dmFileGuid);
4557 if (document->dmUpFileGuid) {
4558 INSERT_STRING_ATTRIBUTE(file, "dmUpFileGuid", document->dmUpFileGuid);
4561 /* @dmFileDescr is required */
4562 if (!document->dmFileDescr) {
4563 isds_log_message(context,
4564 _("Document is missing mandatory description (title)"));
4565 err = IE_INVAL;
4566 goto leave;
4568 INSERT_STRING_ATTRIBUTE(file, "dmFileDescr", document->dmFileDescr);
4570 if (document->dmFormat) {
4571 INSERT_STRING_ATTRIBUTE(file, "dmFormat", document->dmFormat);
4575 /* Insert content (body) of the document. */
4576 if (document->is_xml) {
4577 /* XML document requested */
4579 /* Allocate new dmXMLContent */
4580 xmlNodePtr xmlcontent = xmlNewNode(file->ns, BAD_CAST "dmXMLContent");
4581 if (!xmlcontent) {
4582 isds_printf_message(context,
4583 _("Could not allocate dmXMLContent element"));
4584 err = IE_ERROR;
4585 goto leave;
4587 /* Append it */
4588 node = xmlAddChild(file, xmlcontent);
4589 if (!node) {
4590 xmlFreeNode(xmlcontent); xmlcontent = NULL;
4591 isds_printf_message(context,
4592 _("Could not add dmXMLContent child to %s element"),
4593 file->name);
4594 err = IE_ERROR;
4595 goto leave;
4598 /* Copy non-empty node list */
4599 if (document->xml_node_list) {
4600 xmlNodePtr content = xmlDocCopyNodeList(node->doc,
4601 document->xml_node_list);
4602 if (!content) {
4603 isds_printf_message(context,
4604 _("Not enough memory to copy XML document"));
4605 err = IE_NOMEM;
4606 goto leave;
4609 if (!xmlAddChildList(node, content)) {
4610 xmlFreeNodeList(content);
4611 isds_printf_message(context,
4612 _("Error while adding XML document into dmXMLContent"));
4613 err = IE_XML;
4614 goto leave;
4616 /* XXX: We cannot free the content here because it's part of node's
4617 * document since now. It will be freed with it automatically. */
4619 } else {
4620 /* Binary document requested */
4621 err = insert_base64_encoded_string(context, file, NULL, "dmEncodedContent",
4622 document->data, document->data_length);
4623 if (err) goto leave;
4626 leave:
4627 return err;
4631 /* Append XSD tMStatus XML tree into isds_message_copy structure.
4632 * The copy must be preallocated, the date are just appended into structure.
4633 * @context is ISDS context
4634 * @copy is message copy structure
4635 * @xpath_ctx is XPath context with current node as tMStatus */
4636 static isds_error append_TMStatus(struct isds_ctx *context,
4637 struct isds_message_copy *copy, xmlXPathContextPtr xpath_ctx) {
4638 isds_error err = IE_SUCCESS;
4639 xmlXPathObjectPtr result = NULL;
4640 char *code = NULL, *message = NULL;
4642 if (!context) return IE_INVALID_CONTEXT;
4643 if (!copy || !xpath_ctx) return IE_INVAL;
4645 /* Free old values */
4646 zfree(copy->dmStatus);
4647 zfree(copy->dmID);
4649 /* Get error specific to this copy */
4650 EXTRACT_STRING("isds:dmStatus/isds:dmStatusCode", code);
4651 if (!code) {
4652 isds_log_message(context,
4653 _("Missing isds:dmStatusCode under "
4654 "XSD:tMStatus type element"));
4655 err = IE_ISDS;
4656 goto leave;
4659 if (xmlStrcmp((const xmlChar *)code, BAD_CAST "0000")) {
4660 /* This copy failed */
4661 copy->error = IE_ISDS;
4662 EXTRACT_STRING("isds:dmStatus/isds:dmStatusMessage", message);
4663 if (message) {
4664 copy->dmStatus = _isds_astrcat3(code, ": ", message);
4665 if (!copy->dmStatus) {
4666 copy->dmStatus = code;
4667 code = NULL;
4669 } else {
4670 copy->dmStatus = code;
4671 code = NULL;
4673 } else {
4674 /* This copy succeeded. In this case only, message ID is valid */
4675 copy->error = IE_SUCCESS;
4677 EXTRACT_STRING("isds:dmID", copy->dmID);
4678 if (!copy->dmID) {
4679 isds_log(ILF_ISDS, ILL_ERR, _("Server accepted sent message, "
4680 "but did not returned assigned message ID\n"));
4681 err = IE_ISDS;
4685 leave:
4686 free(code);
4687 free(message);
4688 xmlXPathFreeObject(result);
4689 return err;
4693 /* Insert struct isds_approval data (box approval) into XML tree
4694 * @context is session context
4695 * @approval is libisds structure with approval description. NULL is
4696 * acceptable.
4697 * @parent is XML element to append @approval to */
4698 static isds_error insert_GExtApproval(struct isds_ctx *context,
4699 const struct isds_approval *approval, xmlNodePtr parent) {
4701 isds_error err = IE_SUCCESS;
4702 xmlNodePtr node;
4704 if (!context) return IE_INVALID_CONTEXT;
4705 if (!parent) return IE_INVAL;
4707 if (!approval) return IE_SUCCESS;
4709 /* Build XSD:gExtApproval */
4710 INSERT_SCALAR_BOOLEAN(parent, "dbApproved", approval->approved);
4711 INSERT_STRING(parent, "dbExternRefNumber", approval->refference);
4713 leave:
4714 return err;
4718 /* Build ISDS request of XSD tDummyInput type, sent it and check for error
4719 * code
4720 * @context is session context
4721 * @service_name is name of SERVICE_DB_ACCESS
4722 * @response is server SOAP body response as XML document
4723 * @raw_response is automatically reallocated bit stream with response body. Use
4724 * NULL if you don't care
4725 * @raw_response_length is size of @raw_response in bytes
4726 * @code is ISDS status code
4727 * @status_message is ISDS status message
4728 * @return error coded from lower layer, context message will be set up
4729 * appropriately. */
4730 static isds_error build_send_check_dbdummy_request(struct isds_ctx *context,
4731 const xmlChar *service_name,
4732 xmlDocPtr *response, void **raw_response, size_t *raw_response_length,
4733 xmlChar **code, xmlChar **status_message) {
4735 isds_error err = IE_SUCCESS;
4736 char *service_name_locale = NULL;
4737 xmlNodePtr request = NULL, node;
4738 xmlNsPtr isds_ns = NULL;
4740 if (!context) return IE_INVALID_CONTEXT;
4741 if (!service_name) return IE_INVAL;
4742 if (!response || !code || !status_message) return IE_INVAL;
4743 if (!raw_response_length && raw_response) return IE_INVAL;
4745 /* Free output argument */
4746 xmlFreeDoc(*response); *response = NULL;
4747 if (raw_response) zfree(*raw_response);
4748 free(*code);
4749 free(*status_message);
4752 /* Check if connection is established
4753 * TODO: This check should be done downstairs. */
4754 if (!context->curl) return IE_CONNECTION_CLOSED;
4756 service_name_locale = _isds_utf82locale((char*)service_name);
4757 if (!service_name_locale) {
4758 err = IE_NOMEM;
4759 goto leave;
4762 /* Build request */
4763 request = xmlNewNode(NULL, service_name);
4764 if (!request) {
4765 isds_printf_message(context,
4766 _("Could not build %s request"), service_name_locale);
4767 err = IE_ERROR;
4768 goto leave;
4770 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
4771 if(!isds_ns) {
4772 isds_log_message(context, _("Could not create ISDS name space"));
4773 err = IE_ERROR;
4774 goto leave;
4776 xmlSetNs(request, isds_ns);
4779 /* Add XSD:tDummyInput child */
4780 INSERT_STRING(request, "dbDummy", NULL);
4783 isds_log(ILF_ISDS, ILL_DEBUG, _("Sending %s request to ISDS\n"),
4784 service_name_locale);
4786 /* Send request */
4787 err = isds(context, SERVICE_DB_ACCESS, request, response,
4788 raw_response, raw_response_length);
4789 xmlFreeNode(request); request = NULL;
4791 if (err) {
4792 isds_log(ILF_ISDS, ILL_DEBUG,
4793 _("Processing ISDS response on %s request failed\n"),
4794 service_name_locale);
4795 goto leave;
4798 /* Check for response status */
4799 err = isds_response_status(context, SERVICE_DB_ACCESS, *response,
4800 code, status_message, NULL);
4801 if (err) {
4802 isds_log(ILF_ISDS, ILL_DEBUG,
4803 _("ISDS response on %s request is missing status\n"),
4804 service_name_locale);
4805 goto leave;
4808 /* Request processed, but nothing found */
4809 if (xmlStrcmp(*code, BAD_CAST "0000")) {
4810 char *code_locale = _isds_utf82locale((char*) *code);
4811 char *status_message_locale =
4812 _isds_utf82locale((char*) *status_message);
4813 isds_log(ILF_ISDS, ILL_DEBUG,
4814 _("Server refused %s request (code=%s, message=%s)\n"),
4815 service_name_locale, code_locale, status_message_locale);
4816 isds_log_message(context, status_message_locale);
4817 free(code_locale);
4818 free(status_message_locale);
4819 err = IE_ISDS;
4820 goto leave;
4823 leave:
4824 free(service_name_locale);
4825 xmlFreeNode(request);
4826 return err;
4828 #endif
4831 /* Get data about logged in user and his box. */
4832 isds_error isds_GetOwnerInfoFromLogin(struct isds_ctx *context,
4833 struct isds_DbOwnerInfo **db_owner_info) {
4834 isds_error err = IE_SUCCESS;
4835 #if HAVE_LIBCURL
4836 xmlDocPtr response = NULL;
4837 xmlChar *code = NULL, *message = NULL;
4838 xmlXPathContextPtr xpath_ctx = NULL;
4839 xmlXPathObjectPtr result = NULL;
4840 char *string = NULL;
4841 #endif
4843 if (!context) return IE_INVALID_CONTEXT;
4844 zfree(context->long_message);
4845 if (!db_owner_info) return IE_INVAL;
4846 isds_DbOwnerInfo_free(db_owner_info);
4848 #if HAVE_LIBCURL
4849 /* Check if connection is established */
4850 if (!context->curl) return IE_CONNECTION_CLOSED;
4853 /* Do request and check for success */
4854 err = build_send_check_dbdummy_request(context,
4855 BAD_CAST "GetOwnerInfoFromLogin",
4856 &response, NULL, NULL, &code, &message);
4857 if (err) goto leave;
4860 /* Extract data */
4861 /* Prepare structure */
4862 *db_owner_info = calloc(1, sizeof(**db_owner_info));
4863 if (!*db_owner_info) {
4864 err = IE_NOMEM;
4865 goto leave;
4867 xpath_ctx = xmlXPathNewContext(response);
4868 if (!xpath_ctx) {
4869 err = IE_ERROR;
4870 goto leave;
4872 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
4873 err = IE_ERROR;
4874 goto leave;
4877 /* Set context node */
4878 result = xmlXPathEvalExpression(BAD_CAST
4879 "/isds:GetOwnerInfoFromLoginResponse/isds:dbOwnerInfo", xpath_ctx);
4880 if (!result) {
4881 err = IE_ERROR;
4882 goto leave;
4884 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
4885 isds_log_message(context, _("Missing dbOwnerInfo element"));
4886 err = IE_ISDS;
4887 goto leave;
4889 if (result->nodesetval->nodeNr > 1) {
4890 isds_log_message(context, _("Multiple dbOwnerInfo element"));
4891 err = IE_ISDS;
4892 goto leave;
4894 xpath_ctx->node = result->nodesetval->nodeTab[0];
4895 xmlXPathFreeObject(result); result = NULL;
4897 /* Extract it */
4898 err = extract_DbOwnerInfo(context, db_owner_info, xpath_ctx);
4901 leave:
4902 if (err) {
4903 isds_DbOwnerInfo_free(db_owner_info);
4906 free(string);
4907 xmlXPathFreeObject(result);
4908 xmlXPathFreeContext(xpath_ctx);
4910 free(code);
4911 free(message);
4912 xmlFreeDoc(response);
4914 if (!err)
4915 isds_log(ILF_ISDS, ILL_DEBUG,
4916 _("GetOwnerInfoFromLogin request processed by server "
4917 "successfully.\n"));
4918 #else /* not HAVE_LIBCURL */
4919 err = IE_NOTSUP;
4920 #endif
4922 return err;
4926 /* Get data about logged in user. */
4927 isds_error isds_GetUserInfoFromLogin(struct isds_ctx *context,
4928 struct isds_DbUserInfo **db_user_info) {
4929 isds_error err = IE_SUCCESS;
4930 #if HAVE_LIBCURL
4931 xmlDocPtr response = NULL;
4932 xmlChar *code = NULL, *message = NULL;
4933 xmlXPathContextPtr xpath_ctx = NULL;
4934 xmlXPathObjectPtr result = NULL;
4935 #endif
4937 if (!context) return IE_INVALID_CONTEXT;
4938 zfree(context->long_message);
4939 if (!db_user_info) return IE_INVAL;
4940 isds_DbUserInfo_free(db_user_info);
4942 #if HAVE_LIBCURL
4943 /* Check if connection is established */
4944 if (!context->curl) return IE_CONNECTION_CLOSED;
4947 /* Do request and check for success */
4948 err = build_send_check_dbdummy_request(context,
4949 BAD_CAST "GetUserInfoFromLogin",
4950 &response, NULL, NULL, &code, &message);
4951 if (err) goto leave;
4954 /* Extract data */
4955 /* Prepare structure */
4956 *db_user_info = calloc(1, sizeof(**db_user_info));
4957 if (!*db_user_info) {
4958 err = IE_NOMEM;
4959 goto leave;
4961 xpath_ctx = xmlXPathNewContext(response);
4962 if (!xpath_ctx) {
4963 err = IE_ERROR;
4964 goto leave;
4966 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
4967 err = IE_ERROR;
4968 goto leave;
4971 /* Set context node */
4972 result = xmlXPathEvalExpression(BAD_CAST
4973 "/isds:GetUserInfoFromLoginResponse/isds:dbUserInfo", xpath_ctx);
4974 if (!result) {
4975 err = IE_ERROR;
4976 goto leave;
4978 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
4979 isds_log_message(context, _("Missing dbUserInfo element"));
4980 err = IE_ISDS;
4981 goto leave;
4983 if (result->nodesetval->nodeNr > 1) {
4984 isds_log_message(context, _("Multiple dbUserInfo element"));
4985 err = IE_ISDS;
4986 goto leave;
4988 xpath_ctx->node = result->nodesetval->nodeTab[0];
4989 xmlXPathFreeObject(result); result = NULL;
4991 /* Extract it */
4992 err = extract_DbUserInfo(context, db_user_info, xpath_ctx);
4994 leave:
4995 if (err) {
4996 isds_DbUserInfo_free(db_user_info);
4999 xmlXPathFreeObject(result);
5000 xmlXPathFreeContext(xpath_ctx);
5002 free(code);
5003 free(message);
5004 xmlFreeDoc(response);
5006 if (!err)
5007 isds_log(ILF_ISDS, ILL_DEBUG,
5008 _("GetUserInfoFromLogin request processed by server "
5009 "successfully.\n"));
5010 #else /* not HAVE_LIBCURL */
5011 err = IE_NOTSUP;
5012 #endif
5014 return err;
5018 /* Get expiration time of current password
5019 * @context is session context
5020 * @expiration is automatically reallocated time when password expires. If
5021 * password expiration is disables, NULL will be returned. In case of error
5022 * it will be nulled too. */
5023 isds_error isds_get_password_expiration(struct isds_ctx *context,
5024 struct timeval **expiration) {
5025 isds_error err = IE_SUCCESS;
5026 #if HAVE_LIBCURL
5027 xmlDocPtr response = NULL;
5028 xmlChar *code = NULL, *message = NULL;
5029 xmlXPathContextPtr xpath_ctx = NULL;
5030 xmlXPathObjectPtr result = NULL;
5031 char *string = NULL;
5032 #endif
5034 if (!context) return IE_INVALID_CONTEXT;
5035 zfree(context->long_message);
5036 if (!expiration) return IE_INVAL;
5037 zfree(*expiration);
5039 #if HAVE_LIBCURL
5040 /* Check if connection is established */
5041 if (!context->curl) return IE_CONNECTION_CLOSED;
5044 /* Do request and check for success */
5045 err = build_send_check_dbdummy_request(context,
5046 BAD_CAST "GetPasswordInfo",
5047 &response, NULL, NULL, &code, &message);
5048 if (err) goto leave;
5051 /* Extract data */
5052 xpath_ctx = xmlXPathNewContext(response);
5053 if (!xpath_ctx) {
5054 err = IE_ERROR;
5055 goto leave;
5057 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
5058 err = IE_ERROR;
5059 goto leave;
5062 /* Set context node */
5063 result = xmlXPathEvalExpression(BAD_CAST
5064 "/isds:GetPasswordInfoResponse", xpath_ctx);
5065 if (!result) {
5066 err = IE_ERROR;
5067 goto leave;
5069 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
5070 isds_log_message(context,
5071 _("Missing GetPasswordInfoResponse element"));
5072 err = IE_ISDS;
5073 goto leave;
5075 if (result->nodesetval->nodeNr > 1) {
5076 isds_log_message(context,
5077 _("Multiple GetPasswordInfoResponse element"));
5078 err = IE_ISDS;
5079 goto leave;
5081 xpath_ctx->node = result->nodesetval->nodeTab[0];
5082 xmlXPathFreeObject(result); result = NULL;
5084 /* Extract expiration date */
5085 EXTRACT_STRING("isds:pswExpDate", string);
5086 if (string) {
5087 /* And convert it if any returned. Otherwise expiration is disabled. */
5088 err = timestring2timeval((xmlChar *) string, expiration);
5089 if (err) {
5090 char *string_locale = _isds_utf82locale(string);
5091 if (err == IE_DATE) err = IE_ISDS;
5092 isds_printf_message(context,
5093 _("Could not convert pswExpDate as ISO time: %s"),
5094 string_locale);
5095 free(string_locale);
5096 goto leave;
5100 leave:
5101 if (err) {
5102 if (*expiration) {
5103 zfree(*expiration);
5107 free(string);
5108 xmlXPathFreeObject(result);
5109 xmlXPathFreeContext(xpath_ctx);
5111 free(code);
5112 free(message);
5113 xmlFreeDoc(response);
5115 if (!err)
5116 isds_log(ILF_ISDS, ILL_DEBUG,
5117 _("GetPasswordInfo request processed by server "
5118 "successfully.\n"));
5119 #else /* not HAVE_LIBCURL */
5120 err = IE_NOTSUP;
5121 #endif
5123 return err;
5127 #if HAVE_LIBCURL
5128 /* Request delivering new TOTP code from ISDS through side channel before
5129 * changing password.
5130 * @context is session context
5131 * @password is current password.
5132 * @otp auxiliary data required, returns fine grade resolution of OTP procedure.
5133 * Please note the @otp argument must have TOTP OTP method. See isds_login()
5134 * function for more details.
5135 * @refnumber is reallocated serial number of request assigned by ISDS. Use
5136 * NULL, if you don't care.
5137 * @return IE_SUCCESS, if new TOTP code has been sent. Or returns appropriate
5138 * error code. */
5139 static isds_error _isds_request_totp_code(struct isds_ctx *context,
5140 const char *password, struct isds_otp *otp, char **refnumber) {
5141 isds_error err = IE_SUCCESS;
5142 char *saved_url = NULL; /* No copy */
5143 #if HAVE_CURL_REAUTHORIZATION_BUG
5144 CURL *saved_curl = NULL; /* No copy */
5145 #endif
5146 xmlNsPtr isds_ns = NULL;
5147 xmlNodePtr request = NULL;
5148 xmlDocPtr response = NULL;
5149 xmlChar *code = NULL, *message = NULL;
5150 const xmlChar *codes[] = {
5151 BAD_CAST "2300",
5152 BAD_CAST "2301",
5153 BAD_CAST "2302"
5155 const char *meanings[] = {
5156 N_("Unexpected error"),
5157 N_("One-time code cannot be re-send faster than once a 30 seconds"),
5158 N_("One-time code could not been sent. Try later again.")
5160 const isds_otp_resolution resolutions[] = {
5161 OTP_RESOLUTION_UNKNOWN,
5162 OTP_RESOLUTION_TO_FAST,
5163 OTP_RESOLUTION_TOTP_NOT_SENT
5166 if (NULL == context) return IE_INVALID_CONTEXT;
5167 zfree(context->long_message);
5168 if (NULL == password) {
5169 isds_log_message(context,
5170 _("Second argument (password) of isds_change_password() "
5171 "is NULL"));
5172 return IE_INVAL;
5175 /* Check if connection is established
5176 * TODO: This check should be done downstairs. */
5177 if (!context->curl) return IE_CONNECTION_CLOSED;
5179 if (!context->otp) {
5180 isds_log_message(context, _("This function requires OTP-authenticated "
5181 "context"));
5182 return IE_INVALID_CONTEXT;
5184 if (NULL == otp) {
5185 isds_log_message(context, _("If one-time password authentication "
5186 "method is in use, requesting new OTP code requires "
5187 "one-time credentials argument either"));
5188 return IE_INVAL;
5190 if (otp->method != OTP_TIME) {
5191 isds_log_message(context, _("Requesting new time-based OTP code from "
5192 "server requires one-time password authentication "
5193 "method"));
5194 return IE_INVAL;
5196 if (otp->otp_code != NULL) {
5197 isds_log_message(context, _("Requesting new time-based OTP code from "
5198 "server requires undefined OTP code member in "
5199 "one-time credentials argument"));
5200 return IE_INVAL;
5204 /* Build request */
5205 request = xmlNewNode(NULL, BAD_CAST "SendSMSCode");
5206 if (!request) {
5207 isds_log_message(context, _("Could not build SendSMSCode request"));
5208 return IE_ERROR;
5210 isds_ns = xmlNewNs(request, BAD_CAST OISDS_NS, NULL);
5211 if(!isds_ns) {
5212 isds_log_message(context, _("Could not create ISDS name space"));
5213 xmlFreeNode(request);
5214 return IE_ERROR;
5216 xmlSetNs(request, isds_ns);
5218 /* Change URL temporarily for sending this request only */
5220 char *new_url = NULL;
5221 if ((err = _isds_build_url_from_context(context,
5222 "%1$.*2$sasws/changePassword", &new_url))) {
5223 goto leave;
5225 saved_url = context->url;
5226 context->url = new_url;
5229 /* Store credentials for sending this request only */
5230 context->otp_credentials = otp;
5231 _isds_discard_credentials(context, 0);
5232 if ((err = _isds_store_credentials(context, context->saved_username,
5233 password, NULL))) {
5234 _isds_discard_credentials(context, 0);
5235 goto leave;
5237 #if HAVE_CURL_REAUTHORIZATION_BUG
5238 saved_curl = context->curl;
5239 context->curl = curl_easy_init();
5240 if (NULL == context->curl) {
5241 err = IE_ERROR;
5242 goto leave;
5244 if (context->timeout) {
5245 err = isds_set_timeout(context, context->timeout);
5246 if (err) goto leave;
5248 #endif
5250 isds_log(ILF_ISDS, ILL_DEBUG, _("Sending SendSMSCode request to ISDS\n"));
5252 /* Sent request */
5253 err = isds(context, SERVICE_ASWS, request, &response, NULL, NULL);
5255 /* Remove temporal credentials */
5256 _isds_discard_credentials(context, 0);
5257 /* Detach pointer to OTP credentials from context */
5258 context->otp_credentials = NULL;
5259 /* Keep context->otp true to keep signaling this is OTP session */
5261 /* Destroy request */
5262 xmlFreeNode(request); request = NULL;
5264 if (err) {
5265 isds_log(ILF_ISDS, ILL_DEBUG,
5266 _("Processing ISDS response on SendSMSCode request failed\n"));
5267 goto leave;
5270 /* Check for response status */
5271 err = isds_response_status(context, SERVICE_ASWS, response,
5272 &code, &message, (xmlChar **)refnumber);
5273 if (err) {
5274 isds_log(ILF_ISDS, ILL_DEBUG,
5275 _("ISDS response on SendSMSCode request is missing "
5276 "status\n"));
5277 goto leave;
5280 /* Check for error */
5281 if (xmlStrcmp(code, BAD_CAST "0000")) {
5282 char *code_locale = _isds_utf82locale((char*)code);
5283 char *message_locale = _isds_utf82locale((char*)message);
5284 int i;
5285 isds_log(ILF_ISDS, ILL_DEBUG,
5286 _("Server refused to send new code on SendSMSCode "
5287 "request (code=%s, message=%s)\n"),
5288 code_locale, message_locale);
5290 /* Check for known error codes */
5291 for (i = 0; i < sizeof(codes)/sizeof(*codes); i++) {
5292 if (!xmlStrcmp(code, codes[i])) break;
5294 if (i < sizeof(codes)/sizeof(*codes)) {
5295 isds_log_message(context, _(meanings[i]));
5296 /* Mimic otp->resolution according to the code, specification does
5297 * prescribe OTP header to be available. */
5298 if (OTP_RESOLUTION_SUCCESS == otp->resolution &&
5299 OTP_RESOLUTION_UNKNOWN != resolutions[i])
5300 otp->resolution = resolutions[i];
5301 } else
5302 isds_log_message(context, message_locale);
5304 free(code_locale);
5305 free(message_locale);
5307 err = IE_ISDS;
5308 goto leave;
5311 /* Otherwise new code sent successfully */
5312 /* Mimic otp->resolution according to the code, specification does
5313 * prescribe OTP header to be available. */
5314 if (OTP_RESOLUTION_SUCCESS == otp->resolution)
5315 otp->resolution = OTP_RESOLUTION_TOTP_SENT;
5317 leave:
5318 if (NULL != saved_url) {
5319 /* Revert URL to original one */
5320 zfree(context->url);
5321 context->url = saved_url;
5323 #if HAVE_CURL_REAUTHORIZATION_BUG
5324 if (NULL != saved_curl) {
5325 if (context->curl != NULL) curl_easy_cleanup(context->curl);
5326 context->curl = saved_curl;
5328 #endif
5330 free(code);
5331 free(message);
5332 xmlFreeDoc(response);
5333 xmlFreeNode(request);
5335 if (!err)
5336 isds_log(ILF_ISDS, ILL_DEBUG,
5337 _("New OTP code has been sent successfully on SendSMSCode "
5338 "request.\n"));
5339 return err;
5343 /* Convert response status code to isds_error code and set long message
5344 * @context is context to save long message to
5345 * @map is mapping from codes to errors and messages. Pass NULL for generic
5346 * handling.
5347 * @code is status code to translate
5348 * @message is non-localized status message to put into long message in case
5349 * of uknown error. It can be NULL if server did not provide any.
5350 * @return desired isds_error or IE_ISDS for unknown code or IE_INVAL for
5351 * invalid invocation. */
5352 static isds_error statuscode2isds_error(struct isds_ctx *context,
5353 const struct code_map_isds_error *map,
5354 const xmlChar *code, const xmlChar *message) {
5355 if (NULL == code) {
5356 isds_log_message(context,
5357 _("NULL status code passed to statuscode2isds_error()"));
5358 return IE_INVAL;
5361 if (NULL != map) {
5362 /* Check for known error codes */
5363 for (int i=0; map->codes[i] != NULL; i++) {
5364 if (!xmlStrcmp(code, map->codes[i])) {
5365 isds_log_message(context, _(map->meanings[i]));
5366 return map->errors[i];
5371 /* Other error */
5372 if (xmlStrcmp(code, BAD_CAST "0000")) {
5373 char *message_locale = _isds_utf82locale((char*)message);
5374 if (NULL == message_locale)
5375 isds_log_message(context, _("ISDS server returned unknown error"));
5376 else
5377 isds_log_message(context, message_locale);
5378 free(message_locale);
5379 return IE_ISDS;
5382 return IE_SUCCESS;
5384 #endif
5387 /* Change user password in ISDS.
5388 * User must supply old password, new password will takes effect after some
5389 * time, current session can continue. Password must fulfill some constraints.
5390 * @context is session context
5391 * @old_password is current password.
5392 * @new_password is requested new password
5393 * @otp auxiliary data required if one-time password authentication is in use,
5394 * defines OTP code (if known) and returns fine grade resolution of OTP
5395 * procedure. Pass NULL, if one-time password authentication is not needed.
5396 * Please note the @otp argument must match OTP method used at log-in time. See
5397 * isds_login() function for more details.
5398 * @refnumber is reallocated serial number of request assigned by ISDS. Use
5399 * NULL, if you don't care.
5400 * @return IE_SUCCESS, if password has been changed. Or returns appropriate
5401 * error code. It can return IE_PARTIAL_SUCCESS if OTP is in use and server is
5402 * awaiting OTP code that has been delivered by side channel to the user. */
5403 isds_error isds_change_password(struct isds_ctx *context,
5404 const char *old_password, const char *new_password,
5405 struct isds_otp *otp, char **refnumber) {
5406 isds_error err = IE_SUCCESS;
5407 #if HAVE_LIBCURL
5408 char *saved_url = NULL; /* No copy */
5409 #if HAVE_CURL_REAUTHORIZATION_BUG
5410 CURL *saved_curl = NULL; /* No copy */
5411 #endif
5412 xmlNsPtr isds_ns = NULL;
5413 xmlNodePtr request = NULL, node;
5414 xmlDocPtr response = NULL;
5415 xmlChar *code = NULL, *message = NULL;
5416 const xmlChar *codes[] = {
5417 BAD_CAST "1066",
5418 BAD_CAST "1067",
5419 BAD_CAST "1079",
5420 BAD_CAST "1080",
5421 BAD_CAST "1081",
5422 BAD_CAST "1082",
5423 BAD_CAST "1083",
5424 BAD_CAST "1090",
5425 BAD_CAST "1091",
5426 BAD_CAST "2300",
5427 BAD_CAST "9204"
5429 const char *meanings[] = {
5430 N_("Password length must be between 8 and 32 characters"),
5431 N_("Password cannot be reused"), /* Server does not distinguish 1067
5432 and 1091 on ChangePasswordOTP */
5433 N_("Password contains forbidden character"),
5434 N_("Password must contain at least one upper-case letter, "
5435 "one lower-case, and one digit"),
5436 N_("Password cannot contain sequence of three identical characters"),
5437 N_("Password cannot contain user identifier"),
5438 N_("Password is too simmple"),
5439 N_("Old password is not valid"),
5440 N_("Password cannot be reused"),
5441 N_("Unexpected error"),
5442 N_("LDAP update error")
5444 #endif
5446 if (!context) return IE_INVALID_CONTEXT;
5447 zfree(context->long_message);
5448 if (NULL != refnumber)
5449 zfree(*refnumber);
5450 if (NULL == old_password) {
5451 isds_log_message(context,
5452 _("Second argument (old password) of isds_change_password() "
5453 "is NULL"));
5454 return IE_INVAL;
5456 if (NULL == otp && NULL == new_password) {
5457 isds_log_message(context,
5458 _("Third argument (new password) of isds_change_password() "
5459 "is NULL"));
5460 return IE_INVAL;
5463 #if HAVE_LIBCURL
5464 /* Check if connection is established
5465 * TODO: This check should be done downstairs. */
5466 if (!context->curl) return IE_CONNECTION_CLOSED;
5468 if (context->otp && NULL == otp) {
5469 isds_log_message(context, _("If one-time password authentication "
5470 "method is in use, changing password requires one-time "
5471 "credentials either"));
5472 return IE_INVAL;
5475 /* Build ChangeISDSPassword request */
5476 request = xmlNewNode(NULL, (NULL == otp) ? BAD_CAST "ChangeISDSPassword" :
5477 BAD_CAST "ChangePasswordOTP");
5478 if (!request) {
5479 isds_log_message(context, (NULL == otp) ?
5480 _("Could not build ChangeISDSPassword request") :
5481 _("Could not build ChangePasswordOTP request"));
5482 return IE_ERROR;
5484 isds_ns = xmlNewNs(request,
5485 (NULL == otp) ? BAD_CAST ISDS_NS : BAD_CAST OISDS_NS,
5486 NULL);
5487 if(!isds_ns) {
5488 isds_log_message(context, _("Could not create ISDS name space"));
5489 xmlFreeNode(request);
5490 return IE_ERROR;
5492 xmlSetNs(request, isds_ns);
5494 INSERT_STRING(request, "dbOldPassword", old_password);
5495 INSERT_STRING(request, "dbNewPassword", new_password);
5497 if (NULL != otp) {
5498 otp->resolution = OTP_RESOLUTION_UNKNOWN;
5499 switch (otp->method) {
5500 case OTP_HMAC:
5501 isds_log(ILF_SEC, ILL_INFO,
5502 _("Selected authentication method: "
5503 "HMAC-based one-time password\n"));
5504 INSERT_STRING(request, "dbOTPType", BAD_CAST "HOTP");
5505 break;
5506 case OTP_TIME:
5507 isds_log(ILF_SEC, ILL_INFO,
5508 _("Selected authentication method: "
5509 "Time-based one-time password\n"));
5510 INSERT_STRING(request, "dbOTPType", BAD_CAST "TOTP");
5511 if (otp->otp_code == NULL) {
5512 isds_log(ILF_SEC, ILL_INFO,
5513 _("OTP code has not been provided by "
5514 "application, requesting server for "
5515 "new one.\n"));
5516 err = _isds_request_totp_code(context, old_password, otp,
5517 refnumber);
5518 if (err == IE_SUCCESS) err = IE_PARTIAL_SUCCESS;
5519 goto leave;
5521 } else {
5522 isds_log(ILF_SEC, ILL_INFO,
5523 _("OTP code has been provided by "
5524 "application, not requesting server "
5525 "for new one.\n"));
5527 break;
5528 default:
5529 isds_log_message(context,
5530 _("Unknown one-time password authentication "
5531 "method requested by application"));
5532 err = IE_ENUM;
5533 goto leave;
5536 /* Change URL temporarily for sending this request only */
5538 char *new_url = NULL;
5539 if ((err = _isds_build_url_from_context(context,
5540 "%1$.*2$sasws/changePassword", &new_url))) {
5541 goto leave;
5543 saved_url = context->url;
5544 context->url = new_url;
5547 /* Store credentials for sending this request only */
5548 context->otp_credentials = otp;
5549 _isds_discard_credentials(context, 0);
5550 if ((err = _isds_store_credentials(context, context->saved_username,
5551 old_password, NULL))) {
5552 _isds_discard_credentials(context, 0);
5553 goto leave;
5555 #if HAVE_CURL_REAUTHORIZATION_BUG
5556 saved_curl = context->curl;
5557 context->curl = curl_easy_init();
5558 if (NULL == context->curl) {
5559 err = IE_ERROR;
5560 goto leave;
5562 if (context->timeout) {
5563 err = isds_set_timeout(context, context->timeout);
5564 if (err) goto leave;
5566 #endif
5569 isds_log(ILF_ISDS, ILL_DEBUG, (NULL == otp) ?
5570 _("Sending ChangeISDSPassword request to ISDS\n") :
5571 _("Sending ChangePasswordOTP request to ISDS\n"));
5573 /* Sent request */
5574 err = isds(context, (NULL == otp) ? SERVICE_DB_ACCESS : SERVICE_ASWS,
5575 request, &response, NULL, NULL);
5577 if (otp) {
5578 /* Remove temporal credentials */
5579 _isds_discard_credentials(context, 0);
5580 /* Detach pointer to OTP credentials from context */
5581 context->otp_credentials = NULL;
5582 /* Keep context->otp true to keep signaling this is OTP session */
5585 /* Destroy request */
5586 xmlFreeNode(request); request = NULL;
5588 if (err) {
5589 isds_log(ILF_ISDS, ILL_DEBUG, (NULL == otp) ?
5590 _("Processing ISDS response on ChangeISDSPassword "
5591 "request failed\n") :
5592 _("Processing ISDS response on ChangePasswordOTP "
5593 "request failed\n"));
5594 goto leave;
5597 /* Check for response status */
5598 err = isds_response_status(context,
5599 (NULL == otp) ? SERVICE_DB_ACCESS : SERVICE_ASWS, response,
5600 &code, &message, (xmlChar **)refnumber);
5601 if (err) {
5602 isds_log(ILF_ISDS, ILL_DEBUG, (NULL == otp) ?
5603 _("ISDS response on ChangeISDSPassword request is missing "
5604 "status\n") :
5605 _("ISDS response on ChangePasswordOTP request is missing "
5606 "status\n"));
5607 goto leave;
5610 /* Check for known error codes */
5611 for (int i=0; i < sizeof(codes)/sizeof(*codes); i++) {
5612 if (!xmlStrcmp(code, codes[i])) {
5613 char *code_locale = _isds_utf82locale((char*)code);
5614 char *message_locale = _isds_utf82locale((char*)message);
5615 isds_log(ILF_ISDS, ILL_DEBUG, (NULL == otp) ?
5616 _("Server refused to change password on ChangeISDSPassword "
5617 "request (code=%s, message=%s)\n") :
5618 _("Server refused to change password on ChangePasswordOTP "
5619 "request (code=%s, message=%s)\n"),
5620 code_locale, message_locale);
5621 free(code_locale);
5622 free(message_locale);
5623 isds_log_message(context, _(meanings[i]));
5624 err = IE_INVAL;
5625 goto leave;
5629 /* Other error */
5630 if (xmlStrcmp(code, BAD_CAST "0000")) {
5631 char *code_locale = _isds_utf82locale((char*)code);
5632 char *message_locale = _isds_utf82locale((char*)message);
5633 isds_log(ILF_ISDS, ILL_DEBUG, (NULL == otp) ?
5634 _("Server refused to change password on ChangeISDSPassword "
5635 "request (code=%s, message=%s)\n") :
5636 _("Server refused to change password on ChangePasswordOTP "
5637 "request (code=%s, message=%s)\n"),
5638 code_locale, message_locale);
5639 isds_log_message(context, message_locale);
5640 free(code_locale);
5641 free(message_locale);
5642 err = IE_ISDS;
5643 goto leave;
5646 /* Otherwise password changed successfully */
5648 leave:
5649 if (NULL != saved_url) {
5650 /* Revert URL to original one */
5651 zfree(context->url);
5652 context->url = saved_url;
5654 #if HAVE_CURL_REAUTHORIZATION_BUG
5655 if (NULL != saved_curl) {
5656 if (context->curl != NULL) curl_easy_cleanup(context->curl);
5657 context->curl = saved_curl;
5659 #endif
5661 free(code);
5662 free(message);
5663 xmlFreeDoc(response);
5664 xmlFreeNode(request);
5666 if (!err)
5667 isds_log(ILF_ISDS, ILL_DEBUG, (NULL == otp) ?
5668 _("Password changed successfully on ChangeISDSPassword "
5669 "request.\n") :
5670 _("Password changed successfully on ChangePasswordOTP "
5671 "request.\n"));
5672 #else /* not HAVE_LIBCURL */
5673 err = IE_NOTSUP;
5674 #endif
5676 return err;
5680 #if HAVE_LIBCURL
5681 /* Generic middle part with request sending and response check.
5682 * It sends prepared request and checks for error code.
5683 * @context is ISDS session context.
5684 * @service is ISDS service handler
5685 * @service_name is name in scope of given @service
5686 * @request is XML tree with request. Will be freed to save memory.
5687 * @response is XML document outputting ISDS response.
5688 * @refnumber is reallocated serial number of request assigned by ISDS. Use
5689 * @map is mapping from status code to library error. Pass NULL if no special
5690 * handling is requested.
5691 * NULL, if you don't care. */
5692 static isds_error send_destroy_request_check_response(
5693 struct isds_ctx *context,
5694 const isds_service service, const xmlChar *service_name,
5695 xmlNodePtr *request, xmlDocPtr *response, xmlChar **refnumber,
5696 const struct code_map_isds_error *map) {
5697 isds_error err = IE_SUCCESS;
5698 char *service_name_locale = NULL;
5699 xmlChar *code = NULL, *message = NULL;
5702 if (!context) return IE_INVALID_CONTEXT;
5703 if (!service_name || *service_name == '\0' || !request || !*request ||
5704 !response)
5705 return IE_INVAL;
5707 /* Check if connection is established
5708 * TODO: This check should be done downstairs. */
5709 if (!context->curl) return IE_CONNECTION_CLOSED;
5711 service_name_locale = _isds_utf82locale((char*) service_name);
5712 if (!service_name_locale) {
5713 err = IE_NOMEM;
5714 goto leave;
5717 isds_log(ILF_ISDS, ILL_DEBUG, _("Sending %s request to ISDS\n"),
5718 service_name_locale);
5720 /* Send request */
5721 err = isds(context, service, *request, response, NULL, NULL);
5722 xmlFreeNode(*request); *request = NULL;
5724 if (err) {
5725 isds_log(ILF_ISDS, ILL_DEBUG,
5726 _("Processing ISDS response on %s request failed\n"),
5727 service_name_locale);
5728 goto leave;
5731 /* Check for response status */
5732 err = isds_response_status(context, service, *response,
5733 &code, &message, refnumber);
5734 if (err) {
5735 isds_log(ILF_ISDS, ILL_DEBUG,
5736 _("ISDS response on %s request is missing status\n"),
5737 service_name_locale);
5738 goto leave;
5741 err = statuscode2isds_error(context, map, code, message);
5743 /* Request processed, but server failed */
5744 if (xmlStrcmp(code, BAD_CAST "0000")) {
5745 char *code_locale = _isds_utf82locale((char*) code);
5746 char *message_locale = _isds_utf82locale((char*) message);
5747 isds_log(ILF_ISDS, ILL_DEBUG,
5748 _("Server refused %s request (code=%s, message=%s)\n"),
5749 service_name_locale, code_locale, message_locale);
5750 free(code_locale);
5751 free(message_locale);
5752 goto leave;
5756 leave:
5757 free(code);
5758 free(message);
5759 if (err && *response) {
5760 xmlFreeDoc(*response);
5761 *response = NULL;
5763 if (*request) {
5764 xmlFreeNode(*request);
5765 *request = NULL;
5767 free(service_name_locale);
5769 return err;
5773 /* Generic bottom half with request sending.
5774 * It sends prepared request, checks for error code, destroys response and
5775 * request and log success or failure.
5776 * @context is ISDS session context.
5777 * @service is ISDS service handler
5778 * @service_name is name in scope of given @service
5779 * @request is XML tree with request. Will be freed to save memory.
5780 * @refnumber is reallocated serial number of request assigned by ISDS. Use
5781 * NULL, if you don't care. */
5782 static isds_error send_request_check_drop_response(
5783 struct isds_ctx *context,
5784 const isds_service service, const xmlChar *service_name,
5785 xmlNodePtr *request, xmlChar **refnumber) {
5786 isds_error err = IE_SUCCESS;
5787 xmlDocPtr response = NULL;
5790 if (!context) return IE_INVALID_CONTEXT;
5791 if (!service_name || *service_name == '\0' || !request || !*request)
5792 return IE_INVAL;
5794 /* Send request and check response*/
5795 err = send_destroy_request_check_response(context,
5796 service, service_name, request, &response, refnumber, NULL);
5798 xmlFreeDoc(response);
5800 if (*request) {
5801 xmlFreeNode(*request);
5802 *request = NULL;
5805 if (!err) {
5806 char *service_name_locale = _isds_utf82locale((char *) service_name);
5807 isds_log(ILF_ISDS, ILL_DEBUG,
5808 _("%s request processed by server successfully.\n"),
5809 service_name_locale);
5810 free(service_name_locale);
5813 return err;
5817 /* Insert isds_credentials_delivery structure into XML request if not NULL
5818 * @context is session context
5819 * @credentials_delivery is NULL if to omit, non-NULL to signal on-line
5820 * credentials delivery. The email field is passed.
5821 * @parent is XML element where to insert */
5822 static isds_error insert_credentials_delivery(struct isds_ctx *context,
5823 const struct isds_credentials_delivery *credentials_delivery,
5824 xmlNodePtr parent) {
5825 isds_error err = IE_SUCCESS;
5826 xmlNodePtr node;
5828 if (!context) return IE_INVALID_CONTEXT;
5829 if (!parent) return IE_INVAL;
5831 if (credentials_delivery) {
5832 /* Following elements are valid only for services:
5833 * NewAccessData, AddDataBoxUser, CreateDataBox */
5834 INSERT_SCALAR_BOOLEAN(parent, "dbVirtual", 1);
5835 INSERT_STRING(parent, "email", credentials_delivery->email);
5838 leave:
5839 return err;
5843 /* Extract credentials delivery from ISDS response.
5844 * @context is session context
5845 * @credentials_delivery is pointer to valid structure to fill in returned
5846 * user's password (and new log-in name). If NULL, do not extract the data.
5847 * @response is pointer to XML document with ISDS response
5848 * @request_name is UTF-8 encoded name of ISDS service the @response it to.
5849 * @return IE_SUCCESS even if new user name has not been found because it's not
5850 * clear whether it's returned always. */
5851 static isds_error extract_credentials_delivery(struct isds_ctx *context,
5852 struct isds_credentials_delivery *credentials_delivery,
5853 xmlDocPtr response, const char *request_name) {
5854 isds_error err = IE_SUCCESS;
5855 xmlXPathContextPtr xpath_ctx = NULL;
5856 xmlXPathObjectPtr result = NULL;
5857 char *xpath_query = NULL;
5859 if (!context) return IE_INVALID_CONTEXT;
5860 if (credentials_delivery) {
5861 zfree(credentials_delivery->token);
5862 zfree(credentials_delivery->new_user_name);
5864 if (!response || !request_name || !*request_name) return IE_INVAL;
5867 /* Extract optional token */
5868 if (credentials_delivery) {
5869 xpath_ctx = xmlXPathNewContext(response);
5870 if (!xpath_ctx) {
5871 err = IE_ERROR;
5872 goto leave;
5874 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
5875 err = IE_ERROR;
5876 goto leave;
5879 /* Verify root element */
5880 if (-1 == isds_asprintf(&xpath_query, "/isds:%sResponse",
5881 request_name)) {
5882 err = IE_NOMEM;
5883 goto leave;
5885 result = xmlXPathEvalExpression(BAD_CAST xpath_query, xpath_ctx);
5886 if (!result) {
5887 err = IE_ERROR;
5888 goto leave;
5890 if (!xmlXPathNodeSetIsEmpty(result->nodesetval)) {
5891 char *request_name_locale = _isds_utf82locale(request_name);
5892 isds_log(ILF_ISDS, ILL_WARNING,
5893 _("Wrong element in ISDS response for %s request "
5894 "while extracting credentials delivery details\n"),
5895 request_name_locale);
5896 free(request_name_locale);
5897 err = IE_ERROR;
5898 goto leave;
5900 xpath_ctx->node = result->nodesetval->nodeTab[0];
5903 /* XXX: isds:dbUserID is provided only on NewAccessData. Leave it
5904 * optional. */
5905 EXTRACT_STRING("isds:dbUserID", credentials_delivery->new_user_name);
5907 EXTRACT_STRING("isds:dbAccessDataId", credentials_delivery->token);
5908 if (!credentials_delivery->token) {
5909 char *request_name_locale = _isds_utf82locale(request_name);
5910 isds_log(ILF_ISDS, ILL_ERR,
5911 _("ISDS did not return token on %s request "
5912 "even if requested\n"), request_name_locale);
5913 free(request_name_locale);
5914 err = IE_ERROR;
5918 leave:
5919 free(xpath_query);
5920 xmlXPathFreeObject(result);
5921 xmlXPathFreeContext(xpath_ctx);
5923 return err;
5927 /* Build XSD:tCreateDBInput request type for box creating.
5928 * @context is session context
5929 * @request outputs built XML tree
5930 * @service_name is request name of SERVICE_DB_MANIPULATION service
5931 * @box is box description to create including single primary user (in case of
5932 * FO box type)
5933 * @users is list of struct isds_DbUserInfo (primary users in case of non-FO
5934 * box, or contact address of PFO box owner)
5935 * @former_names is optional former name of box owner. Pass NULL if otherwise.
5936 * @upper_box_id is optional ID of supper box if currently created box is
5937 * subordinated.
5938 * @ceo_label is optional title of OVM box owner (e.g. mayor); NULL, if you
5939 * don't care.
5940 * @credentials_delivery is valid pointer if ISDS should return token that box
5941 * owner can use to obtain his new credentials in on-line way. Then valid email
5942 * member value should be supplied.
5943 * @approval is optional external approval of box manipulation */
5944 static isds_error build_CreateDBInput_request(struct isds_ctx *context,
5945 xmlNodePtr *request, const xmlChar *service_name,
5946 const struct isds_DbOwnerInfo *box, const struct isds_list *users,
5947 const xmlChar *former_names, const xmlChar *upper_box_id,
5948 const xmlChar *ceo_label,
5949 const struct isds_credentials_delivery *credentials_delivery,
5950 const struct isds_approval *approval) {
5951 isds_error err = IE_SUCCESS;
5952 xmlNsPtr isds_ns = NULL;
5953 xmlNodePtr node, dbPrimaryUsers;
5954 xmlChar *string = NULL;
5955 const struct isds_list *item;
5958 if (!context) return IE_INVALID_CONTEXT;
5959 if (!request || !service_name || service_name[0] == '\0' || !box)
5960 return IE_INVAL;
5963 /* Build CreateDataBox-similar request */
5964 *request = xmlNewNode(NULL, service_name);
5965 if (!*request) {
5966 char *service_name_locale = _isds_utf82locale((char*) service_name);
5967 isds_printf_message(context, _("Could build %s request"),
5968 service_name_locale);
5969 free(service_name_locale);
5970 return IE_ERROR;
5972 if (context->type == CTX_TYPE_TESTING_REQUEST_COLLECTOR) {
5973 isds_ns = xmlNewNs(*request, BAD_CAST ISDS1_NS, NULL);
5974 if (!isds_ns) {
5975 isds_log_message(context, _("Could not create ISDS1 name space"));
5976 xmlFreeNode(*request);
5977 return IE_ERROR;
5979 } else {
5980 isds_ns = xmlNewNs(*request, BAD_CAST ISDS_NS, NULL);
5981 if (!isds_ns) {
5982 isds_log_message(context, _("Could not create ISDS name space"));
5983 xmlFreeNode(*request);
5984 return IE_ERROR;
5987 xmlSetNs(*request, isds_ns);
5989 INSERT_ELEMENT(node, *request, "dbOwnerInfo");
5990 err = insert_DbOwnerInfo(context, box, node);
5991 if (err) goto leave;
5993 /* Insert users */
5994 /* XXX: There is bug in XSD: XSD says at least one dbUserInfo must exist,
5995 * verbose documentation allows none dbUserInfo */
5996 INSERT_ELEMENT(dbPrimaryUsers, *request, "dbPrimaryUsers");
5997 for (item = users; item; item = item->next) {
5998 if (item->data) {
5999 INSERT_ELEMENT(node, dbPrimaryUsers, "dbUserInfo");
6000 err = insert_DbUserInfo(context,
6001 (struct isds_DbUserInfo *) item->data, node);
6002 if (err) goto leave;
6006 INSERT_STRING(*request, "dbFormerNames", former_names);
6007 INSERT_STRING(*request, "dbUpperDBId", upper_box_id);
6008 INSERT_STRING(*request, "dbCEOLabel", ceo_label);
6010 err = insert_credentials_delivery(context, credentials_delivery, *request);
6011 if (err) goto leave;
6013 err = insert_GExtApproval(context, approval, *request);
6014 if (err) goto leave;
6016 leave:
6017 if (err) {
6018 xmlFreeNode(*request);
6019 *request = NULL;
6021 free(string);
6022 return err;
6024 #endif /* HAVE_LIBCURL */
6027 /* Create new box.
6028 * @context is session context
6029 * @box is box description to create including single primary user (in case of
6030 * FO box type). It outputs box ID assigned by ISDS in dbID element.
6031 * @users is list of struct isds_DbUserInfo (primary users in case of non-FO
6032 * box, or contact address of PFO box owner)
6033 * @former_names is optional former name of box owner. Pass NULL if you don't care.
6034 * @upper_box_id is optional ID of supper box if currently created box is
6035 * subordinated.
6036 * @ceo_label is optional title of OVM box owner (e.g. mayor)
6037 * @credentials_delivery is NULL if new password should be delivered off-line
6038 * to box owner. It is valid pointer if owner should obtain new password on-line
6039 * on dedicated web server. Then input @credentials_delivery.email value is
6040 * his e-mail address he must provide to dedicated web server together
6041 * with output reallocated @credentials_delivery.token member. Output
6042 * member @credentials_delivery.new_user_name is unused up on this call.
6043 * @approval is optional external approval of box manipulation
6044 * @refnumber is reallocated serial number of request assigned by ISDS. Use
6045 * NULL, if you don't care.*/
6046 isds_error isds_add_box(struct isds_ctx *context,
6047 struct isds_DbOwnerInfo *box, const struct isds_list *users,
6048 const char *former_names, const char *upper_box_id,
6049 const char *ceo_label,
6050 struct isds_credentials_delivery *credentials_delivery,
6051 const struct isds_approval *approval, char **refnumber) {
6052 isds_error err = IE_SUCCESS;
6053 #if HAVE_LIBCURL
6054 xmlNodePtr request = NULL;
6055 xmlDocPtr response = NULL;
6056 xmlXPathContextPtr xpath_ctx = NULL;
6057 xmlXPathObjectPtr result = NULL;
6058 #endif
6061 if (!context) return IE_INVALID_CONTEXT;
6062 zfree(context->long_message);
6063 if (credentials_delivery) {
6064 zfree(credentials_delivery->token);
6065 zfree(credentials_delivery->new_user_name);
6067 if (!box) return IE_INVAL;
6069 #if HAVE_LIBCURL
6070 /* Scratch box ID */
6071 zfree(box->dbID);
6073 /* Build CreateDataBox request */
6074 err = build_CreateDBInput_request(context,
6075 &request, BAD_CAST "CreateDataBox",
6076 box, users, (xmlChar *) former_names, (xmlChar *) upper_box_id,
6077 (xmlChar *) ceo_label, credentials_delivery, approval);
6078 if (err) goto leave;
6080 /* Send it to server and process response */
6081 err = send_destroy_request_check_response(context,
6082 SERVICE_DB_MANIPULATION, BAD_CAST "CreateDataBox", &request,
6083 &response, (xmlChar **) refnumber, NULL);
6085 /* Extract box ID */
6086 xpath_ctx = xmlXPathNewContext(response);
6087 if (!xpath_ctx) {
6088 err = IE_ERROR;
6089 goto leave;
6091 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
6092 err = IE_ERROR;
6093 goto leave;
6095 EXTRACT_STRING("/isds:CreateDataBoxResponse/isds:dbID", box->dbID);
6097 /* Extract optional token */
6098 err = extract_credentials_delivery(context, credentials_delivery, response,
6099 "CreateDataBox");
6101 leave:
6102 xmlXPathFreeObject(result);
6103 xmlXPathFreeContext(xpath_ctx);
6104 xmlFreeDoc(response);
6105 xmlFreeNode(request);
6107 if (!err) {
6108 isds_log(ILF_ISDS, ILL_DEBUG,
6109 _("CreateDataBox request processed by server successfully.\n"));
6111 #else /* not HAVE_LIBCURL */
6112 err = IE_NOTSUP;
6113 #endif
6115 return err;
6119 /* Notify ISDS about new PFO entity.
6120 * This function has no real effect.
6121 * @context is session context
6122 * @box is PFO description including single primary user.
6123 * @users is list of struct isds_DbUserInfo (contact address of PFO box owner)
6124 * @former_names is optional undocumented string. Pass NULL if you don't care.
6125 * @upper_box_id is optional ID of supper box if currently created box is
6126 * subordinated.
6127 * @ceo_label is optional title of OVM box owner (e.g. mayor)
6128 * @approval is optional external approval of box manipulation
6129 * @refnumber is reallocated serial number of request assigned by ISDS. Use
6130 * NULL, if you don't care.*/
6131 isds_error isds_add_pfoinfo(struct isds_ctx *context,
6132 const struct isds_DbOwnerInfo *box, const struct isds_list *users,
6133 const char *former_names, const char *upper_box_id,
6134 const char *ceo_label, const struct isds_approval *approval,
6135 char **refnumber) {
6136 isds_error err = IE_SUCCESS;
6137 #if HAVE_LIBCURL
6138 xmlNodePtr request = NULL;
6139 #endif
6141 if (!context) return IE_INVALID_CONTEXT;
6142 zfree(context->long_message);
6143 if (!box) return IE_INVAL;
6145 #if HAVE_LIBCURL
6146 /* Build CreateDataBoxPFOInfo request */
6147 err = build_CreateDBInput_request(context,
6148 &request, BAD_CAST "CreateDataBoxPFOInfo",
6149 box, users, (xmlChar *) former_names, (xmlChar *) upper_box_id,
6150 (xmlChar *) ceo_label, NULL, approval);
6151 if (err) goto leave;
6153 /* Send it to server and process response */
6154 err = send_request_check_drop_response(context,
6155 SERVICE_DB_MANIPULATION, BAD_CAST "CreateDataBox", &request,
6156 (xmlChar **) refnumber);
6157 /* XXX: XML Schema names output dbID element but textual documentation
6158 * states no box identifier is returned. */
6159 leave:
6160 xmlFreeNode(request);
6161 #else /* not HAVE_LIBCURL */
6162 err = IE_NOTSUP;
6163 #endif
6164 return err;
6168 /* Common implementation for removing given box.
6169 * @context is session context
6170 * @service_name is UTF-8 encoded name fo ISDS service
6171 * @box is box description to delete
6172 * @since is date of box owner cancellation. Only tm_year, tm_mon and tm_mday
6173 * carry sane value. If NULL, do not inject this information into request.
6174 * @approval is optional external approval of box manipulation
6175 * @refnumber is reallocated serial number of request assigned by ISDS. Use
6176 * NULL, if you don't care.*/
6177 isds_error _isds_delete_box_common(struct isds_ctx *context,
6178 const xmlChar *service_name,
6179 const struct isds_DbOwnerInfo *box, const struct tm *since,
6180 const struct isds_approval *approval, char **refnumber) {
6181 isds_error err = IE_SUCCESS;
6182 #if HAVE_LIBCURL
6183 xmlNsPtr isds_ns = NULL;
6184 xmlNodePtr request = NULL;
6185 xmlNodePtr node;
6186 xmlChar *string = NULL;
6187 #endif
6190 if (!context) return IE_INVALID_CONTEXT;
6191 zfree(context->long_message);
6192 if (!service_name || !*service_name || !box) return IE_INVAL;
6195 #if HAVE_LIBCURL
6196 /* Build DeleteDataBox(Promptly) request */
6197 request = xmlNewNode(NULL, service_name);
6198 if (!request) {
6199 char *service_name_locale = _isds_utf82locale((char*)service_name);
6200 isds_printf_message(context,
6201 _("Could build %s request"), service_name_locale);
6202 free(service_name_locale);
6203 return IE_ERROR;
6205 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
6206 if(!isds_ns) {
6207 isds_log_message(context, _("Could not create ISDS name space"));
6208 xmlFreeNode(request);
6209 return IE_ERROR;
6211 xmlSetNs(request, isds_ns);
6213 INSERT_ELEMENT(node, request, "dbOwnerInfo");
6214 err = insert_DbOwnerInfo(context, box, node);
6215 if (err) goto leave;
6217 if (since) {
6218 err = tm2datestring(since, &string);
6219 if (err) {
6220 isds_log_message(context,
6221 _("Could not convert `since' argument to ISO date string"));
6222 goto leave;
6224 INSERT_STRING(request, "dbOwnerTerminationDate", string);
6225 zfree(string);
6228 err = insert_GExtApproval(context, approval, request);
6229 if (err) goto leave;
6232 /* Send it to server and process response */
6233 err = send_request_check_drop_response(context, SERVICE_DB_MANIPULATION,
6234 service_name, &request, (xmlChar **) refnumber);
6236 leave:
6237 xmlFreeNode(request);
6238 free(string);
6239 #else /* not HAVE_LIBCURL */
6240 err = IE_NOTSUP;
6241 #endif
6242 return err;
6246 /* Remove given box permanently.
6247 * @context is session context
6248 * @box is box description to delete
6249 * @since is date of box owner cancellation. Only tm_year, tm_mon and tm_mday
6250 * carry sane value.
6251 * @approval is optional external approval of box manipulation
6252 * @refnumber is reallocated serial number of request assigned by ISDS. Use
6253 * NULL, if you don't care.*/
6254 isds_error isds_delete_box(struct isds_ctx *context,
6255 const struct isds_DbOwnerInfo *box, const struct tm *since,
6256 const struct isds_approval *approval, char **refnumber) {
6257 if (!context) return IE_INVALID_CONTEXT;
6258 zfree(context->long_message);
6259 if (!box || !since) return IE_INVAL;
6261 return _isds_delete_box_common(context, BAD_CAST "DeleteDataBox",
6262 box, since, approval, refnumber);
6266 /* Undocumented function.
6267 * @context is session context
6268 * @box is box description to delete
6269 * @approval is optional external approval of box manipulation
6270 * @refnumber is reallocated serial number of request assigned by ISDS. Use
6271 * NULL, if you don't care.*/
6272 isds_error isds_delete_box_promptly(struct isds_ctx *context,
6273 const struct isds_DbOwnerInfo *box,
6274 const struct isds_approval *approval, char **refnumber) {
6275 if (!context) return IE_INVALID_CONTEXT;
6276 zfree(context->long_message);
6277 if (!box) return IE_INVAL;
6279 return _isds_delete_box_common(context, BAD_CAST "DeleteDataBoxPromptly",
6280 box, NULL, approval, refnumber);
6284 /* Update data about given box.
6285 * @context is session context
6286 * @old_box current box description
6287 * @new_box are updated data about @old_box
6288 * @approval is optional external approval of box manipulation
6289 * @refnumber is reallocated serial number of request assigned by ISDS. Use
6290 * NULL, if you don't care.*/
6291 isds_error isds_UpdateDataBoxDescr(struct isds_ctx *context,
6292 const struct isds_DbOwnerInfo *old_box,
6293 const struct isds_DbOwnerInfo *new_box,
6294 const struct isds_approval *approval, char **refnumber) {
6295 isds_error err = IE_SUCCESS;
6296 #if HAVE_LIBCURL
6297 xmlNsPtr isds_ns = NULL;
6298 xmlNodePtr request = NULL;
6299 xmlNodePtr node;
6300 #endif
6303 if (!context) return IE_INVALID_CONTEXT;
6304 zfree(context->long_message);
6305 if (!old_box || !new_box) return IE_INVAL;
6308 #if HAVE_LIBCURL
6309 /* Build UpdateDataBoxDescr request */
6310 request = xmlNewNode(NULL, BAD_CAST "UpdateDataBoxDescr");
6311 if (!request) {
6312 isds_log_message(context,
6313 _("Could build UpdateDataBoxDescr request"));
6314 return IE_ERROR;
6316 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
6317 if(!isds_ns) {
6318 isds_log_message(context, _("Could not create ISDS name space"));
6319 xmlFreeNode(request);
6320 return IE_ERROR;
6322 xmlSetNs(request, isds_ns);
6324 INSERT_ELEMENT(node, request, "dbOldOwnerInfo");
6325 err = insert_DbOwnerInfo(context, old_box, node);
6326 if (err) goto leave;
6328 INSERT_ELEMENT(node, request, "dbNewOwnerInfo");
6329 err = insert_DbOwnerInfo(context, new_box, node);
6330 if (err) goto leave;
6332 err = insert_GExtApproval(context, approval, request);
6333 if (err) goto leave;
6336 /* Send it to server and process response */
6337 err = send_request_check_drop_response(context, SERVICE_DB_MANIPULATION,
6338 BAD_CAST "UpdateDataBoxDescr", &request, (xmlChar **) refnumber);
6340 leave:
6341 xmlFreeNode(request);
6342 #else /* not HAVE_LIBCURL */
6343 err = IE_NOTSUP;
6344 #endif
6346 return err;
6350 #if HAVE_LIBCURL
6351 /* Build ISDS request of XSD tIdDbInput type, sent it and check for error
6352 * code
6353 * @context is session context
6354 * @service is SOAP service
6355 * @service_name is name of request in @service
6356 * @box_id_element is name of element to wrap the @box_id. NULL means "dbID".
6357 * @box_id is box ID of interest
6358 * @approval is optional external approval of box manipulation
6359 * @response is server SOAP body response as XML document
6360 * @refnumber is reallocated serial number of request assigned by ISDS. Use
6361 * NULL, if you don't care.
6362 * @return error coded from lower layer, context message will be set up
6363 * appropriately. */
6364 static isds_error build_send_dbid_request_check_response(
6365 struct isds_ctx *context, const isds_service service,
6366 const xmlChar *service_name, const xmlChar *box_id_element,
6367 const xmlChar *box_id, const struct isds_approval *approval,
6368 xmlDocPtr *response, xmlChar **refnumber) {
6370 isds_error err = IE_SUCCESS;
6371 char *service_name_locale = NULL, *box_id_locale = NULL;
6372 xmlNodePtr request = NULL, node;
6373 xmlNsPtr isds_ns = NULL;
6375 if (!context) return IE_INVALID_CONTEXT;
6376 if (!service_name || !box_id) return IE_INVAL;
6377 if (!response) return IE_INVAL;
6379 /* Free output argument */
6380 xmlFreeDoc(*response); *response = NULL;
6382 /* Prepare strings */
6383 service_name_locale = _isds_utf82locale((char*)service_name);
6384 if (!service_name_locale) {
6385 err = IE_NOMEM;
6386 goto leave;
6388 box_id_locale = _isds_utf82locale((char*)box_id);
6389 if (!box_id_locale) {
6390 err = IE_NOMEM;
6391 goto leave;
6394 /* Build request */
6395 request = xmlNewNode(NULL, service_name);
6396 if (!request) {
6397 isds_printf_message(context,
6398 _("Could not build %s request for %s box"), service_name_locale,
6399 box_id_locale);
6400 err = IE_ERROR;
6401 goto leave;
6403 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
6404 if(!isds_ns) {
6405 isds_log_message(context, _("Could not create ISDS name space"));
6406 err = IE_ERROR;
6407 goto leave;
6409 xmlSetNs(request, isds_ns);
6411 /* Add XSD:tIdDbInput children */
6412 if (NULL == box_id_element) box_id_element = BAD_CAST "dbID";
6413 INSERT_STRING(request, box_id_element, box_id);
6414 err = insert_GExtApproval(context, approval, request);
6415 if (err) goto leave;
6417 /* Send request and check response*/
6418 err = send_destroy_request_check_response(context,
6419 service, service_name, &request, response, refnumber, NULL);
6421 leave:
6422 free(service_name_locale);
6423 free(box_id_locale);
6424 xmlFreeNode(request);
6425 return err;
6427 #endif /* HAVE_LIBCURL */
6430 /* Get data about all users assigned to given box.
6431 * @context is session context
6432 * @box_id is box ID
6433 * @users is automatically reallocated list of struct isds_DbUserInfo */
6434 isds_error isds_GetDataBoxUsers(struct isds_ctx *context, const char *box_id,
6435 struct isds_list **users) {
6436 isds_error err = IE_SUCCESS;
6437 #if HAVE_LIBCURL
6438 xmlDocPtr response = NULL;
6439 xmlXPathContextPtr xpath_ctx = NULL;
6440 xmlXPathObjectPtr result = NULL;
6441 int i;
6442 struct isds_list *item, *prev_item = NULL;
6443 #endif
6445 if (!context) return IE_INVALID_CONTEXT;
6446 zfree(context->long_message);
6447 if (!users || !box_id) return IE_INVAL;
6448 isds_list_free(users);
6451 #if HAVE_LIBCURL
6452 /* Do request and check for success */
6453 err = build_send_dbid_request_check_response(context,
6454 SERVICE_DB_MANIPULATION, BAD_CAST "GetDataBoxUsers", NULL,
6455 BAD_CAST box_id, NULL, &response, NULL);
6456 if (err) goto leave;
6459 /* Extract data */
6460 /* Prepare structure */
6461 xpath_ctx = xmlXPathNewContext(response);
6462 if (!xpath_ctx) {
6463 err = IE_ERROR;
6464 goto leave;
6466 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
6467 err = IE_ERROR;
6468 goto leave;
6471 /* Set context node */
6472 result = xmlXPathEvalExpression(BAD_CAST
6473 "/isds:GetDataBoxUsersResponse/isds:dbUsers/isds:dbUserInfo",
6474 xpath_ctx);
6475 if (!result) {
6476 err = IE_ERROR;
6477 goto leave;
6479 if (!xmlXPathNodeSetIsEmpty(result->nodesetval)) {
6480 /* Iterate over all users */
6481 for (i = 0; i < result->nodesetval->nodeNr; i++) {
6483 /* Prepare structure */
6484 item = calloc(1, sizeof(*item));
6485 if (!item) {
6486 err = IE_NOMEM;
6487 goto leave;
6489 item->destructor = (void(*)(void**))isds_DbUserInfo_free;
6490 if (i == 0) *users = item;
6491 else prev_item->next = item;
6492 prev_item = item;
6494 /* Extract it */
6495 xpath_ctx->node = result->nodesetval->nodeTab[i];
6496 err = extract_DbUserInfo(context,
6497 (struct isds_DbUserInfo **) (&item->data), xpath_ctx);
6498 if (err) goto leave;
6502 leave:
6503 if (err) {
6504 isds_list_free(users);
6507 xmlXPathFreeObject(result);
6508 xmlXPathFreeContext(xpath_ctx);
6509 xmlFreeDoc(response);
6511 if (!err)
6512 isds_log(ILF_ISDS, ILL_DEBUG,
6513 _("GetDataBoxUsers request processed by server "
6514 "successfully.\n"));
6515 #else /* not HAVE_LIBCURL */
6516 err = IE_NOTSUP;
6517 #endif
6519 return err;
6523 /* Update data about user assigned to given box.
6524 * @context is session context
6525 * @box is box identification
6526 * @old_user identifies user to update
6527 * @new_user are updated data about @old_user
6528 * @refnumber is reallocated serial number of request assigned by ISDS. Use
6529 * NULL, if you don't care.*/
6530 isds_error isds_UpdateDataBoxUser(struct isds_ctx *context,
6531 const struct isds_DbOwnerInfo *box,
6532 const struct isds_DbUserInfo *old_user,
6533 const struct isds_DbUserInfo *new_user,
6534 char **refnumber) {
6535 isds_error err = IE_SUCCESS;
6536 #if HAVE_LIBCURL
6537 xmlNsPtr isds_ns = NULL;
6538 xmlNodePtr request = NULL;
6539 xmlNodePtr node;
6540 #endif
6543 if (!context) return IE_INVALID_CONTEXT;
6544 zfree(context->long_message);
6545 if (!box || !old_user || !new_user) return IE_INVAL;
6548 #if HAVE_LIBCURL
6549 /* Build UpdateDataBoxUser request */
6550 request = xmlNewNode(NULL, BAD_CAST "UpdateDataBoxUser");
6551 if (!request) {
6552 isds_log_message(context,
6553 _("Could build UpdateDataBoxUser request"));
6554 return IE_ERROR;
6556 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
6557 if(!isds_ns) {
6558 isds_log_message(context, _("Could not create ISDS name space"));
6559 xmlFreeNode(request);
6560 return IE_ERROR;
6562 xmlSetNs(request, isds_ns);
6564 INSERT_ELEMENT(node, request, "dbOwnerInfo");
6565 err = insert_DbOwnerInfo(context, box, node);
6566 if (err) goto leave;
6568 INSERT_ELEMENT(node, request, "dbOldUserInfo");
6569 err = insert_DbUserInfo(context, old_user, node);
6570 if (err) goto leave;
6572 INSERT_ELEMENT(node, request, "dbNewUserInfo");
6573 err = insert_DbUserInfo(context, new_user, node);
6574 if (err) goto leave;
6576 /* Send it to server and process response */
6577 err = send_request_check_drop_response(context, SERVICE_DB_MANIPULATION,
6578 BAD_CAST "UpdateDataBoxUser", &request, (xmlChar **) refnumber);
6580 leave:
6581 xmlFreeNode(request);
6582 #else /* not HAVE_LIBCURL */
6583 err = IE_NOTSUP;
6584 #endif
6586 return err;
6590 /* Undocumented function.
6591 * @context is session context
6592 * @box_id is UTF-8 encoded box identifier
6593 * @token is UTF-8 encoded temporary password
6594 * @user_id outputs UTF-8 encoded reallocated user identifier
6595 * @password outpus UTF-8 encoded reallocated user password
6596 * Output arguments will be nulled in case of error */
6597 isds_error isds_activate(struct isds_ctx *context,
6598 const char *box_id, const char *token,
6599 char **user_id, char **password) {
6600 isds_error err = IE_SUCCESS;
6601 #if HAVE_LIBCURL
6602 xmlNsPtr isds_ns = NULL;
6603 xmlNodePtr request = NULL, node;
6604 xmlDocPtr response = NULL;
6605 xmlXPathContextPtr xpath_ctx = NULL;
6606 xmlXPathObjectPtr result = NULL;
6607 #endif
6610 if (!context) return IE_INVALID_CONTEXT;
6611 zfree(context->long_message);
6613 if (user_id) zfree(*user_id);
6614 if (password) zfree(*password);
6616 if (!box_id || !token || !user_id || !password) return IE_INVAL;
6619 #if HAVE_LIBCURL
6620 /* Build Activate request */
6621 request = xmlNewNode(NULL, BAD_CAST "Activate");
6622 if (!request) {
6623 isds_log_message(context, _("Could build Activate request"));
6624 return IE_ERROR;
6626 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
6627 if(!isds_ns) {
6628 isds_log_message(context, _("Could not create ISDS name space"));
6629 xmlFreeNode(request);
6630 return IE_ERROR;
6632 xmlSetNs(request, isds_ns);
6634 INSERT_STRING(request, "dbAccessDataId", token);
6635 CHECK_FOR_STRING_LENGTH(box_id, 7, 7, "dbID");
6636 INSERT_STRING(request, "dbID", box_id);
6639 /* Send request and check response*/
6640 err = send_destroy_request_check_response(context,
6641 SERVICE_DB_MANIPULATION, BAD_CAST "Activate", &request,
6642 &response, NULL, NULL);
6643 if (err) goto leave;
6646 /* Extract data */
6647 xpath_ctx = xmlXPathNewContext(response);
6648 if (!xpath_ctx) {
6649 err = IE_ERROR;
6650 goto leave;
6652 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
6653 err = IE_ERROR;
6654 goto leave;
6656 result = xmlXPathEvalExpression(BAD_CAST "/isds:ActivateResponse",
6657 xpath_ctx);
6658 if (!result) {
6659 err = IE_ERROR;
6660 goto leave;
6662 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
6663 isds_log_message(context, _("Missing ActivateResponse element"));
6664 err = IE_ISDS;
6665 goto leave;
6667 if (result->nodesetval->nodeNr > 1) {
6668 isds_log_message(context, _("Multiple ActivateResponse element"));
6669 err = IE_ISDS;
6670 goto leave;
6672 xpath_ctx->node = result->nodesetval->nodeTab[0];
6673 xmlXPathFreeObject(result); result = NULL;
6675 EXTRACT_STRING("isds:userId", *user_id);
6676 if (!*user_id)
6677 isds_log(ILF_ISDS, ILL_ERR, _("Server accepted Activate request, "
6678 "but did not return `userId' element.\n"));
6680 EXTRACT_STRING("isds:password", *password);
6681 if (!*password)
6682 isds_log(ILF_ISDS, ILL_ERR, _("Server accepted Activate request, "
6683 "but did not return `password' element.\n"));
6685 leave:
6686 xmlXPathFreeObject(result);
6687 xmlXPathFreeContext(xpath_ctx);
6688 xmlFreeDoc(response);
6689 xmlFreeNode(request);
6691 if (!err)
6692 isds_log(ILF_ISDS, ILL_DEBUG,
6693 _("Activate request processed by server successfully.\n"));
6694 #else /* not HAVE_LIBCURL */
6695 err = IE_NOTSUP;
6696 #endif
6698 return err;
6702 /* Reset credentials of user assigned to given box.
6703 * @context is session context
6704 * @box is box identification
6705 * @user identifies user to reset password
6706 * @fee_paid is true if fee has been paid, false otherwise
6707 * @approval is optional external approval of box manipulation
6708 * @credentials_delivery is NULL if new password should be delivered off-line
6709 * to the user. It is valid pointer if user should obtain new password on-line
6710 * on dedicated web server. Then input @credentials_delivery.email value is
6711 * user's e-mail address user must provide to dedicated web server together
6712 * with @credentials_delivery.token. The output reallocated token user needs
6713 * to use to authorize on the web server to view his new password. Output
6714 * reallocated @credentials_delivery.new_user_name is user's log-in name that
6715 * ISDS changed up on this call. (No reason why server could change the name
6716 * is known now.)
6717 * @refnumber is reallocated serial number of request assigned by ISDS. Use
6718 * NULL, if you don't care.*/
6719 isds_error isds_reset_password(struct isds_ctx *context,
6720 const struct isds_DbOwnerInfo *box,
6721 const struct isds_DbUserInfo *user,
6722 const _Bool fee_paid, const struct isds_approval *approval,
6723 struct isds_credentials_delivery *credentials_delivery,
6724 char **refnumber) {
6725 isds_error err = IE_SUCCESS;
6726 #if HAVE_LIBCURL
6727 xmlNsPtr isds_ns = NULL;
6728 xmlNodePtr request = NULL, node;
6729 xmlDocPtr response = NULL;
6730 #endif
6733 if (!context) return IE_INVALID_CONTEXT;
6734 zfree(context->long_message);
6736 if (credentials_delivery) {
6737 zfree(credentials_delivery->token);
6738 zfree(credentials_delivery->new_user_name);
6740 if (!box || !user) return IE_INVAL;
6743 #if HAVE_LIBCURL
6744 /* Build NewAccessData request */
6745 request = xmlNewNode(NULL, BAD_CAST "NewAccessData");
6746 if (!request) {
6747 isds_log_message(context,
6748 _("Could build NewAccessData request"));
6749 return IE_ERROR;
6751 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
6752 if(!isds_ns) {
6753 isds_log_message(context, _("Could not create ISDS name space"));
6754 xmlFreeNode(request);
6755 return IE_ERROR;
6757 xmlSetNs(request, isds_ns);
6759 INSERT_ELEMENT(node, request, "dbOwnerInfo");
6760 err = insert_DbOwnerInfo(context, box, node);
6761 if (err) goto leave;
6763 INSERT_ELEMENT(node, request, "dbUserInfo");
6764 err = insert_DbUserInfo(context, user, node);
6765 if (err) goto leave;
6767 INSERT_SCALAR_BOOLEAN(request, "dbFeePaid", fee_paid);
6769 err = insert_credentials_delivery(context, credentials_delivery, request);
6770 if (err) goto leave;
6772 err = insert_GExtApproval(context, approval, request);
6773 if (err) goto leave;
6775 /* Send request and check response*/
6776 err = send_destroy_request_check_response(context,
6777 SERVICE_DB_MANIPULATION, BAD_CAST "NewAccessData", &request,
6778 &response, (xmlChar **) refnumber, NULL);
6779 if (err) goto leave;
6782 /* Extract optional token */
6783 err = extract_credentials_delivery(context, credentials_delivery,
6784 response, "NewAccessData");
6786 leave:
6787 xmlFreeDoc(response);
6788 xmlFreeNode(request);
6790 if (!err)
6791 isds_log(ILF_ISDS, ILL_DEBUG,
6792 _("NewAccessData request processed by server "
6793 "successfully.\n"));
6794 #else /* not HAVE_LIBCURL */
6795 err = IE_NOTSUP;
6796 #endif
6798 return err;
6802 /* Build ISDS request of XSD tAddDBUserInput type, sent it, check for error
6803 * code, destroy response and log success.
6804 * @context is ISDS session context.
6805 * @service_name is name of SERVICE_DB_MANIPULATION service
6806 * @box is box identification
6807 * @user identifies user to remove
6808 * @credentials_delivery is NULL if new user's password should be delivered
6809 * off-line to the user. It is valid pointer if user should obtain new
6810 * password on-line on dedicated web server. Then input
6811 * @credentials_delivery.email value is user's e-mail address user must
6812 * provide to dedicated web server together with @credentials_delivery.token.
6813 * The output reallocated token user needs to use to authorize on the web
6814 * server to view his new password. Output reallocated
6815 * @credentials_delivery.new_user_name is user's log-in name that ISDS
6816 * assingned or changed up on this call.
6817 * @approval is optional external approval of box manipulation
6818 * @refnumber is reallocated serial number of request assigned by ISDS. Use
6819 * NULL, if you don't care. */
6820 static isds_error build_send_manipulationboxuser_request_check_drop_response(
6821 struct isds_ctx *context, const xmlChar *service_name,
6822 const struct isds_DbOwnerInfo *box, const struct isds_DbUserInfo *user,
6823 struct isds_credentials_delivery *credentials_delivery,
6824 const struct isds_approval *approval, xmlChar **refnumber) {
6825 isds_error err = IE_SUCCESS;
6826 #if HAVE_LIBCURL
6827 xmlNsPtr isds_ns = NULL;
6828 xmlNodePtr request = NULL, node;
6829 xmlDocPtr response = NULL;
6830 #endif
6833 if (!context) return IE_INVALID_CONTEXT;
6834 zfree(context->long_message);
6835 if (credentials_delivery) {
6836 zfree(credentials_delivery->token);
6837 zfree(credentials_delivery->new_user_name);
6839 if (!service_name || service_name[0] == '\0' || !box || !user)
6840 return IE_INVAL;
6843 #if HAVE_LIBCURL
6844 /* Build NewAccessData or similar request */
6845 request = xmlNewNode(NULL, service_name);
6846 if (!request) {
6847 char *service_name_locale = _isds_utf82locale((char *) service_name);
6848 isds_printf_message(context, _("Could not build %s request"),
6849 service_name_locale);
6850 free(service_name_locale);
6851 return IE_ERROR;
6853 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
6854 if(!isds_ns) {
6855 isds_log_message(context, _("Could not create ISDS name space"));
6856 xmlFreeNode(request);
6857 return IE_ERROR;
6859 xmlSetNs(request, isds_ns);
6861 INSERT_ELEMENT(node, request, "dbOwnerInfo");
6862 err = insert_DbOwnerInfo(context, box, node);
6863 if (err) goto leave;
6865 INSERT_ELEMENT(node, request, "dbUserInfo");
6866 err = insert_DbUserInfo(context, user, node);
6867 if (err) goto leave;
6869 err = insert_credentials_delivery(context, credentials_delivery, request);
6870 if (err) goto leave;
6872 err = insert_GExtApproval(context, approval, request);
6873 if (err) goto leave;
6876 /* Send request and check response*/
6877 err = send_destroy_request_check_response(context,
6878 SERVICE_DB_MANIPULATION, service_name, &request, &response,
6879 refnumber, NULL);
6881 xmlFreeNode(request);
6882 request = NULL;
6884 /* Pick up credentials_delivery if requested */
6885 err = extract_credentials_delivery(context, credentials_delivery, response,
6886 (char *)service_name);
6888 leave:
6889 xmlFreeDoc(response);
6890 if (request) xmlFreeNode(request);
6892 if (!err) {
6893 char *service_name_locale = _isds_utf82locale((char *) service_name);
6894 isds_log(ILF_ISDS, ILL_DEBUG,
6895 _("%s request processed by server successfully.\n"),
6896 service_name_locale);
6897 free(service_name_locale);
6899 #else /* not HAVE_LIBCURL */
6900 err = IE_NOTSUP;
6901 #endif
6903 return err;
6907 /* Assign new user to given box.
6908 * @context is session context
6909 * @box is box identification
6910 * @user defines new user to add
6911 * @credentials_delivery is NULL if new user's password should be delivered
6912 * off-line to the user. It is valid pointer if user should obtain new
6913 * password on-line on dedicated web server. Then input
6914 * @credentials_delivery.email value is user's e-mail address user must
6915 * provide to dedicated web server together with @credentials_delivery.token.
6916 * The output reallocated token user needs to use to authorize on the web
6917 * server to view his new password. Output reallocated
6918 * @credentials_delivery.new_user_name is user's log-in name that ISDS
6919 * assingned up on this call.
6920 * @approval is optional external approval of box manipulation
6921 * @refnumber is reallocated serial number of request assigned by ISDS. Use
6922 * NULL, if you don't care.*/
6923 isds_error isds_add_user(struct isds_ctx *context,
6924 const struct isds_DbOwnerInfo *box, const struct isds_DbUserInfo *user,
6925 struct isds_credentials_delivery *credentials_delivery,
6926 const struct isds_approval *approval, char **refnumber) {
6927 return build_send_manipulationboxuser_request_check_drop_response(context,
6928 BAD_CAST "AddDataBoxUser", box, user, credentials_delivery,
6929 approval, (xmlChar **) refnumber);
6933 /* Remove user assigned to given box.
6934 * @context is session context
6935 * @box is box identification
6936 * @user identifies user to remove
6937 * @approval is optional external approval of box manipulation
6938 * @refnumber is reallocated serial number of request assigned by ISDS. Use
6939 * NULL, if you don't care.*/
6940 isds_error isds_delete_user(struct isds_ctx *context,
6941 const struct isds_DbOwnerInfo *box, const struct isds_DbUserInfo *user,
6942 const struct isds_approval *approval, char **refnumber) {
6943 return build_send_manipulationboxuser_request_check_drop_response(context,
6944 BAD_CAST "DeleteDataBoxUser", box, user, NULL, approval,
6945 (xmlChar **) refnumber);
6949 /* Get list of boxes in ZIP archive.
6950 * @context is session context
6951 * @list_identifier is UTF-8 encoded string identifying boxes of interrest.
6952 * System recognizes following values currently: ALL (all boxes), UPG
6953 * (effectively OVM boxes), OVM (OVM gross type boxes), OPN (boxes allowing
6954 * receiving commercial messages). This argument is a string because
6955 * specification states new values can appear in the future. Not all list
6956 * types are available to all users.
6957 * @buffer is automatically reallocated memory to store the list of boxes. The
6958 * list is zipped CSV file.
6959 * @buffer_length is size of @buffer data in bytes.
6960 * In case of error @buffer will be freed and @buffer_length will be
6961 * undefined.*/
6962 isds_error isds_get_box_list_archive(struct isds_ctx *context,
6963 const char *list_identifier, void **buffer, size_t *buffer_length) {
6964 isds_error err = IE_SUCCESS;
6965 #if HAVE_LIBCURL
6966 xmlNsPtr isds_ns = NULL;
6967 xmlNodePtr request = NULL, node;
6968 xmlDocPtr response = NULL;
6969 xmlXPathContextPtr xpath_ctx = NULL;
6970 xmlXPathObjectPtr result = NULL;
6971 char *string = NULL;
6972 #endif
6975 if (!context) return IE_INVALID_CONTEXT;
6976 zfree(context->long_message);
6977 if (buffer) zfree(*buffer);
6978 if (!buffer || !buffer_length) return IE_INVAL;
6981 #if HAVE_LIBCURL
6982 /* Check if connection is established
6983 * TODO: This check should be done downstairs. */
6984 if (!context->curl) return IE_CONNECTION_CLOSED;
6987 /* Build AuthenticateMessage request */
6988 request = xmlNewNode(NULL, BAD_CAST "GetDataBoxList");
6989 if (!request) {
6990 isds_log_message(context,
6991 _("Could not build GetDataBoxList request"));
6992 return IE_ERROR;
6994 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
6995 if(!isds_ns) {
6996 isds_log_message(context, _("Could not create ISDS name space"));
6997 xmlFreeNode(request);
6998 return IE_ERROR;
7000 xmlSetNs(request, isds_ns);
7001 INSERT_STRING(request, "dblType", list_identifier);
7003 /* Send request to server and process response */
7004 err = send_destroy_request_check_response(context,
7005 SERVICE_DB_SEARCH, BAD_CAST "GetDataBoxList", &request,
7006 &response, NULL, NULL);
7007 if (err) goto leave;
7010 /* Extract Base-64 encoded ZIP file */
7011 xpath_ctx = xmlXPathNewContext(response);
7012 if (!xpath_ctx) {
7013 err = IE_ERROR;
7014 goto leave;
7016 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
7017 err = IE_ERROR;
7018 goto leave;
7020 EXTRACT_STRING("/isds:GetDataBoxListResponse/isds:dblData", string);
7022 /* Decode non-empty archive */
7023 if (string && string[0] != '\0') {
7024 *buffer_length = _isds_b64decode(string, buffer);
7025 if (*buffer_length == (size_t) -1) {
7026 isds_printf_message(context,
7027 _("Error while Base64-decoding box list archive"));
7028 err = IE_ERROR;
7029 goto leave;
7034 leave:
7035 free(string);
7036 xmlXPathFreeObject(result);
7037 xmlXPathFreeContext(xpath_ctx);
7038 xmlFreeDoc(response);
7039 xmlFreeNode(request);
7041 if (!err) {
7042 isds_log(ILF_ISDS, ILL_DEBUG, _("GetDataBoxList request "
7043 "processed by server successfully.\n"));
7045 #else /* not HAVE_LIBCURL */
7046 err = IE_NOTSUP;
7047 #endif
7049 return err;
7053 /* Find boxes suiting given criteria.
7054 * @criteria is filter. You should fill in at least some members.
7055 * @boxes is automatically reallocated list of isds_DbOwnerInfo structures,
7056 * possibly empty. Input NULL or valid old structure.
7057 * @return:
7058 * IE_SUCCESS if search succeeded, @boxes contains useful data
7059 * IE_NOEXIST if no such box exists, @boxes will be NULL
7060 * IE_2BIG if too much boxes exist and server truncated the results, @boxes
7061 * contains still valid data
7062 * other code if something bad happens. @boxes will be NULL. */
7063 isds_error isds_FindDataBox(struct isds_ctx *context,
7064 const struct isds_DbOwnerInfo *criteria,
7065 struct isds_list **boxes) {
7066 isds_error err = IE_SUCCESS;
7067 #if HAVE_LIBCURL
7068 _Bool truncated = 0;
7069 xmlNsPtr isds_ns = NULL;
7070 xmlNodePtr request = NULL;
7071 xmlDocPtr response = NULL;
7072 xmlChar *code = NULL, *message = NULL;
7073 xmlNodePtr db_owner_info;
7074 xmlXPathContextPtr xpath_ctx = NULL;
7075 xmlXPathObjectPtr result = NULL;
7076 xmlChar *string = NULL;
7077 #endif
7080 if (!context) return IE_INVALID_CONTEXT;
7081 zfree(context->long_message);
7082 if (!boxes) return IE_INVAL;
7083 isds_list_free(boxes);
7085 if (!criteria) {
7086 return IE_INVAL;
7089 #if HAVE_LIBCURL
7090 /* Check if connection is established
7091 * TODO: This check should be done downstairs. */
7092 if (!context->curl) return IE_CONNECTION_CLOSED;
7095 /* Build FindDataBox request */
7096 request = xmlNewNode(NULL, BAD_CAST "FindDataBox");
7097 if (!request) {
7098 isds_log_message(context,
7099 _("Could build FindDataBox request"));
7100 return IE_ERROR;
7102 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
7103 if(!isds_ns) {
7104 isds_log_message(context, _("Could not create ISDS name space"));
7105 xmlFreeNode(request);
7106 return IE_ERROR;
7108 xmlSetNs(request, isds_ns);
7109 db_owner_info = xmlNewChild(request, NULL, BAD_CAST "dbOwnerInfo", NULL);
7110 if (!db_owner_info) {
7111 isds_log_message(context, _("Could not add dbOwnerInfo child to "
7112 "FindDataBox element"));
7113 xmlFreeNode(request);
7114 return IE_ERROR;
7117 err = insert_DbOwnerInfo(context, criteria, db_owner_info);
7118 if (err) goto leave;
7121 isds_log(ILF_ISDS, ILL_DEBUG, _("Sending FindDataBox request to ISDS\n"));
7123 /* Sent request */
7124 err = isds(context, SERVICE_DB_SEARCH, request, &response, NULL, NULL);
7126 /* Destroy request */
7127 xmlFreeNode(request); request = NULL;
7129 if (err) {
7130 isds_log(ILF_ISDS, ILL_DEBUG,
7131 _("Processing ISDS response on FindDataBox "
7132 "request failed\n"));
7133 goto leave;
7136 /* Check for response status */
7137 err = isds_response_status(context, SERVICE_DB_SEARCH, response,
7138 &code, &message, NULL);
7139 if (err) {
7140 isds_log(ILF_ISDS, ILL_DEBUG,
7141 _("ISDS response on FindDataBox request is missing status\n"));
7142 goto leave;
7145 /* Request processed, but nothing found */
7146 if (!xmlStrcmp(code, BAD_CAST "0002") ||
7147 !xmlStrcmp(code, BAD_CAST "5001")) {
7148 char *code_locale = _isds_utf82locale((char*)code);
7149 char *message_locale = _isds_utf82locale((char*)message);
7150 isds_log(ILF_ISDS, ILL_DEBUG,
7151 _("Server did not found any box on FindDataBox request "
7152 "(code=%s, message=%s)\n"), code_locale, message_locale);
7153 isds_log_message(context, message_locale);
7154 free(code_locale);
7155 free(message_locale);
7156 err = IE_NOEXIST;
7157 goto leave;
7160 /* Warning, not a error */
7161 if (!xmlStrcmp(code, BAD_CAST "0003")) {
7162 char *code_locale = _isds_utf82locale((char*)code);
7163 char *message_locale = _isds_utf82locale((char*)message);
7164 isds_log(ILF_ISDS, ILL_DEBUG,
7165 _("Server truncated response on FindDataBox request "
7166 "(code=%s, message=%s)\n"), code_locale, message_locale);
7167 isds_log_message(context, message_locale);
7168 free(code_locale);
7169 free(message_locale);
7170 truncated = 1;
7173 /* Other error */
7174 else if (xmlStrcmp(code, BAD_CAST "0000")) {
7175 char *code_locale = _isds_utf82locale((char*)code);
7176 char *message_locale = _isds_utf82locale((char*)message);
7177 isds_log(ILF_ISDS, ILL_DEBUG,
7178 _("Server refused FindDataBox request "
7179 "(code=%s, message=%s)\n"), code_locale, message_locale);
7180 isds_log_message(context, message_locale);
7181 free(code_locale);
7182 free(message_locale);
7183 err = IE_ISDS;
7184 goto leave;
7187 xpath_ctx = xmlXPathNewContext(response);
7188 if (!xpath_ctx) {
7189 err = IE_ERROR;
7190 goto leave;
7192 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
7193 err = IE_ERROR;
7194 goto leave;
7197 /* Extract boxes if they present */
7198 result = xmlXPathEvalExpression(BAD_CAST
7199 "/isds:FindDataBoxResponse/isds:dbResults/isds:dbOwnerInfo",
7200 xpath_ctx);
7201 if (!result) {
7202 err = IE_ERROR;
7203 goto leave;
7205 if (!xmlXPathNodeSetIsEmpty(result->nodesetval)) {
7206 struct isds_list *item, *prev_item = NULL;
7207 for (int i = 0; i < result->nodesetval->nodeNr; i++) {
7208 item = calloc(1, sizeof(*item));
7209 if (!item) {
7210 err = IE_NOMEM;
7211 goto leave;
7214 item->destructor = (void (*)(void **))isds_DbOwnerInfo_free;
7215 if (i == 0) *boxes = item;
7216 else prev_item->next = item;
7217 prev_item = item;
7219 xpath_ctx->node = result->nodesetval->nodeTab[i];
7220 err = extract_DbOwnerInfo(context,
7221 (struct isds_DbOwnerInfo **) &(item->data), xpath_ctx);
7222 if (err) goto leave;
7226 leave:
7227 if (err) {
7228 isds_list_free(boxes);
7229 } else {
7230 if (truncated) err = IE_2BIG;
7233 free(string);
7234 xmlFreeNode(request);
7235 xmlXPathFreeObject(result);
7236 xmlXPathFreeContext(xpath_ctx);
7238 free(code);
7239 free(message);
7240 xmlFreeDoc(response);
7242 if (!err)
7243 isds_log(ILF_ISDS, ILL_DEBUG,
7244 _("FindDataBox request processed by server successfully.\n"));
7245 #else /* not HAVE_LIBCURL */
7246 err = IE_NOTSUP;
7247 #endif
7249 return err;
7253 /* Get status of a box.
7254 * @context is ISDS session context.
7255 * @box_id is UTF-8 encoded box identifier as zero terminated string
7256 * @box_status is return value of box status.
7257 * @return:
7258 * IE_SUCCESS if box has been found and its status retrieved
7259 * IE_NOEXIST if box is not known to ISDS server
7260 * or other appropriate error.
7261 * You can use isds_DbState to enumerate box status. However out of enum
7262 * range value can be returned too. This is feature because ISDS
7263 * specification leaves the set of values open.
7264 * Be ware that status DBSTATE_REMOVED is signaled as IE_SUCCESS. That means
7265 * the box has been deleted, but ISDS still lists its former existence. */
7266 isds_error isds_CheckDataBox(struct isds_ctx *context, const char *box_id,
7267 long int *box_status) {
7268 isds_error err = IE_SUCCESS;
7269 #if HAVE_LIBCURL
7270 xmlNsPtr isds_ns = NULL;
7271 xmlNodePtr request = NULL, db_id;
7272 xmlDocPtr response = NULL;
7273 xmlChar *code = NULL, *message = NULL;
7274 xmlXPathContextPtr xpath_ctx = NULL;
7275 xmlXPathObjectPtr result = NULL;
7276 xmlChar *string = NULL;
7277 #endif
7279 if (!context) return IE_INVALID_CONTEXT;
7280 zfree(context->long_message);
7281 if (!box_status || !box_id || *box_id == '\0') return IE_INVAL;
7283 #if HAVE_LIBCURL
7284 /* Check if connection is established
7285 * TODO: This check should be done downstairs. */
7286 if (!context->curl) return IE_CONNECTION_CLOSED;
7289 /* Build CheckDataBox request */
7290 request = xmlNewNode(NULL, BAD_CAST "CheckDataBox");
7291 if (!request) {
7292 isds_log_message(context,
7293 _("Could build CheckDataBox request"));
7294 return IE_ERROR;
7296 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
7297 if(!isds_ns) {
7298 isds_log_message(context, _("Could not create ISDS name space"));
7299 xmlFreeNode(request);
7300 return IE_ERROR;
7302 xmlSetNs(request, isds_ns);
7303 db_id = xmlNewTextChild(request, NULL, BAD_CAST "dbID", (xmlChar *) box_id);
7304 if (!db_id) {
7305 isds_log_message(context, _("Could not add dbID child to "
7306 "CheckDataBox element"));
7307 xmlFreeNode(request);
7308 return IE_ERROR;
7312 isds_log(ILF_ISDS, ILL_DEBUG, _("Sending CheckDataBox request to ISDS\n"));
7314 /* Sent request */
7315 err = isds(context, SERVICE_DB_SEARCH, request, &response, NULL, NULL);
7317 /* Destroy request */
7318 xmlFreeNode(request);
7320 if (err) {
7321 isds_log(ILF_ISDS, ILL_DEBUG,
7322 _("Processing ISDS response on CheckDataBox "
7323 "request failed\n"));
7324 goto leave;
7327 /* Check for response status */
7328 err = isds_response_status(context, SERVICE_DB_SEARCH, response,
7329 &code, &message, NULL);
7330 if (err) {
7331 isds_log(ILF_ISDS, ILL_DEBUG,
7332 _("ISDS response on CheckDataBox request is missing status\n"));
7333 goto leave;
7336 /* Request processed, but nothing found */
7337 if (!xmlStrcmp(code, BAD_CAST "5001")) {
7338 char *box_id_locale = _isds_utf82locale((char*)box_id);
7339 char *code_locale = _isds_utf82locale((char*)code);
7340 char *message_locale = _isds_utf82locale((char*)message);
7341 isds_log(ILF_ISDS, ILL_DEBUG,
7342 _("Server did not found box %s on CheckDataBox request "
7343 "(code=%s, message=%s)\n"),
7344 box_id_locale, code_locale, message_locale);
7345 isds_log_message(context, message_locale);
7346 free(box_id_locale);
7347 free(code_locale);
7348 free(message_locale);
7349 err = IE_NOEXIST;
7350 goto leave;
7353 /* Other error */
7354 else if (xmlStrcmp(code, BAD_CAST "0000")) {
7355 char *code_locale = _isds_utf82locale((char*)code);
7356 char *message_locale = _isds_utf82locale((char*)message);
7357 isds_log(ILF_ISDS, ILL_DEBUG,
7358 _("Server refused CheckDataBox request "
7359 "(code=%s, message=%s)\n"), code_locale, message_locale);
7360 isds_log_message(context, message_locale);
7361 free(code_locale);
7362 free(message_locale);
7363 err = IE_ISDS;
7364 goto leave;
7367 /* Extract data */
7368 xpath_ctx = xmlXPathNewContext(response);
7369 if (!xpath_ctx) {
7370 err = IE_ERROR;
7371 goto leave;
7373 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
7374 err = IE_ERROR;
7375 goto leave;
7377 result = xmlXPathEvalExpression(BAD_CAST "/isds:CheckDataBoxResponse",
7378 xpath_ctx);
7379 if (!result) {
7380 err = IE_ERROR;
7381 goto leave;
7383 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
7384 isds_log_message(context, _("Missing CheckDataBoxResponse element"));
7385 err = IE_ISDS;
7386 goto leave;
7388 if (result->nodesetval->nodeNr > 1) {
7389 isds_log_message(context, _("Multiple CheckDataBoxResponse element"));
7390 err = IE_ISDS;
7391 goto leave;
7393 xpath_ctx->node = result->nodesetval->nodeTab[0];
7394 xmlXPathFreeObject(result); result = NULL;
7396 EXTRACT_LONGINT("isds:dbState", box_status, 1);
7399 leave:
7400 free(string);
7401 xmlXPathFreeObject(result);
7402 xmlXPathFreeContext(xpath_ctx);
7404 free(code);
7405 free(message);
7406 xmlFreeDoc(response);
7408 if (!err)
7409 isds_log(ILF_ISDS, ILL_DEBUG,
7410 _("CheckDataBox request processed by server successfully.\n"));
7411 #else /* not HAVE_LIBCURL */
7412 err = IE_NOTSUP;
7413 #endif
7415 return err;
7419 /* Get list of permissions to send commercial messages.
7420 * @context is ISDS session context.
7421 * @box_id is UTF-8 encoded sender box identifier as zero terminated string
7422 * @permissions is a reallocated list of permissions (struct
7423 * isds_commercial_permission*) to send commercial messages from @box_id. The
7424 * order of permissions is significant as the server applies the permissions
7425 * and associated pre-paid credits in the order. Empty list means no
7426 * permission.
7427 * @return:
7428 * IE_SUCCESS if the list has been obtained correctly,
7429 * or other appropriate error. */
7430 isds_error isds_get_commercial_permissions(struct isds_ctx *context,
7431 const char *box_id, struct isds_list **permissions) {
7432 isds_error err = IE_SUCCESS;
7433 #if HAVE_LIBCURL
7434 xmlDocPtr response = NULL;
7435 xmlXPathContextPtr xpath_ctx = NULL;
7436 xmlXPathObjectPtr result = NULL;
7437 #endif
7439 if (!context) return IE_INVALID_CONTEXT;
7440 zfree(context->long_message);
7441 if (NULL == permissions) return IE_INVAL;
7442 isds_list_free(permissions);
7443 if (NULL == box_id) return IE_INVAL;
7445 #if HAVE_LIBCURL
7446 /* Check if connection is established */
7447 if (!context->curl) return IE_CONNECTION_CLOSED;
7449 /* Do request and check for success */
7450 err = build_send_dbid_request_check_response(context,
7451 SERVICE_DB_SEARCH, BAD_CAST "PDZInfo", BAD_CAST "PDZSender",
7452 BAD_CAST box_id, NULL, &response, NULL);
7453 if (!err) {
7454 isds_log(ILF_ISDS, ILL_DEBUG,
7455 _("PDZInfo request processed by server successfully.\n"));
7458 /* Extract data */
7459 /* Prepare structure */
7460 xpath_ctx = xmlXPathNewContext(response);
7461 if (!xpath_ctx) {
7462 err = IE_ERROR;
7463 goto leave;
7465 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
7466 err = IE_ERROR;
7467 goto leave;
7470 /* Set context node */
7471 result = xmlXPathEvalExpression(BAD_CAST
7472 "/isds:PDZInfoResponse/isds:dbPDZRecords/isds:dbPDZRecord",
7473 xpath_ctx);
7474 if (!result) {
7475 err = IE_ERROR;
7476 goto leave;
7478 if (!xmlXPathNodeSetIsEmpty(result->nodesetval)) {
7479 /* Iterate over all permission records */
7480 for (long unsigned int i = 0; i < result->nodesetval->nodeNr; i++) {
7481 struct isds_list *item, *prev_item = NULL;
7483 /* Prepare structure */
7484 item = calloc(1, sizeof(*item));
7485 if (!item) {
7486 err = IE_NOMEM;
7487 goto leave;
7489 item->destructor = (void(*)(void**))isds_commercial_permission_free;
7490 if (i == 0) *permissions = item;
7491 else prev_item->next = item;
7492 prev_item = item;
7494 /* Extract it */
7495 xpath_ctx->node = result->nodesetval->nodeTab[i];
7496 err = extract_DbPDZRecord(context,
7497 (struct isds_commercial_permission **) (&item->data),
7498 xpath_ctx);
7499 if (err) goto leave;
7503 leave:
7504 if (err) {
7505 isds_list_free(permissions);
7508 xmlXPathFreeObject(result);
7509 xmlXPathFreeContext(xpath_ctx);
7510 xmlFreeDoc(response);
7512 #else /* not HAVE_LIBCURL */
7513 err = IE_NOTSUP;
7514 #endif
7516 return err;
7520 /* Get details about credit for sending pre-paid commercial messages.
7521 * @context is ISDS session context.
7522 * @box_id is UTF-8 encoded sender box identifier as zero terminated string.
7523 * @from_date is first day of credit history to return in @history. Only
7524 * tm_year, tm_mon and tm_mday carry sane value.
7525 * @to_date is last day of credit history to return in @history. Only
7526 * tm_year, tm_mon and tm_mday carry sane value.
7527 * @credit outputs current credit value into pre-allocated memory. Pass NULL
7528 * if you don't care.
7529 * @email outputs notification e-mail address where notifications about credit
7530 * are sent. This is automatically reallocated string.
7531 * Pass NULL if you don't care. It can return NULL if no address is defined.
7532 * @history outputs auto-reallocated list of pointers to struct
7533 * isds_credit_event. Events in closed interval @from_time to @to_time are
7534 * returned. Pass NULL @to_time and @from_time if you don't care.
7535 * @return:
7536 * IE_SUCCESS if the credit details have been obtained correctly,
7537 * or other appropriate error. Please note that server allows to retrieve
7538 * only limited history of events. */
7539 isds_error isds_get_commercial_credit(struct isds_ctx *context,
7540 const char *box_id,
7541 const struct tm *from_date, const struct tm *to_date,
7542 long int *credit, char **email, struct isds_list **history) {
7543 isds_error err = IE_SUCCESS;
7544 #if HAVE_LIBCURL
7545 char *box_id_locale = NULL;
7546 xmlNodePtr request = NULL, node;
7547 xmlNsPtr isds_ns = NULL;
7548 xmlChar *string = NULL;
7550 xmlDocPtr response = NULL;
7551 xmlXPathContextPtr xpath_ctx = NULL;
7552 xmlXPathObjectPtr result = NULL;
7554 const xmlChar *codes[] = {
7555 /* TODO: Gather codes by experiment */
7556 BAD_CAST "",
7557 BAD_CAST "",
7558 BAD_CAST "",
7559 BAD_CAST "",
7560 BAD_CAST "",
7561 NULL
7563 const char *meanings[] = {
7564 "Insufficient priviledges for the box",
7565 "The box does not exist",
7566 "Date is too long (history is not available after 15 months)",
7567 "Interval is too long (limit is 3 months)",
7568 "Invalid date"
7570 const isds_error errors[] = {
7571 IE_ISDS,
7572 IE_NOEXIST,
7573 IE_DATE,
7574 IE_DATE,
7575 IE_DATE,
7577 struct code_map_isds_error map = {
7578 .codes = codes,
7579 .meanings = meanings,
7580 .errors = errors
7582 #endif
7584 if (!context) return IE_INVALID_CONTEXT;
7585 zfree(context->long_message);
7587 /* Free output argument */
7588 if (NULL != credit) *credit = 0;
7589 if (NULL != email) zfree(*email);
7590 isds_list_free(history);
7592 if (NULL == box_id) return IE_INVAL;
7594 #if HAVE_LIBCURL
7595 /* Check if connection is established */
7596 if (NULL == context->curl) return IE_CONNECTION_CLOSED;
7598 box_id_locale = _isds_utf82locale((char*)box_id);
7599 if (NULL == box_id_locale) {
7600 err = IE_NOMEM;
7601 goto leave;
7604 /* Build request */
7605 request = xmlNewNode(NULL, BAD_CAST "DataBoxCreditInfo");
7606 if (NULL == request) {
7607 isds_printf_message(context,
7608 _("Could not build DataBoxCreditInfo request for %s box"),
7609 box_id_locale);
7610 err = IE_ERROR;
7611 goto leave;
7613 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
7614 if(!isds_ns) {
7615 isds_log_message(context, _("Could not create ISDS name space"));
7616 err = IE_ERROR;
7617 goto leave;
7619 xmlSetNs(request, isds_ns);
7621 /* Add mandatory XSD:tIdDbInput child */
7622 INSERT_STRING(request, BAD_CAST "dbID", box_id);
7623 /* Add optional dates */
7624 if (from_date) {
7625 err = tm2datestring(from_date, &string);
7626 if (err) {
7627 isds_log_message(context,
7628 _("Could not convert `from_date' argument to ISO date "
7629 "string"));
7630 goto leave;
7632 INSERT_STRING(request, "ciFromDate", string);
7633 zfree(string);
7635 if (to_date) {
7636 err = tm2datestring(to_date, &string);
7637 if (err) {
7638 isds_log_message(context,
7639 _("Could not convert `to_date' argument to ISO date "
7640 "string"));
7641 goto leave;
7643 INSERT_STRING(request, "ciTodate", string);
7644 zfree(string);
7647 /* Send request and check response*/
7648 err = send_destroy_request_check_response(context,
7649 SERVICE_DB_SEARCH, BAD_CAST "DataBoxCreditInfo",
7650 &request, &response, NULL, &map);
7651 if (err) goto leave;
7654 /* Extract data */
7655 /* Set context to the root */
7656 xpath_ctx = xmlXPathNewContext(response);
7657 if (!xpath_ctx) {
7658 err = IE_ERROR;
7659 goto leave;
7661 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
7662 err = IE_ERROR;
7663 goto leave;
7665 result = xmlXPathEvalExpression(BAD_CAST "/isds:DataBoxCreditInfoResponse",
7666 xpath_ctx);
7667 if (!result) {
7668 err = IE_ERROR;
7669 goto leave;
7671 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
7672 isds_log_message(context, _("Missing DataBoxCreditInfoResponse element"));
7673 err = IE_ISDS;
7674 goto leave;
7676 if (result->nodesetval->nodeNr > 1) {
7677 isds_log_message(context, _("Multiple DataBoxCreditInfoResponse element"));
7678 err = IE_ISDS;
7679 goto leave;
7681 xpath_ctx->node = result->nodesetval->nodeTab[0];
7682 xmlXPathFreeObject(result); result = NULL;
7684 /* Extract common data */
7685 if (NULL != credit) EXTRACT_LONGINT("isds:currentCredit", credit, 1);
7686 if (NULL != email) EXTRACT_STRING("isds:notifEmail", *email);
7688 /* Extract records */
7689 if (NULL == history) goto leave;
7690 result = xmlXPathEvalExpression(BAD_CAST "isds:ciRecords/isds:ciRecord",
7691 xpath_ctx);
7692 if (!result) {
7693 err = IE_ERROR;
7694 goto leave;
7696 if (!xmlXPathNodeSetIsEmpty(result->nodesetval)) {
7697 /* Iterate over all records */
7698 for (long unsigned int i = 0; i < result->nodesetval->nodeNr; i++) {
7699 struct isds_list *item, *prev_item = NULL;
7701 /* Prepare structure */
7702 item = calloc(1, sizeof(*item));
7703 if (!item) {
7704 err = IE_NOMEM;
7705 goto leave;
7707 item->destructor = (void(*)(void**))isds_credit_event_free;
7708 if (i == 0) *history = item;
7709 else prev_item->next = item;
7710 prev_item = item;
7712 /* Extract it */
7713 xpath_ctx->node = result->nodesetval->nodeTab[i];
7714 err = extract_CiRecord(context,
7715 (struct isds_credit_event **) (&item->data),
7716 xpath_ctx);
7717 if (err) goto leave;
7721 leave:
7722 if (!err) {
7723 isds_log(ILF_ISDS, ILL_DEBUG,
7724 _("DataBoxCreditInfo request processed by server successfully.\n"));
7726 if (err) {
7727 isds_list_free(history);
7728 zfree(*email)
7731 free(box_id_locale);
7732 xmlXPathFreeObject(result);
7733 xmlXPathFreeContext(xpath_ctx);
7734 xmlFreeDoc(response);
7736 #else /* not HAVE_LIBCURL */
7737 err = IE_NOTSUP;
7738 #endif
7740 return err;
7744 /* Build ISDS request of XSD tIdDbInput type, sent it, check for error
7745 * code, destroy response and log success.
7746 * @context is ISDS session context.
7747 * @service_name is name of SERVICE_DB_MANIPULATION service
7748 * @box_id is UTF-8 encoded box identifier as zero terminated string
7749 * @approval is optional external approval of box manipulation
7750 * @refnumber is reallocated serial number of request assigned by ISDS. Use
7751 * NULL, if you don't care. */
7752 static isds_error build_send_manipulationdbid_request_check_drop_response(
7753 struct isds_ctx *context, const xmlChar *service_name,
7754 const xmlChar *box_id, const struct isds_approval *approval,
7755 xmlChar **refnumber) {
7756 isds_error err = IE_SUCCESS;
7757 #if HAVE_LIBCURL
7758 xmlDocPtr response = NULL;
7759 #endif
7761 if (!context) return IE_INVALID_CONTEXT;
7762 zfree(context->long_message);
7763 if (!service_name || *service_name == '\0' || !box_id) return IE_INVAL;
7765 #if HAVE_LIBCURL
7766 /* Check if connection is established */
7767 if (!context->curl) return IE_CONNECTION_CLOSED;
7769 /* Do request and check for success */
7770 err = build_send_dbid_request_check_response(context,
7771 SERVICE_DB_MANIPULATION, service_name, NULL, box_id, approval,
7772 &response, refnumber);
7773 xmlFreeDoc(response);
7775 if (!err) {
7776 char *service_name_locale = _isds_utf82locale((char *) service_name);
7777 isds_log(ILF_ISDS, ILL_DEBUG,
7778 _("%s request processed by server successfully.\n"),
7779 service_name_locale);
7780 free(service_name_locale);
7782 #else /* not HAVE_LIBCURL */
7783 err = IE_NOTSUP;
7784 #endif
7786 return err;
7790 /* Switch box into state where box can receive commercial messages (off by
7791 * default)
7792 * @context is ISDS session context.
7793 * @box_id is UTF-8 encoded box identifier as zero terminated string
7794 * @allow is true for enable, false for disable commercial messages income
7795 * @approval is optional external approval of box manipulation
7796 * @refnumber is reallocated serial number of request assigned by ISDS. Use
7797 * NULL, if you don't care. */
7798 isds_error isds_switch_commercial_receiving(struct isds_ctx *context,
7799 const char *box_id, const _Bool allow,
7800 const struct isds_approval *approval, char **refnumber) {
7801 return build_send_manipulationdbid_request_check_drop_response(context,
7802 (allow) ? BAD_CAST "SetOpenAddressing" :
7803 BAD_CAST "ClearOpenAddressing",
7804 BAD_CAST box_id, approval, (xmlChar **) refnumber);
7808 /* Switch box into / out of state where non-OVM box can act as OVM (e.g. force
7809 * message acceptance). This is just a box permission. Sender must apply
7810 * such role by sending each message.
7811 * @context is ISDS session context.
7812 * @box_id is UTF-8 encoded box identifier as zero terminated string
7813 * @allow is true for enable, false for disable OVM role permission
7814 * @approval is optional external approval of box manipulation
7815 * @refnumber is reallocated serial number of request assigned by ISDS. Use
7816 * NULL, if you don't care. */
7817 isds_error isds_switch_effective_ovm(struct isds_ctx *context,
7818 const char *box_id, const _Bool allow,
7819 const struct isds_approval *approval, char **refnumber) {
7820 return build_send_manipulationdbid_request_check_drop_response(context,
7821 (allow) ? BAD_CAST "SetEffectiveOVM" :
7822 BAD_CAST "ClearEffectiveOVM",
7823 BAD_CAST box_id, approval, (xmlChar **) refnumber);
7827 /* Build ISDS request of XSD tOwnerInfoInput type, sent it, check for error
7828 * code, destroy response and log success.
7829 * @context is ISDS session context.
7830 * @service_name is name of SERVICE_DB_MANIPULATION service
7831 * @owner is structure describing box
7832 * @approval is optional external approval of box manipulation
7833 * @refnumber is reallocated serial number of request assigned by ISDS. Use
7834 * NULL, if you don't care. */
7835 static isds_error build_send_manipulationdbowner_request_check_drop_response(
7836 struct isds_ctx *context, const xmlChar *service_name,
7837 const struct isds_DbOwnerInfo *owner,
7838 const struct isds_approval *approval, xmlChar **refnumber) {
7839 isds_error err = IE_SUCCESS;
7840 #if HAVE_LIBCURL
7841 char *service_name_locale = NULL;
7842 xmlNodePtr request = NULL, db_owner_info;
7843 xmlNsPtr isds_ns = NULL;
7844 #endif
7847 if (!context) return IE_INVALID_CONTEXT;
7848 zfree(context->long_message);
7849 if (!service_name || *service_name == '\0' || !owner) return IE_INVAL;
7851 #if HAVE_LIBCURL
7852 service_name_locale = _isds_utf82locale((char*)service_name);
7853 if (!service_name_locale) {
7854 err = IE_NOMEM;
7855 goto leave;
7858 /* Build request */
7859 request = xmlNewNode(NULL, service_name);
7860 if (!request) {
7861 isds_printf_message(context,
7862 _("Could not build %s request"), service_name_locale);
7863 err = IE_ERROR;
7864 goto leave;
7866 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
7867 if(!isds_ns) {
7868 isds_log_message(context, _("Could not create ISDS name space"));
7869 err = IE_ERROR;
7870 goto leave;
7872 xmlSetNs(request, isds_ns);
7875 /* Add XSD:tOwnerInfoInput child*/
7876 INSERT_ELEMENT(db_owner_info, request, "dbOwnerInfo");
7877 err = insert_DbOwnerInfo(context, owner, db_owner_info);
7878 if (err) goto leave;
7880 /* Add XSD:gExtApproval*/
7881 err = insert_GExtApproval(context, approval, request);
7882 if (err) goto leave;
7884 /* Send it to server and process response */
7885 err = send_request_check_drop_response(context, SERVICE_DB_MANIPULATION,
7886 service_name, &request, refnumber);
7888 leave:
7889 xmlFreeNode(request);
7890 free(service_name_locale);
7891 #else /* not HAVE_LIBCURL */
7892 err = IE_NOTSUP;
7893 #endif
7895 return err;
7899 /* Switch box accessibility state on request of box owner.
7900 * Despite the name, owner must do the request off-line. This function is
7901 * designed for such off-line meeting points (e.g. Czech POINT).
7902 * @context is ISDS session context.
7903 * @box identifies box to switch accessibility state.
7904 * @allow is true for making accessible, false to disallow access.
7905 * @approval is optional external approval of box manipulation
7906 * @refnumber is reallocated serial number of request assigned by ISDS. Use
7907 * NULL, if you don't care. */
7908 isds_error isds_switch_box_accessibility_on_owner_request(
7909 struct isds_ctx *context, const struct isds_DbOwnerInfo *box,
7910 const _Bool allow, const struct isds_approval *approval,
7911 char **refnumber) {
7912 return build_send_manipulationdbowner_request_check_drop_response(context,
7913 (allow) ? BAD_CAST "EnableOwnDataBox" :
7914 BAD_CAST "DisableOwnDataBox",
7915 box, approval, (xmlChar **) refnumber);
7919 /* Disable box accessibility on law enforcement (e.g. by prison) since exact
7920 * date.
7921 * @context is ISDS session context.
7922 * @box identifies box to switch accessibility state.
7923 * @since is date since accessibility has been denied. This can be past too.
7924 * Only tm_year, tm_mon and tm_mday carry sane value.
7925 * @approval is optional external approval of box manipulation
7926 * @refnumber is reallocated serial number of request assigned by ISDS. Use
7927 * NULL, if you don't care. */
7928 isds_error isds_disable_box_accessibility_externaly(
7929 struct isds_ctx *context, const struct isds_DbOwnerInfo *box,
7930 const struct tm *since, const struct isds_approval *approval,
7931 char **refnumber) {
7932 isds_error err = IE_SUCCESS;
7933 #if HAVE_LIBCURL
7934 char *service_name_locale = NULL;
7935 xmlNodePtr request = NULL, node;
7936 xmlNsPtr isds_ns = NULL;
7937 xmlChar *string = NULL;
7938 #endif
7941 if (!context) return IE_INVALID_CONTEXT;
7942 zfree(context->long_message);
7943 if (!box || !since) return IE_INVAL;
7945 #if HAVE_LIBCURL
7946 /* Build request */
7947 request = xmlNewNode(NULL, BAD_CAST "DisableDataBoxExternally");
7948 if (!request) {
7949 isds_printf_message(context,
7950 _("Could not build %s request"), "DisableDataBoxExternally");
7951 err = IE_ERROR;
7952 goto leave;
7954 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
7955 if(!isds_ns) {
7956 isds_log_message(context, _("Could not create ISDS name space"));
7957 err = IE_ERROR;
7958 goto leave;
7960 xmlSetNs(request, isds_ns);
7963 /* Add @box identification */
7964 INSERT_ELEMENT(node, request, "dbOwnerInfo");
7965 err = insert_DbOwnerInfo(context, box, node);
7966 if (err) goto leave;
7968 /* Add @since date */
7969 err = tm2datestring(since, &string);
7970 if(err) {
7971 isds_log_message(context,
7972 _("Could not convert `since' argument to ISO date string"));
7973 goto leave;
7975 INSERT_STRING(request, "dbOwnerDisableDate", string);
7976 zfree(string);
7978 /* Add @approval */
7979 err = insert_GExtApproval(context, approval, request);
7980 if (err) goto leave;
7982 /* Send it to server and process response */
7983 err = send_request_check_drop_response(context, SERVICE_DB_MANIPULATION,
7984 BAD_CAST "DisableDataBoxExternally", &request,
7985 (xmlChar **) refnumber);
7987 leave:
7988 free(string);
7989 xmlFreeNode(request);
7990 free(service_name_locale);
7991 #else /* not HAVE_LIBCURL */
7992 err = IE_NOTSUP;
7993 #endif
7995 return err;
7999 #if HAVE_LIBCURL
8000 /* Insert struct isds_message data (envelope (recipient data optional) and
8001 * documents into XML tree
8002 * @context is session context
8003 * @outgoing_message is libisds structure with message data
8004 * @create_message is XML CreateMessage or CreateMultipleMessage element
8005 * @process_recipient true for recipient data serialization, false for no
8006 * serialization */
8007 static isds_error insert_envelope_files(struct isds_ctx *context,
8008 const struct isds_message *outgoing_message, xmlNodePtr create_message,
8009 const _Bool process_recipient) {
8011 isds_error err = IE_SUCCESS;
8012 xmlNodePtr envelope, dm_files, node;
8013 xmlChar *string = NULL;
8015 if (!context) return IE_INVALID_CONTEXT;
8016 if (!outgoing_message || !create_message) return IE_INVAL;
8019 /* Build envelope */
8020 envelope = xmlNewChild(create_message, NULL, BAD_CAST "dmEnvelope", NULL);
8021 if (!envelope) {
8022 isds_printf_message(context, _("Could not add dmEnvelope child to "
8023 "%s element"), create_message->name);
8024 return IE_ERROR;
8027 if (!outgoing_message->envelope) {
8028 isds_log_message(context, _("Outgoing message is missing envelope"));
8029 err = IE_INVAL;
8030 goto leave;
8033 /* Insert optional message type */
8034 err = insert_message_type(context, outgoing_message->envelope->dmType,
8035 envelope);
8036 if (err) goto leave;
8038 INSERT_STRING(envelope, "dmSenderOrgUnit",
8039 outgoing_message->envelope->dmSenderOrgUnit);
8040 INSERT_LONGINT(envelope, "dmSenderOrgUnitNum",
8041 outgoing_message->envelope->dmSenderOrgUnitNum, string);
8043 if (process_recipient) {
8044 if (!outgoing_message->envelope->dbIDRecipient) {
8045 isds_log_message(context,
8046 _("Outgoing message is missing recipient box identifier"));
8047 err = IE_INVAL;
8048 goto leave;
8050 INSERT_STRING(envelope, "dbIDRecipient",
8051 outgoing_message->envelope->dbIDRecipient);
8053 INSERT_STRING(envelope, "dmRecipientOrgUnit",
8054 outgoing_message->envelope->dmRecipientOrgUnit);
8055 INSERT_LONGINT(envelope, "dmRecipientOrgUnitNum",
8056 outgoing_message->envelope->dmRecipientOrgUnitNum, string);
8057 INSERT_STRING(envelope, "dmToHands",
8058 outgoing_message->envelope->dmToHands);
8061 CHECK_FOR_STRING_LENGTH(outgoing_message->envelope->dmAnnotation, 0, 255,
8062 "dmAnnotation");
8063 INSERT_STRING(envelope, "dmAnnotation",
8064 outgoing_message->envelope->dmAnnotation);
8066 CHECK_FOR_STRING_LENGTH(outgoing_message->envelope->dmRecipientRefNumber,
8067 0, 50, "dmRecipientRefNumber");
8068 INSERT_STRING(envelope, "dmRecipientRefNumber",
8069 outgoing_message->envelope->dmRecipientRefNumber);
8071 CHECK_FOR_STRING_LENGTH(outgoing_message->envelope->dmSenderRefNumber,
8072 0, 50, "dmSenderRefNumber");
8073 INSERT_STRING(envelope, "dmSenderRefNumber",
8074 outgoing_message->envelope->dmSenderRefNumber);
8076 CHECK_FOR_STRING_LENGTH(outgoing_message->envelope->dmRecipientIdent,
8077 0, 50, "dmRecipientIdent");
8078 INSERT_STRING(envelope, "dmRecipientIdent",
8079 outgoing_message->envelope->dmRecipientIdent);
8081 CHECK_FOR_STRING_LENGTH(outgoing_message->envelope->dmSenderIdent,
8082 0, 50, "dmSenderIdent");
8083 INSERT_STRING(envelope, "dmSenderIdent",
8084 outgoing_message->envelope->dmSenderIdent);
8086 INSERT_LONGINT(envelope, "dmLegalTitleLaw",
8087 outgoing_message->envelope->dmLegalTitleLaw, string);
8088 INSERT_LONGINT(envelope, "dmLegalTitleYear",
8089 outgoing_message->envelope->dmLegalTitleYear, string);
8090 INSERT_STRING(envelope, "dmLegalTitleSect",
8091 outgoing_message->envelope->dmLegalTitleSect);
8092 INSERT_STRING(envelope, "dmLegalTitlePar",
8093 outgoing_message->envelope->dmLegalTitlePar);
8094 INSERT_STRING(envelope, "dmLegalTitlePoint",
8095 outgoing_message->envelope->dmLegalTitlePoint);
8097 INSERT_BOOLEAN(envelope, "dmPersonalDelivery",
8098 outgoing_message->envelope->dmPersonalDelivery);
8099 INSERT_BOOLEAN(envelope, "dmAllowSubstDelivery",
8100 outgoing_message->envelope->dmAllowSubstDelivery);
8102 /* ???: Should we require value for dbEffectiveOVM sender?
8103 * ISDS has default as true */
8104 INSERT_BOOLEAN(envelope, "dmOVM", outgoing_message->envelope->dmOVM);
8105 INSERT_BOOLEAN(envelope, "dmOVM",
8106 outgoing_message->envelope->dmPublishOwnID);
8109 /* Append dmFiles */
8110 if (!outgoing_message->documents) {
8111 isds_log_message(context,
8112 _("Outgoing message is missing list of documents"));
8113 err = IE_INVAL;
8114 goto leave;
8116 dm_files = xmlNewChild(create_message, NULL, BAD_CAST "dmFiles", NULL);
8117 if (!dm_files) {
8118 isds_printf_message(context, _("Could not add dmFiles child to "
8119 "%s element"), create_message->name);
8120 err = IE_ERROR;
8121 goto leave;
8124 /* Check for document hierarchy */
8125 err = _isds_check_documents_hierarchy(context, outgoing_message->documents);
8126 if (err) goto leave;
8128 /* Process each document */
8129 for (struct isds_list *item =
8130 (struct isds_list *) outgoing_message->documents;
8131 item; item = item->next) {
8132 if (!item->data) {
8133 isds_log_message(context,
8134 _("List of documents contains empty item"));
8135 err = IE_INVAL;
8136 goto leave;
8138 /* FIXME: Check for dmFileMetaType and for document references.
8139 * Only first document can be of MAIN type */
8140 err = insert_document(context, (struct isds_document*) item->data,
8141 dm_files);
8143 if (err) goto leave;
8146 leave:
8147 free(string);
8148 return err;
8150 #endif /* HAVE_LIBCURL */
8153 /* Send a message via ISDS to a recipient
8154 * @context is session context
8155 * @outgoing_message is message to send; Some members are mandatory (like
8156 * dbIDRecipient), some are optional and some are irrelevant (especially data
8157 * about sender). Included pointer to isds_list documents must contain at
8158 * least one document of FILEMETATYPE_MAIN. This is read-write structure, some
8159 * members will be filled with valid data from ISDS. Exact list of write
8160 * members is subject to change. Currently dmID is changed.
8161 * @return ISDS_SUCCESS, or other error code if something goes wrong. */
8162 isds_error isds_send_message(struct isds_ctx *context,
8163 struct isds_message *outgoing_message) {
8165 isds_error err = IE_SUCCESS;
8166 #if HAVE_LIBCURL
8167 xmlNsPtr isds_ns = NULL;
8168 xmlNodePtr request = NULL;
8169 xmlDocPtr response = NULL;
8170 xmlChar *code = NULL, *message = NULL;
8171 xmlXPathContextPtr xpath_ctx = NULL;
8172 xmlXPathObjectPtr result = NULL;
8173 /*_Bool message_is_complete = 0;*/
8174 #endif
8176 if (!context) return IE_INVALID_CONTEXT;
8177 zfree(context->long_message);
8178 if (!outgoing_message) return IE_INVAL;
8180 #if HAVE_LIBCURL
8181 /* Check if connection is established
8182 * TODO: This check should be done downstairs. */
8183 if (!context->curl) return IE_CONNECTION_CLOSED;
8186 /* Build CreateMessage request */
8187 request = xmlNewNode(NULL, BAD_CAST "CreateMessage");
8188 if (!request) {
8189 isds_log_message(context,
8190 _("Could not build CreateMessage request"));
8191 return IE_ERROR;
8193 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
8194 if(!isds_ns) {
8195 isds_log_message(context, _("Could not create ISDS name space"));
8196 xmlFreeNode(request);
8197 return IE_ERROR;
8199 xmlSetNs(request, isds_ns);
8201 /* Append envelope and files */
8202 err = insert_envelope_files(context, outgoing_message, request, 1);
8203 if (err) goto leave;
8206 /* Signal we can serialize message since now */
8207 /*message_is_complete = 1;*/
8210 isds_log(ILF_ISDS, ILL_DEBUG, _("Sending CreateMessage request to ISDS\n"));
8212 /* Sent request */
8213 err = isds(context, SERVICE_DM_OPERATIONS, request, &response, NULL, NULL);
8215 /* Don't' destroy request, we want to provide it to application later */
8217 if (err) {
8218 isds_log(ILF_ISDS, ILL_DEBUG,
8219 _("Processing ISDS response on CreateMessage "
8220 "request failed\n"));
8221 goto leave;
8224 /* Check for response status */
8225 err = isds_response_status(context, SERVICE_DM_OPERATIONS, response,
8226 &code, &message, NULL);
8227 if (err) {
8228 isds_log(ILF_ISDS, ILL_DEBUG,
8229 _("ISDS response on CreateMessage request "
8230 "is missing status\n"));
8231 goto leave;
8234 /* Request processed, but refused by server or server failed */
8235 if (xmlStrcmp(code, BAD_CAST "0000")) {
8236 char *box_id_locale =
8237 _isds_utf82locale((char*)outgoing_message->envelope->dbIDRecipient);
8238 char *code_locale = _isds_utf82locale((char*)code);
8239 char *message_locale = _isds_utf82locale((char*)message);
8240 isds_log(ILF_ISDS, ILL_DEBUG,
8241 _("Server did not accept message for %s on CreateMessage "
8242 "request (code=%s, message=%s)\n"),
8243 box_id_locale, code_locale, message_locale);
8244 isds_log_message(context, message_locale);
8245 free(box_id_locale);
8246 free(code_locale);
8247 free(message_locale);
8248 err = IE_ISDS;
8249 goto leave;
8253 /* Extract data */
8254 xpath_ctx = xmlXPathNewContext(response);
8255 if (!xpath_ctx) {
8256 err = IE_ERROR;
8257 goto leave;
8259 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
8260 err = IE_ERROR;
8261 goto leave;
8263 result = xmlXPathEvalExpression(BAD_CAST "/isds:CreateMessageResponse",
8264 xpath_ctx);
8265 if (!result) {
8266 err = IE_ERROR;
8267 goto leave;
8269 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
8270 isds_log_message(context, _("Missing CreateMessageResponse element"));
8271 err = IE_ISDS;
8272 goto leave;
8274 if (result->nodesetval->nodeNr > 1) {
8275 isds_log_message(context, _("Multiple CreateMessageResponse element"));
8276 err = IE_ISDS;
8277 goto leave;
8279 xpath_ctx->node = result->nodesetval->nodeTab[0];
8280 xmlXPathFreeObject(result); result = NULL;
8282 if (outgoing_message->envelope->dmID) {
8283 free(outgoing_message->envelope->dmID);
8284 outgoing_message->envelope->dmID = NULL;
8286 EXTRACT_STRING("isds:dmID", outgoing_message->envelope->dmID);
8287 if (!outgoing_message->envelope->dmID) {
8288 isds_log(ILF_ISDS, ILL_ERR, _("Server accepted sent message, "
8289 "but did not return assigned message ID\n"));
8292 leave:
8293 /* TODO: Serialize message into structure member raw */
8294 /* XXX: Each web service transport message in different format.
8295 * Therefore it's not possible to save them directly.
8296 * To save them, one must figure out common format.
8297 * We can leave it on application, or we can implement the ESS format. */
8298 /*if (message_is_complete) {
8299 if (outgoing_message->envelope->dmID) {
8301 /* Add assigned message ID as first child*/
8302 /*xmlNodePtr dmid_text = xmlNewText(
8303 (xmlChar *) outgoing_message->envelope->dmID);
8304 if (!dmid_text) goto serialization_failed;
8306 xmlNodePtr dmid_element = xmlNewNode(envelope->ns,
8307 BAD_CAST "dmID");
8308 if (!dmid_element) {
8309 xmlFreeNode(dmid_text);
8310 goto serialization_failed;
8313 xmlNodePtr dmid_element_with_text =
8314 xmlAddChild(dmid_element, dmid_text);
8315 if (!dmid_element_with_text) {
8316 xmlFreeNode(dmid_element);
8317 xmlFreeNode(dmid_text);
8318 goto serialization_failed;
8321 node = xmlAddPrevSibling(envelope->childern,
8322 dmid_element_with_text);
8323 if (!node) {
8324 xmlFreeNodeList(dmid_element_with_text);
8325 goto serialization_failed;
8329 /* Serialize message with ID into raw */
8330 /*buffer = serialize_element(envelope)*/
8331 /* }
8333 serialization_failed:
8337 /* Clean up */
8338 xmlXPathFreeObject(result);
8339 xmlXPathFreeContext(xpath_ctx);
8341 free(code);
8342 free(message);
8343 xmlFreeDoc(response);
8344 xmlFreeNode(request);
8346 if (!err)
8347 isds_log(ILF_ISDS, ILL_DEBUG,
8348 _("CreateMessage request processed by server "
8349 "successfully.\n"));
8350 #else /* not HAVE_LIBCURL */
8351 err = IE_NOTSUP;
8352 #endif
8354 return err;
8358 /* Send a message via ISDS to a multiple recipients
8359 * @context is session context
8360 * @outgoing_message is message to send; Some members are mandatory,
8361 * some are optional and some are irrelevant (especially data
8362 * about sender). Data about recipient will be substituted by ISDS from
8363 * @copies. Included pointer to isds_list documents must
8364 * contain at least one document of FILEMETATYPE_MAIN.
8365 * @copies is list of isds_message_copy structures addressing all desired
8366 * recipients. This is read-write structure, some members will be filled with
8367 * valid data from ISDS (message IDs, error codes, error descriptions).
8368 * @return
8369 * ISDS_SUCCESS if all messages have been sent
8370 * ISDS_PARTIAL_SUCCESS if sending of some messages has failed (failed and
8371 * succeeded messages can be identified by copies->data->error),
8372 * or other error code if something other goes wrong. */
8373 isds_error isds_send_message_to_multiple_recipients(struct isds_ctx *context,
8374 const struct isds_message *outgoing_message,
8375 struct isds_list *copies) {
8377 isds_error err = IE_SUCCESS;
8378 #if HAVE_LIBCURL
8379 isds_error append_err;
8380 xmlNsPtr isds_ns = NULL;
8381 xmlNodePtr request = NULL, recipients, recipient, node;
8382 struct isds_list *item;
8383 struct isds_message_copy *copy;
8384 xmlDocPtr response = NULL;
8385 xmlChar *code = NULL, *message = NULL;
8386 xmlXPathContextPtr xpath_ctx = NULL;
8387 xmlXPathObjectPtr result = NULL;
8388 xmlChar *string = NULL;
8389 int i;
8390 #endif
8392 if (!context) return IE_INVALID_CONTEXT;
8393 zfree(context->long_message);
8394 if (!outgoing_message || !copies) return IE_INVAL;
8396 #if HAVE_LIBCURL
8397 /* Check if connection is established
8398 * TODO: This check should be done downstairs. */
8399 if (!context->curl) return IE_CONNECTION_CLOSED;
8402 /* Build CreateMultipleMessage request */
8403 request = xmlNewNode(NULL, BAD_CAST "CreateMultipleMessage");
8404 if (!request) {
8405 isds_log_message(context,
8406 _("Could not build CreateMultipleMessage request"));
8407 return IE_ERROR;
8409 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
8410 if(!isds_ns) {
8411 isds_log_message(context, _("Could not create ISDS name space"));
8412 xmlFreeNode(request);
8413 return IE_ERROR;
8415 xmlSetNs(request, isds_ns);
8418 /* Build recipients */
8419 recipients = xmlNewChild(request, NULL, BAD_CAST "dmRecipients", NULL);
8420 if (!recipients) {
8421 isds_log_message(context, _("Could not add dmRecipients child to "
8422 "CreateMultipleMessage element"));
8423 xmlFreeNode(request);
8424 return IE_ERROR;
8427 /* Insert each recipient */
8428 for (item = copies; item; item = item->next) {
8429 copy = (struct isds_message_copy *) item->data;
8430 if (!copy) {
8431 isds_log_message(context,
8432 _("`copies' list item contains empty data"));
8433 err = IE_INVAL;
8434 goto leave;
8437 recipient = xmlNewChild(recipients, NULL, BAD_CAST "dmRecipient", NULL);
8438 if (!recipient) {
8439 isds_log_message(context, _("Could not add dmRecipient child to "
8440 "dmRecipients element"));
8441 err = IE_ERROR;
8442 goto leave;
8445 if (!copy->dbIDRecipient) {
8446 isds_log_message(context,
8447 _("Message copy is missing recipient box identifier"));
8448 err = IE_INVAL;
8449 goto leave;
8451 INSERT_STRING(recipient, "dbIDRecipient", copy->dbIDRecipient);
8452 INSERT_STRING(recipient, "dmRecipientOrgUnit",
8453 copy->dmRecipientOrgUnit);
8454 INSERT_LONGINT(recipient, "dmRecipientOrgUnitNum",
8455 copy->dmRecipientOrgUnitNum, string);
8456 INSERT_STRING(recipient, "dmToHands", copy->dmToHands);
8459 /* Append envelope and files */
8460 err = insert_envelope_files(context, outgoing_message, request, 0);
8461 if (err) goto leave;
8464 isds_log(ILF_ISDS, ILL_DEBUG,
8465 _("Sending CreateMultipleMessage request to ISDS\n"));
8467 /* Sent request */
8468 err = isds(context, SERVICE_DM_OPERATIONS, request, &response, NULL, NULL);
8469 if (err) {
8470 isds_log(ILF_ISDS, ILL_DEBUG,
8471 _("Processing ISDS response on CreateMultipleMessage "
8472 "request failed\n"));
8473 goto leave;
8476 /* Check for response status */
8477 err = isds_response_status(context, SERVICE_DM_OPERATIONS, response,
8478 &code, &message, NULL);
8479 if (err) {
8480 isds_log(ILF_ISDS, ILL_DEBUG,
8481 _("ISDS response on CreateMultipleMessage request "
8482 "is missing status\n"));
8483 goto leave;
8486 /* Request processed, but some copies failed */
8487 if (!xmlStrcmp(code, BAD_CAST "0004")) {
8488 char *box_id_locale =
8489 _isds_utf82locale((char*)outgoing_message->envelope->dbIDRecipient);
8490 char *code_locale = _isds_utf82locale((char*)code);
8491 char *message_locale = _isds_utf82locale((char*)message);
8492 isds_log(ILF_ISDS, ILL_DEBUG,
8493 _("Server did accept message for multiple recipients "
8494 "on CreateMultipleMessage request but delivery to "
8495 "some of them failed (code=%s, message=%s)\n"),
8496 box_id_locale, code_locale, message_locale);
8497 isds_log_message(context, message_locale);
8498 free(box_id_locale);
8499 free(code_locale);
8500 free(message_locale);
8501 err = IE_PARTIAL_SUCCESS;
8504 /* Request refused by server as whole */
8505 else if (xmlStrcmp(code, BAD_CAST "0000")) {
8506 char *box_id_locale =
8507 _isds_utf82locale((char*)outgoing_message->envelope->dbIDRecipient);
8508 char *code_locale = _isds_utf82locale((char*)code);
8509 char *message_locale = _isds_utf82locale((char*)message);
8510 isds_log(ILF_ISDS, ILL_DEBUG,
8511 _("Server did not accept message for multiple recipients "
8512 "on CreateMultipleMessage request (code=%s, message=%s)\n"),
8513 box_id_locale, code_locale, message_locale);
8514 isds_log_message(context, message_locale);
8515 free(box_id_locale);
8516 free(code_locale);
8517 free(message_locale);
8518 err = IE_ISDS;
8519 goto leave;
8523 /* Extract data */
8524 xpath_ctx = xmlXPathNewContext(response);
8525 if (!xpath_ctx) {
8526 err = IE_ERROR;
8527 goto leave;
8529 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
8530 err = IE_ERROR;
8531 goto leave;
8533 result = xmlXPathEvalExpression(
8534 BAD_CAST "/isds:CreateMultipleMessageResponse"
8535 "/isds:dmMultipleStatus/isds:dmSingleStatus",
8536 xpath_ctx);
8537 if (!result) {
8538 err = IE_ERROR;
8539 goto leave;
8541 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
8542 isds_log_message(context, _("Missing isds:dmSingleStatus element"));
8543 err = IE_ISDS;
8544 goto leave;
8547 /* Extract message ID and delivery status for each copy */
8548 for (item = copies, i = 0; item && i < result->nodesetval->nodeNr;
8549 item = item->next, i++) {
8550 copy = (struct isds_message_copy *) item->data;
8551 xpath_ctx->node = result->nodesetval->nodeTab[i];
8553 append_err = append_TMStatus(context, copy, xpath_ctx);
8554 if (append_err) {
8555 err = append_err;
8556 goto leave;
8559 if (item || i < result->nodesetval->nodeNr) {
8560 isds_printf_message(context, _("ISDS returned unexpected number of "
8561 "message copy delivery states: %d"),
8562 result->nodesetval->nodeNr);
8563 err = IE_ISDS;
8564 goto leave;
8568 leave:
8569 /* Clean up */
8570 free(string);
8571 xmlXPathFreeObject(result);
8572 xmlXPathFreeContext(xpath_ctx);
8574 free(code);
8575 free(message);
8576 xmlFreeDoc(response);
8577 xmlFreeNode(request);
8579 if (!err)
8580 isds_log(ILF_ISDS, ILL_DEBUG,
8581 _("CreateMultipleMessageResponse request processed by server "
8582 "successfully.\n"));
8583 #else /* not HAVE_LIBCURL */
8584 err = IE_NOTSUP;
8585 #endif
8587 return err;
8591 /* Get list of messages. This is common core for getting sent or received
8592 * messages.
8593 * Any criterion argument can be NULL, if you don't care about it.
8594 * @context is session context. Must not be NULL.
8595 * @outgoing_direction is true if you want list of outgoing messages,
8596 * it's false if you want incoming messages.
8597 * @from_time is minimal time and date of message sending inclusive.
8598 * @to_time is maximal time and date of message sending inclusive
8599 * @organization_unit_number is number of sender/recipient respectively.
8600 * @status_filter is bit field of isds_message_status values. Use special
8601 * value MESSAGESTATE_ANY to signal you don't care. (It's defined as union of
8602 * all values, you can use bit-wise arithmetic if you want.)
8603 * @offset is index of first message we are interested in. First message is 1.
8604 * Set to 0 (or 1) if you don't care.
8605 * @number is maximal length of list you want to get as input value, outputs
8606 * number of messages matching these criteria. Can be NULL if you don't care
8607 * (applies to output value either).
8608 * @messages is automatically reallocated list of isds_message's. Be ware that
8609 * it returns only brief overview (envelope and some other fields) about each
8610 * message, not the complete message. FIXME: Specify exact fields.
8611 * The list is sorted by delivery time in ascending order.
8612 * Use NULL if you don't care about don't need the data (useful if you want to
8613 * know only the @number). If you provide &NULL, list will be allocated on
8614 * heap, if you provide pointer to non-NULL, list will be freed automatically
8615 * at first. Also in case of error the list will be NULLed.
8616 * @return IE_SUCCESS or appropriate error code. */
8617 static isds_error isds_get_list_of_messages(struct isds_ctx *context,
8618 _Bool outgoing_direction,
8619 const struct timeval *from_time, const struct timeval *to_time,
8620 const long int *organization_unit_number,
8621 const unsigned int status_filter,
8622 const unsigned long int offset, unsigned long int *number,
8623 struct isds_list **messages) {
8625 isds_error err = IE_SUCCESS;
8626 #if HAVE_LIBCURL
8627 xmlNsPtr isds_ns = NULL;
8628 xmlNodePtr request = NULL, node;
8629 xmlDocPtr response = NULL;
8630 xmlChar *code = NULL, *message = NULL;
8631 xmlXPathContextPtr xpath_ctx = NULL;
8632 xmlXPathObjectPtr result = NULL;
8633 xmlChar *string = NULL;
8634 long unsigned int count = 0;
8635 #endif
8637 if (!context) return IE_INVALID_CONTEXT;
8638 zfree(context->long_message);
8640 /* Free former message list if any */
8641 if (messages) isds_list_free(messages);
8643 #if HAVE_LIBCURL
8644 /* Check if connection is established
8645 * TODO: This check should be done downstairs. */
8646 if (!context->curl) return IE_CONNECTION_CLOSED;
8648 /* Build GetListOf*Messages request */
8649 request = xmlNewNode(NULL,
8650 (outgoing_direction) ?
8651 BAD_CAST "GetListOfSentMessages" :
8652 BAD_CAST "GetListOfReceivedMessages"
8654 if (!request) {
8655 isds_log_message(context,
8656 (outgoing_direction) ?
8657 _("Could not build GetListOfSentMessages request") :
8658 _("Could not build GetListOfReceivedMessages request")
8660 return IE_ERROR;
8662 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
8663 if(!isds_ns) {
8664 isds_log_message(context, _("Could not create ISDS name space"));
8665 xmlFreeNode(request);
8666 return IE_ERROR;
8668 xmlSetNs(request, isds_ns);
8671 if (from_time) {
8672 err = timeval2timestring(from_time, &string);
8673 if (err) goto leave;
8675 INSERT_STRING(request, "dmFromTime", string);
8676 free(string); string = NULL;
8678 if (to_time) {
8679 err = timeval2timestring(to_time, &string);
8680 if (err) goto leave;
8682 INSERT_STRING(request, "dmToTime", string);
8683 free(string); string = NULL;
8685 if (outgoing_direction) {
8686 INSERT_LONGINT(request, "dmSenderOrgUnitNum",
8687 organization_unit_number, string);
8688 } else {
8689 INSERT_LONGINT(request, "dmRecipientOrgUnitNum",
8690 organization_unit_number, string);
8693 if (status_filter > MESSAGESTATE_ANY) {
8694 isds_printf_message(context,
8695 _("Invalid message state filter value: %ld"), status_filter);
8696 err = IE_INVAL;
8697 goto leave;
8699 INSERT_ULONGINTNOPTR(request, "dmStatusFilter", status_filter, string);
8701 if (offset > 0 ) {
8702 INSERT_ULONGINTNOPTR(request, "dmOffset", offset, string);
8703 } else {
8704 INSERT_STRING(request, "dmOffset", "1");
8707 /* number 0 means no limit */
8708 if (number && *number == 0) {
8709 INSERT_STRING(request, "dmLimit", NULL);
8710 } else {
8711 INSERT_ULONGINT(request, "dmLimit", number, string);
8715 isds_log(ILF_ISDS, ILL_DEBUG,
8716 (outgoing_direction) ?
8717 _("Sending GetListOfSentMessages request to ISDS\n") :
8718 _("Sending GetListOfReceivedMessages request to ISDS\n")
8721 /* Sent request */
8722 err = isds(context, SERVICE_DM_INFO, request, &response, NULL, NULL);
8723 xmlFreeNode(request); request = NULL;
8725 if (err) {
8726 isds_log(ILF_ISDS, ILL_DEBUG,
8727 (outgoing_direction) ?
8728 _("Processing ISDS response on GetListOfSentMessages "
8729 "request failed\n") :
8730 _("Processing ISDS response on GetListOfReceivedMessages "
8731 "request failed\n")
8733 goto leave;
8736 /* Check for response status */
8737 err = isds_response_status(context, SERVICE_DM_INFO, response,
8738 &code, &message, NULL);
8739 if (err) {
8740 isds_log(ILF_ISDS, ILL_DEBUG,
8741 (outgoing_direction) ?
8742 _("ISDS response on GetListOfSentMessages request "
8743 "is missing status\n") :
8744 _("ISDS response on GetListOfReceivedMessages request "
8745 "is missing status\n")
8747 goto leave;
8750 /* Request processed, but nothing found */
8751 if (xmlStrcmp(code, BAD_CAST "0000")) {
8752 char *code_locale = _isds_utf82locale((char*)code);
8753 char *message_locale = _isds_utf82locale((char*)message);
8754 isds_log(ILF_ISDS, ILL_DEBUG,
8755 (outgoing_direction) ?
8756 _("Server refused GetListOfSentMessages request "
8757 "(code=%s, message=%s)\n") :
8758 _("Server refused GetListOfReceivedMessages request "
8759 "(code=%s, message=%s)\n"),
8760 code_locale, message_locale);
8761 isds_log_message(context, message_locale);
8762 free(code_locale);
8763 free(message_locale);
8764 err = IE_ISDS;
8765 goto leave;
8769 /* Extract data */
8770 xpath_ctx = xmlXPathNewContext(response);
8771 if (!xpath_ctx) {
8772 err = IE_ERROR;
8773 goto leave;
8775 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
8776 err = IE_ERROR;
8777 goto leave;
8779 result = xmlXPathEvalExpression(
8780 (outgoing_direction) ?
8781 BAD_CAST "/isds:GetListOfSentMessagesResponse/"
8782 "isds:dmRecords/isds:dmRecord" :
8783 BAD_CAST "/isds:GetListOfReceivedMessagesResponse/"
8784 "isds:dmRecords/isds:dmRecord",
8785 xpath_ctx);
8786 if (!result) {
8787 err = IE_ERROR;
8788 goto leave;
8791 /* Fill output arguments in */
8792 if (!xmlXPathNodeSetIsEmpty(result->nodesetval)) {
8793 struct isds_envelope *envelope;
8794 struct isds_list *item = NULL, *last_item = NULL;
8796 for (count = 0; count < result->nodesetval->nodeNr; count++) {
8797 /* Create new message */
8798 item = calloc(1, sizeof(*item));
8799 if (!item) {
8800 err = IE_NOMEM;
8801 goto leave;
8803 item->destructor = (void(*)(void**)) &isds_message_free;
8804 item->data = calloc(1, sizeof(struct isds_message));
8805 if (!item->data) {
8806 isds_list_free(&item);
8807 err = IE_NOMEM;
8808 goto leave;
8811 /* Extract envelope data */
8812 xpath_ctx->node = result->nodesetval->nodeTab[count];
8813 envelope = NULL;
8814 err = extract_DmRecord(context, &envelope, xpath_ctx);
8815 if (err) {
8816 isds_list_free(&item);
8817 goto leave;
8820 /* Attach extracted envelope */
8821 ((struct isds_message *) item->data)->envelope = envelope;
8823 /* Append new message into the list */
8824 if (!*messages) {
8825 *messages = last_item = item;
8826 } else {
8827 last_item->next = item;
8828 last_item = item;
8832 if (number) *number = count;
8834 leave:
8835 if (err) {
8836 isds_list_free(messages);
8839 free(string);
8840 xmlXPathFreeObject(result);
8841 xmlXPathFreeContext(xpath_ctx);
8843 free(code);
8844 free(message);
8845 xmlFreeDoc(response);
8846 xmlFreeNode(request);
8848 if (!err)
8849 isds_log(ILF_ISDS, ILL_DEBUG,
8850 (outgoing_direction) ?
8851 _("GetListOfSentMessages request processed by server "
8852 "successfully.\n") :
8853 _("GetListOfReceivedMessages request processed by server "
8854 "successfully.\n")
8856 #else /* not HAVE_LIBCURL */
8857 err = IE_NOTSUP;
8858 #endif
8859 return err;
8863 /* Get list of outgoing (already sent) messages.
8864 * Any criterion argument can be NULL, if you don't care about it.
8865 * @context is session context. Must not be NULL.
8866 * @from_time is minimal time and date of message sending inclusive.
8867 * @to_time is maximal time and date of message sending inclusive
8868 * @dmSenderOrgUnitNum is the same as isds_envelope.dmSenderOrgUnitNum
8869 * @status_filter is bit field of isds_message_status values. Use special
8870 * value MESSAGESTATE_ANY to signal you don't care. (It's defined as union of
8871 * all values, you can use bit-wise arithmetic if you want.)
8872 * @offset is index of first message we are interested in. First message is 1.
8873 * Set to 0 (or 1) if you don't care.
8874 * @number is maximal length of list you want to get as input value, outputs
8875 * number of messages matching these criteria. Can be NULL if you don't care
8876 * (applies to output value either).
8877 * @messages is automatically reallocated list of isds_message's. Be ware that
8878 * it returns only brief overview (envelope and some other fields) about each
8879 * message, not the complete message. FIXME: Specify exact fields.
8880 * The list is sorted by delivery time in ascending order.
8881 * Use NULL if you don't care about the meta data (useful if you want to know
8882 * only the @number). If you provide &NULL, list will be allocated on heap,
8883 * if you provide pointer to non-NULL, list will be freed automatically at
8884 * first. Also in case of error the list will be NULLed.
8885 * @return IE_SUCCESS or appropriate error code. */
8886 isds_error isds_get_list_of_sent_messages(struct isds_ctx *context,
8887 const struct timeval *from_time, const struct timeval *to_time,
8888 const long int *dmSenderOrgUnitNum, const unsigned int status_filter,
8889 const unsigned long int offset, unsigned long int *number,
8890 struct isds_list **messages) {
8892 return isds_get_list_of_messages(
8893 context, 1,
8894 from_time, to_time, dmSenderOrgUnitNum, status_filter,
8895 offset, number,
8896 messages);
8900 /* Get list of incoming (addressed to you) messages.
8901 * Any criterion argument can be NULL, if you don't care about it.
8902 * @context is session context. Must not be NULL.
8903 * @from_time is minimal time and date of message sending inclusive.
8904 * @to_time is maximal time and date of message sending inclusive
8905 * @dmRecipientOrgUnitNum is the same as isds_envelope.dmRecipientOrgUnitNum
8906 * @status_filter is bit field of isds_message_status values. Use special
8907 * value MESSAGESTATE_ANY to signal you don't care. (It's defined as union of
8908 * all values, you can use bit-wise arithmetic if you want.)
8909 * @offset is index of first message we are interested in. First message is 1.
8910 * Set to 0 (or 1) if you don't care.
8911 * @number is maximal length of list you want to get as input value, outputs
8912 * number of messages matching these criteria. Can be NULL if you don't care
8913 * (applies to output value either).
8914 * @messages is automatically reallocated list of isds_message's. Be ware that
8915 * it returns only brief overview (envelope and some other fields) about each
8916 * message, not the complete message. FIXME: Specify exact fields.
8917 * Use NULL if you don't care about the meta data (useful if you want to know
8918 * only the @number). If you provide &NULL, list will be allocated on heap,
8919 * if you provide pointer to non-NULL, list will be freed automatically at
8920 * first. Also in case of error the list will be NULLed.
8921 * @return IE_SUCCESS or appropriate error code. */
8922 isds_error isds_get_list_of_received_messages(struct isds_ctx *context,
8923 const struct timeval *from_time, const struct timeval *to_time,
8924 const long int *dmRecipientOrgUnitNum,
8925 const unsigned int status_filter,
8926 const unsigned long int offset, unsigned long int *number,
8927 struct isds_list **messages) {
8929 return isds_get_list_of_messages(
8930 context, 0,
8931 from_time, to_time, dmRecipientOrgUnitNum, status_filter,
8932 offset, number,
8933 messages);
8937 /* Get list of sent message state changes.
8938 * Any criterion argument can be NULL, if you don't care about it.
8939 * @context is session context. Must not be NULL.
8940 * @from_time is minimal time and date of status changes inclusive
8941 * @to_time is maximal time and date of status changes inclusive
8942 * @changed_states is automatically reallocated list of
8943 * isds_message_status_change's. If you provide &NULL, list will be allocated
8944 * on heap, if you provide pointer to non-NULL, list will be freed
8945 * automatically at first. Also in case of error the list will be NULLed.
8946 * XXX: The list item ordering is not specified.
8947 * XXX: Server provides only `recent' changes.
8948 * @return IE_SUCCESS or appropriate error code. */
8949 isds_error isds_get_list_of_sent_message_state_changes(
8950 struct isds_ctx *context,
8951 const struct timeval *from_time, const struct timeval *to_time,
8952 struct isds_list **changed_states) {
8954 isds_error err = IE_SUCCESS;
8955 #if HAVE_LIBCURL
8956 xmlNsPtr isds_ns = NULL;
8957 xmlNodePtr request = NULL, node;
8958 xmlDocPtr response = NULL;
8959 xmlXPathContextPtr xpath_ctx = NULL;
8960 xmlXPathObjectPtr result = NULL;
8961 xmlChar *string = NULL;
8962 long unsigned int count = 0;
8963 #endif
8965 if (!context) return IE_INVALID_CONTEXT;
8966 zfree(context->long_message);
8968 /* Free former message list if any */
8969 isds_list_free(changed_states);
8971 #if HAVE_LIBCURL
8972 /* Check if connection is established
8973 * TODO: This check should be done downstairs. */
8974 if (!context->curl) return IE_CONNECTION_CLOSED;
8976 /* Build GetMessageStateChanges request */
8977 request = xmlNewNode(NULL, BAD_CAST "GetMessageStateChanges");
8978 if (!request) {
8979 isds_log_message(context,
8980 _("Could not build GetMessageStateChanges request"));
8981 return IE_ERROR;
8983 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
8984 if(!isds_ns) {
8985 isds_log_message(context, _("Could not create ISDS name space"));
8986 xmlFreeNode(request);
8987 return IE_ERROR;
8989 xmlSetNs(request, isds_ns);
8992 if (from_time) {
8993 err = timeval2timestring(from_time, &string);
8994 if (err) goto leave;
8996 INSERT_STRING(request, "dmFromTime", string);
8997 zfree(string);
8999 if (to_time) {
9000 err = timeval2timestring(to_time, &string);
9001 if (err) goto leave;
9003 INSERT_STRING(request, "dmToTime", string);
9004 zfree(string);
9007 /* Sent request */
9008 err = send_destroy_request_check_response(context,
9009 SERVICE_DM_INFO, BAD_CAST "GetMessageStateChanges", &request,
9010 &response, NULL, NULL);
9011 if (err) goto leave;
9014 /* Extract data */
9015 xpath_ctx = xmlXPathNewContext(response);
9016 if (!xpath_ctx) {
9017 err = IE_ERROR;
9018 goto leave;
9020 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
9021 err = IE_ERROR;
9022 goto leave;
9024 result = xmlXPathEvalExpression(
9025 BAD_CAST "/isds:GetMessageStateChangesResponse/"
9026 "isds:dmRecords/isds:dmRecord", xpath_ctx);
9027 if (!result) {
9028 err = IE_ERROR;
9029 goto leave;
9032 /* Fill output arguments in */
9033 if (!xmlXPathNodeSetIsEmpty(result->nodesetval)) {
9034 struct isds_list *item = NULL, *last_item = NULL;
9036 for (count = 0; count < result->nodesetval->nodeNr; count++) {
9037 /* Create new status change */
9038 item = calloc(1, sizeof(*item));
9039 if (!item) {
9040 err = IE_NOMEM;
9041 goto leave;
9043 item->destructor =
9044 (void(*)(void**)) &isds_message_status_change_free;
9046 /* Extract message status change */
9047 xpath_ctx->node = result->nodesetval->nodeTab[count];
9048 err = extract_StateChangesRecord(context,
9049 (struct isds_message_status_change **) &item->data,
9050 xpath_ctx);
9051 if (err) {
9052 isds_list_free(&item);
9053 goto leave;
9056 /* Append new message status change into the list */
9057 if (!*changed_states) {
9058 *changed_states = last_item = item;
9059 } else {
9060 last_item->next = item;
9061 last_item = item;
9066 leave:
9067 if (err) {
9068 isds_list_free(changed_states);
9071 free(string);
9072 xmlXPathFreeObject(result);
9073 xmlXPathFreeContext(xpath_ctx);
9074 xmlFreeDoc(response);
9075 xmlFreeNode(request);
9077 if (!err)
9078 isds_log(ILF_ISDS, ILL_DEBUG,
9079 _("GetMessageStateChanges request processed by server "
9080 "successfully.\n"));
9081 #else /* not HAVE_LIBCURL */
9082 err = IE_NOTSUP;
9083 #endif
9084 return err;
9088 #if HAVE_LIBCURL
9089 /* Build ISDS request of XSD tIDMessInput type, sent it and check for error
9090 * code
9091 * @context is session context
9092 * @service is ISDS WS service handler
9093 * @service_name is name of SERVICE_DM_OPERATIONS
9094 * @message_id is message ID to send as service argument to ISDS
9095 * @response is server SOAP body response as XML document
9096 * @raw_response is automatically reallocated bit stream with response body. Use
9097 * NULL if you don't care
9098 * @raw_response_length is size of @raw_response in bytes
9099 * @code is ISDS status code
9100 * @status_message is ISDS status message
9101 * @return error coded from lower layer, context message will be set up
9102 * appropriately. */
9103 static isds_error build_send_check_message_request(struct isds_ctx *context,
9104 const isds_service service, const xmlChar *service_name,
9105 const char *message_id,
9106 xmlDocPtr *response, void **raw_response, size_t *raw_response_length,
9107 xmlChar **code, xmlChar **status_message) {
9109 isds_error err = IE_SUCCESS;
9110 char *service_name_locale = NULL, *message_id_locale = NULL;
9111 xmlNodePtr request = NULL, node;
9112 xmlNsPtr isds_ns = NULL;
9114 if (!context) return IE_INVALID_CONTEXT;
9115 if (!service_name || !message_id) return IE_INVAL;
9116 if (!response || !code || !status_message) return IE_INVAL;
9117 if (!raw_response_length && raw_response) return IE_INVAL;
9119 /* Free output argument */
9120 xmlFreeDoc(*response); *response = NULL;
9121 if (raw_response) zfree(*raw_response);
9122 free(*code);
9123 free(*status_message);
9126 /* Check if connection is established
9127 * TODO: This check should be done downstairs. */
9128 if (!context->curl) return IE_CONNECTION_CLOSED;
9130 service_name_locale = _isds_utf82locale((char*)service_name);
9131 message_id_locale = _isds_utf82locale(message_id);
9132 if (!service_name_locale || !message_id_locale) {
9133 err = IE_NOMEM;
9134 goto leave;
9137 /* Build request */
9138 request = xmlNewNode(NULL, service_name);
9139 if (!request) {
9140 isds_printf_message(context,
9141 _("Could not build %s request for %s message ID"),
9142 service_name_locale, message_id_locale);
9143 err = IE_ERROR;
9144 goto leave;
9146 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
9147 if(!isds_ns) {
9148 isds_log_message(context, _("Could not create ISDS name space"));
9149 err = IE_ERROR;
9150 goto leave;
9152 xmlSetNs(request, isds_ns);
9155 /* Add requested ID */
9156 err = validate_message_id_length(context, (xmlChar *) message_id);
9157 if (err) goto leave;
9158 INSERT_STRING(request, "dmID", message_id);
9161 isds_log(ILF_ISDS, ILL_DEBUG,
9162 _("Sending %s request for %s message ID to ISDS\n"),
9163 service_name_locale, message_id_locale);
9165 /* Send request */
9166 err = isds(context, service, request, response,
9167 raw_response, raw_response_length);
9168 xmlFreeNode(request); request = NULL;
9170 if (err) {
9171 isds_log(ILF_ISDS, ILL_DEBUG,
9172 _("Processing ISDS response on %s request failed\n"),
9173 service_name_locale);
9174 goto leave;
9177 /* Check for response status */
9178 err = isds_response_status(context, service, *response,
9179 code, status_message, NULL);
9180 if (err) {
9181 isds_log(ILF_ISDS, ILL_DEBUG,
9182 _("ISDS response on %s request is missing status\n"),
9183 service_name_locale);
9184 goto leave;
9187 /* Request processed, but nothing found */
9188 if (xmlStrcmp(*code, BAD_CAST "0000")) {
9189 char *code_locale = _isds_utf82locale((char*) *code);
9190 char *status_message_locale = _isds_utf82locale((char*) *status_message);
9191 isds_log(ILF_ISDS, ILL_DEBUG,
9192 _("Server refused %s request for %s message ID "
9193 "(code=%s, message=%s)\n"),
9194 service_name_locale, message_id_locale,
9195 code_locale, status_message_locale);
9196 isds_log_message(context, status_message_locale);
9197 free(code_locale);
9198 free(status_message_locale);
9199 err = IE_ISDS;
9200 goto leave;
9203 leave:
9204 free(message_id_locale);
9205 free(service_name_locale);
9206 xmlFreeNode(request);
9207 return err;
9211 /* Find dmSignature in ISDS response, extract decoded CMS structure, extract
9212 * signed data and free ISDS response.
9213 * @context is session context
9214 * @message_id is UTF-8 encoded message ID for logging purpose
9215 * @response is parsed XML document. It will be freed and NULLed in the middle
9216 * of function run to save memory. This is not guaranteed in case of error.
9217 * @request_name is name of ISDS request used to construct response root
9218 * element name and for logging purpose.
9219 * @raw is reallocated output buffer with DER encoded CMS data
9220 * @raw_length is size of @raw buffer in bytes
9221 * @returns standard error codes, in case of error, @raw will be freed and
9222 * NULLed, @response sometimes. */
9223 static isds_error find_extract_signed_data_free_response(
9224 struct isds_ctx *context, const xmlChar *message_id,
9225 xmlDocPtr *response, const xmlChar *request_name,
9226 void **raw, size_t *raw_length) {
9228 isds_error err = IE_SUCCESS;
9229 char *xpath_expression = NULL;
9230 xmlXPathContextPtr xpath_ctx = NULL;
9231 xmlXPathObjectPtr result = NULL;
9232 char *encoded_structure = NULL;
9234 if (!context) return IE_INVALID_CONTEXT;
9235 if (!raw) return IE_INVAL;
9236 zfree(*raw);
9237 if (!message_id || !response || !*response || !request_name || !raw_length)
9238 return IE_INVAL;
9240 /* Build XPath expression */
9241 xpath_expression = _isds_astrcat3("/isds:", (char *) request_name,
9242 "Response/isds:dmSignature");
9243 if (!xpath_expression) return IE_NOMEM;
9245 /* Extract data */
9246 xpath_ctx = xmlXPathNewContext(*response);
9247 if (!xpath_ctx) {
9248 err = IE_ERROR;
9249 goto leave;
9251 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
9252 err = IE_ERROR;
9253 goto leave;
9255 result = xmlXPathEvalExpression(BAD_CAST xpath_expression, xpath_ctx);
9256 if (!result) {
9257 err = IE_ERROR;
9258 goto leave;
9260 /* Empty response */
9261 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
9262 char *message_id_locale = _isds_utf82locale((char*) message_id);
9263 isds_printf_message(context,
9264 _("Server did not return any signed data for message ID `%s' "
9265 "on %s request"),
9266 message_id_locale, request_name);
9267 free(message_id_locale);
9268 err = IE_ISDS;
9269 goto leave;
9271 /* More responses */
9272 if (result->nodesetval->nodeNr > 1) {
9273 char *message_id_locale = _isds_utf82locale((char*) message_id);
9274 isds_printf_message(context,
9275 _("Server did return more signed data for message ID `%s' "
9276 "on %s request"),
9277 message_id_locale, request_name);
9278 free(message_id_locale);
9279 err = IE_ISDS;
9280 goto leave;
9282 /* One response */
9283 xpath_ctx->node = result->nodesetval->nodeTab[0];
9285 /* Extract PKCS#7 structure */
9286 EXTRACT_STRING(".", encoded_structure);
9287 if (!encoded_structure) {
9288 isds_log_message(context, _("dmSignature element is empty"));
9291 /* Here we have delivery info as standalone CMS in encoded_structure.
9292 * We don't need any other data, free them: */
9293 xmlXPathFreeObject(result); result = NULL;
9294 xmlXPathFreeContext(xpath_ctx); xpath_ctx = NULL;
9295 xmlFreeDoc(*response); *response = NULL;
9298 /* Decode PKCS#7 to DER format */
9299 *raw_length = _isds_b64decode(encoded_structure, raw);
9300 if (*raw_length == (size_t) -1) {
9301 isds_log_message(context,
9302 _("Error while Base64-decoding PKCS#7 structure"));
9303 err = IE_ERROR;
9304 goto leave;
9307 leave:
9308 if (err) {
9309 zfree(*raw);
9310 raw_length = 0;
9313 free(encoded_structure);
9314 xmlXPathFreeObject(result);
9315 xmlXPathFreeContext(xpath_ctx);
9316 free(xpath_expression);
9318 return err;
9320 #endif /* HAVE_LIBCURL */
9323 /* Download incoming message envelope identified by ID.
9324 * @context is session context
9325 * @message_id is message identifier (you can get them from
9326 * isds_get_list_of_received_messages())
9327 * @message is automatically reallocated message retrieved from ISDS.
9328 * It will miss documents per se. Use isds_get_received_message(), if you are
9329 * interested in documents (content) too.
9330 * Returned hash and timestamp require documents to be verifiable. */
9331 isds_error isds_get_received_envelope(struct isds_ctx *context,
9332 const char *message_id, struct isds_message **message) {
9334 isds_error err = IE_SUCCESS;
9335 #if HAVE_LIBCURL
9336 xmlDocPtr response = NULL;
9337 xmlChar *code = NULL, *status_message = NULL;
9338 xmlXPathContextPtr xpath_ctx = NULL;
9339 xmlXPathObjectPtr result = NULL;
9340 #endif
9342 if (!context) return IE_INVALID_CONTEXT;
9343 zfree(context->long_message);
9345 /* Free former message if any */
9346 if (!message) return IE_INVAL;
9347 isds_message_free(message);
9349 #if HAVE_LIBCURL
9350 /* Do request and check for success */
9351 err = build_send_check_message_request(context, SERVICE_DM_INFO,
9352 BAD_CAST "MessageEnvelopeDownload", message_id,
9353 &response, NULL, NULL, &code, &status_message);
9354 if (err) goto leave;
9356 /* Extract data */
9357 xpath_ctx = xmlXPathNewContext(response);
9358 if (!xpath_ctx) {
9359 err = IE_ERROR;
9360 goto leave;
9362 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
9363 err = IE_ERROR;
9364 goto leave;
9366 result = xmlXPathEvalExpression(
9367 BAD_CAST "/isds:MessageEnvelopeDownloadResponse/"
9368 "isds:dmReturnedMessageEnvelope",
9369 xpath_ctx);
9370 if (!result) {
9371 err = IE_ERROR;
9372 goto leave;
9374 /* Empty response */
9375 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
9376 char *message_id_locale = _isds_utf82locale((char*) message_id);
9377 isds_printf_message(context,
9378 _("Server did not return any envelope for ID `%s' "
9379 "on MessageEnvelopeDownload request"), message_id_locale);
9380 free(message_id_locale);
9381 err = IE_ISDS;
9382 goto leave;
9384 /* More envelops */
9385 if (result->nodesetval->nodeNr > 1) {
9386 char *message_id_locale = _isds_utf82locale((char*) message_id);
9387 isds_printf_message(context,
9388 _("Server did return more envelopes for ID `%s' "
9389 "on MessageEnvelopeDownload request"), message_id_locale);
9390 free(message_id_locale);
9391 err = IE_ISDS;
9392 goto leave;
9394 /* One message */
9395 xpath_ctx->node = result->nodesetval->nodeTab[0];
9397 /* Extract the envelope (= message without documents, hence 0) */
9398 err = extract_TReturnedMessage(context, 0, message, xpath_ctx);
9399 if (err) goto leave;
9401 /* Save XML blob */
9402 err = serialize_subtree(context, xpath_ctx->node, &(*message)->raw,
9403 &(*message)->raw_length);
9405 leave:
9406 if (err) {
9407 isds_message_free(message);
9410 xmlXPathFreeObject(result);
9411 xmlXPathFreeContext(xpath_ctx);
9413 free(code);
9414 free(status_message);
9415 if (!*message || !(*message)->xml) {
9416 xmlFreeDoc(response);
9419 if (!err)
9420 isds_log(ILF_ISDS, ILL_DEBUG,
9421 _("MessageEnvelopeDownload request processed by server "
9422 "successfully.\n")
9424 #else /* not HAVE_LIBCURL */
9425 err = IE_NOTSUP;
9426 #endif
9427 return err;
9431 /* Load delivery info of any format from buffer.
9432 * @context is session context
9433 * @raw_type advertises format of @buffer content. Only delivery info types
9434 * are accepted.
9435 * @buffer is DER encoded PKCS#7 structure with signed delivery info. You can
9436 * retrieve such data from message->raw after calling
9437 * isds_get_signed_delivery_info().
9438 * @length is length of buffer in bytes.
9439 * @message is automatically reallocated message parsed from @buffer.
9440 * @strategy selects how buffer will be attached into raw isds_message member.
9441 * */
9442 isds_error isds_load_delivery_info(struct isds_ctx *context,
9443 const isds_raw_type raw_type,
9444 const void *buffer, const size_t length,
9445 struct isds_message **message, const isds_buffer_strategy strategy) {
9447 isds_error err = IE_SUCCESS;
9448 message_ns_type message_ns;
9449 xmlDocPtr message_doc = NULL;
9450 xmlXPathContextPtr xpath_ctx = NULL;
9451 xmlXPathObjectPtr result = NULL;
9452 void *xml_stream = NULL;
9453 size_t xml_stream_length = 0;
9455 if (!context) return IE_INVALID_CONTEXT;
9456 zfree(context->long_message);
9457 if (!message) return IE_INVAL;
9458 isds_message_free(message);
9459 if (!buffer) return IE_INVAL;
9462 /* Select buffer format and extract XML from CMS*/
9463 switch (raw_type) {
9464 case RAWTYPE_DELIVERYINFO:
9465 message_ns = MESSAGE_NS_UNSIGNED;
9466 xml_stream = (void *) buffer;
9467 xml_stream_length = length;
9468 break;
9470 case RAWTYPE_PLAIN_SIGNED_DELIVERYINFO:
9471 message_ns = MESSAGE_NS_SIGNED_DELIVERY;
9472 xml_stream = (void *) buffer;
9473 xml_stream_length = length;
9474 break;
9476 case RAWTYPE_CMS_SIGNED_DELIVERYINFO:
9477 message_ns = MESSAGE_NS_SIGNED_DELIVERY;
9478 err = _isds_extract_cms_data(context, buffer, length,
9479 &xml_stream, &xml_stream_length);
9480 if (err) goto leave;
9481 break;
9483 default:
9484 isds_log_message(context, _("Bad raw delivery representation type"));
9485 return IE_INVAL;
9486 break;
9489 isds_log(ILF_ISDS, ILL_DEBUG,
9490 _("Delivery info content:\n%.*s\nEnd of delivery info\n"),
9491 xml_stream_length, xml_stream);
9493 /* Convert delivery info XML stream into XPath context */
9494 message_doc = xmlParseMemory(xml_stream, xml_stream_length);
9495 if (!message_doc) {
9496 err = IE_XML;
9497 goto leave;
9499 xpath_ctx = xmlXPathNewContext(message_doc);
9500 if (!xpath_ctx) {
9501 err = IE_ERROR;
9502 goto leave;
9504 /* XXX: Name spaces mangled for signed delivery info:
9505 * http://isds.czechpoint.cz/v20/delivery:
9507 * <q:GetDeliveryInfoResponse xmlns:q="http://isds.czechpoint.cz/v20/delivery">
9508 * <q:dmDelivery>
9509 * <p:dmDm xmlns:p="http://isds.czechpoint.cz/v20">
9510 * <p:dmID>170272</p:dmID>
9511 * ...
9512 * </p:dmDm>
9513 * <q:dmHash algorithm="SHA-1">...</q:dmHash>
9514 * ...
9515 * </q:dmEvents>...</q:dmEvents>
9516 * </q:dmDelivery>
9517 * </q:GetDeliveryInfoResponse>
9518 * */
9519 if (_isds_register_namespaces(xpath_ctx, message_ns)) {
9520 err = IE_ERROR;
9521 goto leave;
9523 result = xmlXPathEvalExpression(
9524 BAD_CAST "/sisds:GetDeliveryInfoResponse/sisds:dmDelivery",
9525 xpath_ctx);
9526 if (!result) {
9527 err = IE_ERROR;
9528 goto leave;
9530 /* Empty delivery info */
9531 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
9532 isds_printf_message(context,
9533 _("XML document is not sisds:dmDelivery document"));
9534 err = IE_ISDS;
9535 goto leave;
9537 /* More delivery info's */
9538 if (result->nodesetval->nodeNr > 1) {
9539 isds_printf_message(context,
9540 _("XML document has more sisds:dmDelivery elements"));
9541 err = IE_ISDS;
9542 goto leave;
9544 /* One delivery info */
9545 xpath_ctx->node = result->nodesetval->nodeTab[0];
9547 /* Extract the envelope (= message without documents, hence 0).
9548 * XXX: extract_TReturnedMessage() can obtain attachments size,
9549 * but delivery info carries none. It's coded as option elements,
9550 * so it should work. */
9551 err = extract_TReturnedMessage(context, 0, message, xpath_ctx);
9552 if (err) goto leave;
9554 /* Extract events */
9555 err = move_xpathctx_to_child(context, BAD_CAST "sisds:dmEvents", xpath_ctx);
9556 if (err == IE_NOEXIST || err == IE_NOTUNIQ) { err = IE_ISDS; goto leave; }
9557 if (err) { err = IE_ERROR; goto leave; }
9558 err = extract_events(context, &(*message)->envelope->events, xpath_ctx);
9559 if (err) goto leave;
9561 /* Append raw CMS structure into message */
9562 (*message)->raw_type = raw_type;
9563 switch (strategy) {
9564 case BUFFER_DONT_STORE:
9565 break;
9566 case BUFFER_COPY:
9567 (*message)->raw = malloc(length);
9568 if (!(*message)->raw) {
9569 err = IE_NOMEM;
9570 goto leave;
9572 memcpy((*message)->raw, buffer, length);
9573 (*message)->raw_length = length;
9574 break;
9575 case BUFFER_MOVE:
9576 (*message)->raw = (void *) buffer;
9577 (*message)->raw_length = length;
9578 break;
9579 default:
9580 err = IE_ENUM;
9581 goto leave;
9584 leave:
9585 if (err) {
9586 if (*message && strategy == BUFFER_MOVE) (*message)->raw = NULL;
9587 isds_message_free(message);
9590 xmlXPathFreeObject(result);
9591 xmlXPathFreeContext(xpath_ctx);
9592 if (!*message || !(*message)->xml) {
9593 xmlFreeDoc(message_doc);
9595 if (xml_stream != buffer) _isds_cms_data_free(xml_stream);
9597 if (!err)
9598 isds_log(ILF_ISDS, ILL_DEBUG,
9599 _("Delivery info loaded successfully.\n"));
9600 return err;
9604 /* Download signed delivery info-sheet of given message identified by ID.
9605 * @context is session context
9606 * @message_id is message identifier (you can get them from
9607 * isds_get_list_of_{sent,received}_messages())
9608 * @message is automatically reallocated message retrieved from ISDS.
9609 * It will miss documents per se. Use isds_get_signed_received_message(),
9610 * if you are interested in documents (content). OTOH, only this function
9611 * can get list events message has gone through. */
9612 isds_error isds_get_signed_delivery_info(struct isds_ctx *context,
9613 const char *message_id, struct isds_message **message) {
9615 isds_error err = IE_SUCCESS;
9616 #if HAVE_LIBCURL
9617 xmlDocPtr response = NULL;
9618 xmlChar *code = NULL, *status_message = NULL;
9619 void *raw = NULL;
9620 size_t raw_length = 0;
9621 #endif
9623 if (!context) return IE_INVALID_CONTEXT;
9624 zfree(context->long_message);
9626 /* Free former message if any */
9627 if (!message) return IE_INVAL;
9628 isds_message_free(message);
9630 #if HAVE_LIBCURL
9631 /* Do request and check for success */
9632 err = build_send_check_message_request(context, SERVICE_DM_INFO,
9633 BAD_CAST "GetSignedDeliveryInfo", message_id,
9634 &response, NULL, NULL, &code, &status_message);
9635 if (err) goto leave;
9637 /* Find signed delivery info, extract it into raw and maybe free
9638 * response */
9639 err = find_extract_signed_data_free_response(context,
9640 (xmlChar *)message_id, &response,
9641 BAD_CAST "GetSignedDeliveryInfo", &raw, &raw_length);
9642 if (err) goto leave;
9644 /* Parse delivery info */
9645 err = isds_load_delivery_info(context,
9646 RAWTYPE_CMS_SIGNED_DELIVERYINFO, raw, raw_length,
9647 message, BUFFER_MOVE);
9648 if (err) goto leave;
9650 raw = NULL;
9652 leave:
9653 if (err) {
9654 isds_message_free(message);
9657 free(raw);
9658 free(code);
9659 free(status_message);
9660 xmlFreeDoc(response);
9662 if (!err)
9663 isds_log(ILF_ISDS, ILL_DEBUG,
9664 _("GetSignedDeliveryInfo request processed by server "
9665 "successfully.\n")
9667 #else /* not HAVE_LIBCURL */
9668 err = IE_NOTSUP;
9669 #endif
9670 return err;
9674 /* Download delivery info-sheet of given message identified by ID.
9675 * @context is session context
9676 * @message_id is message identifier (you can get them from
9677 * isds_get_list_of_{sent,received}_messages())
9678 * @message is automatically reallocated message retrieved from ISDS.
9679 * It will miss documents per se. Use isds_get_received_message(), if you are
9680 * interested in documents (content). OTOH, only this function can get list
9681 * of events message has gone through. */
9682 isds_error isds_get_delivery_info(struct isds_ctx *context,
9683 const char *message_id, struct isds_message **message) {
9685 isds_error err = IE_SUCCESS;
9686 #if HAVE_LIBCURL
9687 xmlDocPtr response = NULL;
9688 xmlChar *code = NULL, *status_message = NULL;
9689 xmlNodePtr delivery_node = NULL;
9690 void *raw = NULL;
9691 size_t raw_length = 0;
9692 #endif
9694 if (!context) return IE_INVALID_CONTEXT;
9695 zfree(context->long_message);
9697 /* Free former message if any */
9698 if (!message) return IE_INVAL;
9699 isds_message_free(message);
9701 #if HAVE_LIBCURL
9702 /* Do request and check for success */
9703 err = build_send_check_message_request(context, SERVICE_DM_INFO,
9704 BAD_CAST "GetDeliveryInfo", message_id,
9705 &response, NULL, NULL, &code, &status_message);
9706 if (err) goto leave;
9709 /* Serialize delivery info */
9710 delivery_node = xmlDocGetRootElement(response);
9711 if (!delivery_node) {
9712 char *message_id_locale = _isds_utf82locale((char*) message_id);
9713 isds_printf_message(context,
9714 _("Server did not return any delivery info for ID `%s' "
9715 "on GetDeliveryInfo request"), message_id_locale);
9716 free(message_id_locale);
9717 err = IE_ISDS;
9718 goto leave;
9720 err = serialize_subtree(context, delivery_node, &raw, &raw_length);
9721 if (err) goto leave;
9723 /* Parse delivery info */
9724 /* TODO: Here we parse the response second time. We could single delivery
9725 * parser from isds_load_delivery_info() to make things faster. */
9726 err = isds_load_delivery_info(context,
9727 RAWTYPE_DELIVERYINFO, raw, raw_length,
9728 message, BUFFER_MOVE);
9729 if (err) goto leave;
9731 raw = NULL;
9734 leave:
9735 if (err) {
9736 isds_message_free(message);
9739 free(raw);
9740 free(code);
9741 free(status_message);
9742 xmlFreeDoc(response);
9744 if (!err)
9745 isds_log(ILF_ISDS, ILL_DEBUG,
9746 _("GetDeliveryInfo request processed by server "
9747 "successfully.\n")
9749 #else /* not HAVE_LIBCURL */
9750 err = IE_NOTSUP;
9751 #endif
9752 return err;
9756 /* Download incoming message identified by ID.
9757 * @context is session context
9758 * @message_id is message identifier (you can get them from
9759 * isds_get_list_of_received_messages())
9760 * @message is automatically reallocated message retrieved from ISDS */
9761 isds_error isds_get_received_message(struct isds_ctx *context,
9762 const char *message_id, struct isds_message **message) {
9764 isds_error err = IE_SUCCESS;
9765 #if HAVE_LIBCURL
9766 xmlDocPtr response = NULL;
9767 void *xml_stream = NULL;
9768 size_t xml_stream_length;
9769 xmlChar *code = NULL, *status_message = NULL;
9770 xmlXPathContextPtr xpath_ctx = NULL;
9771 xmlXPathObjectPtr result = NULL;
9772 char *phys_path = NULL;
9773 size_t phys_start, phys_end;
9774 #endif
9776 if (!context) return IE_INVALID_CONTEXT;
9777 zfree(context->long_message);
9779 /* Free former message if any */
9780 if (message) isds_message_free(message);
9782 #if HAVE_LIBCURL
9783 /* Do request and check for success */
9784 err = build_send_check_message_request(context, SERVICE_DM_OPERATIONS,
9785 BAD_CAST "MessageDownload", message_id,
9786 &response, &xml_stream, &xml_stream_length,
9787 &code, &status_message);
9788 if (err) goto leave;
9790 /* Extract data */
9791 xpath_ctx = xmlXPathNewContext(response);
9792 if (!xpath_ctx) {
9793 err = IE_ERROR;
9794 goto leave;
9796 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
9797 err = IE_ERROR;
9798 goto leave;
9800 result = xmlXPathEvalExpression(
9801 BAD_CAST "/isds:MessageDownloadResponse/isds:dmReturnedMessage",
9802 xpath_ctx);
9803 if (!result) {
9804 err = IE_ERROR;
9805 goto leave;
9807 /* Empty response */
9808 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
9809 char *message_id_locale = _isds_utf82locale((char*) message_id);
9810 isds_printf_message(context,
9811 _("Server did not return any message for ID `%s' "
9812 "on MessageDownload request"), message_id_locale);
9813 free(message_id_locale);
9814 err = IE_ISDS;
9815 goto leave;
9817 /* More messages */
9818 if (result->nodesetval->nodeNr > 1) {
9819 char *message_id_locale = _isds_utf82locale((char*) message_id);
9820 isds_printf_message(context,
9821 _("Server did return more messages for ID `%s' "
9822 "on MessageDownload request"), message_id_locale);
9823 free(message_id_locale);
9824 err = IE_ISDS;
9825 goto leave;
9827 /* One message */
9828 xpath_ctx->node = result->nodesetval->nodeTab[0];
9830 /* Extract the message */
9831 err = extract_TReturnedMessage(context, 1, message, xpath_ctx);
9832 if (err) goto leave;
9834 /* Locate raw XML blob */
9835 phys_path = strdup(
9836 SOAP_NS PHYSXML_NS_SEPARATOR "Envelope"
9837 PHYSXML_ELEMENT_SEPARATOR
9838 SOAP_NS PHYSXML_NS_SEPARATOR "Body"
9839 PHYSXML_ELEMENT_SEPARATOR
9840 ISDS_NS PHYSXML_NS_SEPARATOR "MessageDownloadResponse"
9842 if (!phys_path) {
9843 err = IE_NOMEM;
9844 goto leave;
9846 err = _isds_find_element_boundary(xml_stream, xml_stream_length,
9847 phys_path, &phys_start, &phys_end);
9848 zfree(phys_path);
9849 if (err) {
9850 isds_log_message(context,
9851 _("Substring with isds:MessageDownloadResponse element "
9852 "could not be located in raw SOAP message"));
9853 goto leave;
9855 /* Save XML blob */
9856 /*err = serialize_subtree(context, xpath_ctx->node, &(*message)->raw,
9857 &(*message)->raw_length);*/
9858 /* TODO: Store name space declarations from ancestors */
9859 /* TODO: Handle non-UTF-8 encoding (XML prologue) */
9860 (*message)->raw_type = RAWTYPE_INCOMING_MESSAGE;
9861 (*message)->raw_length = phys_end - phys_start + 1;
9862 (*message)->raw = malloc((*message)->raw_length);
9863 if (!(*message)->raw) {
9864 err = IE_NOMEM;
9865 goto leave;
9867 memcpy((*message)->raw, xml_stream + phys_start, (*message)->raw_length);
9870 leave:
9871 if (err) {
9872 isds_message_free(message);
9875 free(phys_path);
9877 xmlXPathFreeObject(result);
9878 xmlXPathFreeContext(xpath_ctx);
9880 free(code);
9881 free(status_message);
9882 free(xml_stream);
9883 if (!*message || !(*message)->xml) {
9884 xmlFreeDoc(response);
9887 if (!err)
9888 isds_log(ILF_ISDS, ILL_DEBUG,
9889 _("MessageDownload request processed by server "
9890 "successfully.\n")
9892 #else /* not HAVE_LIBCURL */
9893 err = IE_NOTSUP;
9894 #endif
9895 return err;
9899 /* Load message of any type from buffer.
9900 * @context is session context
9901 * @raw_type defines content type of @buffer. Only message types are allowed.
9902 * @buffer is message raw representation. Format (CMS, plain signed,
9903 * message direction) is defined in @raw_type. You can retrieve such data
9904 * from message->raw after calling isds_get_[signed]{received,sent}_message().
9905 * @length is length of buffer in bytes.
9906 * @message is automatically reallocated message parsed from @buffer.
9907 * @strategy selects how buffer will be attached into raw isds_message member.
9908 * */
9909 isds_error isds_load_message(struct isds_ctx *context,
9910 const isds_raw_type raw_type, const void *buffer, const size_t length,
9911 struct isds_message **message, const isds_buffer_strategy strategy) {
9913 isds_error err = IE_SUCCESS;
9914 void *xml_stream = NULL;
9915 size_t xml_stream_length = 0;
9916 message_ns_type message_ns;
9917 xmlDocPtr message_doc = NULL;
9918 xmlXPathContextPtr xpath_ctx = NULL;
9919 xmlXPathObjectPtr result = NULL;
9921 if (!context) return IE_INVALID_CONTEXT;
9922 zfree(context->long_message);
9923 if (!message) return IE_INVAL;
9924 isds_message_free(message);
9925 if (!buffer) return IE_INVAL;
9928 /* Select buffer format and extract XML from CMS*/
9929 switch (raw_type) {
9930 case RAWTYPE_INCOMING_MESSAGE:
9931 message_ns = MESSAGE_NS_UNSIGNED;
9932 xml_stream = (void *) buffer;
9933 xml_stream_length = length;
9934 break;
9936 case RAWTYPE_PLAIN_SIGNED_INCOMING_MESSAGE:
9937 message_ns = MESSAGE_NS_SIGNED_INCOMING;
9938 xml_stream = (void *) buffer;
9939 xml_stream_length = length;
9940 break;
9942 case RAWTYPE_CMS_SIGNED_INCOMING_MESSAGE:
9943 message_ns = MESSAGE_NS_SIGNED_INCOMING;
9944 err = _isds_extract_cms_data(context, buffer, length,
9945 &xml_stream, &xml_stream_length);
9946 if (err) goto leave;
9947 break;
9949 case RAWTYPE_PLAIN_SIGNED_OUTGOING_MESSAGE:
9950 message_ns = MESSAGE_NS_SIGNED_OUTGOING;
9951 xml_stream = (void *) buffer;
9952 xml_stream_length = length;
9953 break;
9955 case RAWTYPE_CMS_SIGNED_OUTGOING_MESSAGE:
9956 message_ns = MESSAGE_NS_SIGNED_OUTGOING;
9957 err = _isds_extract_cms_data(context, buffer, length,
9958 &xml_stream, &xml_stream_length);
9959 if (err) goto leave;
9960 break;
9962 default:
9963 isds_log_message(context, _("Bad raw message representation type"));
9964 return IE_INVAL;
9965 break;
9968 isds_log(ILF_ISDS, ILL_DEBUG,
9969 _("Loading message:\n%.*s\nEnd of message\n"),
9970 xml_stream_length, xml_stream);
9972 /* Convert messages XML stream into XPath context */
9973 message_doc = xmlParseMemory(xml_stream, xml_stream_length);
9974 if (!message_doc) {
9975 err = IE_XML;
9976 goto leave;
9978 xpath_ctx = xmlXPathNewContext(message_doc);
9979 if (!xpath_ctx) {
9980 err = IE_ERROR;
9981 goto leave;
9983 /* XXX: Standard name space for unsigned incoming direction:
9984 * http://isds.czechpoint.cz/v20/
9986 * XXX: Name spaces mangled for signed outgoing direction:
9987 * http://isds.czechpoint.cz/v20/SentMessage:
9989 * <q:MessageDownloadResponse
9990 * xmlns:q="http://isds.czechpoint.cz/v20/SentMessage">
9991 * <q:dmReturnedMessage>
9992 * <p:dmDm xmlns:p="http://isds.czechpoint.cz/v20">
9993 * <p:dmID>151916</p:dmID>
9994 * ...
9995 * </p:dmDm>
9996 * <q:dmHash algorithm="SHA-1">...</q:dmHash>
9997 * ...
9998 * <q:dmAttachmentSize>260</q:dmAttachmentSize>
9999 * </q:dmReturnedMessage>
10000 * </q:MessageDownloadResponse>
10002 * XXX: Name spaces mangled for signed incoming direction:
10003 * http://isds.czechpoint.cz/v20/message:
10005 * <q:MessageDownloadResponse
10006 * xmlns:q="http://isds.czechpoint.cz/v20/message">
10007 * <q:dmReturnedMessage>
10008 * <p:dmDm xmlns:p="http://isds.czechpoint.cz/v20">
10009 * <p:dmID>151916</p:dmID>
10010 * ...
10011 * </p:dmDm>
10012 * <q:dmHash algorithm="SHA-1">...</q:dmHash>
10013 * ...
10014 * <q:dmAttachmentSize>260</q:dmAttachmentSize>
10015 * </q:dmReturnedMessage>
10016 * </q:MessageDownloadResponse>
10018 * Stupidity of ISDS developers is unlimited */
10019 if (_isds_register_namespaces(xpath_ctx, message_ns)) {
10020 err = IE_ERROR;
10021 goto leave;
10023 result = xmlXPathEvalExpression(
10024 BAD_CAST "/sisds:MessageDownloadResponse/sisds:dmReturnedMessage",
10025 xpath_ctx);
10026 if (!result) {
10027 err = IE_ERROR;
10028 goto leave;
10030 /* Empty message */
10031 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
10032 isds_printf_message(context,
10033 _("XML document does not contain "
10034 "sisds:dmReturnedMessage element"));
10035 err = IE_ISDS;
10036 goto leave;
10038 /* More messages */
10039 if (result->nodesetval->nodeNr > 1) {
10040 isds_printf_message(context,
10041 _("XML document has more sisds:dmReturnedMessage elements"));
10042 err = IE_ISDS;
10043 goto leave;
10045 /* One message */
10046 xpath_ctx->node = result->nodesetval->nodeTab[0];
10048 /* Extract the message */
10049 err = extract_TReturnedMessage(context, 1, message, xpath_ctx);
10050 if (err) goto leave;
10052 /* Append raw buffer into message */
10053 (*message)->raw_type = raw_type;
10054 switch (strategy) {
10055 case BUFFER_DONT_STORE:
10056 break;
10057 case BUFFER_COPY:
10058 (*message)->raw = malloc(length);
10059 if (!(*message)->raw) {
10060 err = IE_NOMEM;
10061 goto leave;
10063 memcpy((*message)->raw, buffer, length);
10064 (*message)->raw_length = length;
10065 break;
10066 case BUFFER_MOVE:
10067 (*message)->raw = (void *) buffer;
10068 (*message)->raw_length = length;
10069 break;
10070 default:
10071 err = IE_ENUM;
10072 goto leave;
10076 leave:
10077 if (err) {
10078 if (*message && strategy == BUFFER_MOVE) (*message)->raw = NULL;
10079 isds_message_free(message);
10082 if (xml_stream != buffer) _isds_cms_data_free(xml_stream);
10083 xmlXPathFreeObject(result);
10084 xmlXPathFreeContext(xpath_ctx);
10085 if (!*message || !(*message)->xml) {
10086 xmlFreeDoc(message_doc);
10089 if (!err)
10090 isds_log(ILF_ISDS, ILL_DEBUG, _("Message loaded successfully.\n"));
10091 return err;
10095 /* Determine type of raw message or delivery info according some heuristics.
10096 * It does not validate the raw blob.
10097 * @context is session context
10098 * @raw_type returns content type of @buffer. Valid only if exit code of this
10099 * function is IE_SUCCESS. The pointer must be valid. This is no automatically
10100 * reallocated memory.
10101 * @buffer is message raw representation.
10102 * @length is length of buffer in bytes. */
10103 isds_error isds_guess_raw_type(struct isds_ctx *context,
10104 isds_raw_type *raw_type, const void *buffer, const size_t length) {
10105 isds_error err;
10106 void *xml_stream = NULL;
10107 size_t xml_stream_length = 0;
10108 xmlDocPtr document = NULL;
10109 xmlNodePtr root = NULL;
10111 if (!context) return IE_INVALID_CONTEXT;
10112 zfree(context->long_message);
10113 if (length == 0 || !buffer) return IE_INVAL;
10114 if (!raw_type) return IE_INVAL;
10116 /* Try CMS */
10117 err = _isds_extract_cms_data(context, buffer, length,
10118 &xml_stream, &xml_stream_length);
10119 if (err) {
10120 xml_stream = (void *) buffer;
10121 xml_stream_length = (size_t) length;
10122 err = IE_SUCCESS;
10125 /* Try XML */
10126 document = xmlParseMemory(xml_stream, xml_stream_length);
10127 if (!document) {
10128 isds_printf_message(context,
10129 _("Could not parse data as XML document"));
10130 err = IE_NOTSUP;
10131 goto leave;
10134 /* Get root element */
10135 root = xmlDocGetRootElement(document);
10136 if (!root) {
10137 isds_printf_message(context,
10138 _("XML document is missing root element"));
10139 err = IE_XML;
10140 goto leave;
10143 if (!root->ns || !root->ns->href) {
10144 isds_printf_message(context,
10145 _("Root element does not belong to any name space"));
10146 err = IE_NOTSUP;
10147 goto leave;
10150 /* Test name space */
10151 if (!xmlStrcmp(root->ns->href, BAD_CAST SISDS_INCOMING_NS)) {
10152 if (xml_stream == buffer)
10153 *raw_type = RAWTYPE_PLAIN_SIGNED_INCOMING_MESSAGE;
10154 else
10155 *raw_type = RAWTYPE_CMS_SIGNED_INCOMING_MESSAGE;
10156 } else if (!xmlStrcmp(root->ns->href, BAD_CAST SISDS_OUTGOING_NS)) {
10157 if (xml_stream == buffer)
10158 *raw_type = RAWTYPE_PLAIN_SIGNED_OUTGOING_MESSAGE;
10159 else
10160 *raw_type = RAWTYPE_CMS_SIGNED_OUTGOING_MESSAGE;
10161 } else if (!xmlStrcmp(root->ns->href, BAD_CAST SISDS_DELIVERY_NS)) {
10162 if (xml_stream == buffer)
10163 *raw_type = RAWTYPE_PLAIN_SIGNED_DELIVERYINFO;
10164 else
10165 *raw_type = RAWTYPE_CMS_SIGNED_DELIVERYINFO;
10166 } else if (!xmlStrcmp(root->ns->href, BAD_CAST ISDS_NS)) {
10167 if (xml_stream != buffer) {
10168 isds_printf_message(context,
10169 _("Document in ISDS name space is encapsulated into CMS" ));
10170 err = IE_NOTSUP;
10171 } else if (!xmlStrcmp(root->name, BAD_CAST "MessageDownloadResponse"))
10172 *raw_type = RAWTYPE_INCOMING_MESSAGE;
10173 else if (!xmlStrcmp(root->name, BAD_CAST "GetDeliveryInfoResponse"))
10174 *raw_type = RAWTYPE_DELIVERYINFO;
10175 else {
10176 isds_printf_message(context,
10177 _("Unknown root element in ISDS name space"));
10178 err = IE_NOTSUP;
10180 } else {
10181 isds_printf_message(context,
10182 _("Unknown name space"));
10183 err = IE_NOTSUP;
10186 leave:
10187 if (xml_stream != buffer) _isds_cms_data_free(xml_stream);
10188 xmlFreeDoc(document);
10189 return err;
10193 /* Download signed incoming/outgoing message identified by ID.
10194 * @context is session context
10195 * @output is true for outgoing message, false for incoming message
10196 * @message_id is message identifier (you can get them from
10197 * isds_get_list_of_{sent,received}_messages())
10198 * @message is automatically reallocated message retrieved from ISDS. The raw
10199 * member will be filled with PKCS#7 structure in DER format. */
10200 static isds_error isds_get_signed_message(struct isds_ctx *context,
10201 const _Bool outgoing, const char *message_id,
10202 struct isds_message **message) {
10204 isds_error err = IE_SUCCESS;
10205 #if HAVE_LIBCURL
10206 xmlDocPtr response = NULL;
10207 xmlChar *code = NULL, *status_message = NULL;
10208 xmlXPathContextPtr xpath_ctx = NULL;
10209 xmlXPathObjectPtr result = NULL;
10210 char *encoded_structure = NULL;
10211 void *raw = NULL;
10212 size_t raw_length = 0;
10213 #endif
10215 if (!context) return IE_INVALID_CONTEXT;
10216 zfree(context->long_message);
10217 if (!message) return IE_INVAL;
10218 isds_message_free(message);
10220 #if HAVE_LIBCURL
10221 /* Do request and check for success */
10222 err = build_send_check_message_request(context, SERVICE_DM_OPERATIONS,
10223 (outgoing) ? BAD_CAST "SignedSentMessageDownload" :
10224 BAD_CAST "SignedMessageDownload",
10225 message_id, &response, NULL, NULL, &code, &status_message);
10226 if (err) goto leave;
10228 /* Find signed message, extract it into raw and maybe free
10229 * response */
10230 err = find_extract_signed_data_free_response(context,
10231 (xmlChar *)message_id, &response,
10232 (outgoing) ? BAD_CAST "SignedSentMessageDownload" :
10233 BAD_CAST "SignedMessageDownload",
10234 &raw, &raw_length);
10235 if (err) goto leave;
10237 /* Parse message */
10238 err = isds_load_message(context,
10239 (outgoing) ? RAWTYPE_CMS_SIGNED_OUTGOING_MESSAGE :
10240 RAWTYPE_CMS_SIGNED_INCOMING_MESSAGE,
10241 raw, raw_length, message, BUFFER_MOVE);
10242 if (err) goto leave;
10244 raw = NULL;
10246 leave:
10247 if (err) {
10248 isds_message_free(message);
10251 free(encoded_structure);
10252 xmlXPathFreeObject(result);
10253 xmlXPathFreeContext(xpath_ctx);
10254 free(raw);
10256 free(code);
10257 free(status_message);
10258 xmlFreeDoc(response);
10260 if (!err)
10261 isds_log(ILF_ISDS, ILL_DEBUG,
10262 (outgoing) ?
10263 _("SignedSentMessageDownload request processed by server "
10264 "successfully.\n") :
10265 _("SignedMessageDownload request processed by server "
10266 "successfully.\n")
10268 #else /* not HAVE_LIBCURL */
10269 err = IE_NOTSUP;
10270 #endif
10271 return err;
10275 /* Download signed incoming message identified by ID.
10276 * @context is session context
10277 * @message_id is message identifier (you can get them from
10278 * isds_get_list_of_received_messages())
10279 * @message is automatically reallocated message retrieved from ISDS. The raw
10280 * member will be filled with PKCS#7 structure in DER format. */
10281 isds_error isds_get_signed_received_message(struct isds_ctx *context,
10282 const char *message_id, struct isds_message **message) {
10283 return isds_get_signed_message(context, 0, message_id, message);
10287 /* Download signed outgoing message identified by ID.
10288 * @context is session context
10289 * @message_id is message identifier (you can get them from
10290 * isds_get_list_of_sent_messages())
10291 * @message is automatically reallocated message retrieved from ISDS. The raw
10292 * member will be filled with PKCS#7 structure in DER format. */
10293 isds_error isds_get_signed_sent_message(struct isds_ctx *context,
10294 const char *message_id, struct isds_message **message) {
10295 return isds_get_signed_message(context, 1, message_id, message);
10299 /* Get type and name of user who sent a message identified by ID.
10300 * @context is session context
10301 * @message_id is message identifier
10302 * @sender_type is pointer to automatically allocated type of sender detected
10303 * from @raw_sender_type string. If @raw_sender_type is unknown to this
10304 * library or to the server, NULL will be returned. Pass NULL if you don't
10305 * care about it.
10306 * @raw_sender_type is automatically reallocated UTF-8 string describing
10307 * sender type or NULL if not known to server. Pass NULL if you don't care.
10308 * @sender_name is automatically reallocated UTF-8 name of user who sent the
10309 * message, or NULL if not known to ISDS. Pass NULL if you don't care. */
10310 isds_error isds_get_message_sender(struct isds_ctx *context,
10311 const char *message_id, isds_sender_type **sender_type,
10312 char **raw_sender_type, char **sender_name) {
10313 isds_error err = IE_SUCCESS;
10314 #if HAVE_LIBCURL
10315 xmlDocPtr response = NULL;
10316 xmlChar *code = NULL, *status_message = NULL;
10317 xmlXPathContextPtr xpath_ctx = NULL;
10318 xmlXPathObjectPtr result = NULL;
10319 char *type_string = NULL;
10320 #endif
10322 if (!context) return IE_INVALID_CONTEXT;
10323 zfree(context->long_message);
10324 if (sender_type) zfree(*sender_type);
10325 if (raw_sender_type) zfree(*raw_sender_type);
10326 if (sender_name) zfree(*sender_name);
10327 if (!message_id) return IE_INVAL;
10329 #if HAVE_LIBCURL
10330 /* Do request and check for success */
10331 err = build_send_check_message_request(context, SERVICE_DM_INFO,
10332 BAD_CAST "GetMessageAuthor",
10333 message_id, &response, NULL, NULL, &code, &status_message);
10334 if (err) goto leave;
10336 /* Extract data */
10337 xpath_ctx = xmlXPathNewContext(response);
10338 if (!xpath_ctx) {
10339 err = IE_ERROR;
10340 goto leave;
10342 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
10343 err = IE_ERROR;
10344 goto leave;
10346 result = xmlXPathEvalExpression(
10347 BAD_CAST "/isds:GetMessageAuthorResponse", xpath_ctx);
10348 if (!result) {
10349 err = IE_ERROR;
10350 goto leave;
10352 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
10353 isds_log_message(context,
10354 _("Missing GetMessageAuthorResponse element"));
10355 err = IE_ISDS;
10356 goto leave;
10358 if (result->nodesetval->nodeNr > 1) {
10359 isds_log_message(context,
10360 _("Multiple GetMessageAuthorResponse element"));
10361 err = IE_ISDS;
10362 goto leave;
10364 xpath_ctx->node = result->nodesetval->nodeTab[0];
10365 xmlXPathFreeObject(result); result = NULL;
10367 /* Fill output arguments in */
10368 EXTRACT_STRING("isds:userType", type_string);
10369 if (type_string) {
10370 *sender_type = calloc(1, sizeof(**sender_type));
10371 if (!*sender_type) {
10372 err = IE_NOMEM;
10373 goto leave;
10376 if (sender_type) {
10377 err = string2isds_sender_type((xmlChar *)type_string,
10378 *sender_type);
10379 if (err) {
10380 zfree(*sender_type);
10381 if (err == IE_ENUM) {
10382 err = IE_SUCCESS;
10383 char *type_string_locale = _isds_utf82locale(type_string);
10384 isds_log(ILF_ISDS, ILL_WARNING,
10385 _("Unknown isds:userType value: %s"),
10386 type_string_locale);
10387 free(type_string_locale);
10392 if (sender_type)
10393 EXTRACT_STRING("isds:authorName", *sender_name);
10395 leave:
10396 if (err) {
10397 if (sender_type) zfree(*sender_type);
10398 zfree(type_string);
10399 if (sender_name) zfree(*sender_name);
10401 if (raw_sender_type) *raw_sender_type = type_string;
10403 xmlXPathFreeObject(result);
10404 xmlXPathFreeContext(xpath_ctx);
10406 free(code);
10407 free(status_message);
10408 xmlFreeDoc(response);
10410 if (!err)
10411 isds_log(ILF_ISDS, ILL_DEBUG,
10412 _("GetMessageAuthor request processed by server "
10413 "successfully.\n"));
10414 #else /* not HAVE_LIBCURL */
10415 err = IE_NOTSUP;
10416 #endif
10417 return err;
10421 /* Retrieve hash of message identified by ID stored in ISDS.
10422 * @context is session context
10423 * @message_id is message identifier
10424 * @hash is automatically reallocated message hash downloaded from ISDS.
10425 * Message must exist in system and must not be deleted. */
10426 isds_error isds_download_message_hash(struct isds_ctx *context,
10427 const char *message_id, struct isds_hash **hash) {
10429 isds_error err = IE_SUCCESS;
10430 #if HAVE_LIBCURL
10431 xmlDocPtr response = NULL;
10432 xmlChar *code = NULL, *status_message = NULL;
10433 xmlXPathContextPtr xpath_ctx = NULL;
10434 xmlXPathObjectPtr result = NULL;
10435 #endif
10437 if (!context) return IE_INVALID_CONTEXT;
10438 zfree(context->long_message);
10440 isds_hash_free(hash);
10442 #if HAVE_LIBCURL
10443 err = build_send_check_message_request(context, SERVICE_DM_INFO,
10444 BAD_CAST "VerifyMessage", message_id,
10445 &response, NULL, NULL, &code, &status_message);
10446 if (err) goto leave;
10449 /* Extract data */
10450 xpath_ctx = xmlXPathNewContext(response);
10451 if (!xpath_ctx) {
10452 err = IE_ERROR;
10453 goto leave;
10455 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
10456 err = IE_ERROR;
10457 goto leave;
10459 result = xmlXPathEvalExpression(
10460 BAD_CAST "/isds:VerifyMessageResponse",
10461 xpath_ctx);
10462 if (!result) {
10463 err = IE_ERROR;
10464 goto leave;
10466 /* Empty response */
10467 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
10468 char *message_id_locale = _isds_utf82locale((char*) message_id);
10469 isds_printf_message(context,
10470 _("Server did not return any response for ID `%s' "
10471 "on VerifyMessage request"), message_id_locale);
10472 free(message_id_locale);
10473 err = IE_ISDS;
10474 goto leave;
10476 /* More responses */
10477 if (result->nodesetval->nodeNr > 1) {
10478 char *message_id_locale = _isds_utf82locale((char*) message_id);
10479 isds_printf_message(context,
10480 _("Server did return more responses for ID `%s' "
10481 "on VerifyMessage request"), message_id_locale);
10482 free(message_id_locale);
10483 err = IE_ISDS;
10484 goto leave;
10486 /* One response */
10487 xpath_ctx->node = result->nodesetval->nodeTab[0];
10489 /* Extract the hash */
10490 err = find_and_extract_DmHash(context, hash, xpath_ctx);
10492 leave:
10493 if (err) {
10494 isds_hash_free(hash);
10497 xmlXPathFreeObject(result);
10498 xmlXPathFreeContext(xpath_ctx);
10500 free(code);
10501 free(status_message);
10502 xmlFreeDoc(response);
10504 if (!err)
10505 isds_log(ILF_ISDS, ILL_DEBUG,
10506 _("VerifyMessage request processed by server "
10507 "successfully.\n")
10509 #else /* not HAVE_LIBCURL */
10510 err = IE_NOTSUP;
10511 #endif
10512 return err;
10516 /* Erase message specified by @message_id from long term storage. Other
10517 * message cannot be erased on user request.
10518 * @context is session context
10519 * @message_id is message identifier.
10520 * @incoming is true for incoming message, false for outgoing message.
10521 * @return
10522 * IE_SUCCESS if message has ben removed
10523 * IE_INVAL if message does not exist in long term storage or message
10524 * belongs to different box
10525 * TODO: IE_NOEPRM if user has no permission to erase a message */
10526 isds_error isds_delete_message_from_storage(struct isds_ctx *context,
10527 const char *message_id, _Bool incoming) {
10528 isds_error err = IE_SUCCESS;
10529 #if HAVE_LIBCURL
10530 xmlNodePtr request = NULL, node;
10531 xmlNsPtr isds_ns = NULL;
10532 xmlDocPtr response = NULL;
10533 xmlChar *code = NULL, *status_message = NULL;
10534 #endif
10536 if (!context) return IE_INVALID_CONTEXT;
10537 zfree(context->long_message);
10538 if (NULL == message_id) return IE_INVAL;
10540 /* Check if connection is established
10541 * TODO: This check should be done downstairs. */
10542 if (!context->curl) return IE_CONNECTION_CLOSED;
10544 #if HAVE_LIBCURL
10545 /* Build request */
10546 request = xmlNewNode(NULL, BAD_CAST "EraseMessage");
10547 if (!request) {
10548 isds_log_message(context,
10549 _("Could build EraseMessage request"));
10550 return IE_ERROR;
10552 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
10553 if(!isds_ns) {
10554 isds_log_message(context, _("Could not create ISDS name space"));
10555 xmlFreeNode(request);
10556 return IE_ERROR;
10558 xmlSetNs(request, isds_ns);
10560 err = validate_message_id_length(context, (xmlChar *) message_id);
10561 if (err) goto leave;
10562 INSERT_STRING(request, "dmID", message_id);
10564 INSERT_SCALAR_BOOLEAN(request, "dmIncoming", incoming);
10567 /* Send request */
10568 isds_log(ILF_ISDS, ILL_DEBUG, _("Sending EraseMessage request for "
10569 "message ID %s to ISDS\n"), message_id);
10570 err = isds(context, SERVICE_DM_INFO, request, &response, NULL, NULL);
10571 xmlFreeNode(request); request = NULL;
10573 if (err) {
10574 isds_log(ILF_ISDS, ILL_DEBUG,
10575 _("Processing ISDS response on EraseMessage request "
10576 "failed\n"));
10577 goto leave;
10580 /* Check for response status */
10581 err = isds_response_status(context, SERVICE_DM_INFO, response,
10582 &code, &status_message, NULL);
10583 if (err) {
10584 isds_log(ILF_ISDS, ILL_DEBUG,
10585 _("ISDS response on EraseMessage request is missing "
10586 "status\n"));
10587 goto leave;
10590 /* Check server status code */
10591 if (!xmlStrcmp(code, BAD_CAST "1211")) {
10592 isds_log_message(context, _("Message to erase belongs to other box"));
10593 err = IE_INVAL;
10594 } else if (!xmlStrcmp(code, BAD_CAST "1219")) {
10595 isds_log_message(context, _("Message to erase is not saved in "
10596 "long term storage or the direction does not match"));
10597 err = IE_INVAL;
10598 } else if (xmlStrcmp(code, BAD_CAST "0000")) {
10599 char *code_locale = _isds_utf82locale((char*) code);
10600 char *message_locale = _isds_utf82locale((char*) status_message);
10601 isds_log(ILF_ISDS, ILL_DEBUG,
10602 _("Server refused EraseMessage request "
10603 "(code=%s, message=%s)\n"),
10604 code_locale, message_locale);
10605 isds_log_message(context, message_locale);
10606 free(code_locale);
10607 free(message_locale);
10608 err = IE_ISDS;
10609 goto leave;
10612 leave:
10613 free(code);
10614 free(status_message);
10615 xmlFreeDoc(response);
10616 xmlFreeNode(request);
10618 if (!err)
10619 isds_log(ILF_ISDS, ILL_DEBUG,
10620 _("EraseMessage request processed by server "
10621 "successfully.\n")
10623 #else /* not HAVE_LIBCURL */
10624 err = IE_NOTSUP;
10625 #endif
10626 return err;
10630 /* Mark message as read. This is a transactional commit function to acknowledge
10631 * to ISDS the message has been downloaded and processed by client properly.
10632 * @context is session context
10633 * @message_id is message identifier. */
10634 isds_error isds_mark_message_read(struct isds_ctx *context,
10635 const char *message_id) {
10637 isds_error err = IE_SUCCESS;
10638 #if HAVE_LIBCURL
10639 xmlDocPtr response = NULL;
10640 xmlChar *code = NULL, *status_message = NULL;
10641 #endif
10643 if (!context) return IE_INVALID_CONTEXT;
10644 zfree(context->long_message);
10646 #if HAVE_LIBCURL
10647 /* Do request and check for success */
10648 err = build_send_check_message_request(context, SERVICE_DM_INFO,
10649 BAD_CAST "MarkMessageAsDownloaded", message_id,
10650 &response, NULL, NULL, &code, &status_message);
10652 free(code);
10653 free(status_message);
10654 xmlFreeDoc(response);
10656 if (!err)
10657 isds_log(ILF_ISDS, ILL_DEBUG,
10658 _("MarkMessageAsDownloaded request processed by server "
10659 "successfully.\n")
10661 #else /* not HAVE_LIBCURL */
10662 err = IE_NOTSUP;
10663 #endif
10664 return err;
10668 /* Mark message as received by recipient. This is applicable only to
10669 * commercial message. Use envelope->dmType message member to distinguish
10670 * commercial message from government message. Government message is
10671 * received automatically (by law), commercial message on recipient request.
10672 * @context is session context
10673 * @message_id is message identifier. */
10674 isds_error isds_mark_message_received(struct isds_ctx *context,
10675 const char *message_id) {
10677 isds_error err = IE_SUCCESS;
10678 #if HAVE_LIBCURL
10679 xmlDocPtr response = NULL;
10680 xmlChar *code = NULL, *status_message = NULL;
10681 #endif
10683 if (!context) return IE_INVALID_CONTEXT;
10684 zfree(context->long_message);
10686 #if HAVE_LIBCURL
10687 /* Do request and check for success */
10688 err = build_send_check_message_request(context, SERVICE_DM_INFO,
10689 BAD_CAST "ConfirmDelivery", message_id,
10690 &response, NULL, NULL, &code, &status_message);
10692 free(code);
10693 free(status_message);
10694 xmlFreeDoc(response);
10696 if (!err)
10697 isds_log(ILF_ISDS, ILL_DEBUG,
10698 _("ConfirmDelivery request processed by server "
10699 "successfully.\n")
10701 #else /* not HAVE_LIBCURL */
10702 err = IE_NOTSUP;
10703 #endif
10704 return err;
10708 /* Send document for authorized conversion into Czech POINT system.
10709 * This is public anonymous service, no log-in necessary. Special context is
10710 * used to reuse keep-a-live HTTPS connection.
10711 * @context is Czech POINT session context. DO NOT use context connected to
10712 * ISDS server. Use new context or context used by this function previously.
10713 * @document is document to convert. Only data, data_length, dmFileDescr and
10714 * is_xml members are significant. Be ware that not all document formats can be
10715 * converted (signed PDF 1.3 and higher only (2010-02 state)).
10716 * @id is reallocated identifier assigned by Czech POINT system to
10717 * your document on submit. Use is to tell it to Czech POINT officer.
10718 * @date is reallocated document submit date (submitted documents
10719 * expires after some period). Only tm_year, tm_mon and tm_mday carry sane
10720 * value. */
10721 isds_error czp_convert_document(struct isds_ctx *context,
10722 const struct isds_document *document,
10723 char **id, struct tm **date) {
10724 isds_error err = IE_SUCCESS;
10725 #if HAVE_LIBCURL
10726 xmlNsPtr deposit_ns = NULL, empty_ns = NULL;
10727 xmlNodePtr request = NULL, node;
10728 xmlDocPtr response = NULL;
10730 xmlXPathContextPtr xpath_ctx = NULL;
10731 xmlXPathObjectPtr result = NULL;
10732 long int status = -1;
10733 long int *status_ptr = &status;
10734 char *string = NULL;
10735 #endif
10738 if (!context) return IE_INVALID_CONTEXT;
10739 zfree(context->long_message);
10740 if (!document || !id || !date) return IE_INVAL;
10742 if (document->is_xml) {
10743 isds_log_message(context,
10744 _("XML documents cannot be submitted to conversion"));
10745 return IE_NOTSUP;
10748 /* Free output arguments */
10749 zfree(*id);
10750 zfree(*date);
10752 #if HAVE_LIBCURL
10753 /* Store configuration */
10754 context->type = CTX_TYPE_CZP;
10755 free(context->url);
10756 context->url = strdup("https://www.czechpoint.cz/uschovna/services.php");
10757 if (!(context->url))
10758 return IE_NOMEM;
10760 /* Prepare CURL handle if not yet connected */
10761 if (!context->curl) {
10762 context->curl = curl_easy_init();
10763 if (!(context->curl))
10764 return IE_ERROR;
10767 /* Build conversion request */
10768 request = xmlNewNode(NULL, BAD_CAST "saveDocument");
10769 if (!request) {
10770 isds_log_message(context,
10771 _("Could not build Czech POINT conversion request"));
10772 return IE_ERROR;
10774 deposit_ns = xmlNewNs(request, BAD_CAST DEPOSIT_NS, BAD_CAST "dep");
10775 if(!deposit_ns) {
10776 isds_log_message(context,
10777 _("Could not create Czech POINT deposit name space"));
10778 xmlFreeNode(request);
10779 return IE_ERROR;
10781 xmlSetNs(request, deposit_ns);
10783 /* Insert children. They are in empty namespace! */
10784 empty_ns = xmlNewNs(request, BAD_CAST "", NULL);
10785 if(!empty_ns) {
10786 isds_log_message(context, _("Could not create empty name space"));
10787 err = IE_ERROR;
10788 goto leave;
10790 INSERT_STRING_WITH_NS(request, empty_ns, "conversionID", "0");
10791 INSERT_STRING_WITH_NS(request, empty_ns, "fileName",
10792 document->dmFileDescr);
10794 /* Document encoded in Base64 */
10795 err = insert_base64_encoded_string(context, request, empty_ns, "document",
10796 document->data, document->data_length);
10797 if (err) goto leave;
10799 isds_log(ILF_ISDS, ILL_DEBUG,
10800 _("Submitting document for conversion into Czech POINT deposit"));
10802 /* Send conversion request */
10803 err = _czp_czpdeposit(context, request, &response);
10804 xmlFreeNode(request); request = NULL;
10806 if (err) {
10807 czp_do_close_connection(context);
10808 goto leave;
10812 /* Extract response */
10813 xpath_ctx = xmlXPathNewContext(response);
10814 if (!xpath_ctx) {
10815 err = IE_ERROR;
10816 goto leave;
10818 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
10819 err = IE_ERROR;
10820 goto leave;
10822 result = xmlXPathEvalExpression(
10823 BAD_CAST "/deposit:saveDocumentResponse/return",
10824 xpath_ctx);
10825 if (!result) {
10826 err = IE_ERROR;
10827 goto leave;
10829 /* Empty response */
10830 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
10831 isds_printf_message(context,
10832 _("Missing `return' element in Czech POINT deposit response"));
10833 err = IE_ISDS;
10834 goto leave;
10836 /* More responses */
10837 if (result->nodesetval->nodeNr > 1) {
10838 isds_printf_message(context,
10839 _("Multiple `return' element in Czech POINT deposit response"));
10840 err = IE_ISDS;
10841 goto leave;
10843 /* One response */
10844 xpath_ctx->node = result->nodesetval->nodeTab[0];
10846 /* Get status */
10847 EXTRACT_LONGINT("status", status_ptr, 1);
10848 if (status) {
10849 EXTRACT_STRING("statusMsg", string);
10850 char *string_locale = _isds_utf82locale(string);
10851 isds_printf_message(context,
10852 _("Czech POINT deposit refused document for conversion "
10853 "(code=%ld, message=%s)"),
10854 status, string_locale);
10855 free(string_locale);
10856 err = IE_ISDS;
10857 goto leave;
10860 /* Get document ID */
10861 EXTRACT_STRING("documentID", *id);
10863 /* Get submit date */
10864 EXTRACT_STRING("dateInserted", string);
10865 if (string) {
10866 *date = calloc(1, sizeof(**date));
10867 if (!*date) {
10868 err = IE_NOMEM;
10869 goto leave;
10871 err = _isds_datestring2tm((xmlChar *)string, *date);
10872 if (err) {
10873 if (err == IE_NOTSUP) {
10874 err = IE_ISDS;
10875 char *string_locale = _isds_utf82locale(string);
10876 isds_printf_message(context,
10877 _("Invalid dateInserted value: %s"), string_locale);
10878 free(string_locale);
10880 goto leave;
10884 leave:
10885 free(string);
10886 xmlXPathFreeObject(result);
10887 xmlXPathFreeContext(xpath_ctx);
10889 xmlFreeDoc(response);
10890 xmlFreeNode(request);
10892 if (!err) {
10893 char *id_locale = _isds_utf82locale((char *) *id);
10894 isds_log(ILF_ISDS, ILL_DEBUG,
10895 _("Document %s has been submitted for conversion "
10896 "to server successfully\n"), id_locale);
10897 free(id_locale);
10899 #else /* not HAVE_LIBCURL */
10900 err = IE_NOTSUP;
10901 #endif
10902 return err;
10906 /* Close possibly opened connection to Czech POINT document deposit.
10907 * @context is Czech POINT session context. */
10908 isds_error czp_close_connection(struct isds_ctx *context) {
10909 if (!context) return IE_INVALID_CONTEXT;
10910 zfree(context->long_message);
10911 #if HAVE_LIBCURL
10912 return czp_do_close_connection(context);
10913 #else
10914 return IE_NOTSUP;
10915 #endif
10919 /* Send request for new box creation in testing ISDS instance.
10920 * It's not possible to request for a production box currently, as it
10921 * communicates via e-mail.
10922 * XXX: This function does not work either. Server complains about invalid
10923 * e-mail address.
10924 * XXX: Remove context->type hacks in isds.c and validator.c when removing
10925 * this function
10926 * @context is special session context for box creation request. DO NOT use
10927 * standard context as it could reveal your password. Use fresh new context or
10928 * context previously used by this function.
10929 * @box is box description to create including single primary user (in case of
10930 * FO box type). It outputs box ID assigned by ISDS in dbID element.
10931 * @users is list of struct isds_DbUserInfo (primary users in case of non-FO
10932 * box, or contact address of PFO box owner). The email member is mandatory as
10933 * it will be used to deliver credentials.
10934 * @former_names is former name of box owner. Pass NULL if you don't care.
10935 * @approval is optional external approval of box manipulation
10936 * @refnumber is reallocated serial number of request assigned by ISDS. Use
10937 * NULL, if you don't care.*/
10938 isds_error isds_request_new_testing_box(struct isds_ctx *context,
10939 struct isds_DbOwnerInfo *box, const struct isds_list *users,
10940 const char *former_names, const struct isds_approval *approval,
10941 char **refnumber) {
10942 isds_error err = IE_SUCCESS;
10943 #if HAVE_LIBCURL
10944 xmlNodePtr request = NULL;
10945 xmlDocPtr response = NULL;
10946 xmlXPathContextPtr xpath_ctx = NULL;
10947 xmlXPathObjectPtr result = NULL;
10948 #endif
10951 if (!context) return IE_INVALID_CONTEXT;
10952 zfree(context->long_message);
10953 if (!box) return IE_INVAL;
10955 #if HAVE_LIBCURL
10956 if (!box->email || box->email[0] == '\0') {
10957 isds_log_message(context, _("E-mail field is mandatory"));
10958 return IE_INVAL;
10961 /* Scratch box ID */
10962 zfree(box->dbID);
10964 /* Store configuration */
10965 context->type = CTX_TYPE_TESTING_REQUEST_COLLECTOR;
10966 free(context->url);
10967 context->url = strdup("http://78.102.19.203/testbox/request_box.php");
10968 if (!(context->url))
10969 return IE_NOMEM;
10971 /* Prepare CURL handle if not yet connected */
10972 if (!context->curl) {
10973 context->curl = curl_easy_init();
10974 if (!(context->curl))
10975 return IE_ERROR;
10978 /* Build CreateDataBox request */
10979 err = build_CreateDBInput_request(context,
10980 &request, BAD_CAST "CreateDataBox",
10981 box, users, (xmlChar *) former_names, NULL, NULL, NULL, approval);
10982 if (err) goto leave;
10984 /* Send it to server and process response */
10985 err = send_destroy_request_check_response(context,
10986 SERVICE_DB_MANIPULATION, BAD_CAST "CreateDataBox", &request,
10987 &response, (xmlChar **) refnumber, NULL);
10988 if (err) goto leave;
10990 /* Extract box ID */
10991 xpath_ctx = xmlXPathNewContext(response);
10992 if (!xpath_ctx) {
10993 err = IE_ERROR;
10994 goto leave;
10996 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
10997 err = IE_ERROR;
10998 goto leave;
11000 EXTRACT_STRING("/isds:CreateDataBoxResponse/isds:dbID", box->dbID);
11002 leave:
11003 xmlXPathFreeObject(result);
11004 xmlXPathFreeContext(xpath_ctx);
11005 xmlFreeDoc(response);
11006 xmlFreeNode(request);
11008 if (!err) {
11009 isds_log(ILF_ISDS, ILL_DEBUG,
11010 _("CreateDataBox request processed by server successfully.\n"));
11012 #else /* not HAVE_LIBCURL */
11013 err = IE_NOTSUP;
11014 #endif
11016 return err;
11020 /* Submit CMS signed message to ISDS to verify its originality. This is
11021 * stronger form of isds_verify_message_hash() because ISDS does more checks
11022 * than simple one (potentialy old weak) hash comparison.
11023 * @context is session context
11024 * @message is memory with raw CMS signed message bit stream
11025 * @length is @message size in bytes
11026 * @return
11027 * IE_SUCCESS if message originates in ISDS
11028 * IE_NOTEQUAL if message is unknown to ISDS
11029 * other code for other errors */
11030 isds_error isds_authenticate_message(struct isds_ctx *context,
11031 const void *message, size_t length) {
11032 isds_error err = IE_SUCCESS;
11033 #if HAVE_LIBCURL
11034 xmlNsPtr isds_ns = NULL;
11035 xmlNodePtr request = NULL;
11036 xmlDocPtr response = NULL;
11037 xmlXPathContextPtr xpath_ctx = NULL;
11038 xmlXPathObjectPtr result = NULL;
11039 _Bool *authentic = NULL;
11040 #endif
11042 if (!context) return IE_INVALID_CONTEXT;
11043 zfree(context->long_message);
11044 if (!message || length == 0) return IE_INVAL;
11046 #if HAVE_LIBCURL
11047 /* Check if connection is established
11048 * TODO: This check should be done downstairs. */
11049 if (!context->curl) return IE_CONNECTION_CLOSED;
11052 /* Build AuthenticateMessage request */
11053 request = xmlNewNode(NULL, BAD_CAST "AuthenticateMessage");
11054 if (!request) {
11055 isds_log_message(context,
11056 _("Could not build AuthenticateMessage request"));
11057 return IE_ERROR;
11059 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
11060 if(!isds_ns) {
11061 isds_log_message(context, _("Could not create ISDS name space"));
11062 xmlFreeNode(request);
11063 return IE_ERROR;
11065 xmlSetNs(request, isds_ns);
11067 /* Insert Base64 encoded message */
11068 err = insert_base64_encoded_string(context, request, NULL, "dmMessage",
11069 message, length);
11070 if (err) goto leave;
11072 /* Send request to server and process response */
11073 err = send_destroy_request_check_response(context,
11074 SERVICE_DM_OPERATIONS, BAD_CAST "AuthenticateMessage", &request,
11075 &response, NULL, NULL);
11076 if (err) goto leave;
11079 /* ISDS has decided */
11080 xpath_ctx = xmlXPathNewContext(response);
11081 if (!xpath_ctx) {
11082 err = IE_ERROR;
11083 goto leave;
11085 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
11086 err = IE_ERROR;
11087 goto leave;
11090 EXTRACT_BOOLEAN("/isds:AuthenticateMessageResponse/isds:dmAuthResult", authentic);
11092 if (!authentic) {
11093 isds_log_message(context,
11094 _("Server did not return any response on "
11095 "AuthenticateMessage request"));
11096 err = IE_ISDS;
11097 goto leave;
11099 if (*authentic) {
11100 isds_log(ILF_ISDS, ILL_DEBUG,
11101 _("ISDS authenticated the message successfully\n"));
11102 } else {
11103 isds_log_message(context, _("ISDS does not know the message"));
11104 err = IE_NOTEQUAL;
11108 leave:
11109 free(authentic);
11110 xmlXPathFreeObject(result);
11111 xmlXPathFreeContext(xpath_ctx);
11113 xmlFreeDoc(response);
11114 xmlFreeNode(request);
11115 #else /* not HAVE_LIBCURL */
11116 err = IE_NOTSUP;
11117 #endif
11119 return err;
11123 /* Submit CMS signed message or delivery info to ISDS to re-sign the content
11124 * including adding new CMS time stamp. Only CMS blobs without time stamp can
11125 * be re-signed.
11126 * @context is session context
11127 * @input_data is memory with raw CMS signed message or delivery info bit
11128 * stream to re-sign
11129 * @input_length is @input_data size in bytes
11130 * @output_data is pointer to auto-allocated memory where to store re-signed
11131 * input data blob. Caller must free it.
11132 * @output_data is pointer where to store @output_data size in bytes
11133 * @valid_to is pointer to auto-allocated date of time stamp expiration.
11134 * Only tm_year, tm_mon and tm_mday will be set. Pass NULL, if you don't care.
11135 * @return
11136 * IE_SUCCESS if CMS blob has been re-signed successfully
11137 * other code for other errors */
11138 isds_error isds_resign_message(struct isds_ctx *context,
11139 const void *input_data, size_t input_length,
11140 void **output_data, size_t *output_length, struct tm **valid_to) {
11141 isds_error err = IE_SUCCESS;
11142 #if HAVE_LIBCURL
11143 xmlNsPtr isds_ns = NULL;
11144 xmlNodePtr request = NULL;
11145 xmlDocPtr response = NULL;
11146 xmlXPathContextPtr xpath_ctx = NULL;
11147 xmlXPathObjectPtr result = NULL;
11148 char *string = NULL;
11149 const xmlChar *codes[] = {
11150 BAD_CAST "2200",
11151 BAD_CAST "2201",
11152 BAD_CAST "2204",
11153 BAD_CAST "2207",
11154 NULL
11156 const char *meanings[] = {
11157 "Message is bad",
11158 "Message is not original",
11159 "Message already contains time stamp in CAdES-EPES or CAdES-T CMS structure",
11160 "Time stamp could not been generated in time"
11162 const isds_error errors[] = {
11163 IE_INVAL,
11164 IE_NOTUNIQ,
11165 IE_INVAL,
11166 IE_ISDS,
11168 struct code_map_isds_error map = {
11169 .codes = codes,
11170 .meanings = meanings,
11171 .errors = errors
11173 #endif
11175 if (NULL != output_data) *output_data = NULL;
11176 if (NULL != output_length) *output_length = 0;
11177 if (NULL != valid_to) *valid_to = NULL;
11179 if (NULL == context) return IE_INVALID_CONTEXT;
11180 zfree(context->long_message);
11181 if (NULL == input_data || 0 == input_length) {
11182 isds_log_message(context, _("Empty CMS blob on input"));
11183 return IE_INVAL;
11185 if (NULL == output_data || NULL == output_length) {
11186 isds_log_message(context,
11187 _("NULL pointer provided for output CMS blob"));
11188 return IE_INVAL;
11191 #if HAVE_LIBCURL
11192 /* Check if connection is established
11193 * TODO: This check should be done downstairs. */
11194 if (!context->curl) return IE_CONNECTION_CLOSED;
11197 /* Build Re-signISDSDocument request */
11198 request = xmlNewNode(NULL, BAD_CAST "Re-signISDSDocument");
11199 if (!request) {
11200 isds_log_message(context,
11201 _("Could not build Re-signISDSDocument request"));
11202 return IE_ERROR;
11204 isds_ns = xmlNewNs(request, BAD_CAST ISDS_NS, NULL);
11205 if(!isds_ns) {
11206 isds_log_message(context, _("Could not create ISDS name space"));
11207 xmlFreeNode(request);
11208 return IE_ERROR;
11210 xmlSetNs(request, isds_ns);
11212 /* Insert Base64 encoded CMS blob */
11213 err = insert_base64_encoded_string(context, request, NULL, "dmDoc",
11214 input_data, input_length);
11215 if (err) goto leave;
11217 /* Send request to server and process response */
11218 err = send_destroy_request_check_response(context,
11219 SERVICE_DM_OPERATIONS, BAD_CAST "Re-signISDSDocument", &request,
11220 &response, NULL, &map);
11221 if (err) goto leave;
11224 /* Extract re-signed data */
11225 xpath_ctx = xmlXPathNewContext(response);
11226 if (!xpath_ctx) {
11227 err = IE_ERROR;
11228 goto leave;
11230 if (_isds_register_namespaces(xpath_ctx, MESSAGE_NS_UNSIGNED)) {
11231 err = IE_ERROR;
11232 goto leave;
11234 result = xmlXPathEvalExpression(
11235 BAD_CAST "/isds:Re-signISDSDocumentResponse", xpath_ctx);
11236 if (!result) {
11237 err = IE_ERROR;
11238 goto leave;
11240 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
11241 isds_log_message(context,
11242 _("Missing Re-signISDSDocumentResponse element"));
11243 err = IE_ISDS;
11244 goto leave;
11246 if (result->nodesetval->nodeNr > 1) {
11247 isds_log_message(context,
11248 _("Multiple Re-signISDSDocumentResponse element"));
11249 err = IE_ISDS;
11250 goto leave;
11252 xpath_ctx->node = result->nodesetval->nodeTab[0];
11253 xmlXPathFreeObject(result); result = NULL;
11255 EXTRACT_STRING("isds:dmResultDoc", string);
11256 /* Decode non-empty data */
11257 if (NULL != string && string[0] != '\0') {
11258 *output_length = _isds_b64decode(string, output_data);
11259 if (*output_length == (size_t) -1) {
11260 isds_log_message(context,
11261 _("Error while Base64-decoding re-signed data"));
11262 err = IE_ERROR;
11263 goto leave;
11265 } else {
11266 isds_log_message(context, _("Server did not send re-signed data"));
11267 err = IE_ISDS;
11268 goto leave;
11270 zfree(string);
11272 if (NULL != valid_to) {
11273 /* Get time stamp expiration date */
11274 EXTRACT_STRING("isds:dmValidTo", string);
11275 if (NULL != string) {
11276 *valid_to = calloc(1, sizeof(**valid_to));
11277 if (!*valid_to) {
11278 err = IE_NOMEM;
11279 goto leave;
11281 err = _isds_datestring2tm((xmlChar *)string, *valid_to);
11282 if (err) {
11283 if (err == IE_NOTSUP) {
11284 err = IE_ISDS;
11285 char *string_locale = _isds_utf82locale(string);
11286 isds_printf_message(context,
11287 _("Invalid dmValidTo value: %s"), string_locale);
11288 free(string_locale);
11290 goto leave;
11295 leave:
11296 free(string);
11298 xmlXPathFreeObject(result);
11299 xmlXPathFreeContext(xpath_ctx);
11301 xmlFreeDoc(response);
11302 xmlFreeNode(request);
11303 #else /* not HAVE_LIBCURL */
11304 err = IE_NOTSUP;
11305 #endif
11307 return err;
11310 #undef INSERT_ELEMENT
11311 #undef CHECK_FOR_STRING_LENGTH
11312 #undef INSERT_STRING_ATTRIBUTE
11313 #undef INSERT_ULONGINTNOPTR
11314 #undef INSERT_ULONGINT
11315 #undef INSERT_LONGINT
11316 #undef INSERT_BOOLEAN
11317 #undef INSERT_SCALAR_BOOLEAN
11318 #undef INSERT_STRING
11319 #undef INSERT_STRING_WITH_NS
11320 #undef EXTRACT_STRING_ATTRIBUTE
11321 #undef EXTRACT_ULONGINT
11322 #undef EXTRACT_LONGINT
11323 #undef EXTRACT_BOOLEAN
11324 #undef EXTRACT_STRING
11327 /* Compute hash of message from raw representation and store it into envelope.
11328 * Original hash structure will be destroyed in envelope.
11329 * @context is session context
11330 * @message is message carrying raw XML message blob
11331 * @algorithm is desired hash algorithm to use */
11332 isds_error isds_compute_message_hash(struct isds_ctx *context,
11333 struct isds_message *message, const isds_hash_algorithm algorithm) {
11334 isds_error err = IE_SUCCESS;
11335 const char *nsuri;
11336 void *xml_stream = NULL;
11337 size_t xml_stream_length;
11338 size_t phys_start, phys_end;
11339 char *phys_path = NULL;
11340 struct isds_hash *new_hash = NULL;
11343 if (!context) return IE_INVALID_CONTEXT;
11344 zfree(context->long_message);
11345 if (!message) return IE_INVAL;
11347 if (!message->raw) {
11348 isds_log_message(context,
11349 _("Message does not carry raw representation"));
11350 return IE_INVAL;
11353 switch (message->raw_type) {
11354 case RAWTYPE_INCOMING_MESSAGE:
11355 nsuri = ISDS_NS;
11356 xml_stream = message->raw;
11357 xml_stream_length = message->raw_length;
11358 break;
11360 case RAWTYPE_PLAIN_SIGNED_INCOMING_MESSAGE:
11361 nsuri = SISDS_INCOMING_NS;
11362 xml_stream = message->raw;
11363 xml_stream_length = message->raw_length;
11364 break;
11366 case RAWTYPE_CMS_SIGNED_INCOMING_MESSAGE:
11367 nsuri = SISDS_INCOMING_NS;
11368 err = _isds_extract_cms_data(context,
11369 message->raw, message->raw_length,
11370 &xml_stream, &xml_stream_length);
11371 if (err) goto leave;
11372 break;
11374 case RAWTYPE_PLAIN_SIGNED_OUTGOING_MESSAGE:
11375 nsuri = SISDS_OUTGOING_NS;
11376 xml_stream = message->raw;
11377 xml_stream_length = message->raw_length;
11378 break;
11380 case RAWTYPE_CMS_SIGNED_OUTGOING_MESSAGE:
11381 nsuri = SISDS_OUTGOING_NS;
11382 err = _isds_extract_cms_data(context,
11383 message->raw, message->raw_length,
11384 &xml_stream, &xml_stream_length);
11385 if (err) goto leave;
11386 break;
11388 default:
11389 isds_log_message(context, _("Bad raw representation type"));
11390 return IE_INVAL;
11391 break;
11395 /* XXX: Hash is computed from original string representing isds:dmDm
11396 * subtree. That means no encoding, white space, xmlns attributes changes.
11397 * In other words, input for hash can be invalid XML stream. */
11398 if (-1 == isds_asprintf(&phys_path, "%s%s%s%s",
11399 nsuri, PHYSXML_NS_SEPARATOR "MessageDownloadResponse"
11400 PHYSXML_ELEMENT_SEPARATOR,
11401 nsuri, PHYSXML_NS_SEPARATOR "dmReturnedMessage"
11402 PHYSXML_ELEMENT_SEPARATOR
11403 ISDS_NS PHYSXML_NS_SEPARATOR "dmDm")) {
11404 err = IE_NOMEM;
11405 goto leave;
11407 err = _isds_find_element_boundary(xml_stream, xml_stream_length,
11408 phys_path, &phys_start, &phys_end);
11409 zfree(phys_path);
11410 if (err) {
11411 isds_log_message(context,
11412 _("Substring with isds:dmDM element could not be located "
11413 "in raw message"));
11414 goto leave;
11418 /* Compute hash */
11419 new_hash = calloc(1, sizeof(*new_hash));
11420 if (!new_hash) {
11421 err = IE_NOMEM;
11422 goto leave;
11424 new_hash->algorithm = algorithm;
11425 err = _isds_compute_hash(xml_stream + phys_start, phys_end - phys_start + 1,
11426 new_hash);
11427 if (err) {
11428 isds_log_message(context, _("Could not compute message hash"));
11429 goto leave;
11432 /* Save computed hash */
11433 if (!message->envelope) {
11434 message->envelope = calloc(1, sizeof(*message->envelope));
11435 if (!message->envelope) {
11436 err = IE_NOMEM;
11437 goto leave;
11440 isds_hash_free(&message->envelope->hash);
11441 message->envelope->hash = new_hash;
11443 leave:
11444 if (err) {
11445 isds_hash_free(&new_hash);
11448 free(phys_path);
11449 if (xml_stream != message->raw) free(xml_stream);
11450 return err;
11454 /* Compare two hashes.
11455 * @h1 is first hash
11456 * @h2 is another hash
11457 * @return
11458 * IE_SUCCESS if hashes equal
11459 * IE_NOTUNIQ if hashes are comparable, but they don't equal
11460 * IE_ENUM if not comparable, but both structures defined
11461 * IE_INVAL if some of the structures are undefined (NULL)
11462 * IE_ERROR if internal error occurs */
11463 isds_error isds_hash_cmp(const struct isds_hash *h1, const struct isds_hash *h2) {
11464 if (h1 == NULL || h2 == NULL) return IE_INVAL;
11465 if (h1->algorithm != h2->algorithm) return IE_ENUM;
11466 if (h1->length != h2->length) return IE_ERROR;
11467 if (h1->length > 0 && !h1->value) return IE_ERROR;
11468 if (h2->length > 0 && !h2->value) return IE_ERROR;
11470 for (int i = 0; i < h1->length; i++) {
11471 if (((uint8_t *) (h1->value))[i] != ((uint8_t *) (h2->value))[i])
11472 return IE_NOTEQUAL;
11474 return IE_SUCCESS;
11478 /* Check message has gone through ISDS by comparing message hash stored in
11479 * ISDS and locally computed hash. You must provide message with valid raw
11480 * member (do not use isds_load_message(..., BUFFER_DONT_STORE)).
11481 * This is convenient wrapper for isds_download_message_hash(),
11482 * isds_compute_message_hash(), and isds_hash_cmp() sequence.
11483 * @context is session context
11484 * @message is message with valid raw and envelope member; envelope->hash
11485 * member will be changed during function run. Use envelope on heap only.
11486 * @return
11487 * IE_SUCCESS if message originates in ISDS
11488 * IE_NOTEQUAL if message is unknown to ISDS
11489 * other code for other errors */
11490 isds_error isds_verify_message_hash(struct isds_ctx *context,
11491 struct isds_message *message) {
11492 isds_error err = IE_SUCCESS;
11493 struct isds_hash *downloaded_hash = NULL;
11495 if (!context) return IE_INVALID_CONTEXT;
11496 zfree(context->long_message);
11497 if (!message) return IE_INVAL;
11499 if (!message->envelope) {
11500 isds_log_message(context,
11501 _("Given message structure is missing envelope"));
11502 return IE_INVAL;
11504 if (!message->raw) {
11505 isds_log_message(context,
11506 _("Given message structure is missing raw representation"));
11507 return IE_INVAL;
11510 err = isds_download_message_hash(context, message->envelope->dmID,
11511 &downloaded_hash);
11512 if (err) goto leave;
11514 err = isds_compute_message_hash(context, message,
11515 downloaded_hash->algorithm);
11516 if (err) goto leave;
11518 err = isds_hash_cmp(downloaded_hash, message->envelope->hash);
11520 leave:
11521 isds_hash_free(&downloaded_hash);
11522 return err;
11526 /* Search for document by document ID in list of documents. IDs are compared
11527 * as UTF-8 string.
11528 * @documents is list of isds_documents
11529 * @id is document identifier
11530 * @return first matching document or NULL. */
11531 const struct isds_document *isds_find_document_by_id(
11532 const struct isds_list *documents, const char *id) {
11533 const struct isds_list *item;
11534 const struct isds_document *document;
11536 for (item = documents; item; item = item->next) {
11537 document = (struct isds_document *) item->data;
11538 if (!document) continue;
11540 if (!xmlStrcmp((xmlChar *) id, (xmlChar *) document->dmFileGuid))
11541 return document;
11544 return NULL;
11548 /* Normalize @mime_type to be proper MIME type.
11549 * ISDS servers pass invalid MIME types (e.g. "pdf"). This function tries to
11550 * guess regular MIME type (e.g. "application/pdf").
11551 * @mime_type is UTF-8 encoded MIME type to fix
11552 * @return original @mime_type if no better interpretation exists, or
11553 * constant static UTF-8 encoded string with proper MIME type. */
11554 const char *isds_normalize_mime_type(const char *mime_type) {
11555 if (!mime_type) return NULL;
11557 for (int offset = 0;
11558 offset < sizeof(extension_map_mime)/sizeof(extension_map_mime[0]);
11559 offset += 2) {
11560 if (!xmlStrcmp((const xmlChar*) mime_type, extension_map_mime[offset]))
11561 return (const char *) extension_map_mime[offset + 1];
11564 return mime_type;
11568 /*int isds_get_message(struct isds_ctx *context, const unsigned int id,
11569 struct isds_message **message);
11570 int isds_send_message(struct isds_ctx *context, struct isds_message *message);
11571 int isds_list_messages(struct isds_ctx *context, struct isds_message **message);
11572 int isds_find_recipient(struct isds_ctx *context, const struct address *pattern,
11573 struct isds_address **address);
11575 int isds_message_free(struct isds_message **message);
11576 int isds_address_free(struct isds_address **address);
11580 /* Makes known all relevant namespaces to given XPath context
11581 * @xpath_ctx is XPath context
11582 * @message_ns selects proper message name space. Unsigned and signed
11583 * messages and delivery info's differ in prefix and URI. */
11584 _hidden isds_error _isds_register_namespaces(xmlXPathContextPtr xpath_ctx,
11585 const message_ns_type message_ns) {
11586 const xmlChar *message_namespace = NULL;
11588 if (!xpath_ctx) return IE_ERROR;
11590 switch(message_ns) {
11591 case MESSAGE_NS_1:
11592 message_namespace = BAD_CAST ISDS1_NS; break;
11593 case MESSAGE_NS_UNSIGNED:
11594 message_namespace = BAD_CAST ISDS_NS; break;
11595 case MESSAGE_NS_SIGNED_INCOMING:
11596 message_namespace = BAD_CAST SISDS_INCOMING_NS; break;
11597 case MESSAGE_NS_SIGNED_OUTGOING:
11598 message_namespace = BAD_CAST SISDS_OUTGOING_NS; break;
11599 case MESSAGE_NS_SIGNED_DELIVERY:
11600 message_namespace = BAD_CAST SISDS_DELIVERY_NS; break;
11601 default:
11602 return IE_ENUM;
11605 if (xmlXPathRegisterNs(xpath_ctx, BAD_CAST "soap", BAD_CAST SOAP_NS))
11606 return IE_ERROR;
11607 if (xmlXPathRegisterNs(xpath_ctx, BAD_CAST "isds", BAD_CAST ISDS_NS))
11608 return IE_ERROR;
11609 if (xmlXPathRegisterNs(xpath_ctx, BAD_CAST "oisds", BAD_CAST OISDS_NS))
11610 return IE_ERROR;
11611 if (xmlXPathRegisterNs(xpath_ctx, BAD_CAST "sisds", message_namespace))
11612 return IE_ERROR;
11613 if (xmlXPathRegisterNs(xpath_ctx, BAD_CAST "xs", BAD_CAST SCHEMA_NS))
11614 return IE_ERROR;
11615 if (xmlXPathRegisterNs(xpath_ctx, BAD_CAST "deposit", BAD_CAST DEPOSIT_NS))
11616 return IE_ERROR;
11617 return IE_SUCCESS;