dracut.sh: reduce code
[dracut.git] / skipcpio / skipcpio.c
blob30699816d5c5da312aa77271c68071b79130341e
1 /* dracut-install.c -- install files and executables
3 Copyright (C) 2012 Harald Hoyer
4 Copyright (C) 2012 Red Hat, Inc. All rights reserved.
6 This program is free software: you can redistribute it and/or modify
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with this program; If not, see <http://www.gnu.org/licenses/>.
20 #define PROGRAM_VERSION_STRING "1"
22 #ifndef _GNU_SOURCE
23 #define _GNU_SOURCE
24 #endif
26 #include <stdbool.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <unistd.h>
30 #include <string.h>
32 #define CPIO_END "TRAILER!!!"
33 #define CPIO_ENDLEN (sizeof(CPIO_END)-1)
35 static char buf[CPIO_ENDLEN * 2 + 1];
37 int main(int argc, char **argv)
39 FILE *f;
40 size_t s;
42 if (argc != 2) {
43 fprintf(stderr, "Usage: %s <file>\n", argv[0]);
44 exit(1);
47 f = fopen(argv[1], "r");
49 if (f == NULL) {
50 fprintf(stderr, "Cannot open file '%s'\n", argv[1]);
51 exit(1);
54 s = fread(buf, 6, 1, f);
55 if (s <= 0) {
56 fprintf(stderr, "Read error from file '%s'\n", argv[1]);
57 fclose(f);
58 exit(1);
60 fseek(f, 0, SEEK_SET);
62 /* check, if this is a cpio archive */
63 if (buf[0] == '0' && buf[1] == '7' && buf[2] == '0' && buf[3] == '7' && buf[4] == '0' && buf[5] == '1') {
64 long pos = 0;
66 /* Search for CPIO_END */
67 do {
68 char *h;
69 fseek(f, pos, SEEK_SET);
70 buf[sizeof(buf) - 1] = 0;
71 s = fread(buf, CPIO_ENDLEN, 2, f);
72 if (s <= 0)
73 break;
75 h = strstr(buf, CPIO_END);
76 if (h) {
77 pos = (h - buf) + pos + CPIO_ENDLEN;
78 fseek(f, pos, SEEK_SET);
79 break;
81 pos += CPIO_ENDLEN;
82 } while (!feof(f));
84 if (feof(f)) {
85 /* CPIO_END not found, just cat the whole file */
86 fseek(f, 0, SEEK_SET);
87 } else {
88 /* skip zeros */
89 while (!feof(f)) {
90 size_t i;
92 buf[sizeof(buf) - 1] = 0;
93 s = fread(buf, 1, sizeof(buf) - 1, f);
94 if (s <= 0)
95 break;
97 for (i = 0; (i < s) && (buf[i] == 0); i++) ;
99 if (buf[i] != 0) {
100 pos += i;
101 fseek(f, pos, SEEK_SET);
102 break;
105 pos += s;
109 /* cat out the rest */
110 while (!feof(f)) {
111 s = fread(buf, 1, sizeof(buf), f);
112 if (s <= 0)
113 break;
115 s = fwrite(buf, 1, s, stdout);
116 if (s <= 0)
117 break;
119 fclose(f);
121 return EXIT_SUCCESS;