timeval.tv_sec does not have to be of type time_t
[libisds.git] / client / common.c
blobcd12fe5593581738e267480663425ff0418aff85
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 <inttypes.h>
9 #include <errno.h>
10 #include <sys/types.h>
11 #include <sys/stat.h>
12 #include <fcntl.h>
13 #include <unistd.h>
14 #include <sys/mman.h>
15 #include <isds.h>
17 char credentials_file[] = "../test_credentials";
19 static int read_config(char **line, int order) {
20 FILE *file;
21 size_t length = 0;
22 char *eol;
24 if (!line) return -1;
25 free(*line);
26 *line = NULL;
28 file = fopen(credentials_file, "r");
29 if (!file) {
30 fprintf(stderr, "Could open %s\n", credentials_file);
31 return -1;
34 for (int i = 0; i < order; i++) {
35 if (-1 == getline(line, &length, file)) {
36 fprintf(stderr, "Could not read line #%d from %s: ",
37 i + 1, credentials_file);
38 if (ferror(file))
39 fprintf(stderr, "error occured\n");
40 else if (feof(file))
41 fprintf(stderr, "end of file reached\n");
42 else
43 fprintf(stderr, "I don't know why\n");
44 fclose(file);
45 free(*line);
46 *line = NULL;
47 return -1;
51 fclose(file);
53 eol = strpbrk(*line, "\r\n");
54 if (eol) *eol = '\0';
56 return 0;
59 const char *username(void) {
60 static char *username;
62 if (!username) {
63 username = getenv("ISDS_USERNAME");
64 if (!username)
65 read_config(&username, 1);
67 return username;
70 const char *password(void) {
71 static char *password;
73 if (!password) {
74 password = getenv("ISDS_PASSWORD");
75 if (!password)
76 read_config(&password, 2);
78 return password;
81 void print_DbState(const long int state) {
82 switch(state) {
83 case DBSTATE_ACCESSIBLE: printf("ACCESSIBLE\n"); break;
84 case DBSTATE_TEMP_UNACCESSIBLE: printf("TEMP_UNACCESSIBLE\n"); break;
85 case DBSTATE_NOT_YET_ACCESSIBLE: printf("NOT_YET_ACCESSIBLE\n"); break;
86 case DBSTATE_PERM_UNACCESSIBLE: printf("PERM_UNACCESSIBLE\n"); break;
87 case DBSTATE_REMOVED: printf("REMOVED\n"); break;
88 default: printf("<unknown state %ld>\n", state);
92 void print_DbType(const long int *type) {
93 if (!type) printf("NULL\n");
94 else
95 switch(*type) {
96 case DBTYPE_SYSTEM: printf("SYSTEM\n"); break;
97 case DBTYPE_FO: printf("FO\n"); break;
98 case DBTYPE_PFO: printf("PFO\n"); break;
99 case DBTYPE_PFO_ADVOK: printf("PFO_ADVOK\n"); break;
100 case DBTYPE_PFO_DANPOR: printf("PFO_DAPOR\n"); break;
101 case DBTYPE_PFO_INSSPR: printf("PFO_INSSPR\n"); break;
102 case DBTYPE_PO: printf("PO\n"); break;
103 case DBTYPE_PO_ZAK: printf("PO_ZAK\n"); break;
104 case DBTYPE_PO_REQ: printf("PO_REQ\n"); break;
105 case DBTYPE_OVM: printf("OVM\n"); break;
106 case DBTYPE_OVM_NOTAR: printf("OVM_NOTAR\n"); break;
107 case DBTYPE_OVM_EXEKUT: printf("OVM_EXEKUT\n"); break;
108 case DBTYPE_OVM_REQ: printf("OVM_REQ\n"); break;
109 default: printf("<unknown type %ld>\n", *type);
114 void print_UserType(const long int *type) {
115 if (!type) printf("NULL\n");
116 else
117 switch(*type) {
118 case USERTYPE_PRIMARY: printf("PRIMARY\n"); break;
119 case USERTYPE_ENTRUSTED: printf("ENTRUSTED\n"); break;
120 case USERTYPE_ADMINISTRATOR: printf("ADMINISTRATOR\n"); break;
121 case USERTYPE_OFFICIAL: printf("OFFICIAL\n"); break;
122 default: printf("<unknown type %ld>\n", *type);
127 void print_sender_type(const isds_sender_type *type) {
128 if (!type) printf("NULL\n");
129 else
130 switch(*type) {
131 case SENDERTYPE_PRIMARY: printf("PRIMARY\n"); break;
132 case SENDERTYPE_ENTRUSTED: printf("ENTRUSTED\n"); break;
133 case SENDERTYPE_ADMINISTRATOR: printf("ADMINISTRATOR\n"); break;
134 case SENDERTYPE_OFFICIAL: printf("OFFICIAL\n"); break;
135 case SENDERTYPE_VIRTUAL: printf("VIRTUAL\n"); break;
136 default: printf("<unknown type %u>\n", *type);
141 void print_UserPrivils(const long int *privils) {
143 const char *priviledges[] = {
144 "READ_NON_PERSONAL",
145 "READ_ALL",
146 "CREATE_DM",
147 "VIEW_INFO",
148 "SEARCH_DB",
149 "OWNER_ADM",
150 "READ_VAULT",
151 "ERASE_VAULT"
153 const int priviledges_count = sizeof(priviledges)/sizeof(priviledges[0]);
155 if (!privils) printf("NULL\n");
156 else {
157 printf("%ld (", *privils);
159 for (int i = 0; i < priviledges_count; i++) {
160 if (*privils & (1<<i)) {
161 printf(
162 ((i + 1) == priviledges_count) ? "%s" : "%s|",
163 priviledges[i]);
167 printf(")\n");
172 void print_hash(const struct isds_hash *hash) {
173 if (!hash) {
174 printf("NULL\n");
175 return;
178 switch(hash->algorithm) {
179 case HASH_ALGORITHM_MD5: printf("MD5 "); break;
180 case HASH_ALGORITHM_SHA_1: printf("SHA-1 "); break;
181 case HASH_ALGORITHM_SHA_256: printf("SHA-256 "); break;
182 case HASH_ALGORITHM_SHA_512: printf("SHA-512 "); break;
183 default: printf("<Unknown hash algorithm %d> ", hash->algorithm);
184 break;
187 if (!hash->value) printf("<NULL>");
188 else
189 for (size_t i = 0; i < hash->length; i++) {
190 if (i > 0) printf(":");
191 printf("%02x", ((uint8_t *)(hash->value))[i]);
194 printf("\n");
198 void print_raw_type(const isds_raw_type type) {
199 switch(type) {
200 case RAWTYPE_INCOMING_MESSAGE:
201 printf("INCOMING_MESSAGE\n"); break;
202 case RAWTYPE_PLAIN_SIGNED_INCOMING_MESSAGE:
203 printf("PLAIN_SIGNED_INCOMING_MESSAGE\n"); break;
204 case RAWTYPE_CMS_SIGNED_INCOMING_MESSAGE:
205 printf("CMS_SIGNED_INCOMING_MESSAGE\n"); break;
206 case RAWTYPE_PLAIN_SIGNED_OUTGOING_MESSAGE:
207 printf("PLAIN_SIGNED_OUTGOING_MESSAGE\n"); break;
208 case RAWTYPE_CMS_SIGNED_OUTGOING_MESSAGE:
209 printf("CMS_SIGNED_OUTGOING_MESSAGE\n"); break;
210 case RAWTYPE_DELIVERYINFO:
211 printf("DELIVERYINFO\n"); break;
212 case RAWTYPE_PLAIN_SIGNED_DELIVERYINFO:
213 printf("PLAIN_SIGNED_DELIVERYINFO\n"); break;
214 case RAWTYPE_CMS_SIGNED_DELIVERYINFO:
215 printf("CMS_SIGNED_DELIVERYINFO\n"); break;
216 default:
217 printf("<Unknown raw type %d> ", type);
218 break;
222 static void print_dmMessageStatus(const isds_message_status *status) {
223 if (!status) printf("NULL\n");
224 else
225 switch(*status) {
226 case MESSAGESTATE_SENT: printf("SENT\n"); break;
227 case MESSAGESTATE_STAMPED: printf("STAMPED\n"); break;
228 case MESSAGESTATE_INFECTED: printf("INFECTED\n"); break;
229 case MESSAGESTATE_DELIVERED: printf("DELIVERED\n"); break;
230 case MESSAGESTATE_SUBSTITUTED: printf("SUBSTITUTED\n"); break;
231 case MESSAGESTATE_RECEIVED: printf("RECEIVED\n"); break;
232 case MESSAGESTATE_READ: printf("READ\n"); break;
233 case MESSAGESTATE_UNDELIVERABLE: printf("UNDELIVERABLE\n"); break;
234 case MESSAGESTATE_REMOVED: printf("REMOVED\n"); break;
235 case MESSAGESTATE_IN_SAFE: printf("IN_SAFE\n"); break;
236 default: printf("<unknown type %d>\n", *status);
240 void print_bool(const _Bool *boolean) {
241 printf("%s\n", (!boolean) ? "NULL" : ((*boolean)? "true" : "false") );
245 void print_longint(const long int *number) {
246 if (!number) printf("NULL\n");
247 else printf("%ld\n", *number);
251 void print_PersonName(const struct isds_PersonName *personName) {
252 printf("\tpersonName = ");
253 if (!personName) printf("NULL\n");
254 else {
255 printf("{\n");
256 printf("\t\tpnFirstName = %s\n", personName->pnFirstName);
257 printf("\t\tpnMiddleName = %s\n", personName->pnMiddleName);
258 printf("\t\tpnLastName = %s\n", personName->pnLastName);
259 printf("\t\tpnLastNameAtBirth = %s\n", personName->pnLastNameAtBirth);
260 printf("\t}\n");
265 void print_Address(const struct isds_Address *address) {
266 printf("\taddress = ");
267 if (!address) printf("NULL\n");
268 else {
269 printf("{\n");
270 printf("\t\tadCity = %s\n", address->adCity);
271 printf("\t\tadStreet = %s\n", address->adStreet);
272 printf("\t\tadNumberInStreet = %s\n", address->adNumberInStreet);
273 printf("\t\tadNumberInMunicipality = %s\n",
274 address->adNumberInMunicipality);
275 printf("\t\tadZipCode = %s\n", address->adZipCode);
276 printf("\t\tadState = %s\n", address->adState);
277 printf("\t}\n");
282 void print_date(const struct tm *date) {
283 if (!date) printf("NULL\n");
284 else printf("%s", asctime(date));
288 void print_DbOwnerInfo(const struct isds_DbOwnerInfo *info) {
289 printf("dbOwnerInfo = ");
291 if (!info) {
292 printf("NULL\n");
293 return;
296 printf("{\n");
297 printf("\tdbID = %s\n", info->dbID);
299 printf("\tdbType = ");
300 print_DbType((long int *) (info->dbType));
301 printf("\tic = %s\n", info->ic);
303 print_PersonName(info->personName);
305 printf("\tfirmName = %s\n", info->firmName);
307 printf("\tbirthInfo = ");
308 if (!info->birthInfo) printf("NULL\n");
309 else {
310 printf("{\n");
312 printf("\t\tbiDate = ");
313 print_date(info->birthInfo->biDate);
315 printf("\t\tbiCity = %s\n", info->birthInfo->biCity);
316 printf("\t\tbiCounty = %s\n", info->birthInfo->biCounty);
317 printf("\t\tbiState = %s\n", info->birthInfo->biState);
318 printf("\t}\n");
321 print_Address(info->address);
323 printf("\tnationality = %s\n", info->nationality);
324 printf("\temail = %s\n", info->email);
325 printf("\ttelNumber = %s\n", info->telNumber);
326 printf("\tidentifier = %s\n", info->identifier);
327 printf("\tregistryCode = %s\n", info->registryCode);
329 printf("\tdbState = ");
330 if (!info->dbState) printf("NULL\n");
331 else print_DbState(*(info->dbState));
333 printf("\tdbEffectiveOVM = ");
334 print_bool(info->dbEffectiveOVM);
336 printf("\tdbOpenAddressing = ");
337 print_bool(info->dbOpenAddressing);
339 printf("}\n");
344 void print_DbUserInfo(const struct isds_DbUserInfo *info) {
345 printf("dbUserInfo = ");
347 if (!info) {
348 printf("NULL\n");
349 return;
352 printf("{\n");
353 printf("\tuserID = %s\n", info->userID);
355 printf("\tuserType = ");
356 print_UserType((long int *) (info->userType));
358 printf("\tuserPrivils = ");
359 print_UserPrivils(info->userPrivils);
361 print_PersonName(info->personName);
362 print_Address(info->address);
364 printf("\tbiDate = ");
365 print_date(info->biDate);
367 printf("\tic = %s\n", info->ic);
368 printf("\tfirmName = %s\n", info->firmName);
370 printf("\tcaStreet = %s\n", info->caStreet);
371 printf("\tcaCity = %s\n", info->caCity);
372 printf("\tcaZipCode = %s\n", info->caZipCode);
373 printf("\tcaState = %s\n", info->caState);
375 printf("}\n");
379 void print_timeval(const struct timeval *time) {
380 struct tm broken;
381 char buffer[128];
382 time_t seconds_as_time_t;
384 if (!time) {
385 printf("NULL\n");
386 return;
389 /* MinGW32 GCC 4.8+ uses 64-bit time_t but time->tv_sec is defined as
390 * 32-bit long in Microsoft API. Convert value to the type expected by
391 * gmtime_r(). */
392 seconds_as_time_t = time->tv_sec;
393 if (!localtime_r(&seconds_as_time_t, &broken)) goto error;
394 if (!strftime(buffer, sizeof(buffer)/sizeof(char), "%c", &broken))
395 goto error;
396 printf("%s, %" PRIdMAX " us\n", buffer, (intmax_t)time->tv_usec);
397 return;
399 error:
400 printf("<Error while formating>\n>");
401 return;
405 void print_event_type(const isds_event_type *type) {
406 if (!type) {
407 printf("NULL");
408 return;
410 switch (*type) {
411 case EVENT_UKNOWN: printf("UNKNOWN\n"); break;
412 case EVENT_ENTERED_SYSTEM: printf("ENTERED_SYSTEM\n"); break;
413 case EVENT_ACCEPTED_BY_RECIPIENT:
414 printf("ACCEPTED_BY_RECIPIENT\n"); break;
415 case EVENT_ACCEPTED_BY_FICTION:
416 printf("DELIVERED_BY_FICTION\n"); break;
417 case EVENT_UNDELIVERABLE:
418 printf("UNDELIVERABLE\n"); break;
419 case EVENT_COMMERCIAL_ACCEPTED:
420 printf("COMMERCIAL_ACCEPTED\n"); break;
421 case EVENT_DELIVERED:
422 printf("DELIVERED\n"); break;
423 case EVENT_PRIMARY_LOGIN:
424 printf("PRIMARY_LOGIN\n"); break;
425 case EVENT_ENTRUSTED_LOGIN:
426 printf("ENTRUSTED_LOGIN\n"); break;
427 case EVENT_SYSCERT_LOGIN:
428 printf("SYSCERT_LOGIN\n"); break;
429 default: printf("<unknown type %d>\n", *type);
434 void print_events(const struct isds_list *events) {
435 const struct isds_list *item;
436 const struct isds_event *event;
438 if (!events) {
439 printf("NULL\n");
440 return;
443 printf("{\n");
445 for (item = events; item; item = item->next) {
446 event = (struct isds_event *) item->data;
447 printf("\t\t\tevent = ");
448 if (!event) printf("NULL");
449 else {
450 printf("{\n");
452 printf("\t\t\t\ttype = ");
453 print_event_type(event->type);
455 printf("\t\t\t\tdescription = %s\n", event->description);
457 printf("\t\t\t\ttime = ");
458 print_timeval(event->time);
460 printf("\t\t\t}\n");
464 printf("\t\t}\n");
468 void print_envelope(const struct isds_envelope *envelope) {
469 printf("\tenvelope = ");
471 if (!envelope) {
472 printf("NULL\n");
473 return;
475 printf("{\n");
477 printf("\t\tdmID = %s\n", envelope->dmID);
478 printf("\t\tdbIDSender = %s\n", envelope->dbIDSender);
479 printf("\t\tdmSender = %s\n", envelope->dmSender);
480 printf("\t\tdmSenderAddress = %s\n", envelope->dmSenderAddress);
481 printf("\t\tdmSenderType = ");
482 print_DbType(envelope->dmSenderType);
483 printf("\t\tdmRecipient = %s\n", envelope->dmRecipient);
484 printf("\t\tdmRecipientAddress = %s\n", envelope->dmRecipientAddress);
485 printf("\t\tdmAmbiguousRecipient = ");
486 print_bool(envelope->dmAmbiguousRecipient);
487 printf("\t\tdmType = %s\n", envelope->dmType);
489 printf("\t\tdmSenderOrgUnit = %s\n", envelope->dmSenderOrgUnit);
490 printf("\t\tdmSenderOrgUnitNum = ");
491 print_longint(envelope->dmSenderOrgUnitNum);
492 printf("\t\tdbIDRecipient = %s\n", envelope->dbIDRecipient);
493 printf("\t\tdmRecipientOrgUnit = %s\n", envelope->dmRecipientOrgUnit);
494 printf("\t\tdmRecipientOrgUnitNum = ");
495 print_longint(envelope->dmRecipientOrgUnitNum);
496 printf("\t\tdmToHands = %s\n", envelope->dmToHands);
497 printf("\t\tdmAnnotation = %s\n", envelope->dmAnnotation);
498 printf("\t\tdmRecipientRefNumber = %s\n", envelope->dmRecipientRefNumber);
499 printf("\t\tdmSenderRefNumber = %s\n", envelope->dmSenderRefNumber);
500 printf("\t\tdmRecipientIdent = %s\n", envelope->dmRecipientIdent);
501 printf("\t\tdmSenderIdent = %s\n", envelope->dmSenderIdent);
503 printf("\t\tdmLegalTitleLaw = ");
504 print_longint(envelope->dmLegalTitleLaw);
505 printf("\t\tdmLegalTitleYear = ");
506 print_longint(envelope->dmLegalTitleYear);
507 printf("\t\tdmLegalTitleSect = %s\n", envelope->dmLegalTitleSect);
508 printf("\t\tdmLegalTitlePar = %s\n", envelope->dmLegalTitlePar);
509 printf("\t\tdmLegalTitlePoint = %s\n", envelope->dmLegalTitlePoint);
511 printf("\t\tdmPersonalDelivery = ");
512 print_bool(envelope->dmPersonalDelivery);
513 printf("\t\tdmAllowSubstDelivery = ");
514 print_bool(envelope->dmAllowSubstDelivery);
515 printf("\t\tdmOVM = ");
516 print_bool(envelope->dmOVM);
517 printf("\t\tdmPublishOwnID = ");
518 print_bool(envelope->dmPublishOwnID);
520 printf("\t\tdmOrdinal = ");
521 if (!envelope->dmOrdinal) printf("NULL\n");
522 else printf("%lu\n", *(envelope->dmOrdinal));
524 printf("\t\tdmMessageStatus = ");
525 print_dmMessageStatus(envelope->dmMessageStatus);
527 printf("\t\tdmAttachmentSize = ");
528 if (!envelope->dmAttachmentSize) printf("NULL\n");
529 else printf("%lu kB\n", *(envelope->dmAttachmentSize));
531 printf("\t\tdmDeliveryTime = ");
532 print_timeval(envelope->dmDeliveryTime);
534 printf("\t\tdmAcceptanceTime = ");
535 print_timeval(envelope->dmAcceptanceTime);
537 printf("\t\thash = ");
538 print_hash(envelope->hash);
540 printf("\t\ttimestamp = %p\n", envelope->timestamp);
541 printf("\t\ttimestamp_length = %zu\n", envelope->timestamp_length);
543 printf("\t\tevents = ");
544 print_events(envelope->events);
546 printf("\t}\n");
550 void print_document(const struct isds_document *document) {
551 printf("\t\tdocument = ");
553 if (!document) {
554 printf("NULL\n");
555 return;
557 printf("\{\n");
559 printf("\t\t\tis_xml = %u\n", !!document->is_xml);
560 printf("\t\t\txml_node_list = %p\n", document->xml_node_list);
562 printf("\t\t\tdata = %p\n", document->data);
563 printf("\t\t\tdata_length = %zu\n", document->data_length);
564 printf("\t\t\tdmMimeType = %s\n", document->dmMimeType);
566 printf("\t\t\tdmFileMetaType = ");
567 switch(document->dmFileMetaType) {
568 case FILEMETATYPE_MAIN: printf("MAIN\n"); break;
569 case FILEMETATYPE_ENCLOSURE: printf("ENCLOSURE\n"); break;
570 case FILEMETATYPE_SIGNATURE: printf("SIGNATURE\n"); break;
571 case FILEMETATYPE_META: printf("META\n"); break;
572 default: printf("<unknown type %d>\n", document->dmFileMetaType);
575 printf("\t\t\tdmFileGuid = %s\n", document->dmFileGuid);
576 printf("\t\t\tdmUpFileGuid = %s\n", document->dmUpFileGuid);
577 printf("\t\t\tdmFileDescr = %s\n", document->dmFileDescr);
578 printf("\t\t\tdmFormat = %s\n", document->dmFormat);
579 printf("\t\t}\n");
583 void print_documents(const struct isds_list *documents) {
584 const struct isds_list *item;
586 printf("\tdocuments = ");
588 if (!documents) {
589 printf("NULL\n");
590 return;
592 printf("{\n");
594 for (item = documents; item; item = item->next) {
595 print_document((struct isds_document *) (item->data));
598 printf("\t}\n");
602 void print_message(const struct isds_message *message) {
603 printf("message = ");
605 if (!message) {
606 printf("NULL\n");
607 return;
610 printf("{\n");
612 printf("\traw = %p\n", message->raw);
613 printf("\traw_length = %zu\n", message->raw_length);
614 printf("\traw_type = ");
615 print_raw_type(message->raw_type);
616 printf("\txml = %p\n", message->xml);
617 print_envelope(message->envelope);
618 print_documents(message->documents);
620 printf("}\n");
623 void print_copies(const struct isds_list *copies) {
624 const struct isds_list *item;
625 struct isds_message_copy *copy;
627 printf("Copies = ");
628 if (!copies) {
629 printf("<NULL>\n");
630 return;
633 printf("{\n");
634 for (item = copies; item; item = item->next) {
635 copy = (struct isds_message_copy *) item->data;
636 printf("\tCopy = ");
638 if (!copy)
639 printf("<NULL>\n");
640 else {
641 printf("{\n");
642 printf("\t\tdbIDRecipient = %s\n", copy->dbIDRecipient);
643 printf("\t\tdmRecipientOrgUnit = %s\n", copy->dmRecipientOrgUnit);
645 printf("\t\tdmRecipientOrgUnitNum = ");
646 if (copy->dmRecipientOrgUnitNum)
647 printf("%ld\n", *copy->dmRecipientOrgUnitNum);
648 else
649 printf("<NULL>\n");
650 printf("\t\tdmToHands = %s\n", copy->dmToHands);
652 printf("\t\terror = %s\n", isds_strerror(copy->error));
653 printf("\t\tdmStatus = %s\n", copy->dmStatus);
654 printf("\t\tdmID = %s\n", copy->dmID);
655 printf("\t}\n");
658 printf("}\n");
661 void print_message_status_change(
662 const struct isds_message_status_change *changed_status) {
663 printf("message_status_change = ");
665 if (!changed_status) {
666 printf("NULL\n");
667 return;
670 printf("{\n");
672 printf("\tdmID = %s\n", changed_status->dmID);
674 printf("\tdmMessageStatus = ");
675 print_dmMessageStatus(changed_status->dmMessageStatus);
677 printf("\ttime = ");
678 print_timeval(changed_status->time);
680 printf("}\n");
683 void compare_hashes(const struct isds_hash *hash1,
684 const struct isds_hash *hash2) {
685 isds_error err;
687 printf("Comparing hashes... ");
688 err = isds_hash_cmp(hash1, hash2);
689 if (err == IE_SUCCESS)
690 printf("Hashes equal\n");
691 else if
692 (err == IE_NOTEQUAL) printf("Hashes differ\n");
693 else
694 printf("isds_hash_cmp() failed: %s\n", isds_strerror(err));
698 int progressbar(double upload_total, double upload_current,
699 double download_total, double download_current,
700 void *data) {
702 printf("Progress: upload %0f/%0f, download %0f/%0f, data=%p\n",
703 upload_current, upload_total, download_current, download_total,
704 data);
705 if (data) {
706 printf("Aborting transfer...\n");
707 return 1;
709 return 0;
713 int mmap_file(const char *file, int *fd, void **buffer, size_t *length) {
714 struct stat file_info;
716 if (!file || !fd || !buffer || !length) return -1;
719 *fd = open(file, O_RDONLY);
720 if (*fd == -1) {
721 fprintf(stderr, "%s: Could not open file: %s\n", file, strerror(errno));
722 return -1;
725 if (-1 == fstat(*fd, &file_info)) {
726 fprintf(stderr, "%s: Could not get file size: %s\n", file,
727 strerror(errno));
728 close(*fd);
729 return -1;
731 if (file_info.st_size < 0) {
732 fprintf(stderr, "File `%s' has negative size: %" PRIdMAX "\n", file,
733 (intmax_t) file_info.st_size);
734 close(*fd);
735 return -1;
737 *length = file_info.st_size;
739 if (!*length) {
740 /* Empty region cannot be mmapped */
741 *buffer = NULL;
742 } else {
743 *buffer = mmap(NULL, *length, PROT_READ, MAP_PRIVATE, *fd, 0);
744 if (*buffer == MAP_FAILED) {
745 fprintf(stderr, "%s: Could not map file to memory: %s\n", file,
746 strerror(errno));
747 close(*fd);
748 return -1;
752 return 0;
756 int munmap_file(int fd, void *buffer, size_t length) {
757 int err = 0;
758 long int page_size = sysconf(_SC_PAGE_SIZE);
759 size_t pages = (length % page_size) ?
760 ((length / page_size) + 1) * page_size:
761 length;
763 if (length) {
764 err = munmap(buffer, pages);
765 if (err) {
766 fprintf(stderr,
767 "Could not unmap memory at %p and length %zu: %s\n",
768 buffer, pages, strerror(errno));
772 err = close(fd);
773 if (err) {
774 fprintf(stderr, "Could close file descriptor %d: %s\n", fd,
775 strerror(errno));
778 return err;
782 static int save_data_to_file(const char *file, const void *data,
783 const size_t length) {
784 int fd;
785 ssize_t written, left = length;
787 if (!file) return -1;
788 if (length > 0 && !data) return -1;
790 fd = open(file, O_WRONLY|O_TRUNC|O_CREAT, 0666);
791 if (fd == -1) {
792 fprintf(stderr, "%s: Could not open file for writing: %s\n",
793 file, strerror(errno));
794 return -1;
797 printf("Writing %zu bytes to file `%s'...\n", length, file);
798 while (left) {
799 written = write(fd, data + length - left, left);
800 if (written == -1) {
801 fprintf(stderr, "%s: Could not save file: %s\n",
802 file, strerror(errno));
803 close(fd);
804 return -1;
806 left-=written;
809 if (-1 == close(fd)) {
810 fprintf(stderr, "%s: Closing file failed: %s\n",
811 file, strerror(errno));
812 return -1;
815 printf("Done.\n");
816 return 0;
820 int save_data(const char *message, const void *data, const size_t length) {
821 if (message)
822 printf("%s\n", message);
823 return save_data_to_file("output", data, length);