File: OFArc.m

package info (click to toggle)
objfw 1.4.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,644 kB
  • sloc: objc: 101,491; asm: 5,083; sh: 4,092; makefile: 1,574; ansic: 709; xml: 367; pascal: 214
file content (917 lines) | stat: -rw-r--r-- 25,006 bytes parent folder | download
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
/*
 * Copyright (c) 2008-2025 Jonathan Schleifer <js@nil.im>
 *
 * All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version 3.0 only,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * version 3.0 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3.0 along with this program. If not, see
 * <https://www.gnu.org/licenses/>.
 */

#include "config.h"

#include <string.h>

#import "OFApplication.h"
#import "OFArray.h"
#import "OFFile.h"
#import "OFFileManager.h"
#import "OFIRI.h"
#import "OFIRIHandler.h"
#import "OFLocale.h"
#import "OFOptionsParser.h"
#import "OFSandbox.h"
#import "OFStdIOStream.h"
#import "OFSystemInfo.h"

#import "OFArc.h"
#import "GZIPArchive.h"
#import "LHAArchive.h"
#import "TarArchive.h"
#import "ZIPArchive.h"
#import "ZooArchive.h"

#ifdef HAVE_TLS_SUPPORT
# import "ObjFWTLS.h"
#endif

#import "OFCreateDirectoryFailedException.h"
#import "OFGetItemAttributesFailedException.h"
#import "OFInvalidArgumentException.h"
#import "OFInvalidFormatException.h"
#import "OFNotImplementedException.h"
#import "OFOpenItemFailedException.h"
#import "OFReadFailedException.h"
#import "OFSeekFailedException.h"
#import "OFWriteFailedException.h"

#define bufferSize 16384

#ifdef OF_AMIGAOS
const char *VER = "$VER: ofarc " OF_PREPROCESSOR_STRINGIFY(OBJFW_VERSION_MAJOR)
    "." OF_PREPROCESSOR_STRINGIFY(OBJFW_VERSION_MINOR) " (" BUILD_DATE ") "
    "\xA9 2008-2025 Jonathan Schleifer";
#endif

#ifdef HAVE_TLS_SUPPORT
void
_reference_to_ObjFWTLS(void)
{
	_ObjFWTLS_reference = 1;
}
#endif

OF_APPLICATION_DELEGATE(OFArc)

static void
help(OFStream *stream, bool full, int status)
{
	[stream writeLine: OF_LOCALIZED(@"usage",
	    @"Usage: %[prog] -[acCfhlnpqtvx] archive.zip [file1 file2 ...]",
	    @"prog", [OFApplication programName])];

	if (full) {
		[stream writeString: @"\n"];
		[stream writeLine: OF_LOCALIZED(@"full_usage",
		    @"Options:\n"
		    @"    -a  --append            Append to archive\n"
		    @"        --archive-comment=  Archive comment to use when "
		    @"creating or appending\n"
		    @"    -c  --create            Create archive\n"
		    @"    -C  --directory=        Extract into the specified "
		    @"directory\n"
		    @"    -E  --encoding=         The encoding used by the "
		    @"archive\n"
		    @"                            (only Tar, LHA and Zoo files)"
		    @"\n"
		    @"    -f  --force             Force / overwrite files\n"
		    @"    -h  --help              Show this help\n"
		    @"        --iri               Use an IRI to access the "
		    @"archive\n"
		    @"    -l  --list              List all files in the archive"
		    @"\n"
		    @"    -n  --no-clobber        Never overwrite files\n"
		    @"    -p  --print             Print one or more files from "
		    @"the archive\n"
		    @"    -q  --quiet             Quiet mode (no output, "
		    @"except errors)\n"
		    @"    -t  --type=             Archive type (gz, lha, tar, "
		    @"tgz, zip, zoo)\n"
		    @"    -v  --verbose           Verbose output for file list"
		    @"\n"
		    @"    -x  --extract           Extract files\n"
		    @"        --version           Print the version "
		    @"information")];
	}

	[OFApplication terminateWithStatus: status];
}

static void
version(void)
{
	[OFStdOut writeFormat: @"ofarc %@ (ObjFW %@) "
			       @"<https://objfw.nil.im/>\n"
			       @"Copyright (c) 2008-2025 Jonathan Schleifer "
			       @"<js@nil.im>\n"
			       @"Licensed under the LGPL 3.0 "
			       @"<https://www.gnu.org/licenses/lgpl-3.0.html>"
			       @"\n",
			       @PACKAGE_VERSION, [OFSystemInfo ObjFWVersion]];
	[OFApplication terminate];
}

static void
mutuallyExclusiveError(OFUnichar shortOption1, OFString *longOption1,
    OFUnichar shortOption2, OFString *longOption2)
{
	OFString *shortOption1Str = [OFString stringWithFormat: @"%C",
								shortOption1];
	OFString *shortOption2Str = [OFString stringWithFormat: @"%C",
								shortOption2];

	[OFStdErr writeLine: OF_LOCALIZED(@"2_options_mutually_exclusive",
	    @"Error: -%[shortopt1] / --%[longopt1] and "
	    @"-%[shortopt2] / --%[longopt2] "
	    @"are mutually exclusive!",
	    @"shortopt1", shortOption1Str,
	    @"longopt1", longOption1,
	    @"shortopt2", shortOption2Str,
	    @"longopt2", longOption2)];
	[OFApplication terminateWithStatus: 1];
}

static OFIRI *
argumentToIRI(OFString *argument, bool isIRI)
{
	if (isIRI)
		return [OFIRI IRIWithString: argument];

	if ([argument isEqual: @"-"])
		return nil;

	return [OFIRI fileIRIWithPath: argument];
}

static void
mutuallyExclusiveError5(OFUnichar shortOption1, OFString *longOption1,
    OFUnichar shortOption2, OFString *longOption2,
    OFUnichar shortOption3, OFString *longOption3,
    OFUnichar shortOption4, OFString *longOption4,
    OFUnichar shortOption5, OFString *longOption5)
{
	OFString *shortOption1Str = [OFString stringWithFormat: @"%C",
								shortOption1];
	OFString *shortOption2Str = [OFString stringWithFormat: @"%C",
								shortOption2];
	OFString *shortOption3Str = [OFString stringWithFormat: @"%C",
								shortOption3];
	OFString *shortOption4Str = [OFString stringWithFormat: @"%C",
								shortOption4];
	OFString *shortOption5Str = [OFString stringWithFormat: @"%C",
								shortOption5];

	[OFStdErr writeLine: OF_LOCALIZED(@"5_options_mutually_exclusive",
	    @"Error: -%[shortopt1] / --%[longopt1], "
	    @"-%[shortopt2] / --%[longopt2], -%[shortopt3] / --%[longopt3], "
	    @"-%[shortopt4] / --%[longopt4] and\n"
	    @"       -%[shortopt5] / --%[longopt5] are mutually exclusive!",
	    @"shortopt1", shortOption1Str,
	    @"longopt1", longOption1,
	    @"shortopt2", shortOption2Str,
	    @"longopt2", longOption2,
	    @"shortopt3", shortOption3Str,
	    @"longopt3", longOption3,
	    @"shortopt4", shortOption4Str,
	    @"longopt4", longOption4,
	    @"shortopt5", shortOption5Str,
	    @"longopt5", longOption5)];
	[OFApplication terminateWithStatus: 1];
}

static void
writingNotSupported(OFString *type)
{
	[OFStdErr writeLine: OF_LOCALIZED(
	    @"writing_not_supported",
	    @"Writing archives of type %[type] is not (yet) supported!",
	    @"type", type)];
}

static void
addFiles(id <Archive> archive, OFArray OF_GENERIC(OFString *) *files,
    OFString *archiveComment)
{
	OFMutableArray *expandedFiles =
	    [OFMutableArray arrayWithCapacity: files.count];
	OFFileManager *fileManager = [OFFileManager defaultManager];

	for (OFString *file in files) {
		OFFileAttributes attributes =
		    [fileManager attributesOfItemAtPath: file];

		if ([attributes.fileType isEqual: OFFileTypeDirectory])
			[expandedFiles addObjectsFromArray:
			    [fileManager subpathsOfDirectoryAtPath: file]];
		else
			[expandedFiles addObject: file];
	}

	if (expandedFiles.count < 1) {
		[OFStdErr writeLine: OF_LOCALIZED(@"add_no_file_specified",
		    @"Need one or more files to add!")];
		[OFApplication terminateWithStatus: 1];
	}

	[archive addFiles: expandedFiles archiveComment: archiveComment];
}

@implementation OFArc
- (void)applicationDidFinishLaunching: (OFNotification *)notification
{
	OFString *archiveComment, *outputDir, *encodingString, *type;
	bool isIRI;
	const OFOptionsParserOption options[] = {
		{ 'a',  @"append", 0, NULL, NULL },
		{ '\0', @"archive-comment", 1, NULL, &archiveComment },
		{ 'c',  @"create", 0, NULL, NULL },
		{ 'C',  @"directory", 1, NULL, &outputDir },
		{ 'E',  @"encoding", 1, NULL, &encodingString },
		{ 'f',  @"force", 0, NULL, NULL },
		{ 'h',  @"help", 0, NULL, NULL },
		{ '\0', @"iri", 0, &isIRI, NULL },
		{ 'l',  @"list", 0, NULL, NULL },
		{ 'n',  @"no-clobber", 0, NULL, NULL },
		{ 'p',  @"print", 0, NULL, NULL },
		{ 'q',  @"quiet", 0, NULL, NULL },
		{ 't',  @"type", 1, NULL, &type },
		{ 'v',  @"verbose", 0, NULL, NULL },
		{ 'x',  @"extract", 0, NULL, NULL },
		{ '\0', @"version", 0, NULL, NULL },
		{ '\0', nil, 0, NULL, NULL }
	};
	OFUnichar option, mode = '\0';
	OFStringEncoding encoding = OFStringEncodingAutodetect;
	OFOptionsParser *optionsParser;
	OFArray OF_GENERIC(OFString *) *remainingArguments, *files;
	OFIRI *IRI;
	id <Archive> archive;

#ifdef OF_HAVE_SANDBOX
	OFSandbox *sandbox = [OFSandbox sandbox];
	sandbox.allowsStdIO = true;
	sandbox.allowsReadingFiles = true;
	sandbox.allowsWritingFiles = true;
	sandbox.allowsCreatingFiles = true;
	sandbox.allowsChangingFileAttributes = true;
	sandbox.allowsUserDatabaseReading = true;
	/* Dropped after parsing options */
	sandbox.allowsUnveil = true;

	[OFApplication of_activateSandbox: sandbox];
#endif

#ifndef OF_AMIGAOS
	[OFLocale addLocalizationDirectoryIRI:
	    [OFIRI fileIRIWithPath: @LOCALIZATION_DIR]];
#else
	[OFLocale addLocalizationDirectoryIRI:
	    [OFIRI fileIRIWithPath: @"PROGDIR:/Data/ofarc/localization"]];
#endif

#ifdef OF_AMIGAOS
	[[OFRunLoop mainRunLoop] addExecSignal: SIGBREAKB_CTRL_C
					target: self
				      selector: @selector(handleBreakCtrlC:)];
#endif

	optionsParser = [OFOptionsParser parserWithOptions: options];
	while ((option = [optionsParser nextOption]) != '\0') {
		switch (option) {
		case 'f':
			if (_overwrite < 0)
				mutuallyExclusiveError(
				    'f', @"force", 'n', @"no-clobber");

			_overwrite = 1;
			break;
		case 'n':
			if (_overwrite > 0)
				mutuallyExclusiveError(
				    'f', @"force", 'n', @"no-clobber");

			_overwrite = -1;
			break;
		case 'v':
			if (_outputLevel < 0)
				mutuallyExclusiveError(
				    'q', @"quiet", 'v', @"verbose");

			_outputLevel++;
			break;
		case 'q':
			if (_outputLevel > 0)
				mutuallyExclusiveError(
				    'q', @"quiet", 'v', @"verbose");

			_outputLevel--;
			break;
		case 'a':
		case 'c':
		case 'l':
		case 'p':
		case 'x':
			if (mode != '\0')
				mutuallyExclusiveError5(
				    'a', @"append",
				    'c', @"create",
				    'l', @"list",
				    'p', @"print",
				    'x', @"extract");

			mode = option;
			break;
		case 'h':
			help(OFStdOut, true, 0);
			break;
		case '-':
			if ([optionsParser.lastLongOption isEqual: @"version"])
				version();
			break;
		case '=':
			[OFStdErr writeLine: OF_LOCALIZED(
			    @"option_takes_no_argument",
			    @"%[prog]: Option --%[opt] takes no argument",
			    @"prog", [OFApplication programName],
			    @"opt", optionsParser.lastLongOption)];

			[OFApplication terminateWithStatus: 1];
			break;
		case ':':
			if (optionsParser.lastLongOption != nil)
				[OFStdErr writeLine: OF_LOCALIZED(
				    @"long_option_requires_argument",
				    @"%[prog]: Option --%[opt] requires an "
				    @"argument",
				    @"prog", [OFApplication programName],
				    @"opt", optionsParser.lastLongOption)];
			else {
				OFString *optStr = [OFString
				    stringWithFormat: @"%C",
				    optionsParser.lastOption];
				[OFStdErr writeLine: OF_LOCALIZED(
				    @"option_requires_argument",
				    @"%[prog]: Option -%[opt] requires an "
				    @"argument",
				    @"prog", [OFApplication programName],
				    @"opt", optStr)];
			}

			[OFApplication terminateWithStatus: 1];
			break;
		case '?':
			if (optionsParser.lastLongOption != nil)
				[OFStdErr writeLine: OF_LOCALIZED(
				    @"unknown_long_option",
				    @"%[prog]: Unknown option: --%[opt]",
				    @"prog", [OFApplication programName],
				    @"opt", optionsParser.lastLongOption)];
			else {
				OFString *optStr = [OFString
				    stringWithFormat: @"%C",
				    optionsParser.lastOption];
				[OFStdErr writeLine: OF_LOCALIZED(
				    @"unknown_option",
				    @"%[prog]: Unknown option: -%[opt]",
				    @"prog", [OFApplication programName],
				    @"opt", optStr)];
			}

			[OFApplication terminateWithStatus: 1];
			break;
		}
	}

	@try {
		if (encodingString != nil)
			encoding = OFStringEncodingParseName(encodingString);
	} @catch (OFInvalidArgumentException *e) {
		[OFStdErr writeLine: OF_LOCALIZED(
		    @"invalid_encoding",
		    @"%[prog]: Invalid encoding: %[encoding]",
		    @"prog", [OFApplication programName],
		    @"encoding", encodingString)];

		[OFApplication terminateWithStatus: 1];
	}

	remainingArguments = optionsParser.remainingArguments;

	switch (mode) {
	case 'a':
	case 'c':
		if (remainingArguments.count < 1)
			help(OFStdErr, false, 1);

		IRI = argumentToIRI(remainingArguments.firstObject, isIRI);
		files = [remainingArguments objectsInRange:
		    OFMakeRange(1, remainingArguments.count - 1)];

#ifdef OF_HAVE_SANDBOX
		if ([IRI.scheme isEqual: @"file"])
			[sandbox unveilPath: IRI.fileSystemRepresentation
				permissions: (mode == 'a' ? @"rwc" : @"wc")];

		for (OFString *path in files)
			[sandbox unveilPath: path permissions: @"r"];

		sandbox.allowsUnveil = false;
		[OFApplication of_activateSandbox: sandbox];
#endif

		archive = [self openArchiveWithIRI: IRI
					      type: type
					      mode: mode
					  encoding: encoding];

		addFiles(archive, files, archiveComment);
		break;
	case 'l':
		if (remainingArguments.count != 1)
			help(OFStdErr, false, 1);

		IRI = argumentToIRI(remainingArguments.firstObject, isIRI);

#ifdef OF_HAVE_SANDBOX
		if ([IRI.scheme isEqual: @"file"])
			[sandbox unveilPath: IRI.fileSystemRepresentation
				permissions: @"r"];

		sandbox.allowsUnveil = false;
		[OFApplication of_activateSandbox: sandbox];
#endif

		archive = [self openArchiveWithIRI: IRI
					      type: type
					      mode: mode
					  encoding: encoding];

		[archive listFiles];
		break;
	case 'p':
		if (remainingArguments.count < 1)
			help(OFStdErr, false, 1);

		IRI = argumentToIRI(remainingArguments.firstObject, isIRI);
		files = [remainingArguments objectsInRange:
		    OFMakeRange(1, remainingArguments.count - 1)];

#ifdef OF_HAVE_SANDBOX
		if ([IRI.scheme isEqual: @"file"])
			[sandbox unveilPath: IRI.fileSystemRepresentation
				permissions: @"r"];

		sandbox.allowsUnveil = false;
		[OFApplication of_activateSandbox: sandbox];
#endif

		archive = [self openArchiveWithIRI: IRI
					      type: type
					      mode: mode
					  encoding: encoding];

		[archive printFiles: files];
		break;
	case 'x':
		if (remainingArguments.count < 1)
			help(OFStdErr, false, 1);

		IRI = argumentToIRI(remainingArguments.firstObject, isIRI);
		files = [remainingArguments objectsInRange:
		    OFMakeRange(1, remainingArguments.count - 1)];

#ifdef OF_HAVE_SANDBOX
		if ([IRI.scheme isEqual: @"file"])
			[sandbox unveilPath: IRI.fileSystemRepresentation
				permissions: @"r"];

		if (files.count > 0)
			for (OFString *path in files)
				[sandbox unveilPath: path permissions: @"wc"];
		else {
			OFString *path = outputDir;

			if (path == nil)
				path = [[OFFileManager defaultManager]
				    currentDirectoryPath];

			/* We need 'r' to change the directory to it. */
			[sandbox unveilPath: path permissions: @"rwc"];
		}

		sandbox.allowsUnveil = false;
		[OFApplication of_activateSandbox: sandbox];
#endif

		archive = [self openArchiveWithIRI: IRI
					      type: type
					      mode: mode
					  encoding: encoding];

#ifdef OF_MACOS
		if ([IRI.scheme isEqual: @"file"]) {
			@try {
				OFString *attributeName =
				    @"com.apple.quarantine";

				_quarantine = objc_retain(
				    [[OFFileManager defaultManager]
				    extendedAttributeDataForName: attributeName
						     ofItemAtIRI: IRI]);
			} @catch (OFGetItemAttributesFailedException *e) {
				if (e.errNo != /*ENOATTR*/ 93)
					@throw e;
			}
		}
#endif

		if (outputDir != nil) {
			OFFileManager *fileManager =
			    [OFFileManager defaultManager];

			if (![fileManager directoryExistsAtPath: outputDir])
				[fileManager createDirectoryAtPath: outputDir
						     createParents: true];

			[fileManager changeCurrentDirectoryPath: outputDir];
		}

		@try {
			[archive extractFiles: files];
		} @catch (OFCreateDirectoryFailedException *e) {
			[OFStdErr writeString: @"\r"];
			[OFStdErr writeLine: OF_LOCALIZED(
			    @"failed_to_create_directory",
			    @"Failed to create directory %[dir]: %[error]",
			    @"dir", e.IRI.fileSystemRepresentation,
			    @"error", OFStrError(e.errNo))];
			_exitStatus = 1;
		} @catch (OFOpenItemFailedException *e) {
			[OFStdErr writeString: @"\r"];
			[OFStdErr writeLine: OF_LOCALIZED(
			    @"failed_to_open_file",
			    @"Failed to open file %[file]: %[error]",
			    @"file", e.path,
			    @"error", OFStrError(e.errNo))];
			_exitStatus = 1;
		}

		break;
	default:
		help(OFStdErr, true, 1);
		break;
	}

	[OFApplication terminateWithStatus: _exitStatus];
}

- (id <Archive>)openArchiveWithIRI: (OFIRI *)IRI
			      type: (OFString *)type
			      mode: (char)mode
			  encoding: (OFStringEncoding)encoding
{
	/* To make clang-analyzer happy about assigning nil to path later. */
	OFString *modeString, *fileModeString;
	OFStream *file = nil;
	id <Archive> archive = nil;

	switch (mode) {
	case 'a':
		modeString = @"a";
		fileModeString = @"r+";
		break;
	case 'c':
		modeString = @"w";
		fileModeString = @"w+";
		break;
	case 'l':
	case 'p':
	case 'x':
		modeString = fileModeString = @"r";
		break;
	default:
		@throw [OFInvalidArgumentException exception];
	}

	if (IRI == nil) {
		switch (mode) {
		case 'a':
		case 'c':
			file = OFStdOut;
			break;
		case 'l':
		case 'p':
		case 'x':
			file = OFStdIn;
			break;
		default:
			@throw [OFInvalidArgumentException exception];
		}
	} else {
		@try {
			file = [OFIRIHandler openItemAtIRI: IRI
						      mode: fileModeString];
		} @catch (OFOpenItemFailedException *e) {
			[OFStdErr writeString: @"\r"];
			[OFStdErr writeLine: OF_LOCALIZED(
			    @"failed_to_open_file",
			    @"Failed to open file %[file]: %[error]",
			    @"file", e.IRI.string,
			    @"error", OFStrError(e.errNo))];
			[OFApplication terminateWithStatus: 1];
		}
	}

	if (type == nil || [type isEqual: @"auto"]) {
		OFString *lowercasePath = IRI.path.lowercaseString;

		/* This one has to be first for obvious reasons */
		if ([lowercasePath hasSuffix: @".tar.gz"] ||
		    [lowercasePath hasSuffix: @".tgz"])
			type = @"tgz";
		else if ([lowercasePath hasSuffix: @".gz"])
			type = @"gz";
		else if ([lowercasePath hasSuffix: @".lha"] ||
		    [lowercasePath hasSuffix: @".lzh"] ||
		    [lowercasePath hasSuffix: @".lzs"] ||
		    [lowercasePath hasSuffix: @".pma"])
			type = @"lha";
		else if ([lowercasePath hasSuffix: @".tar"])
			type = @"tar";
		else if ([lowercasePath hasSuffix: @".zoo"])
			type = @"zoo";
		else
			type = @"zip";
	}

	@try {
		if ([type isEqual: @"gz"])
			archive = [GZIPArchive archiveWithIRI: IRI
						       stream: file
							 mode: modeString
						     encoding: encoding];
		else if ([type isEqual: @"lha"])
			 archive = [LHAArchive archiveWithIRI: IRI
						       stream: file
							 mode: modeString
						      encoding: encoding];
		else if ([type isEqual: @"tar"])
			archive = [TarArchive archiveWithIRI: IRI
						      stream: file
							mode: modeString
						    encoding: encoding];
		else if ([type isEqual: @"tgz"]) {
			OFStream *GZIPStream = [OFGZIPStream
			    streamWithStream: file
					mode: modeString];
			archive = [TarArchive archiveWithIRI: IRI
						      stream: GZIPStream
							mode: modeString
						    encoding: encoding];
		} else if ([type isEqual: @"zip"])
			archive = [ZIPArchive archiveWithIRI: IRI
						      stream: file
							mode: modeString
						    encoding: encoding];
		else if ([type isEqual: @"zoo"])
			archive = [ZooArchive archiveWithIRI: IRI
						      stream: file
							mode: modeString
						    encoding: encoding];
		else {
			[OFStdErr writeLine: OF_LOCALIZED(
			    @"unknown_archive_type",
			    @"Unknown archive type: %[type]",
			    @"type", type)];
			goto error;
		}
	} @catch (OFNotImplementedException *e) {
		if ((mode == 'a' || mode == 'c') && sel_isEqual(e.selector,
		    @selector(initWithStream:mode:))) {
			writingNotSupported(type);
			goto error;
		}

		@throw e;
	} @catch (OFReadFailedException *e) {
		[OFStdErr writeLine: OF_LOCALIZED(@"failed_to_read_file",
		    @"Failed to read file %[file]: %[error]",
		    @"file", IRI.string,
		    @"error", OFStrError(e.errNo))];
		goto error;
	} @catch (OFSeekFailedException *e) {
		[OFStdErr writeLine: OF_LOCALIZED(@"failed_to_seek_in_file",
		    @"Failed to seek in file %[file]: %[error]",
		    @"file", IRI.string,
		    @"error", OFStrError(e.errNo))];
		goto error;
	} @catch (OFInvalidFormatException *e) {
		[OFStdErr writeLine: OF_LOCALIZED(
		    @"file_is_not_a_valid_archive",
		    @"File %[file] is not a valid archive!",
		    @"file", IRI.string)];
		goto error;
	}

	if ((mode == 'a' || mode == 'c') && ![archive respondsToSelector:
	    @selector(addFiles:archiveComment:)]) {
		writingNotSupported(type);
		goto error;
	}

	return archive;

error:
	if (mode == 'c' && IRI != nil)
		[[OFFileManager defaultManager] removeItemAtIRI: IRI];

	[OFApplication terminateWithStatus: 1];
	abort();
}

- (bool)shouldExtractFile: (OFString *)fileName
	      outFileName: (OFString *)outFileName
{
	OFString *line;

	if (_overwrite == 1 ||
	    ![[OFFileManager defaultManager] fileExistsAtPath: outFileName])
		return true;

	if (_overwrite == -1) {
		if (_outputLevel >= 0) {
			[OFStdErr writeString: @" "];
			[OFStdErr writeLine:
			    OF_LOCALIZED(@"file_skipped", @"skipped")];
		}
		return false;
	}

	do {
		[OFStdErr writeString: @"\r"];
		[OFStdErr writeString: OF_LOCALIZED(@"ask_overwrite",
		    @"Overwrite %[file]? [ynAN?]",
		    @"file", fileName)];
		[OFStdErr writeString: @" "];

		line = [OFStdIn readLine];

		if ([line isEqual: @"?"])
			[OFStdErr writeLine: OF_LOCALIZED(
			    @"ask_overwrite_help",
			    @" y: yes\n"
			    @" n: no\n"
			    @" A: always\n"
			    @" N: never")];
	} while (![line isEqual: @"y"] && ![line isEqual: @"n"] &&
	    ![line isEqual: @"N"] && ![line isEqual: @"A"]);

	if ([line isEqual: @"A"])
		_overwrite = 1;
	else if ([line isEqual: @"N"])
		_overwrite = -1;

	if ([line isEqual: @"n"] || [line isEqual: @"N"]) {
		if (_outputLevel >= 0)
			[OFStdErr writeLine: OF_LOCALIZED(@"skipping_file",
			    @"Skipping %[file]...",
			    @"file", fileName)];

		return false;
	}

	if (_outputLevel >= 0)
		[OFStdErr writeString: OF_LOCALIZED(@"extracting_file",
		    @"Extracting %[file]...",
		    @"file", fileName)];

	return true;
}

- (ssize_t)copyBlockFromStream: (OFStream *)input
		      toStream: (OFStream *)output
		      fileName: (OFString *)fileName
{
	char buffer[bufferSize];
	size_t length;

	@try {
		length = [input readIntoBuffer: buffer length: bufferSize];
	} @catch (OFReadFailedException *e) {
		[OFStdErr writeString: @"\r"];
		[OFStdErr writeLine: OF_LOCALIZED(@"failed_to_read_file",
		    @"Failed to read file %[file]: %[error]",
		    @"file", fileName,
		    @"error", OFStrError(e.errNo))];
		return -1;
	}

	@try {
		[output writeBuffer: buffer length: length];
	} @catch (OFWriteFailedException *e) {
		[OFStdErr writeString: @"\r"];
		[OFStdErr writeLine: OF_LOCALIZED(@"failed_to_write_file",
		    @"Failed to write file %[file]: %[error]",
		    @"file", fileName,
		    @"error", OFStrError(e.errNo))];
		return -1;
	}

	return length;
}

- (OFString *)safeLocalPathForPath: (OFString *)path
{
	void *pool = objc_autoreleasePoolPush();

	path = path.stringByStandardizingPath;

#if defined(OF_WINDOWS) || defined(OF_MSDOS)
	if ([path containsString: @":"] || [path hasPrefix: @"\\"]) {
#elif defined(OF_AMIGAOS)
	if ([path containsString: @":"] || [path hasPrefix: @"/"]) {
#else
	if ([path hasPrefix: @"/"]) {
#endif
		objc_autoreleasePoolPop(pool);
		return nil;
	}

	if (path.length == 0) {
		objc_autoreleasePoolPop(pool);
		return nil;
	}

	/*
	 * After -[stringByStandardizingPath], everything representing parent
	 * directory should be at the beginning, so in theory checking the
	 * first component should be enough. But it does not hurt being
	 * paranoid and checking all components, just in case.
	 */
	for (OFString *component in path.pathComponents) {
#ifdef OF_AMIGAOS
		if (component.length == 0 || [component isEqual: @"/"]) {
#else
		if (component.length == 0 || [component isEqual: @".."]) {
#endif
			objc_autoreleasePoolPop(pool);
			return nil;
		}
	}

	objc_retain(path);

	objc_autoreleasePoolPop(pool);

	return objc_autoreleaseReturnValue(path);
}

- (void)quarantineFile: (OFString *)path
{
#ifdef OF_MACOS
	if (_quarantine != nil)
		[[OFFileManager defaultManager]
		    setExtendedAttributeData: _quarantine
				     forName: @"com.apple.quarantine"
				ofItemAtPath: path];
#endif
}

- (void)checkForCancellation
{
#ifdef OF_AMIGAOS
	/*
	 * Perform a single iteration of the run loop to see if we received
	 * Ctrl-C.
	 */
	[[OFRunLoop mainRunLoop] runMode: OFDefaultRunLoopMode
			      beforeDate: [OFDate distantPast]];
#endif
}

#ifdef OF_AMIGAOS
- (void)handleBreakCtrlC: (ULONG)signal
{
	raise(SIGINT);
}
#endif
@end