source: rtems/cpukit/libmisc/untar/untar.c @ 1a8fe67a

5
Last change on this file since 1a8fe67a was 1a8fe67a, checked in by Alexander Krutwig <alexander.krutwig@…>, on 07/13/16 at 07:22:35

Add Untar_FromChunk_Print() + Test

  • Property mode set to 100644
File size: 16.2 KB
Line 
1/**
2 * @file
3
4 * @brief Untar an Image
5 * @ingroup libmisc_untar_img Untar Image
6
7 * FIXME:
8 *   1. Symbolic links are not created.
9 *   2. Untar_FromMemory uses FILE *fp.
10 *   3. How to determine end of archive?
11
12 */
13
14/*
15 *  Written by: Jake Janovetz <janovetz@tempest.ece.uiuc.edu>
16 *
17 *  Copyright 2016 Chris Johns <chrisj@rtems.org>
18 *
19 *  The license and distribution terms for this file may be
20 *  found in the file LICENSE in this distribution or at
21 *  http://www.rtems.org/license/LICENSE.
22 */
23
24#ifdef HAVE_CONFIG_H
25#include "config.h"
26#endif
27
28#include <stdbool.h>
29#include <sys/param.h>
30#include <stdio.h>
31#include <string.h>
32#include <stdlib.h>
33#include <unistd.h>
34#include <errno.h>
35#include <sys/stat.h>
36#include <fcntl.h>
37#include <rtems/untar.h>
38#include <rtems/bspIo.h>
39
40/*
41 * TAR file format:
42
43 *   Offset   Length   Contents
44 *     0    100 bytes  File name ('\0' terminated, 99 maxmum length)
45 *   100      8 bytes  File mode (in octal ascii)
46 *   108      8 bytes  User ID (in octal ascii)
47 *   116      8 bytes  Group ID (in octal ascii)
48 *   124     12 bytes  File size (s) (in octal ascii)
49 *   136     12 bytes  Modify time (in octal ascii)
50 *   148      8 bytes  Header checksum (in octal ascii)
51 *   156      1 bytes  Link flag
52 *   157    100 bytes  Linkname ('\0' terminated, 99 maxmum length)
53 *   257      8 bytes  Magic PAX ("ustar\0" + 2 bytes padding)
54 *   257      8 bytes  Magic GNU tar ("ustar  \0")
55 *   265     32 bytes  User name ('\0' terminated, 31 maxmum length)
56 *   297     32 bytes  Group name ('\0' terminated, 31 maxmum length)
57 *   329      8 bytes  Major device ID (in octal ascii)
58 *   337      8 bytes  Minor device ID (in octal ascii)
59 *   345    155 bytes  Prefix
60 *   512   (s+p)bytes  File contents (s+p) := (((s) + 511) & ~511),
61 *                     round up to 512 bytes
62 *
63 *   Checksum:
64 *   int i, sum;
65 *   char* header = tar_header_pointer;
66 *   sum = 0;
67 *   for(i = 0; i < 512; i++)
68 *       sum += 0xFF & header[i];
69 */
70
71#define MAX_NAME_FIELD_SIZE      99
72
73/*
74 * This converts octal ASCII number representations into an
75 * unsigned long.  Only support 32-bit numbers for now.
76 *
77 * warning: this code is referenced in the IMFS.
78 */
79unsigned long
80_rtems_octal2ulong(
81  const char *octascii,
82  size_t len
83)
84{
85  size_t        i;
86  unsigned long num;
87
88  num = 0;
89  for (i=0; i < len; i++) {
90    if ((octascii[i] < '0') || (octascii[i] > '9')) {
91      continue;
92    }
93    num  = num * 8 + ((unsigned long)(octascii[i] - '0'));
94  }
95  return(num);
96}
97
98/*
99 * Common error message formatter.
100 */
101static void
102Print_Error(const rtems_printer *printer, const char* message, const char* path)
103{
104  rtems_printf(printer, "untar: %s: %s: (%d) %s\n",
105               message, path, errno, strerror(errno));
106}
107
108/*
109 * Get the type of node on in the file system if present.
110 */
111static int
112Stat_Node(const char* path)
113{
114  struct stat sb;
115  if (stat(path, &sb) < 0)
116    return -1;
117  if (S_ISDIR(sb.st_mode))
118    return DIRTYPE;
119  return REGTYPE;
120}
121
122/*
123 * Make the directory path for a file if it does not exist.
124 */
125static int
126Make_Path(const rtems_printer *printer, const char* filename, bool end_is_dir)
127{
128  char* copy = strdup(filename);
129  char* path = copy;
130
131  /*
132   * Skip leading path separators.
133   */
134  while (*path == '/')
135    ++path;
136
137  /*
138   * Any path left?
139   */
140  if (*path != '\0') {
141    bool  path_end = false;
142    char* end = path;
143    int   r;
144
145    /*
146     * Split the path into directory components. Check the node and if a file
147     * and not the end of the path remove it and create a directory. If a
148     * directory and not the end of the path decend into the directory.
149     */
150    while (!path_end) {
151      while (*end != '\0' && *end != '/')
152        ++end;
153
154      /*
155       * Are we at the end of the path?
156       */
157      if (*end == '\0')
158        path_end = true;
159
160      /*
161       * Split the path.
162       */
163      *end = '\0';
164
165      /*
166       * Get the node's status, exists, error, directory or regular? Regular
167       * means not a directory.
168       */
169      r = Stat_Node(path);
170
171      /*
172       * If there are errors other than not existing we are finished.
173       */
174      if (r < 0 && errno != ENOENT) {
175        Print_Error(printer, "stat", path);
176        return -1;
177      }
178
179      /*
180       * If a file remove and create a directory if not the end.
181       */
182      if (r == REGTYPE) {
183        r = unlink(path);
184        if (r < 0) {
185          Print_Error(printer, "unlink", path);
186          free(copy);
187          return -1;
188        }
189        if (!path_end) {
190          r = mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO);
191          if (r < 0) {
192            Print_Error(printer, "mkdir", path);
193            free(copy);
194            return -1;
195          }
196        }
197      }
198      else if (r < 0) {
199        /*
200         * Node does not exist which means the rest of the path will not exist.
201         */
202        while (!path_end) {
203          r = mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO);
204          if (r < 0) {
205            Print_Error(printer, "mkdir", path);
206            free(copy);
207            return -1;
208          }
209          if (!path_end) {
210            *end = '/';
211            ++end;
212          }
213          while (*end != '\0' && *end != '/')
214            ++end;
215          if (*end == '\0')
216            path_end = true;
217        }
218      }
219      else if (path_end && r == DIRTYPE && !end_is_dir) {
220        /*
221         * We only handle a directory if at the end of the path and the end is
222         * a file. If we cannot remove the directory because it is not empty we
223         * raise an error. Otherwise this is a directory and we do nothing
224         * which lets us decend into it.
225         */
226        r = rmdir(path);
227        if (r < 0) {
228          Print_Error(printer, "rmdir", path);
229          free(copy);
230          return -1;
231        }
232      }
233
234      /*
235       * If not the end of the path put back the directory separator.
236       */
237      if (!path_end) {
238        *end = '/';
239        ++end;
240      }
241    }
242  }
243
244  free(copy);
245
246  return 0;
247}
248
249static int
250Untar_ProcessHeader(
251  const char          *bufr,
252  char                *fname,
253  unsigned long       *file_size,
254  unsigned long       *nblocks,
255  unsigned char       *linkflag,
256  const rtems_printer *printer
257)
258{
259  char           linkname[100];
260  int            sum;
261  int            hdr_chksum;
262  int            retval = UNTAR_SUCCESSFUL;
263
264  fname[0] = '\0';
265  *file_size = 0;
266  *nblocks = 0;
267  *linkflag = -1;
268
269  if (strncmp(&bufr[257], "ustar", 5)) {
270    return UNTAR_SUCCESSFUL;
271  }
272
273  /*
274   * Compute the TAR checksum and check with the value in the archive.  The
275   * checksum is computed over the entire header, but the checksum field is
276   * substituted with blanks.
277   */
278  hdr_chksum = _rtems_octal2ulong(&bufr[148], 8);
279  sum        = _rtems_tar_header_checksum(bufr);
280
281  if (sum != hdr_chksum) {
282    rtems_printf(printer, "untar: file header checksum error\n");
283    return UNTAR_INVALID_CHECKSUM;
284  }
285
286  strncpy(fname, bufr, MAX_NAME_FIELD_SIZE);
287  fname[MAX_NAME_FIELD_SIZE] = '\0';
288
289  *linkflag   = bufr[156];
290  *file_size = _rtems_octal2ulong(&bufr[124], 12);
291
292  /*
293   * We've decoded the header, now figure out what it contains and do something
294   * with it.
295   */
296  if (*linkflag == SYMTYPE) {
297    strncpy(linkname, &bufr[157], MAX_NAME_FIELD_SIZE);
298    linkname[MAX_NAME_FIELD_SIZE] = '\0';
299    rtems_printf(printer, "untar: symlink: %s -> %s\n", linkname, fname);
300    symlink(linkname, fname);
301  } else if (*linkflag == REGTYPE) {
302    rtems_printf(printer, "untar: file: %s (%i)\n", fname, (int) *file_size);
303    *nblocks = (((*file_size) + 511) & ~511) / 512;
304    if (Make_Path(printer, fname, false) < 0) {
305      retval  = UNTAR_FAIL;
306    }
307  } else if (*linkflag == DIRTYPE) {
308    int r;
309    rtems_printf(printer, "untar: dir: %s\n", fname);
310    if (Make_Path(printer, fname, true) < 0) {
311      retval  = UNTAR_FAIL;
312    }
313    r = mkdir(fname, S_IRWXU | S_IRWXG | S_IRWXO);
314    if (r < 0) {
315      if (errno == EEXIST) {
316        struct stat stat_buf;
317        if (stat(fname, &stat_buf) == 0) {
318          if (!S_ISDIR(stat_buf.st_mode)) {
319            r = unlink(fname);
320            if (r == 0) {
321              r = mkdir(fname, S_IRWXU | S_IRWXG | S_IRWXO);
322            }
323          }
324        }
325      }
326      if (r < 0) {
327        Print_Error(printer, "mkdir", fname);
328        retval = UNTAR_FAIL;
329      }
330    }
331  }
332
333  return retval;
334}
335
336/*
337 * Function: Untar_FromMemory
338 *
339 * Description:
340 *
341 *    This is a simple subroutine used to rip links, directories, and
342 *    files out of a block of memory.
343 *
344 *
345 * Inputs:
346 *
347 *    void *  tar_buf    - Pointer to TAR buffer.
348 *    size_t  size       - Length of TAR buffer.
349 *
350 *
351 * Output:
352 *
353 *    int - UNTAR_SUCCESSFUL (0)    on successful completion.
354 *          UNTAR_INVALID_CHECKSUM  for an invalid header checksum.
355 *          UNTAR_INVALID_HEADER    for an invalid header.
356 *
357 */
358int
359Untar_FromMemory_Print(
360  void                *tar_buf,
361  size_t               size,
362  const rtems_printer *printer
363)
364{
365  FILE           *fp;
366  const char     *tar_ptr = (const char *)tar_buf;
367  const char     *bufr;
368  char           fname[100];
369  int            retval = UNTAR_SUCCESSFUL;
370  unsigned long  ptr;
371  unsigned long  nblocks;
372  unsigned long  file_size;
373  unsigned char  linkflag;
374
375  rtems_printf(printer, "untar: memory at %p (%zu)\n", tar_buf, size);
376
377  ptr = 0;
378  while (true) {
379    if (ptr + 512 > size) {
380      retval = UNTAR_SUCCESSFUL;
381      break;
382    }
383
384    /* Read the header */
385    bufr = &tar_ptr[ptr];
386    ptr += 512;
387
388    retval = Untar_ProcessHeader(bufr, fname, &file_size, &nblocks, &linkflag, printer);
389
390    if (retval != UNTAR_SUCCESSFUL)
391      break;
392
393    if (linkflag == REGTYPE) {
394      if ((fp = fopen(fname, "w")) == NULL) {
395        Print_Error(printer, "open", fname);
396        ptr += 512 * nblocks;
397      } else {
398        unsigned long sizeToGo = file_size;
399        size_t        len;
400        size_t        i;
401        size_t        n;
402
403        /*
404         * Read out the data.  There are nblocks of data where nblocks is the
405         * file_size rounded to the nearest 512-byte boundary.
406         */
407        for (i = 0; i < nblocks; i++) {
408          len = ((sizeToGo < 512L) ? (sizeToGo) : (512L));
409          n = fwrite(&tar_ptr[ptr], 1, len, fp);
410          if (n != len) {
411            Print_Error(printer, "write", fname);
412            retval  = UNTAR_FAIL;
413            break;
414          }
415          ptr += 512;
416          sizeToGo -= n;
417        }
418        fclose(fp);
419      }
420
421    }
422  }
423
424  return retval;
425}
426
427/*
428 * Function: Untar_FromMemory
429 *
430 * Description:
431 *
432 *    This is a simple subroutine used to rip links, directories, and
433 *    files out of a block of memory.
434 *
435 *
436 * Inputs:
437 *
438 *    void *  tar_buf    - Pointer to TAR buffer.
439 *    size_t  size       - Length of TAR buffer.
440 *
441 *
442 * Output:
443 *
444 *    int - UNTAR_SUCCESSFUL (0)    on successful completion.
445 *          UNTAR_INVALID_CHECKSUM  for an invalid header checksum.
446 *          UNTAR_INVALID_HEADER    for an invalid header.
447 *
448 */
449int
450Untar_FromMemory(
451  void   *tar_buf,
452  size_t  size
453)
454{
455  return Untar_FromMemory_Print(tar_buf, size, false);
456}
457
458/*
459 * Function: Untar_FromFile
460 *
461 * Description:
462 *
463 *    This is a simple subroutine used to rip links, directories, and
464 *    files out of a TAR file.
465 *
466 * Inputs:
467 *
468 *    const char *tar_name   - TAR filename.
469 *
470 * Output:
471 *
472 *    int - UNTAR_SUCCESSFUL (0)    on successful completion.
473 *          UNTAR_INVALID_CHECKSUM  for an invalid header checksum.
474 *          UNTAR_INVALID_HEADER    for an invalid header.
475 */
476int
477Untar_FromFile_Print(
478  const char          *tar_name,
479  const rtems_printer *printer
480)
481{
482  int            fd;
483  char           *bufr;
484  ssize_t        n;
485  char           fname[100];
486  int            retval;
487  unsigned long  i;
488  unsigned long  nblocks;
489  unsigned long  file_size;
490  unsigned char  linkflag;
491
492  retval = UNTAR_SUCCESSFUL;
493
494  if ((fd = open(tar_name, O_RDONLY)) < 0) {
495    return UNTAR_FAIL;
496  }
497
498  bufr = (char *)malloc(512);
499  if (bufr == NULL) {
500    close(fd);
501    return(UNTAR_FAIL);
502  }
503
504  while (1) {
505    /* Read the header */
506    /* If the header read fails, we just consider it the end of the tarfile. */
507    if ((n = read(fd, bufr, 512)) != 512) {
508      break;
509    }
510
511    retval = Untar_ProcessHeader(bufr, fname, &file_size, &nblocks, &linkflag, printer);
512
513    if (retval != UNTAR_SUCCESSFUL)
514      break;
515
516    if (linkflag == REGTYPE) {
517      int out_fd;
518
519      /*
520       * Read out the data.  There are nblocks of data where nblocks
521       * is the size rounded to the nearest 512-byte boundary.
522       */
523
524      if ((out_fd = creat(fname, 0644)) == -1) {
525        (void) lseek(fd, SEEK_CUR, 512UL * nblocks);
526      } else {
527        for (i = 0; i < nblocks; i++) {
528          n = read(fd, bufr, 512);
529          n = MIN(n, file_size - (i * 512UL));
530          (void) write(out_fd, bufr, n);
531        }
532        close(out_fd);
533      }
534    }
535  }
536
537  free(bufr);
538  close(fd);
539
540  return retval;
541}
542
543
544void Untar_ChunkContext_Init(Untar_ChunkContext *context)
545{
546  context->state = UNTAR_CHUNK_HEADER;
547  context->done_bytes = 0;
548  context->out_fd = -1;
549}
550
551int Untar_FromChunk_Print(
552  Untar_ChunkContext *context,
553  void *chunk,
554  size_t chunk_size,
555  const rtems_printer* printer
556)
557{
558  char *buf;
559  size_t done;
560  size_t todo;
561  size_t remaining;
562  size_t consume;
563  int retval;
564  unsigned char linkflag;
565
566  buf = chunk;
567  done = 0;
568  todo = chunk_size;
569
570  while (todo > 0) {
571    switch (context->state) {
572      case UNTAR_CHUNK_HEADER:
573        remaining = 512 - context->done_bytes;
574        consume = MIN(remaining, todo);
575        memcpy(&context->header[context->done_bytes], &buf[done], consume);
576        context->done_bytes += consume;
577
578        if (context->done_bytes == 512) {
579          retval = Untar_ProcessHeader(
580            &context->header[0],
581            &context->fname[0],
582            &context->todo_bytes,
583            &context->todo_blocks,
584            &linkflag,
585            printer
586          );
587
588          if (retval != UNTAR_SUCCESSFUL) {
589            context->state = UNTAR_CHUNK_ERROR;
590            return retval;
591          }
592
593          if (linkflag == REGTYPE) {
594            context->out_fd = creat(&context->fname[0], 0644);
595
596            if (context->out_fd >= 0) {
597              context->state = UNTAR_CHUNK_WRITE;
598              context->done_bytes = 0;
599            } else {
600              context->state = UNTAR_CHUNK_SKIP;
601              context->todo_bytes = 512 * context->todo_blocks;
602              context->done_bytes = 0;
603            }
604          } else {
605              context->done_bytes = 0;
606          }
607        }
608
609        break;
610      case UNTAR_CHUNK_SKIP:
611        remaining = context->todo_bytes - context->done_bytes;
612        consume = MIN(remaining, todo);
613        context->done_bytes += consume;
614
615        if (context->done_bytes == context->todo_bytes) {
616          context->state = UNTAR_CHUNK_HEADER;
617          context->done_bytes = 0;
618        }
619
620        break;
621      case UNTAR_CHUNK_WRITE:
622        remaining = context->todo_bytes - context->done_bytes;
623        consume = MIN(remaining, todo);
624        write(context->out_fd, &buf[done], consume);
625        context->done_bytes += consume;
626
627        if (context->done_bytes == context->todo_bytes) {
628          close(context->out_fd);
629          context->out_fd = -1;
630          context->state = UNTAR_CHUNK_SKIP;
631          context->todo_bytes = 512 * context->todo_blocks - context->todo_bytes;
632          context->done_bytes = 0;
633        }
634
635        break;
636      default:
637        return UNTAR_FAIL;
638    }
639
640    done += consume;
641    todo -= consume;
642  }
643
644  return UNTAR_SUCCESSFUL;
645}
646
647/*
648 * Function: Untar_FromFile
649 *
650 * Description:
651 *
652 *    This is a simple subroutine used to rip links, directories, and
653 *    files out of a TAR file.
654 *
655 * Inputs:
656 *
657 *    const char *tar_name   - TAR filename.
658 *
659 * Output:
660 *
661 *    int - UNTAR_SUCCESSFUL (0)    on successful completion.
662 *          UNTAR_INVALID_CHECKSUM  for an invalid header checksum.
663 *          UNTAR_INVALID_HEADER    for an invalid header.
664 */
665int
666Untar_FromFile(
667  const char *tar_name
668)
669{
670  return Untar_FromFile_Print(tar_name, NULL);
671}
672
673/*
674 * Compute the TAR checksum and check with the value in
675 * the archive.  The checksum is computed over the entire
676 * header, but the checksum field is substituted with blanks.
677 */
678int
679_rtems_tar_header_checksum(
680  const char *bufr
681)
682{
683  int  i, sum;
684
685  sum = 0;
686  for (i=0; i<512; i++) {
687    if ((i >= 148) && (i < 156))
688      sum += 0xff & ' ';
689    else
690     sum += 0xff & bufr[i];
691  }
692  return(sum);
693}
Note: See TracBrowser for help on using the repository browser.