001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.commons.compress.archivers.dump;
020
021import java.util.Collections;
022import java.util.Date;
023import java.util.EnumSet;
024import java.util.HashSet;
025import java.util.Set;
026import org.apache.commons.compress.archivers.ArchiveEntry;
027
028/**
029 * This class represents an entry in a Dump archive. It consists
030 * of the entry's header, the entry's File and any extended attributes.
031 * <p>
032 * DumpEntries that are created from the header bytes read from
033 * an archive are instantiated with the DumpArchiveEntry( byte[] )
034 * constructor. These entries will be used when extracting from
035 * or listing the contents of an archive. These entries have their
036 * header filled in using the header bytes. They also set the File
037 * to null, since they reference an archive entry not a file.
038 * <p>
039 * DumpEntries can also be constructed from nothing but a name.
040 * This allows the programmer to construct the entry by hand, for
041 * instance when only an InputStream is available for writing to
042 * the archive, and the header information is constructed from
043 * other information. In this case the header fields are set to
044 * defaults and the File is set to null.
045 *
046 * <p>
047 * The C structure for a Dump Entry's header is:
048 * <pre>
049 * #define TP_BSIZE    1024          // size of each file block
050 * #define NTREC       10            // number of blocks to write at once
051 * #define HIGHDENSITYTREC 32        // number of blocks to write on high-density tapes
052 * #define TP_NINDIR   (TP_BSIZE/2)  // number if indirect inodes in record
053 * #define TP_NINOS    (TP_NINDIR / sizeof (int32_t))
054 * #define LBLSIZE     16
055 * #define NAMELEN     64
056 *
057 * #define OFS_MAGIC     (int)60011  // old format magic value
058 * #define NFS_MAGIC     (int)60012  // new format magic value
059 * #define FS_UFS2_MAGIC (int)0x19540119
060 * #define CHECKSUM      (int)84446  // constant used in checksum algorithm
061 *
062 * struct  s_spcl {
063 *   int32_t c_type;             // record type (see below)
064 *   int32_t <b>c_date</b>;             // date of this dump
065 *   int32_t <b>c_ddate</b>;            // date of previous dump
066 *   int32_t c_volume;           // dump volume number
067 *   u_int32_t c_tapea;          // logical block of this record
068 *   dump_ino_t c_ino;           // number of inode
069 *   int32_t <b>c_magic</b>;            // magic number (see above)
070 *   int32_t c_checksum;         // record checksum
071 * #ifdef  __linux__
072 *   struct  new_bsd_inode c_dinode;
073 * #else
074 * #ifdef sunos
075 *   struct  new_bsd_inode c_dinode;
076 * #else
077 *   struct  dinode  c_dinode;   // ownership and mode of inode
078 * #endif
079 * #endif
080 *   int32_t c_count;            // number of valid c_addr entries
081 *   union u_data c_data;        // see above
082 *   char    <b>c_label[LBLSIZE]</b>;   // dump label
083 *   int32_t <b>c_level</b>;            // level of this dump
084 *   char    <b>c_filesys[NAMELEN]</b>; // name of dumpped file system
085 *   char    <b>c_dev[NAMELEN]</b>;     // name of dumpped device
086 *   char    <b>c_host[NAMELEN]</b>;    // name of dumpped host
087 *   int32_t c_flags;            // additional information (see below)
088 *   int32_t c_firstrec;         // first record on volume
089 *   int32_t c_ntrec;            // blocksize on volume
090 *   int32_t c_extattributes;    // additional inode info (see below)
091 *   int32_t c_spare[30];        // reserved for future uses
092 * } s_spcl;
093 *
094 * //
095 * // flag values
096 * //
097 * #define DR_NEWHEADER     0x0001  // new format tape header
098 * #define DR_NEWINODEFMT   0x0002  // new format inodes on tape
099 * #define DR_COMPRESSED    0x0080  // dump tape is compressed
100 * #define DR_METAONLY      0x0100  // only the metadata of the inode has been dumped
101 * #define DR_INODEINFO     0x0002  // [SIC] TS_END header contains c_inos information
102 * #define DR_EXTATTRIBUTES 0x8000
103 *
104 * //
105 * // extattributes inode info
106 * //
107 * #define EXT_REGULAR         0
108 * #define EXT_MACOSFNDRINFO   1
109 * #define EXT_MACOSRESFORK    2
110 * #define EXT_XATTR           3
111 *
112 * // used for EA on tape
113 * #define EXT2_GOOD_OLD_INODE_SIZE    128
114 * #define EXT2_XATTR_MAGIC        0xEA020000  // block EA
115 * #define EXT2_XATTR_MAGIC2       0xEA020001  // in inode EA
116 * </pre>
117 * <p>
118 * The fields in <b>bold</b> are the same for all blocks. (This permitted
119 * multiple dumps to be written to a single tape.)
120 * </p>
121 *
122 * <p>
123 * The C structure for the inode (file) information is:
124 * <pre>
125 * struct bsdtimeval {           //  **** alpha-*-linux is deviant
126 *   __u32   tv_sec;
127 *   __u32   tv_usec;
128 * };
129 *
130 * #define NDADDR      12
131 * #define NIADDR       3
132 *
133 * //
134 * // This is the new (4.4) BSD inode structure
135 * // copied from the FreeBSD 2.0 &lt;ufs/ufs/dinode.h&gt; include file
136 * //
137 * struct new_bsd_inode {
138 *   __u16       di_mode;           // file type, standard Unix permissions
139 *   __s16       di_nlink;          // number of hard links to file.
140 *   union {
141 *      __u16       oldids[2];
142 *      __u32       inumber;
143 *   }           di_u;
144 *   u_quad_t    di_size;           // file size
145 *   struct bsdtimeval   di_atime;  // time file was last accessed
146 *   struct bsdtimeval   di_mtime;  // time file was last modified
147 *   struct bsdtimeval   di_ctime;  // time file was created
148 *   __u32       di_db[NDADDR];
149 *   __u32       di_ib[NIADDR];
150 *   __u32       di_flags;          //
151 *   __s32       di_blocks;         // number of disk blocks
152 *   __s32       di_gen;            // generation number
153 *   __u32       di_uid;            // user id (see /etc/passwd)
154 *   __u32       di_gid;            // group id (see /etc/group)
155 *   __s32       di_spare[2];       // unused
156 * };
157 * </pre>
158 * <p>
159 * It is important to note that the header DOES NOT have the name of the
160 * file. It can't since hard links mean that you may have multiple filenames
161 * for a single physical file. You must read the contents of the directory
162 * entries to learn the mapping(s) from filename to inode.
163 * </p>
164 *
165 * <p>
166 * The C structure that indicates if a specific block is a real block
167 * that contains data or is a sparse block that is not persisted to the
168 * disk is:</p>
169 * <pre>
170 * #define TP_BSIZE    1024
171 * #define TP_NINDIR   (TP_BSIZE/2)
172 *
173 * union u_data {
174 *   char    s_addrs[TP_NINDIR]; // 1 =&gt; data; 0 =&gt; hole in inode
175 *   int32_t s_inos[TP_NINOS];   // table of first inode on each volume
176 * } u_data;
177 * </pre>
178 *
179 * @NotThreadSafe
180 */
181public class DumpArchiveEntry implements ArchiveEntry {
182    private String name;
183    private TYPE type = TYPE.UNKNOWN;
184    private int mode;
185    private Set<PERMISSION> permissions = Collections.emptySet();
186    private long size;
187    private long atime;
188    private long mtime;
189    private int uid;
190    private int gid;
191
192    /**
193     * Currently unused
194     */
195    private final DumpArchiveSummary summary = null;
196
197    // this information is available from standard index.
198    private final TapeSegmentHeader header = new TapeSegmentHeader();
199    private String simpleName;
200    private String originalName;
201
202    // this information is available from QFA index
203    private int volume;
204    private long offset;
205    private int ino;
206    private int nlink;
207    private long ctime;
208    private int generation;
209    private boolean isDeleted;
210
211    /**
212     * Default constructor.
213     */
214    public DumpArchiveEntry() {
215    }
216
217    /**
218     * Constructor taking only filename.
219     * @param name pathname
220     * @param simpleName actual filename.
221     */
222    public DumpArchiveEntry(String name, String simpleName) {
223        setName(name);
224        this.simpleName = simpleName;
225    }
226
227    /**
228     * Constructor taking name, inode and type.
229     *
230     * @param name
231     * @param simpleName
232     * @param ino
233     * @param type
234     */
235    protected DumpArchiveEntry(String name, String simpleName, int ino,
236                               TYPE type) {
237        setType(type);
238        setName(name);
239        this.simpleName = simpleName;
240        this.ino = ino;
241        this.offset = 0;
242    }
243
244    /**
245     * Constructor taking tape buffer.
246     * @param buffer
247     * @param offset
248     */
249
250    /**
251     * Returns the path of the entry.
252     * @return the path of the entry.
253     */
254    public String getSimpleName() {
255        return simpleName;
256    }
257
258    /**
259     * Sets the path of the entry.
260     */
261    protected void setSimpleName(String simpleName) {
262        this.simpleName = simpleName;
263    }
264
265    /**
266     * Returns the ino of the entry.
267     */
268    public int getIno() {
269        return header.getIno();
270    }
271
272    /**
273     * Return the number of hard links to the entry.
274     */
275    public int getNlink() {
276        return nlink;
277    }
278
279    /**
280     * Set the number of hard links.
281     */
282    public void setNlink(int nlink) {
283        this.nlink = nlink;
284    }
285
286    /**
287     * Get file creation time.
288     */
289    public Date getCreationTime() {
290        return new Date(ctime);
291    }
292
293    /**
294     * Set the file creation time.
295     */
296    public void setCreationTime(Date ctime) {
297        this.ctime = ctime.getTime();
298    }
299
300    /**
301     * Return the generation of the file.
302     */
303    public int getGeneration() {
304        return generation;
305    }
306
307    /**
308     * Set the generation of the file.
309     */
310    public void setGeneration(int generation) {
311        this.generation = generation;
312    }
313
314    /**
315     * Has this file been deleted? (On valid on incremental dumps.)
316     */
317    public boolean isDeleted() {
318        return isDeleted;
319    }
320
321    /**
322     * Set whether this file has been deleted.
323     */
324    public void setDeleted(boolean isDeleted) {
325        this.isDeleted = isDeleted;
326    }
327
328    /**
329     * Return the offset within the archive
330     */
331    public long getOffset() {
332        return offset;
333    }
334
335    /**
336     * Set the offset within the archive.
337     */
338    public void setOffset(long offset) {
339        this.offset = offset;
340    }
341
342    /**
343     * Return the tape volume where this file is located.
344     */
345    public int getVolume() {
346        return volume;
347    }
348
349    /**
350     * Set the tape volume.
351     */
352    public void setVolume(int volume) {
353        this.volume = volume;
354    }
355
356    /**
357     * Return the type of the tape segment header.
358     */
359    public DumpArchiveConstants.SEGMENT_TYPE getHeaderType() {
360        return header.getType();
361    }
362
363    /**
364     * Return the number of records in this segment.
365     */
366    public int getHeaderCount() {
367        return header.getCount();
368    }
369
370    /**
371     * Return the number of sparse records in this segment.
372     */
373    public int getHeaderHoles() {
374        return header.getHoles();
375    }
376
377    /**
378     * Is this a sparse record?
379     */
380    public boolean isSparseRecord(int idx) {
381        return (header.getCdata(idx) & 0x01) == 0;
382    }
383
384    /**
385     * @see java.lang.Object#hashCode()
386     */
387    @Override
388    public int hashCode() {
389        return ino;
390    }
391
392    /**
393     * @see java.lang.Object#equals(Object o)
394     */
395    @Override
396    public boolean equals(Object o) {
397        if (o == this) {
398            return true;
399        } else if (o == null || !o.getClass().equals(getClass())) {
400            return false;
401        }
402
403        DumpArchiveEntry rhs = (DumpArchiveEntry) o;
404
405        if ((header == null) || (rhs.header == null)) {
406            return false;
407        }
408
409        if (ino != rhs.ino) {
410            return false;
411        }
412
413        if ((summary == null && rhs.summary != null)
414            || (summary != null && !summary.equals(rhs.summary))) {
415            return false;
416        }
417
418        return true;
419    }
420
421    /**
422     * @see java.lang.Object#toString()
423     */
424    @Override
425    public String toString() {
426        return getName();
427    }
428
429    /**
430     * Populate the dump archive entry and tape segment header with
431     * the contents of the buffer.
432     *
433     * @param buffer
434     * @throws Exception
435     */
436    static DumpArchiveEntry parse(byte[] buffer) {
437        DumpArchiveEntry entry = new DumpArchiveEntry();
438        TapeSegmentHeader header = entry.header;
439
440        header.type = DumpArchiveConstants.SEGMENT_TYPE.find(DumpArchiveUtil.convert32(
441                    buffer, 0));
442
443        //header.dumpDate = new Date(1000L * DumpArchiveUtil.convert32(buffer, 4));
444        //header.previousDumpDate = new Date(1000L * DumpArchiveUtil.convert32(
445        //            buffer, 8));
446        header.volume = DumpArchiveUtil.convert32(buffer, 12);
447        //header.tapea = DumpArchiveUtil.convert32(buffer, 16);
448        entry.ino = header.ino = DumpArchiveUtil.convert32(buffer, 20);
449
450        //header.magic = DumpArchiveUtil.convert32(buffer, 24);
451        //header.checksum = DumpArchiveUtil.convert32(buffer, 28);
452        int m = DumpArchiveUtil.convert16(buffer, 32);
453
454        // determine the type of the file.
455        entry.setType(TYPE.find((m >> 12) & 0x0F));
456
457        // determine the standard permissions
458        entry.setMode(m);
459
460        entry.nlink = DumpArchiveUtil.convert16(buffer, 34);
461        // inumber, oldids?
462        entry.setSize(DumpArchiveUtil.convert64(buffer, 40));
463
464        long t = (1000L * DumpArchiveUtil.convert32(buffer, 48)) +
465            (DumpArchiveUtil.convert32(buffer, 52) / 1000);
466        entry.setAccessTime(new Date(t));
467        t = (1000L * DumpArchiveUtil.convert32(buffer, 56)) +
468            (DumpArchiveUtil.convert32(buffer, 60) / 1000);
469        entry.setLastModifiedDate(new Date(t));
470        t = (1000L * DumpArchiveUtil.convert32(buffer, 64)) +
471            (DumpArchiveUtil.convert32(buffer, 68) / 1000);
472        entry.ctime = t;
473
474        // db: 72-119 - direct blocks
475        // id: 120-131 - indirect blocks
476        //entry.flags = DumpArchiveUtil.convert32(buffer, 132);
477        //entry.blocks = DumpArchiveUtil.convert32(buffer, 136);
478        entry.generation = DumpArchiveUtil.convert32(buffer, 140);
479        entry.setUserId(DumpArchiveUtil.convert32(buffer, 144));
480        entry.setGroupId(DumpArchiveUtil.convert32(buffer, 148));
481        // two 32-bit spare values.
482        header.count = DumpArchiveUtil.convert32(buffer, 160);
483
484        header.holes = 0;
485
486        for (int i = 0; (i < 512) && (i < header.count); i++) {
487            if (buffer[164 + i] == 0) {
488                header.holes++;
489            }
490        }
491
492        System.arraycopy(buffer, 164, header.cdata, 0, 512);
493
494        entry.volume = header.getVolume();
495
496        //entry.isSummaryOnly = false;
497        return entry;
498    }
499
500    /**
501     * Update entry with information from next tape segment header.
502     */
503    void update(byte[] buffer) {
504        header.volume = DumpArchiveUtil.convert32(buffer, 16);
505        header.count = DumpArchiveUtil.convert32(buffer, 160);
506
507        header.holes = 0;
508
509        for (int i = 0; (i < 512) && (i < header.count); i++) {
510            if (buffer[164 + i] == 0) {
511                header.holes++;
512            }
513        }
514
515        System.arraycopy(buffer, 164, header.cdata, 0, 512);
516    }
517
518    /**
519     * Archive entry as stored on tape. There is one TSH for (at most)
520     * every 512k in the file.
521     */
522    static class TapeSegmentHeader {
523        private DumpArchiveConstants.SEGMENT_TYPE type;
524        private int volume;
525        private int ino;
526        private int count;
527        private int holes;
528        private final byte[] cdata = new byte[512]; // map of any 'holes'
529
530        public DumpArchiveConstants.SEGMENT_TYPE getType() {
531            return type;
532        }
533
534        public int getVolume() {
535            return volume;
536        }
537
538        public int getIno() {
539            return ino;
540        }
541
542        void setIno(int ino) {
543            this.ino = ino;
544        }
545
546        public int getCount() {
547            return count;
548        }
549
550        public int getHoles() {
551            return holes;
552        }
553
554        public int getCdata(int idx) {
555            return cdata[idx];
556        }
557    }
558
559    /**
560     * Returns the name of the entry.
561     * @return the name of the entry.
562     */
563    public String getName() {
564        return name;
565    }
566
567    /**
568     * Returns the unmodified name of the entry.
569     * @return the name of the entry.
570     */
571    String getOriginalName() {
572        return originalName;
573    }
574
575    /**
576     * Sets the name of the entry.
577     */
578    public final void setName(String name) {
579        this.originalName = name;
580        if (name != null) {
581            if (isDirectory() && !name.endsWith("/")) {
582                name += "/";
583            }
584            if (name.startsWith("./")) {
585                name = name.substring(2);
586            }
587        }
588        this.name = name;
589    }
590
591    public Date getLastModifiedDate() {
592        return new Date(mtime);
593    }
594
595    /**
596     * Is this a directory?
597     */
598    public boolean isDirectory() {
599        return type == TYPE.DIRECTORY;
600    }
601
602    /**
603     * Is this a regular file?
604     */
605    public boolean isFile() {
606        return type == TYPE.FILE;
607    }
608
609    /**
610     * Is this a network device?
611     */
612    public boolean isSocket() {
613        return type == TYPE.SOCKET;
614    }
615
616    /**
617     * Is this a character device?
618     */
619    public boolean isChrDev() {
620        return type == TYPE.CHRDEV;
621    }
622
623    /**
624     * Is this a block device?
625     */
626    public boolean isBlkDev() {
627        return type == TYPE.BLKDEV;
628    }
629
630    /**
631     * Is this a fifo/pipe?
632     */
633    public boolean isFifo() {
634        return type == TYPE.FIFO;
635    }
636
637    /**
638     * Get the type of the entry.
639     */
640    public TYPE getType() {
641        return type;
642    }
643
644    /**
645     * Set the type of the entry.
646     */
647    public void setType(TYPE type) {
648        this.type = type;
649    }
650
651    /**
652     * Return the access permissions on the entry.
653     */
654    public int getMode() {
655        return mode;
656    }
657
658    /**
659     * Set the access permissions on the entry.
660     */
661    public void setMode(int mode) {
662        this.mode = mode & 07777;
663        this.permissions = PERMISSION.find(mode);
664    }
665
666    /**
667     * Returns the permissions on the entry.
668     */
669    public Set<PERMISSION> getPermissions() {
670        return permissions;
671    }
672
673    /**
674     * Returns the size of the entry.
675     */
676    public long getSize() {
677        return isDirectory() ? SIZE_UNKNOWN : size;
678    }
679
680    /**
681     * Returns the size of the entry as read from the archive.
682     */
683    long getEntrySize() {
684        return size;
685    }
686
687    /**
688     * Set the size of the entry.
689     */
690    public void setSize(long size) {
691        this.size = size;
692    }
693
694    /**
695     * Set the time the file was last modified.
696     */
697    public void setLastModifiedDate(Date mtime) {
698        this.mtime = mtime.getTime();
699    }
700
701    /**
702     * Returns the time the file was last accessed.
703     */
704    public Date getAccessTime() {
705        return new Date(atime);
706    }
707
708    /**
709     * Set the time the file was last accessed.
710     */
711    public void setAccessTime(Date atime) {
712        this.atime = atime.getTime();
713    }
714
715    /**
716     * Return the user id.
717     */
718    public int getUserId() {
719        return uid;
720    }
721
722    /**
723     * Set the user id.
724     */
725    public void setUserId(int uid) {
726        this.uid = uid;
727    }
728
729    /**
730     * Return the group id
731     */
732    public int getGroupId() {
733        return gid;
734    }
735
736    /**
737     * Set the group id.
738     */
739    public void setGroupId(int gid) {
740        this.gid = gid;
741    }
742
743    public enum TYPE {
744        WHITEOUT(14),
745        SOCKET(12),
746        LINK(10),
747        FILE(8),
748        BLKDEV(6),
749        DIRECTORY(4),
750        CHRDEV(2),
751        FIFO(1),
752        UNKNOWN(15);
753
754        private int code;
755
756        private TYPE(int code) {
757            this.code = code;
758        }
759
760        public static TYPE find(int code) {
761            TYPE type = UNKNOWN;
762
763            for (TYPE t : TYPE.values()) {
764                if (code == t.code) {
765                    type = t;
766                }
767            }
768
769            return type;
770        }
771    }
772
773    public enum PERMISSION {
774        SETUID(04000),
775        SETGUI(02000),
776        STICKY(01000),
777        USER_READ(00400),
778        USER_WRITE(00200),
779        USER_EXEC(00100),
780        GROUP_READ(00040),
781        GROUP_WRITE(00020),
782        GROUP_EXEC(00010),
783        WORLD_READ(00004),
784        WORLD_WRITE(00002),
785        WORLD_EXEC(00001);
786
787        private int code;
788
789        private PERMISSION(int code) {
790            this.code = code;
791        }
792
793        public static Set<PERMISSION> find(int code) {
794            Set<PERMISSION> set = new HashSet<PERMISSION>();
795
796            for (PERMISSION p : PERMISSION.values()) {
797                if ((code & p.code) == p.code) {
798                    set.add(p);
799                }
800            }
801
802            if (set.isEmpty()) {
803                return Collections.emptySet();
804            }
805
806            return EnumSet.copyOf(set);
807        }
808    }
809}