-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapplesingle.c
1362 lines (1172 loc) · 34.8 KB
/
applesingle.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
applesingle.c - command line utility for manipulating AppleSingle and
AppleDouble files.
Build cmd for Mac OS 10.4:
gcc -DHAVE_DESKTOP_MANAGER -O2 -framework Carbon -lcrypto applesingle.c -o applesingle
Build cmd for later releases (e.g. with openssl installed under /usr/local):
cc -m32 -Wno-deprecated-declarations -O2 -framework Carbon -lcrypto applesingle.c -o applesingle
Build cmd for Linux:
cc -O2 applesingle.c -lcrypto -o applesingle
Copyright (c) 2006, 2009, 2011, 2016, 2019 Finn Thain
Portions of Desktop Manager support code copyright (c) 1992-2002 Apple Computer, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Notes:
* This format is too limited to represent modern HFS+ features like large
forks and POSIX dates. Two files make up an AppleDouble: Data (foo) and
Header (foo.ADF or ._foo in Mac OS X). It appears ._foo is subject to the
same 4 GB resource fork size limit and doesn't encode any dates (only
the resource fork and finder information entries).
* The traditional Finder/Desktop comment is not the same as Spotlight's
kMDItemFinderComment attribute, so Tiger doesn't really provide a way to
store them or access them since the Desktop Database API was deprecated.
* The POSIX file name is a custom extension to the format. It is encoded
in UTF-8 (since HFS+ does this).
* This program is able to output a series of AppleSingle files in one
stream, similar to archive tools like cpio(1) or pax(1). This feature is
presently only really useful for comparing files (and for validating entire
backups) because this program is not able to reconstruct archived files.
However, the command line options syntax is modeled on pax(1) and may
eventually get a "-r" option for this. Or perhaps a better approach would
be instead to extend pax itself (like hfspax).
* The format doesn't accomodate directories, but could probably be extended.
* Apple now ships their own "applesingle" command, which means this one should
be renamed.
* This program doesn't yet have full support for the AppleSingle/AppleDouble
implementation in A/UX. Namely, icons, home filesystem, and native file info
entries aren't implemented. See "A/UX Toolbox: Macintosh ROM Interface".
2006-06-19 First cut.
2009-09-01 Clean up code style. Rewrite help text. Rework argument parsing and
error handling. Add access time suppression. Numerous bug fixes.
2011-03-29 Improve option handling. Clean up comments and indentation.
2011-04-01 Clean up some error messages. Fix AppleDouble rsrc padding bug. Also
improve -v option behaviour. Simplify filename seperator output.
2011-04-03 Fix data fork too big error for AppleSingle encoding.
2016-08-08 Add HAVE_DESKTOP_MANAGER macro to fix build on recent OS releases.
2019-11-23 Add support for non-Mac (e.g. Linux) hosts.
2021-01-05 Minor changes to try to support 64-bit Linux hosts.
*/
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdint.h>
#include <dirent.h>
#include <openssl/md5.h>
#ifdef __MACOSX__
#include <Carbon/Carbon.h>
#define ENABLE_ENCODING
#define EPROTO EFTYPE
#else
#include <stdlib.h>
#include <string.h>
typedef int8_t SInt8;
typedef int16_t SInt16;
typedef int32_t SInt32;
typedef int64_t SInt64;
typedef uint8_t UInt8;
typedef uint16_t UInt16;
typedef uint32_t UInt32;
typedef uint64_t UInt64;
#endif
#ifdef __LP64__
#define UINT64_FMT "lu"
#else
#define UINT64_FMT "llu"
#endif
/* AppleSingle file header and AppleDouble "header file" header. */
struct asHdr {
UInt32 magic;
UInt32 version;
UInt8 filler[16];
UInt16 entries;
} __attribute__ ((packed));
typedef struct asHdr asHdr;
/* Magic numbers. */
enum { kAppleDoubleMagic = 0x00051607, kAppleSingleMagic = 0x00051600 };
/* This program only produces version 2 files. */
#define AS_VERSION 0x00020000
/* Entry descriptor. */
struct asEntryDesc {
UInt32 entry_id;
UInt32 offset;
UInt32 length;
} __attribute__ ((packed));
typedef struct asEntryDesc asEntryDesc;
/* Predefined entry IDs. */
#define AS_DATA 1
#define AS_RESOURCE 2
#define AS_NAME 3
#define AS_COMMENT 4
#define AS_FILE_DATES 8
#define AS_FILE_INFO 9
#define AS_MAC_INFO 10
/* Non-standard entry ID (beware, invented here). */
#define AS_POSIX_NAME 0x00000101 /* Always the first entry, if present */
/* File dates info entry. */
struct asDatesEntry {
SInt32 creation;
SInt32 modification;
SInt32 backup;
SInt32 access;
} __attribute__ ((packed));
typedef struct asDatesEntry asDatesEntry;
/* Mac info entry. */
typedef UInt32 asMacInfoEntry;
/* Mac info entry constants. */
enum { kASMacInfoLocked = 0x01, kASMacInfoProtected = 0x02 };
/* Some error handling routines. */
static char *err_msg = NULL;
static char err_msg_buf[255];
static inline int posix_error3(int e, char *fmt, char *m)
{
if (e == 0)
return 0;
snprintf(err_msg_buf, sizeof(err_msg_buf), fmt, m, strerror(e));
err_msg = err_msg_buf;
return e;
}
static inline int posix_error(int e, char *m)
{
return posix_error3(e, "%s: %s", m);
}
static void report_and_reset_error(char *m)
{
if (err_msg != NULL) {
fprintf(stderr, "%s: %s\n", m, err_msg);
err_msg = NULL;
}
}
#ifdef ENABLE_ENCODING
static inline OSErr carbon_error(OSErr e, char *m)
{
if (e == 0)
return 0;
snprintf(err_msg_buf, sizeof(err_msg_buf), "%s: error %d", m, e);
err_msg = err_msg_buf;
return e;
}
/* A routine to figure out whether the HFS unsigned 48-bit seconds-since-1904
* quantity fits in the AppleSingle/Double signed 32-bit seconds-since-2000
* variable, and also do the conversion.
*/
static int utcdatetime_to_AS(UTCDateTime *utcdt)
{
unsigned int rounding = utcdt->fraction >> 15;
unsigned long long t = ((unsigned long long)utcdt->highSeconds << 32) +
utcdt->lowSeconds + rounding;
if (t == 0)
return 0; /* no need to mess it up further */
if (t < 882006352ULL) {
fprintf(stderr, "timestamp value is too small\n");
return (int)0x80000000;
}
if (t > 5176973647ULL) {
fprintf(stderr, "timestamp value is too large\n");
return (int)0x7fffffff;
}
return (long long)t - 3029490000LL;
}
#ifdef HAVE_DESKTOP_MANAGER /* Not available in 64-bit Carbon (Leopard etc.) */
/* Routines to extract the Finder comment.
* Adapted from Apple's MoreDesktopMgr.c sample.
*/
static OSErr GetDesktopFileName(short vRefNum, Str255 desktopName)
{
OSErr error;
HParamBlockRec pb;
short index;
Boolean found;
pb.fileParam.ioNamePtr = desktopName;
pb.fileParam.ioVRefNum = vRefNum;
pb.fileParam.ioFVersNum = 0;
index = 1;
found = false;
do {
pb.fileParam.ioDirID = fsRtDirID;
pb.fileParam.ioFDirIndex = index;
error = PBHGetFInfoSync(&pb);
if (error == noErr)
if ((pb.fileParam.ioFlFndrInfo.fdType == 'FNDR') &&
(pb.fileParam.ioFlFndrInfo.fdCreator == 'ERIK'))
found = true;
++index;
} while ((error == noErr) && !found);
return error;
}
static OSErr GetVolumeInfoNoName(ConstStr255Param pathname, short vRefNum, HParmBlkPtr pb)
{
Str255 tempPathname;
OSErr error;
if (pb != NULL)
{
pb->volumeParam.ioVRefNum = vRefNum;
if (pathname == NULL) {
pb->volumeParam.ioNamePtr = NULL;
pb->volumeParam.ioVolIndex = 0; /* use ioVRefNum only */
} else {
BlockMoveData(pathname, tempPathname, pathname[0] + 1); /* make a copy of the string and */
pb->volumeParam.ioNamePtr = (StringPtr)tempPathname; /* use the copy so original isn't trashed */
pb->volumeParam.ioVolIndex = -1; /* use ioNamePtr/ioVRefNum combination */
}
error = PBHGetVInfoSync(pb);
pb->volumeParam.ioNamePtr = NULL; /* ioNamePtr may point to local tempPathname, so don't return it */
carbon_error(error, "PBHGetVInfoSync");
}
else
carbon_error(error = paramErr, "GetVolumeInfoNoName");
return error;
}
static OSErr DetermineVRefNum(ConstStr255Param pathname, short vRefNum, short *realVRefNum)
{
HParamBlockRec pb;
OSErr error;
error = GetVolumeInfoNoName(pathname, vRefNum, &pb);
if (error == noErr)
*realVRefNum = pb.volumeParam.ioVRefNum;
return error;
}
enum { kFCMTResType = 'FCMT' };
static OSErr GetCommentFromDesktopFile(short vRefNum, ConstStr255Param name, Str255 comment, short commentID)
{
OSErr error;
short realVRefNum;
Str255 desktopName;
short savedResFile;
short dfRefNum;
StringHandle commentHandle;
/* commentID == 0 means there's no comment */
if (commentID != 0) {
error = DetermineVRefNum(name, vRefNum, &realVRefNum);
if (error == noErr) {
error = GetDesktopFileName(realVRefNum, desktopName);
if (error == noErr) {
savedResFile = CurResFile();
SetResLoad(false);
dfRefNum = HOpenResFile(realVRefNum, fsRtDirID, desktopName, fsRdPerm);
SetResLoad(true);
if (dfRefNum != -1) {
UseResFile(dfRefNum);
/* Get the comment resource */
commentHandle = (StringHandle)Get1Resource(kFCMTResType, commentID);
if (commentHandle != NULL)
if (GetHandleSize((Handle)commentHandle) > 0)
BlockMoveData(*commentHandle, comment, *commentHandle[0] + 1);
else
error = afpItemNotFound;
else
error = afpItemNotFound;
/* restore the resource chain and close the Desktop file */
UseResFile(savedResFile);
CloseResFile(dfRefNum);
} else
carbon_error(error = ResError(), "HOpenResFile");
} else
error = afpItemNotFound;
}
} else
error = afpItemNotFound;
return error;
}
static OSErr DTGetComment(short vRefNum, long dirID, Str255 name, Str255 comment, short commentID)
{
DTPBRec pb;
OSErr error;
if (comment != NULL) {
comment[0] = 0; /* return nothing by default */
/* attempt to open the desktop database */
pb.ioNamePtr = name;
pb.ioVRefNum = vRefNum;
error = PBDTOpenInform(&pb);
if (error == noErr) {
/* There was a desktop database and it's now open */
if ((pb.ioTagInfo & 1) == 1) {
pb.ioDirID = dirID;
pb.ioDTBuffer = (void *)&comment[1];
pb.ioDTReqCount = 255;
error = PBDTGetCommentSync(&pb);
if (error != afpItemNotFound && !carbon_error(error, "PBDTGetCommentSync"))
comment[0] = (unsigned char)pb.ioDTActCount;
}
} else /* There is no desktop database - try the Desktop file */
error = GetCommentFromDesktopFile(vRefNum, name, comment, commentID);
} else
carbon_error(error = paramErr, "DTGetComment");
return error;
}
#endif /* HAVE_DESKTOP_MANAGER */
#define READ_BUFFER_SIZE (32 * 1024)
/* A routine to output a given fork. */
static OSErr dump_fork(UInt64 *pos, FSRef *ref, HFSUniStr255 *forkName)
{
SInt16 forkRefNum;
OSErr err = FSOpenFork(ref, forkName->length, forkName->unicode,
fsRdPerm, &forkRefNum);
if (carbon_error(err, "FSOpenFork")) return err;
char *buf = malloc(READ_BUFFER_SIZE);
if (!buf) {
posix_error(err = errno, "malloc");
FSCloseFork(forkRefNum);
return err;
}
OSErr read_err;
do {
ByteCount n = 0;
read_err = FSReadFork(forkRefNum, fsAtMark | noCacheMask, 0,
READ_BUFFER_SIZE, buf, &n);
*pos += fwrite(buf, 1, n, stdout);
if (posix_error(err = ferror(stdout), "fwrite"))
break;
if (read_err && read_err != eofErr) {
err = carbon_error(read_err, "FSReadFork");
break;
}
} while (!read_err);
free(buf);
FSCloseFork(forkRefNum);
return err;
}
/* Output some nulls. */
static int dump_padding(UInt64 *pos, size_t n)
{
int err;
char *buf = calloc(1, n);
if (buf == NULL) {
posix_error(err = errno, "calloc");
} else {
*pos += fwrite(buf, 1, n, stdout);
posix_error(err = ferror(stdout), "fwrite");
free(buf);
}
return err;
}
/* Output the POSIX name entry. */
static int dump_posix_name(UInt64 *pos, char *p)
{
*pos += fwrite(p, 1, strlen(p), stdout);
return posix_error(ferror(stdout), "fwrite");
}
/* Output the comment entry. */
static int dump_comment(UInt64 *pos, Str255 c)
{
*pos += fwrite(&c[1], 1, (size_t)c[0], stdout);
return posix_error(ferror(stdout), "fwrite");
}
/* Output the name entry. */
static int dump_name(UInt64 *pos, FSSpec *s)
{
*pos += fwrite(&s->name[1], 1, (size_t)s->name[0], stdout);
return posix_error(ferror(stdout), "fwrite");
}
/* Output the Mac info entry. */
static int dump_mac_info(UInt64 *pos, FSCatalogInfo *ci)
{
asMacInfoEntry e = 0;
e |= (ci->nodeFlags & kFSNodeLockedMask) ? kASMacInfoLocked : 0;
e |= (ci->nodeFlags & kFSNodeCopyProtectMask) ? kASMacInfoProtected : 0;
*pos += fwrite(&e, 1, sizeof(e), stdout);
return posix_error(ferror(stdout), "fwrite");
}
/* Output the file dates entry. */
static int dump_file_dates(UInt64 *pos, FSCatalogInfo *ci, short quash_atime)
{
asDatesEntry e;
e.creation = htobe32(utcdatetime_to_AS(&ci->createDate));
e.modification = htobe32(utcdatetime_to_AS(&ci->contentModDate));
e.backup = htobe32(utcdatetime_to_AS(&ci->backupDate));
e.access = htobe32(utcdatetime_to_AS(quash_atime ?
&ci->contentModDate : &ci->accessDate));
*pos += fwrite(&e, 1, sizeof(e), stdout);
return posix_error(ferror(stdout), "fwrite");
}
/* Output the file info entry. */
static int dump_file_info(UInt64 *pos, FSCatalogInfo *ci)
{
*pos += fwrite(&ci->finderInfo, 1, sizeof(ci->finderInfo), stdout);
int err = ferror(stdout);
if (posix_error(err, "fwrite")) return err;
*pos += fwrite(&ci->extFinderInfo, 1, sizeof(ci->extFinderInfo), stdout);
return posix_error(ferror(stdout), "fwrite");
}
/* Output a descriptor. */
static int dump_descriptors(UInt64 *pos, asEntryDesc *p)
{
while (p->entry_id) {
asEntryDesc d;
d.entry_id = htobe32(p.entry_id);
d.offset = htobe32(p.offset);
d.length = htobe32(p.length);
*pos += fwrite(&d, 1, sizeof(d), stdout);
int err = ferror(stdout);
if (posix_error(err, "fwrite")) return err;
p++;
}
return 0;
}
/* Output the file header. */
static int dump_header(UInt64 *pos, int format, short entries)
{
asHdr h;
h.magic = htobe32(format);
h.version = htobe32(AS_VERSION);
h.entries = htobe16(entries);
bzero(&h.filler, sizeof(h.filler));
*pos += fwrite(&h, 1, sizeof(h), stdout);
return posix_error(ferror(stdout), "fwrite");
}
/* Output a file in its AppleSingle or AppleDouble representation,
* with or without its comment entry.
*/
static OSErr encode_file(char *filename, int format, short include_comment,
short include_posixname, short quash_atime)
{
FSRef ref;
OSErr err = FSPathMakeRef((UInt8 *)filename, &ref, false);
if (carbon_error(err, "FSPathMakeRef")) return err;
FSCatalogInfoBitmap theInfo = kFSCatInfoNodeFlags | kFSCatInfoAllDates |
kFSCatInfoFinderInfo | kFSCatInfoFinderXInfo |
kFSCatInfoDataSizes | kFSCatInfoRsrcSizes;
FSCatalogInfo catalogInfo;
FSSpec fsSpec;
err = FSGetCatalogInfo(&ref, theInfo, &catalogInfo, NULL, &fsSpec, NULL);
if (carbon_error(err, "FSGetCatalogInfo"))
return err;
if (catalogInfo.rsrcLogicalSize > 0xffffffffULL)
return posix_error3(EFBIG,
"%s: Resource fork too big for AppleSingle/Double format", filename);
if (catalogInfo.dataLogicalSize > 0xffffffffULL &&
format == kAppleSingleMagic)
return posix_error3(EFBIG,
"%s: Data fork too big for AppleSingle format", filename);
char *comment = NULL;
#ifdef HAVE_DESKTOP_MANAGER
if (include_comment) {
if ((comment = malloc(256)) == NULL)
return posix_error(errno, "malloc");
FXInfo *fxi = (void *)&catalogInfo.extFinderInfo;
err = DTGetComment(fsSpec.vRefNum, fsSpec.parID, fsSpec.name,
(void *)comment, fxi->fdComment);
if (err == afpItemNotFound) {
free(comment);
comment = NULL;
} else {
free(comment);
return err;
}
}
#endif
asEntryDesc des[9];
/* Populate each descriptor in memory before writing them out. */
short entry = 0;
short entries = 5 + (comment != NULL)
+ (format == kAppleSingleMagic)
+ (include_posixname != 0);
des[entry].offset = sizeof(asHdr) + entries * sizeof(asEntryDesc);
if (include_posixname) {
des[entry].entry_id = AS_POSIX_NAME;
des[entry].length = strlen(filename);
entry++;
des[entry].offset = des[entry-1].offset + des[entry-1].length;
}
des[entry].entry_id = AS_FILE_INFO;
des[entry].length = sizeof(FInfo) + sizeof(FXInfo);
entry++;
des[entry].offset = des[entry-1].offset + des[entry-1].length;
des[entry].entry_id = AS_FILE_DATES;
des[entry].length = sizeof(asDatesEntry);
entry++;
des[entry].offset = des[entry-1].offset + des[entry-1].length;
des[entry].entry_id = AS_MAC_INFO;
des[entry].length = sizeof(asMacInfoEntry);
entry++;
des[entry].offset = des[entry-1].offset + des[entry-1].length;
des[entry].entry_id = AS_NAME;
des[entry].length = fsSpec.name[0];
entry++;
if (comment != NULL) {
des[entry].offset = des[entry-1].offset + des[entry-1].length;
des[entry].entry_id = AS_COMMENT;
des[entry].length = comment[0];
entry++;
}
int rsrc_padding = 0;
des[entry].offset = des[entry-1].offset + des[entry-1].length;
des[entry].entry_id = AS_RESOURCE;
des[entry].length = catalogInfo.rsrcLogicalSize;
entry++;
if (format == kAppleSingleMagic) {
if (catalogInfo.rsrcLogicalSize)
rsrc_padding = (4096 - (catalogInfo.rsrcLogicalSize % 4096)) % 4096;
des[entry].offset = des[entry-1].offset +
des[entry-1].length + rsrc_padding;
des[entry].entry_id = AS_DATA;
des[entry].length = catalogInfo.dataLogicalSize;
entry++;
}
des[entry].entry_id = 0; /* sentinel */
/* Having populated the descriptors, write them out following the header,
* then write out their entries.
*/
UInt64 pos = 0;
UInt64 final_pos = des[entry-1].offset + des[entry-1].length;
/* dump header */
err = dump_header(&pos, format, entries);
if (err) goto out;
/* dump descriptors */
err = dump_descriptors(&pos, des);
if (err) goto out;
/* dump entries */
asEntryDesc *cur_des = &des[0];
HFSUniStr255 forkName;
do {
if (pos > 0xffffffffULL) {
posix_error3(err = EFBIG,
"%s: Output too large for AppleSingle/Double format", filename);
goto out;
}
/* sanity check */
if (pos != (unsigned long long)cur_des->offset) {
// fprintf(stderr, "pos %"UINT64_FMT" offset %lu\n", pos, (unsigned long)cur_des->offset);
fprintf(stderr, "Bad position/offset in encode_file()!\n");
err = EIO;
goto out;
}
switch(cur_des->entry_id) {
case AS_POSIX_NAME:
err = dump_posix_name(&pos, filename);
if (err) goto out;
break;
case AS_FILE_INFO:
err = dump_file_info(&pos, &catalogInfo);
if (err) goto out;
break;
case AS_FILE_DATES:
err = dump_file_dates(&pos, &catalogInfo, quash_atime);
if (err) goto out;
break;
case AS_MAC_INFO:
err = dump_mac_info(&pos, &catalogInfo);
if (err) goto out;
break;
case AS_NAME:
err = dump_name(&pos, &fsSpec);
if (err) goto out;
break;
case AS_COMMENT:
err = dump_comment(&pos, (void *)comment);
if (err) goto out;
break;
case AS_RESOURCE:
err = FSGetResourceForkName(&forkName);
if (carbon_error(err, "FSGetResourceForkName")) goto out;
err = dump_fork(&pos, &ref, &forkName);
if (err) goto out;
if (rsrc_padding)
err = dump_padding(&pos, rsrc_padding);
if (err) goto out;
break;
case AS_DATA:
err = FSGetDataForkName(&forkName);
if (carbon_error(err, "FSGetDataForkName")) goto out;
err = dump_fork(&pos, &ref, &forkName);
if (err) goto out;
break;
}
} while ((++cur_des)->entry_id);
/* sanity check */
if (pos != final_pos) {
// fprintf(stderr, "pos %"UINT64_FMT" final_pos %"UINT64_FMT"\n", pos, final_pos);
fprintf(stderr, "Bad position/final position in encode_file()!\n");
err = EIO;
goto out;
}
err = 0;
out:
if (comment)
free(comment);
return err;
}
/* Retrieve a record from a file, given a seperator character. */
static ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream)
{
char *p; // reads stored here
size_t const rchunk = 1; // number of bytes to read
size_t const mchunk = 512; // number of extra bytes to malloc
size_t m = rchunk + 1; // initial buffer size
if (*lineptr) {
if (*n < m) {
*lineptr = (char*)realloc(*lineptr, m);
if (!*lineptr) return -1;
*n = m;
}
} else {
*lineptr = (char*)malloc(m);
if (!*lineptr) return -1;
*n = m;
}
m = 0; // record length including seperator
do {
size_t i; // number of bytes read etc
size_t j = 0; // number of bytes searched
p = *lineptr + m;
i = fread(p, 1, rchunk, stream);
if (i < rchunk && ferror(stream))
return -1;
while (j < i) {
++j;
if (*p++ == (char)delim) {
*p = '\0';
if (j != i) {
if (fseek(stream, j - i, SEEK_CUR))
return -1;
if (feof(stream))
clearerr(stream);
}
m += j;
return m;
}
}
m += j;
if (feof(stream)) {
if (m) return m;
if (!i) return -1;
}
// allocate space for next read plus possible null terminator
i = ((m + ((rchunk + 1 > mchunk) ? rchunk + 1 : mchunk) +
mchunk - 1) / mchunk) * mchunk;
if (i != *n) {
*lineptr = (char*)realloc(*lineptr, i);
if (!*lineptr) return -1;
*n = i;
}
} while (1);
}
#endif // ENABLE_ENCODING
/* Qsort comparison routine for sorting descriptors by offset. */
static int compare_desc_offset(const void * a, const void * b)
{
UInt32 ao = be32toh(((asEntryDesc*)a)->offset);
UInt32 bo = be32toh(((asEntryDesc*)b)->offset);
if (ao < bo)
return -1;
else if (ao > bo)
return 1;
else return 0;
}
/* Routine to convert some input to hex on stdout.
* One line of hex is 8 columns of 8 hex digits,
* with each column having ' ' or '\n' seperator.
*/
#define CHARS_PER_COL (8)
#define COLS_PER_LINE (8)
#define HEX_LINE_CHARS (COLS_PER_LINE * (1 + CHARS_PER_COL))
#define BIN_LINE_BYTES (COLS_PER_LINE * (CHARS_PER_COL / 2))
#define LINES_PER_BUFFER (512)
#define HEX_BUFFER_SIZE (LINES_PER_BUFFER * HEX_LINE_CHARS)
#define BIN_BUFFER_SIZE (LINES_PER_BUFFER * BIN_LINE_BYTES)
static int output_hex(FILE *f, size_t n)
{
char digits[] = "0123456789abcdef";
unsigned char *bin_buf = malloc(BIN_BUFFER_SIZE);
if (bin_buf == NULL) {
perror("malloc");
return errno;
}
unsigned char *hex_buf = malloc(HEX_BUFFER_SIZE);
if (hex_buf == NULL) {
perror("malloc");
free(bin_buf);
return errno;
}
int err = 0;
do {
size_t bin_chunk = n;
if (bin_chunk > BIN_BUFFER_SIZE)
bin_chunk = BIN_BUFFER_SIZE;
size_t i = fread(bin_buf, 1, bin_chunk, f);
if (i < bin_chunk) {
if (feof(f)) {
err = EPROTO;
bin_chunk = i;
} else {
posix_error(err = ferror(f), "fread");
goto out;
}
}
i = 0; /* number of input bytes processed */
unsigned char *b = bin_buf, *h = hex_buf;
while (i < bin_chunk) {
*h++ = digits[*b >> 4];
*h++ = digits[*b & 0x0f];
++b;
++i;
if (i % 4 == 0)
*h++ = (i % 32 == 0) ? '\n' : ' ';
}
size_t hex_chunk;
if (i < 4) {
/* add a '\n' */
hex_chunk = 2 * i + 1;
} else if (i % 4 == 0) {
/* change the last seperator to a '\n' */
hex_chunk = ((i * 2) / 8) * 9;
h--;
} else {
/* add a '\n' */
hex_chunk = ((i * 2) / 8) * 9 + (i % 4) * 2 + 1;
}
*h = '\n';
if (!fwrite(hex_buf, hex_chunk, 1, stdout))
posix_error(err = ferror(stdout), "fwrite");
n -= i;
} while (err == 0 && n > 0);
out:
free(hex_buf);
free(bin_buf);
return err;
}
/* Copy some bytes to stdout. */
static int output_raw(FILE *f, char *buf, unsigned buf_sz, size_t n)
{
size_t chunk = (n > buf_sz) ? buf_sz : n;
while (n) {
if (n < chunk)
chunk = n;
size_t r = fread(buf, 1, chunk, f);
if (!fwrite(buf, r, 1, stdout))
return posix_error(ferror(stdout), "fwrite");
if (r < chunk) {
if (feof(f))
return posix_error(EPROTO, "unexpected EOF");
int read_error = ferror(f);
if (posix_error(read_error, "fread"))
return read_error;
}
n -= r;
}
return 0;
}
/* Output a message digest. */
static int output_digest(FILE *f, char *buf, unsigned buf_sz, size_t n)
{
MD5_CTX c;
MD5_Init(&c);
UInt64 md[2];
size_t chunk = (n > buf_sz) ? buf_sz : n;
while (n) {
if (n < chunk) chunk = n;
size_t r = fread(buf, 1, chunk, f);
if (r < chunk) {
if (feof(f))
return posix_error(EPROTO, "unexpected EOF");
int read_error = ferror(f);
if (posix_error(read_error, "fread"))
return read_error;
}
MD5_Update(&c, buf, r);
n -= r;
}
MD5_Final((void*)md, &c);
printf("%016llx%016llx (md5)\n", md[0], md[1]);
return 0;
}
/* Throw away some input. */
static int discard(FILE *f, char *buf, unsigned buf_sz, size_t n)
{
size_t chunk = (n > buf_sz) ? buf_sz : n;
while (n) {
if (n < chunk) chunk = n;
size_t r = fread(buf, 1, chunk, f);
if (r < chunk) {
if (feof(f))
return posix_error(EPROTO, "unexpected EOF");
int read_error = ferror(f);
if (posix_error(read_error, "fread"))
return read_error;
}
n -= r;
}
return 0;
}
/* Output the name of an entry ID. */
static void output_entry_id(UInt32 id)
{
switch(id) {
case AS_DATA:
printf("data\n");
break;
case AS_RESOURCE:
printf("rsrc\n");
break;
case AS_NAME:
printf("name\n");
break;
case AS_COMMENT:
printf("comment\n");
break;
case AS_FILE_DATES:
printf("file dates\n");
break;
case AS_FILE_INFO:
printf("file info\n");
break;
case AS_MAC_INFO:
printf("mac info\n");
break;
case AS_POSIX_NAME:
printf("posix name\n");
break;
default:
printf("id = %ld\n", (long)id);
}
}
/* Output the filename seperator character. */
static int output_sep(char sep)
{
if (!fwrite(&sep, 1, 1, stdout))
return posix_error(ferror(stdout), "fwrite");
return 0;
}
#define WRITE_BUFFER_SIZE (32 * 1024)
/* Routine to decode an AppleDouble or AppleSingle stream. */