Fix CVE-2018-20482
[tar.git] / src / suffix.c
blobd787ea8fecc91e2979ef8acadff97bbc9010bb4d
1 /* This file is part of GNU tar.
2 Copyright 2007, 2009, 2013-2014, 2016-2017 Free Software Foundation,
3 Inc.
5 Written by Sergey Poznyakoff.
7 GNU tar is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 3, or (at your option) any later
10 version.
12 GNU tar is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
15 Public License for more details.
17 You should have received a copy of the GNU General Public License along
18 with GNU tar. If not, see <http://www.gnu.org/licenses/>. */
20 #include <system.h>
21 #include "common.h"
23 struct compression_suffix
25 const char *suffix;
26 size_t length;
27 const char *program;
30 static struct compression_suffix compression_suffixes[] = {
31 #define __CAT2__(a,b) a ## b
32 #define S(s,p) #s, sizeof (#s) - 1, __CAT2__(p,_PROGRAM)
33 { "tar", 3, NULL },
34 { S(gz, GZIP) },
35 { S(tgz, GZIP) },
36 { S(taz, GZIP) },
37 { S(Z, COMPRESS) },
38 { S(taZ, COMPRESS) },
39 { S(bz2, BZIP2) },
40 { S(tbz, BZIP2) },
41 { S(tbz2, BZIP2) },
42 { S(tz2, BZIP2) },
43 { S(lz, LZIP) },
44 { S(lzma, LZMA) },
45 { S(tlz, LZMA) },
46 { S(lzo, LZOP) },
47 { S(xz, XZ) },
48 { S(txz, XZ) }, /* Slackware */
49 { S(zst, ZSTD) },
50 { S(tzst, ZSTD) },
51 { NULL }
52 #undef S
53 #undef __CAT2__
56 static struct compression_suffix const *
57 find_compression_suffix (const char *name, size_t *ret_len)
59 char *suf = strrchr (name, '.');
61 if (suf)
63 size_t len;
64 struct compression_suffix *p;
66 suf++;
67 len = strlen (suf);
69 for (p = compression_suffixes; p->suffix; p++)
71 if (p->length == len && memcmp (p->suffix, suf, len) == 0)
73 if (ret_len)
74 *ret_len = strlen (name) - len - 1;
75 return p;
79 return NULL;
82 static const char *
83 find_compression_program (const char *name, const char *defprog)
85 struct compression_suffix const *p = find_compression_suffix (name, NULL);
86 if (p)
87 return p->program;
88 return defprog;
91 void
92 set_compression_program_by_suffix (const char *name, const char *defprog)
94 const char *program = find_compression_program (name, defprog);
95 if (program)
96 use_compress_program_option = program;
99 char *
100 strip_compression_suffix (const char *name)
102 char *s = NULL;
103 size_t len;
104 struct compression_suffix const *p = find_compression_suffix (name, &len);
106 if (p)
108 /* Strip an additional ".tar" suffix, but only if the just-stripped
109 "outer" suffix did not begin with "t". */
110 if (len > 4 && strncmp (name + len - 4, ".tar", 4) == 0
111 && p->suffix[0] != 't')
112 len -= 4;
113 if (len == 0)
114 return NULL;
115 s = xmalloc (len + 1);
116 memcpy (s, name, len);
117 s[len] = 0;
119 return s;