TODO: PDZInfo tested
[libisds.git] / client / common.c
blob57a5b78cf5924b72469c537319f770b69964058d
1 #define _XOPEN_SOURCE 700
2 #include <stdlib.h>
3 #include <stdio.h>
4 /*#include <locale.h>*/
5 #include <time.h>
6 #include <string.h>
7 #include <stdint.h>
8 #include <errno.h>
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 #include <fcntl.h>
12 #include <unistd.h>
13 #include <sys/mman.h>
14 #include <isds.h>
16 char credentials_file[] = "../test_credentials";
18 static int read_config(char **line, int order) {
19 FILE *file;
20 size_t length = 0;
21 char *eol;
23 if (!line) return -1;
24 free(*line);
25 *line = NULL;
27 file = fopen(credentials_file, "r");
28 if (!file) {
29 fprintf(stderr, "Could open %s\n", credentials_file);
30 return -1;
33 for (int i = 0; i < order; i++) {
34 if (-1 == getline(line, &length, file)) {
35 fprintf(stderr, "Could not read line #%d from %s: ",
36 i + 1, credentials_file);
37 if (ferror(file))
38 fprintf(stderr, "error occured\n");
39 else if (feof(file))
40 fprintf(stderr, "end of file reached\n");
41 else
42 fprintf(stderr, "I don't know why\n");
43 fclose(file);
44 free(*line);
45 *line = NULL;
46 return -1;
50 fclose(file);
52 eol = strpbrk(*line, "\r\n");
53 if (eol) *eol = '\0';
55 return 0;
58 const char *username(void) {
59 static char *username;
61 if (!username) {
62 username = getenv("ISDS_USERNAME");
63 if (!username)
64 read_config(&username, 1);
66 return username;
69 const char *password(void) {
70 static char *password;
72 if (!password) {
73 password = getenv("ISDS_PASSWORD");
74 if (!password)
75 read_config(&password, 2);
77 return password;
80 void print_DbState(const long int state) {
81 switch(state) {
82 case DBSTATE_ACCESSIBLE: printf("ACCESSIBLE\n"); break;
83 case DBSTATE_TEMP_UNACCESSIBLE: printf("TEMP_UNACCESSIBLE\n"); break;
84 case DBSTATE_NOT_YET_ACCESSIBLE: printf("NOT_YET_ACCESSIBLE\n"); break;
85 case DBSTATE_PERM_UNACCESSIBLE: printf("PERM_UNACCESSIBLE\n"); break;
86 case DBSTATE_REMOVED: printf("REMOVED\n"); break;
87 default: printf("<unknown state %ld>\n", state);
91 void print_DbType(const long int *type) {
92 if (!type) printf("NULL\n");
93 else
94 switch(*type) {
95 case DBTYPE_SYSTEM: printf("SYSTEM\n"); break;
96 case DBTYPE_FO: printf("FO\n"); break;
97 case DBTYPE_PFO: printf("PFO\n"); break;
98 case DBTYPE_PFO_ADVOK: printf("PFO_ADVOK\n"); break;
99 case DBTYPE_PFO_DANPOR: printf("PFO_DAPOR\n"); break;
100 case DBTYPE_PFO_INSSPR: printf("PFO_INSSPR\n"); break;
101 case DBTYPE_PO: printf("PO\n"); break;
102 case DBTYPE_PO_ZAK: printf("PO_ZAK\n"); break;
103 case DBTYPE_PO_REQ: printf("PO_REQ\n"); break;
104 case DBTYPE_OVM: printf("OVM\n"); break;
105 case DBTYPE_OVM_NOTAR: printf("OVM_NOTAR\n"); break;
106 case DBTYPE_OVM_EXEKUT: printf("OVM_EXEKUT\n"); break;
107 case DBTYPE_OVM_REQ: printf("OVM_REQ\n"); break;
108 default: printf("<unknown type %ld>\n", *type);
113 void print_UserType(const long int *type) {
114 if (!type) printf("NULL\n");
115 else
116 switch(*type) {
117 case USERTYPE_PRIMARY: printf("PRIMARY\n"); break;
118 case USERTYPE_ENTRUSTED: printf("ENTRUSTED\n"); break;
119 case USERTYPE_ADMINISTRATOR: printf("ADMINISTRATOR\n"); break;
120 case USERTYPE_OFFICIAL: printf("OFFICIAL\n"); break;
121 default: printf("<unknown type %ld>\n", *type);
126 void print_sender_type(const isds_sender_type *type) {
127 if (!type) printf("NULL\n");
128 else
129 switch(*type) {
130 case SENDERTYPE_PRIMARY: printf("PRIMARY\n"); break;
131 case SENDERTYPE_ENTRUSTED: printf("ENTRUSTED\n"); break;
132 case SENDERTYPE_ADMINISTRATOR: printf("ADMINISTRATOR\n"); break;
133 case SENDERTYPE_OFFICIAL: printf("OFFICIAL\n"); break;
134 case SENDERTYPE_VIRTUAL: printf("VIRTUAL\n"); break;
135 default: printf("<unknown type %u>\n", *type);
140 void print_UserPrivils(const long int *privils) {
142 const char *priviledges[] = {
143 "READ_NON_PERSONAL",
144 "READ_ALL",
145 "CREATE_DM",
146 "VIEW_INFO",
147 "SEARCH_DB",
148 "OWNER_ADM",
149 "READ_VAULT",
150 "ERASE_VAULT"
152 const int priviledges_count = sizeof(priviledges)/sizeof(priviledges[0]);
154 if (!privils) printf("NULL\n");
155 else {
156 printf("%ld (", *privils);
158 for (int i = 0; i < priviledges_count; i++) {
159 if (*privils & (1<<i)) {
160 printf(
161 ((i + 1) == priviledges_count) ? "%s" : "%s|",
162 priviledges[i]);
166 printf(")\n");
171 void print_hash(const struct isds_hash *hash) {
172 if (!hash) {
173 printf("NULL\n");
174 return;
177 switch(hash->algorithm) {
178 case HASH_ALGORITHM_MD5: printf("MD5 "); break;
179 case HASH_ALGORITHM_SHA_1: printf("SHA-1 "); break;
180 case HASH_ALGORITHM_SHA_256: printf("SHA-256 "); break;
181 case HASH_ALGORITHM_SHA_512: printf("SHA-512 "); break;
182 default: printf("<Unknown hash algorithm %d> ", hash->algorithm);
183 break;
186 if (!hash->value) printf("<NULL>");
187 else
188 for (int i = 0; i < hash->length; i++) {
189 if (i > 0) printf(":");
190 printf("%02x", ((uint8_t *)(hash->value))[i]);
193 printf("\n");
197 void print_raw_type(const isds_raw_type type) {
198 switch(type) {
199 case RAWTYPE_INCOMING_MESSAGE:
200 printf("INCOMING_MESSAGE\n"); break;
201 case RAWTYPE_PLAIN_SIGNED_INCOMING_MESSAGE:
202 printf("PLAIN_SIGNED_INCOMING_MESSAGE\n"); break;
203 case RAWTYPE_CMS_SIGNED_INCOMING_MESSAGE:
204 printf("CMS_SIGNED_INCOMING_MESSAGE\n"); break;
205 case RAWTYPE_PLAIN_SIGNED_OUTGOING_MESSAGE:
206 printf("PLAIN_SIGNED_OUTGOING_MESSAGE\n"); break;
207 case RAWTYPE_CMS_SIGNED_OUTGOING_MESSAGE:
208 printf("CMS_SIGNED_OUTGOING_MESSAGE\n"); break;
209 case RAWTYPE_DELIVERYINFO:
210 printf("DELIVERYINFO\n"); break;
211 case RAWTYPE_PLAIN_SIGNED_DELIVERYINFO:
212 printf("PLAIN_SIGNED_DELIVERYINFO\n"); break;
213 case RAWTYPE_CMS_SIGNED_DELIVERYINFO:
214 printf("CMS_SIGNED_DELIVERYINFO\n"); break;
215 default:
216 printf("<Unknown raw type %d> ", type);
217 break;
221 static void print_dmMessageStatus(const isds_message_status *status) {
222 if (!status) printf("NULL\n");
223 else
224 switch(*status) {
225 case MESSAGESTATE_SENT: printf("SENT\n"); break;
226 case MESSAGESTATE_STAMPED: printf("STAMPED\n"); break;
227 case MESSAGESTATE_INFECTED: printf("INFECTED\n"); break;
228 case MESSAGESTATE_DELIVERED: printf("DELIVERED\n"); break;
229 case MESSAGESTATE_SUBSTITUTED: printf("SUBSTITUTED\n"); break;
230 case MESSAGESTATE_RECEIVED: printf("RECEIVED\n"); break;
231 case MESSAGESTATE_READ: printf("READ\n"); break;
232 case MESSAGESTATE_UNDELIVERABLE: printf("UNDELIVERABLE\n"); break;
233 case MESSAGESTATE_REMOVED: printf("REMOVED\n"); break;
234 case MESSAGESTATE_IN_SAFE: printf("IN_SAFE\n"); break;
235 default: printf("<unknown type %d>\n", *status);
239 void print_bool(const _Bool *boolean) {
240 printf("%s\n", (!boolean) ? "NULL" : ((*boolean)? "true" : "false") );
244 void print_longint(const long int *number) {
245 if (!number) printf("NULL\n");
246 else printf("%ld\n", *number);
250 void print_PersonName(const struct isds_PersonName *personName) {
251 printf("\tpersonName = ");
252 if (!personName) printf("NULL\n");
253 else {
254 printf("{\n");
255 printf("\t\tpnFirstName = %s\n", personName->pnFirstName);
256 printf("\t\tpnMiddleName = %s\n", personName->pnMiddleName);
257 printf("\t\tpnLastName = %s\n", personName->pnLastName);
258 printf("\t\tpnLastNameAtBirth = %s\n", personName->pnLastNameAtBirth);
259 printf("\t}\n");
264 void print_Address(const struct isds_Address *address) {
265 printf("\taddress = ");
266 if (!address) printf("NULL\n");
267 else {
268 printf("{\n");
269 printf("\t\tadCity = %s\n", address->adCity);
270 printf("\t\tadStreet = %s\n", address->adStreet);
271 printf("\t\tadNumberInStreet = %s\n", address->adNumberInStreet);
272 printf("\t\tadNumberInMunicipality = %s\n",
273 address->adNumberInMunicipality);
274 printf("\t\tadZipCode = %s\n", address->adZipCode);
275 printf("\t\tadState = %s\n", address->adState);
276 printf("\t}\n");
281 void print_date(const struct tm *date) {
282 if (!date) printf("NULL\n");
283 else printf("%s", asctime(date));
287 void print_DbOwnerInfo(const struct isds_DbOwnerInfo *info) {
288 printf("dbOwnerInfo = ");
290 if (!info) {
291 printf("NULL\n");
292 return;
295 printf("{\n");
296 printf("\tdbID = %s\n", info->dbID);
298 printf("\tdbType = ");
299 print_DbType((long int *) (info->dbType));
300 printf("\tic = %s\n", info->ic);
302 print_PersonName(info->personName);
304 printf("\tfirmName = %s\n", info->firmName);
306 printf("\tbirthInfo = ");
307 if (!info->birthInfo) printf("NULL\n");
308 else {
309 printf("{\n");
311 printf("\t\tbiDate = ");
312 print_date(info->birthInfo->biDate);
314 printf("\t\tbiCity = %s\n", info->birthInfo->biCity);
315 printf("\t\tbiCounty = %s\n", info->birthInfo->biCounty);
316 printf("\t\tbiState = %s\n", info->birthInfo->biState);
317 printf("\t}\n");
320 print_Address(info->address);
322 printf("\tnationality = %s\n", info->nationality);
323 printf("\temail = %s\n", info->email);
324 printf("\ttelNumber = %s\n", info->telNumber);
325 printf("\tidentifier = %s\n", info->identifier);
326 printf("\tregistryCode = %s\n", info->registryCode);
328 printf("\tdbState = ");
329 if (!info->dbState) printf("NULL\n");
330 else print_DbState(*(info->dbState));
332 printf("\tdbEffectiveOVM = ");
333 print_bool(info->dbEffectiveOVM);
335 printf("\tdbOpenAddressing = ");
336 print_bool(info->dbOpenAddressing);
338 printf("}\n");
343 void print_DbUserInfo(const struct isds_DbUserInfo *info) {
344 printf("dbUserInfo = ");
346 if (!info) {
347 printf("NULL\n");
348 return;
351 printf("{\n");
352 printf("\tuserID = %s\n", info->userID);
354 printf("\tuserType = ");
355 print_UserType((long int *) (info->userType));
357 printf("\tuserPrivils = ");
358 print_UserPrivils(info->userPrivils);
360 print_PersonName(info->personName);
361 print_Address(info->address);
363 printf("\tbiDate = ");
364 print_date(info->biDate);
366 printf("\tic = %s\n", info->ic);
367 printf("\tfirmName = %s\n", info->firmName);
369 printf("\tcaStreet = %s\n", info->caStreet);
370 printf("\tcaCity = %s\n", info->caCity);
371 printf("\tcaZipCode = %s\n", info->caZipCode);
372 printf("\tcaState = %s\n", info->caState);
374 printf("}\n");
378 void print_timeval(const struct timeval *time) {
379 struct tm broken;
380 char buffer[128];
382 if (!time) {
383 printf("NULL\n");
384 return;
387 if (!localtime_r(&(time->tv_sec), &broken)) goto error;
388 if (!strftime(buffer, sizeof(buffer)/sizeof(char), "%c", &broken))
389 goto error;
390 printf("%s, %ld us\n", buffer, time->tv_usec);
391 return;
393 error:
394 printf("<Error while formating>\n>");
395 return;
399 void print_event_type(const isds_event_type *type) {
400 if (!type) {
401 printf("NULL");
402 return;
404 switch (*type) {
405 case EVENT_UKNOWN: printf("UNKNOWN\n"); break;
406 case EVENT_ENTERED_SYSTEM: printf("ENTERED_SYSTEM\n"); break;
407 case EVENT_ACCEPTED_BY_RECIPIENT:
408 printf("ACCEPTED_BY_RECIPIENT\n"); break;
409 case EVENT_ACCEPTED_BY_FICTION:
410 printf("DELIVERED_BY_FICTION\n"); break;
411 case EVENT_UNDELIVERABLE:
412 printf("UNDELIVERABLE\n"); break;
413 case EVENT_COMMERCIAL_ACCEPTED:
414 printf("COMMERCIAL_ACCEPTED\n"); break;
415 case EVENT_DELIVERED:
416 printf("DELIVERED\n"); break;
417 case EVENT_PRIMARY_LOGIN:
418 printf("PRIMARY_LOGIN\n"); break;
419 case EVENT_ENTRUSTED_LOGIN:
420 printf("ENTRUSTED_LOGIN\n"); break;
421 case EVENT_SYSCERT_LOGIN:
422 printf("SYSCERT_LOGIN\n"); break;
423 default: printf("<unknown type %d>\n", *type);
428 void print_events(const struct isds_list *events) {
429 const struct isds_list *item;
430 const struct isds_event *event;
432 if (!events) {
433 printf("NULL\n");
434 return;
437 printf("{\n");
439 for (item = events; item; item = item->next) {
440 event = (struct isds_event *) item->data;
441 printf("\t\t\tevent = ");
442 if (!event) printf("NULL");
443 else {
444 printf("{\n");
446 printf("\t\t\t\ttype = ");
447 print_event_type(event->type);
449 printf("\t\t\t\tdescription = %s\n", event->description);
451 printf("\t\t\t\ttime = ");
452 print_timeval(event->time);
454 printf("\t\t\t}\n");
458 printf("\t\t}\n");
462 void print_envelope(const struct isds_envelope *envelope) {
463 printf("\tenvelope = ");
465 if (!envelope) {
466 printf("NULL\n");
467 return;
469 printf("{\n");
471 printf("\t\tdmID = %s\n", envelope->dmID);
472 printf("\t\tdbIDSender = %s\n", envelope->dbIDSender);
473 printf("\t\tdmSender = %s\n", envelope->dmSender);
474 printf("\t\tdmSenderAddress = %s\n", envelope->dmSenderAddress);
475 printf("\t\tdmSenderType = ");
476 print_DbType(envelope->dmSenderType);
477 printf("\t\tdmRecipient = %s\n", envelope->dmRecipient);
478 printf("\t\tdmRecipientAddress = %s\n", envelope->dmRecipientAddress);
479 printf("\t\tdmAmbiguousRecipient = ");
480 print_bool(envelope->dmAmbiguousRecipient);
481 printf("\t\tdmType = %s\n", envelope->dmType);
483 printf("\t\tdmSenderOrgUnit = %s\n", envelope->dmSenderOrgUnit);
484 printf("\t\tdmSenderOrgUnitNum = ");
485 print_longint(envelope->dmSenderOrgUnitNum);
486 printf("\t\tdbIDRecipient = %s\n", envelope->dbIDRecipient);
487 printf("\t\tdmRecipientOrgUnit = %s\n", envelope->dmRecipientOrgUnit);
488 printf("\t\tdmRecipientOrgUnitNum = ");
489 print_longint(envelope->dmRecipientOrgUnitNum);
490 printf("\t\tdmToHands = %s\n", envelope->dmToHands);
491 printf("\t\tdmAnnotation = %s\n", envelope->dmAnnotation);
492 printf("\t\tdmRecipientRefNumber = %s\n", envelope->dmRecipientRefNumber);
493 printf("\t\tdmSenderRefNumber = %s\n", envelope->dmSenderRefNumber);
494 printf("\t\tdmRecipientIdent = %s\n", envelope->dmRecipientIdent);
495 printf("\t\tdmSenderIdent = %s\n", envelope->dmSenderIdent);
497 printf("\t\tdmLegalTitleLaw = ");
498 print_longint(envelope->dmLegalTitleLaw);
499 printf("\t\tdmLegalTitleYear = ");
500 print_longint(envelope->dmLegalTitleYear);
501 printf("\t\tdmLegalTitleSect = %s\n", envelope->dmLegalTitleSect);
502 printf("\t\tdmLegalTitlePar = %s\n", envelope->dmLegalTitlePar);
503 printf("\t\tdmLegalTitlePoint = %s\n", envelope->dmLegalTitlePoint);
505 printf("\t\tdmPersonalDelivery = ");
506 print_bool(envelope->dmPersonalDelivery);
507 printf("\t\tdmAllowSubstDelivery = ");
508 print_bool(envelope->dmAllowSubstDelivery);
509 printf("\t\tdmOVM = ");
510 print_bool(envelope->dmOVM);
511 printf("\t\tdmPublishOwnID = ");
512 print_bool(envelope->dmPublishOwnID);
514 printf("\t\tdmOrdinal = ");
515 if (!envelope->dmOrdinal) printf("NULL\n");
516 else printf("%lu\n", *(envelope->dmOrdinal));
518 printf("\t\tdmMessageStatus = ");
519 print_dmMessageStatus(envelope->dmMessageStatus);
521 printf("\t\tdmAttachmentSize = ");
522 if (!envelope->dmAttachmentSize) printf("NULL\n");
523 else printf("%lu kB\n", *(envelope->dmAttachmentSize));
525 printf("\t\tdmDeliveryTime = ");
526 print_timeval(envelope->dmDeliveryTime);
528 printf("\t\tdmAcceptanceTime = ");
529 print_timeval(envelope->dmAcceptanceTime);
531 printf("\t\thash = ");
532 print_hash(envelope->hash);
534 printf("\t\ttimestamp = %p\n", envelope->timestamp);
535 printf("\t\ttimestamp_length = %zu\n", envelope->timestamp_length);
537 printf("\t\tevents = ");
538 print_events(envelope->events);
540 printf("\t}\n");
544 void print_document(const struct isds_document *document) {
545 printf("\t\tdocument = ");
547 if (!document) {
548 printf("NULL\n");
549 return;
551 printf("\{\n");
553 printf("\t\t\tis_xml = %u\n", !!document->is_xml);
554 printf("\t\t\txml_node_list = %p\n", document->xml_node_list);
556 printf("\t\t\tdata = %p\n", document->data);
557 printf("\t\t\tdata_length = %zu\n", document->data_length);
558 printf("\t\t\tdmMimeType = %s\n", document->dmMimeType);
560 printf("\t\t\tdmFileMetaType = ");
561 switch(document->dmFileMetaType) {
562 case FILEMETATYPE_MAIN: printf("MAIN\n"); break;
563 case FILEMETATYPE_ENCLOSURE: printf("ENCLOSURE\n"); break;
564 case FILEMETATYPE_SIGNATURE: printf("SIGNATURE\n"); break;
565 case FILEMETATYPE_META: printf("META\n"); break;
566 default: printf("<unknown type %d>\n", document->dmFileMetaType);
569 printf("\t\t\tdmFileGuid = %s\n", document->dmFileGuid);
570 printf("\t\t\tdmUpFileGuid = %s\n", document->dmUpFileGuid);
571 printf("\t\t\tdmFileDescr = %s\n", document->dmFileDescr);
572 printf("\t\t\tdmFormat = %s\n", document->dmFormat);
573 printf("\t\t}\n");
577 void print_documents(const struct isds_list *documents) {
578 const struct isds_list *item;
580 printf("\tdocuments = ");
582 if (!documents) {
583 printf("NULL\n");
584 return;
586 printf("{\n");
588 for (item = documents; item; item = item->next) {
589 print_document((struct isds_document *) (item->data));
592 printf("\t}\n");
596 void print_message(const struct isds_message *message) {
597 printf("message = ");
599 if (!message) {
600 printf("NULL\n");
601 return;
604 printf("{\n");
606 printf("\traw = %p\n", message->raw);
607 printf("\traw_length = %zu\n", message->raw_length);
608 printf("\traw_type = ");
609 print_raw_type(message->raw_type);
610 printf("\txml = %p\n", message->xml);
611 print_envelope(message->envelope);
612 print_documents(message->documents);
614 printf("}\n");
617 void print_copies(const struct isds_list *copies) {
618 const struct isds_list *item;
619 struct isds_message_copy *copy;
621 printf("Copies = ");
622 if (!copies) {
623 printf("<NULL>\n");
624 return;
627 printf("{\n");
628 for (item = copies; item; item = item->next) {
629 copy = (struct isds_message_copy *) item->data;
630 printf("\tCopy = ");
632 if (!copy)
633 printf("<NULL>\n");
634 else {
635 printf("{\n");
636 printf("\t\tdbIDRecipient = %s\n", copy->dbIDRecipient);
637 printf("\t\tdmRecipientOrgUnit = %s\n", copy->dmRecipientOrgUnit);
639 printf("\t\tdmRecipientOrgUnitNum = ");
640 if (copy->dmRecipientOrgUnitNum)
641 printf("%ld\n", *copy->dmRecipientOrgUnitNum);
642 else
643 printf("<NULL>\n");
644 printf("\t\tdmToHands = %s\n", copy->dmToHands);
646 printf("\t\terror = %s\n", isds_strerror(copy->error));
647 printf("\t\tdmStatus = %s\n", copy->dmStatus);
648 printf("\t\tdmID = %s\n", copy->dmID);
649 printf("\t}\n");
652 printf("}\n");
655 void print_message_status_change(
656 const struct isds_message_status_change *changed_status) {
657 printf("message_status_change = ");
659 if (!changed_status) {
660 printf("NULL\n");
661 return;
664 printf("{\n");
666 printf("\tdmID = %s\n", changed_status->dmID);
668 printf("\tdmMessageStatus = ");
669 print_dmMessageStatus(changed_status->dmMessageStatus);
671 printf("\ttime = ");
672 print_timeval(changed_status->time);
674 printf("}\n");
677 void compare_hashes(const struct isds_hash *hash1,
678 const struct isds_hash *hash2) {
679 isds_error err;
681 printf("Comparing hashes... ");
682 err = isds_hash_cmp(hash1, hash2);
683 if (err == IE_SUCCESS)
684 printf("Hashes equal\n");
685 else if
686 (err == IE_NOTEQUAL) printf("Hashes differ\n");
687 else
688 printf("isds_hash_cmp() failed: %s\n", isds_strerror(err));
692 int progressbar(double upload_total, double upload_current,
693 double download_total, double download_current,
694 void *data) {
696 printf("Progress: upload %0f/%0f, download %0f/%0f, data=%p\n",
697 upload_current, upload_total, download_current, download_total,
698 data);
699 if (data) {
700 printf("Aborting transfer...\n");
701 return 1;
703 return 0;
707 int mmap_file(const char *file, int *fd, void **buffer, size_t *length) {
708 struct stat file_info;
710 if (!file || !fd || !buffer || !length) return -1;
713 *fd = open(file, O_RDONLY);
714 if (*fd == -1) {
715 fprintf(stderr, "%s: Could not open file: %s\n", file, strerror(errno));
716 return -1;
719 if (-1 == fstat(*fd, &file_info)) {
720 fprintf(stderr, "%s: Could not get file size: %s\n", file,
721 strerror(errno));
722 close(*fd);
723 return -1;
725 if (file_info.st_size < 0) {
726 fprintf(stderr, "File `%s' has negative size: %jd\n", file,
727 (intmax_t) file_info.st_size);
728 close(*fd);
729 return -1;
731 *length = file_info.st_size;
733 if (!*length) {
734 /* Empty region cannot be mmapped */
735 *buffer = NULL;
736 } else {
737 *buffer = mmap(NULL, *length, PROT_READ, MAP_PRIVATE, *fd, 0);
738 if (*buffer == MAP_FAILED) {
739 fprintf(stderr, "%s: Could not map file to memory: %s\n", file,
740 strerror(errno));
741 close(*fd);
742 return -1;
746 return 0;
750 int munmap_file(int fd, void *buffer, size_t length) {
751 int err = 0;
752 long int page_size = sysconf(_SC_PAGE_SIZE);
753 size_t pages = (length % page_size) ?
754 ((length / page_size) + 1) * page_size:
755 length;
757 if (length) {
758 err = munmap(buffer, pages);
759 if (err) {
760 fprintf(stderr,
761 "Could not unmap memory at %p and length %zu: %s\n",
762 buffer, pages, strerror(errno));
766 err = close(fd);
767 if (err) {
768 fprintf(stderr, "Could close file descriptor %d: %s\n", fd,
769 strerror(errno));
772 return err;
776 static int save_data_to_file(const char *file, const void *data,
777 const size_t length) {
778 int fd;
779 ssize_t written, left = length;
781 if (!file) return -1;
782 if (length > 0 && !data) return -1;
784 fd = open(file, O_WRONLY|O_TRUNC|O_CREAT, 0666);
785 if (fd == -1) {
786 fprintf(stderr, "%s: Could not open file for writing: %s\n",
787 file, strerror(errno));
788 return -1;
791 printf("Writing %zu bytes to file `%s'...\n", length, file);
792 while (left) {
793 written = write(fd, data + length - left, left);
794 if (written == -1) {
795 fprintf(stderr, "%s: Could not save file: %s\n",
796 file, strerror(errno));
797 close(fd);
798 return -1;
800 left-=written;
803 if (-1 == close(fd)) {
804 fprintf(stderr, "%s: Closing file failed: %s\n",
805 file, strerror(errno));
806 return -1;
809 printf("Done.\n");
810 return 0;
814 int save_data(const char *message, const void *data, const size_t length) {
815 if (message)
816 printf("%s\n", message);
817 return save_data_to_file("output", data, length);