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
/* GATE PROJECT LICENSE:
+----------------------------------------------------------------------------+
| Copyright(c) 2018-2025, Stefan Meislinger <sm@opengate.at>                 |
| All rights reserved.                                                       |
|                                                                            |
| Redistribution and use in source and binary forms, with or without         |
| modification, are permitted provided that the following conditions are met:|
|                                                                            |
| 1. Redistributions of source code must retain the above copyright notice,  |
|    this list of conditions and the following disclaimer.                   |
| 2. Redistributions in binary form must reproduce the above copyright       |
|    notice, this list of conditions and the following disclaimer in the     |
|    documentation and/or other materials provided with the distribution.    |
|                                                                            |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"|
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE    |
| LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR        |
| CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF       |
| SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS   |
| INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN    |
| CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)    |
| ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF     |
| THE POSSIBILITY OF SUCH DAMAGE.                                            |
+----------------------------------------------------------------------------+
*/

#include "gate/encode/tarstreams.h"
#include "gate/results.h"
#include "gate/debugging.h"

/* TAR file format information taken from:
    https://en.wikipedia.org/wiki/Tar_(computing)
    https://www.gnu.org/software/tar/manual/html_node/Standard.html
*/

typedef struct gate_tarheader
{
    char	filename[100];
    char	filemode[8];
    char	owner[8];
    char	group[8];
    char	size[12];
    char	modify_time[12];
    char	checksum[8];
    char	typeflag;
    char	linkname[100];<--- struct member 'gate_tarheader::linkname' is never used.
    char	magic_id[6];
    char	tar_version[2];
    char	ownername[32];
    char	groupname[32];
    char	device_major[8];<--- struct member 'gate_tarheader::device_major' is never used.
    char	device_minor[8];<--- struct member 'gate_tarheader::device_minor' is never used.
    char	prefix[131];<--- struct member 'gate_tarheader::prefix' is never used.
    char	access_time[12];
    char	change_time[12];
} gate_tarheader_t;


#define GATE_TARHEADER_REGTYPE  '0'		/* regular file */
#define GATE_TARHEADER_AREGTYPE '\0'	/* regular file */
#define GATE_TARHEADER_LNKTYPE  '1'		/* link */
#define GATE_TARHEADER_SYMTYPE  '2'		/* reserved */
#define GATE_TARHEADER_CHRTYPE  '3'		/* character special */
#define GATE_TARHEADER_BLKTYPE  '4'		/* block special */
#define GATE_TARHEADER_DIRTYPE  '5'		/* directory */
#define GATE_TARHEADER_FIFOTYPE '6'		/* FIFO special */
#define GATE_TARHEADER_CONTTYPE '7'		/* reserved */
#define GATE_TARHEADER_XGLTYPE  'g'		/* Global extended header */
#define GATE_TARHEADER_XHDTYPE  'x'		/* Extended header referring to the next file in the archive */

#define GATE_TARHEADER_LONGLINK	'L'		/* Long-Link  */

/* Bits used in the mode field, values in octal.  */
#define GATE_TARHEADER_TSUID	04000	/* set UID on execution */
#define GATE_TARHEADER_TSGID	02000	/* set GID on execution */
#define GATE_TARHEADER_TSVTX	01000	/* reserved */
                                        /* file permissions */
#define GATE_TARHEADER_TUREAD	00400	/* read by owner */
#define GATE_TARHEADER_TUWRITE	00200	/* write by owner */
#define GATE_TARHEADER_TUEXEC	00100	/* execute/search by owner */
#define GATE_TARHEADER_TGREAD	00040	/* read by group */
#define GATE_TARHEADER_TGWRITE	00020	/* write by group */
#define GATE_TARHEADER_TGEXEC	00010	/* execute/search by group */
#define GATE_TARHEADER_TOREAD	00004	/* read by other */
#define GATE_TARHEADER_TOWRITE	00002	/* write by other */
#define GATE_TARHEADER_TOEXEC	00001	/* execute/search by other */


typedef union gate_tarblock
{
    char			 data[512];
    gate_tarheader_t header;
} gate_tarblock_t;

static gate_uint64_t read_octal(char const* buffer, gate_size_t len)
{
    gate_uint64_t ret = 0;
    gate_size_t ndx;
    gate_uint8_t digit;
    char chr;
    --len;

    for (ndx = 0; ndx != len; ++ndx)
    {
        chr = buffer[ndx];
        if ((chr >= '0') && (chr <= '9'))
        {
            digit = (gate_uint8_t)(chr - '0');
            ret *= 8;
            ret += digit;
        }
        else
        {
            break;
        }
    }
    return ret;
}
static void write_octal(gate_uint64_t num, char* buffer, gate_size_t len)
{
    gate_uint8_t digit;
    gate_size_t ndx;

    --len;
    buffer[len] = 0;

    for (ndx = len; ndx > 0;)
    {
        --ndx;
        digit = (gate_uint8_t)(num % 8);
        buffer[ndx] = '0' + digit;
        num /= 8;
    }
}

static gate_uint32_t gate_tarwriter_calculate_checksum(gate_tarblock_t* block)
{
    gate_size_t ndx;
    gate_uint32_t header_checksum = 0;
    for (ndx = 0; ndx != sizeof(block->data); ++ndx)
    {
        header_checksum += (gate_uint8_t)block->data[ndx];
    }
    return header_checksum & 0x1ffff;
}
static gate_uint32_t gate_tarwriter_calculate_checksum_alt(gate_tarblock_t* block)
{
    gate_size_t ndx;
    gate_int32_t header_checksum = 0;
    for (ndx = 0; ndx != sizeof(block->data); ++ndx)
    {
        header_checksum += (gate_int8_t)block->data[ndx];
    }
    return ((gate_uint32_t)header_checksum) & 0x1ffff;
}



static void gate_tarwriter_create_checksum(gate_tarblock_t* block)
{
    gate_size_t ndx;
    gate_uint32_t block_checksum = 0;

    for (ndx = 0; ndx != sizeof(block->header.checksum); ++ndx)
    {
        /* checksum field needs to be filled with blank chars while the checksum is calculated */
        block->header.checksum[ndx] = ' ';
    }

    block_checksum = gate_tarwriter_calculate_checksum(block);

    write_octal(block_checksum, block->header.checksum, sizeof(block->header.checksum) - 1);
}

static gate_bool_t gate_tarreader_verify_checksum(gate_tarblock_t* block)
{
    gate_size_t ndx = 0;
    gate_uint32_t block_checksum;
    gate_uint32_t block_checksum_alt;
    gate_uint32_t read_checksum = (gate_uint32_t)read_octal(block->header.checksum, sizeof(block->header.checksum));

    for (ndx = 0; ndx != sizeof(block->header.checksum); ++ndx)
    {
        /* checksum field needs to be filled with blank chars while the checksum is calculated */
        block->header.checksum[ndx] = ' ';
    }

    block_checksum = gate_tarwriter_calculate_checksum(block);
    block_checksum_alt = gate_tarwriter_calculate_checksum_alt(block);

    return (read_checksum == block_checksum) || (read_checksum == block_checksum_alt);
}


static char const* const longlink_token = "././@LongLink";
static gate_size_t const longlink_token_len = 13;




gate_result_t gate_tarwriter_create(gate_tarwriter_t* writer, gate_stream_t* stream)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    do
    {
        gate_mem_clear(writer, sizeof(gate_tarwriter_t));
        if (stream == NULL)
        {
            ret = GATE_RESULT_INVALIDARG;
            break;
        }
        writer->stream = stream;
        gate_object_retain(writer->stream);
        if (gate_object_implements_interface((gate_object_t*)stream, GATE_INTERFACE_NAME_CONTROLSTREAM))
        {
            writer->control_stream = (gate_controlstream_t*)stream;
        }
        ret = GATE_RESULT_OK;
    } while (0);
    return ret;
}


static gate_result_t gate_tarwriter_add_long_name(gate_tarwriter_t* writer, char const* path, gate_size_t path_len, gate_tarblock_t const* src_block)
{
    gate_result_t ret = GATE_RESULT_OK;
    gate_tarblock_t block = GATE_INIT_EMPTY;
    gate_size_t written = 0;
    gate_size_t diff;

    do
    {
        gate_mem_copy(&block, src_block, sizeof(block));
        gate_mem_clear(&block.header.filename[longlink_token_len],
            sizeof(block.header.filename) - longlink_token_len);
        gate_mem_copy(block.header.filename, longlink_token, longlink_token_len);
        block.header.typeflag = GATE_TARHEADER_LONGLINK;

        write_octal(path_len, block.header.size, sizeof(block.header.size));

        gate_tarwriter_create_checksum(&block);

        ret = gate_stream_write_block(writer->stream, block.data, sizeof(block.data), &written);
        GATE_BREAK_IF_FAILED(ret);
        writer->bytes_written += written;

        ret = gate_stream_write_block(writer->stream, path, path_len, &written);
        GATE_BREAK_IF_FAILED(ret);
        writer->bytes_written += written;

        diff = path_len % sizeof(block.data);
        if (diff != 0)
        {
            gate_mem_clear(&block, sizeof(block));
            ret = gate_stream_write_block(writer->stream, block.data, sizeof(block.data) - diff, &written);
            GATE_BREAK_IF_FAILED(ret);
            writer->bytes_written += written;
        }
    } while (0);

    return ret;
}

gate_result_t gate_tarwriter_add(gate_tarwriter_t* writer, gate_tarentry_t const* entry, gate_stream_t* stream)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    gate_tarblock_t block = GATE_INIT_EMPTY;
    gate_uint32_t tar_attribs = 0;
    gate_int64_t unix_time = 0;
    gate_result_t result;
    /*gate_uint32_t header_checksum = 0;*/
    gate_size_t len;
    gate_size_t written = 0;
    gate_uint64_t data_written = 0;
    gate_size_t diff;
    gate_size_t filename_len;
    gate_size_t path_len;

    do
    {
        if (NULL == writer->stream)
        {
            ret = GATE_RESULT_NOTAVAILABLE;
            break;
        }

        path_len = gate_str_length_max(entry->path, sizeof(entry->path));

        filename_len = gate_str_print_text(block.header.filename, sizeof(block.header.filename),
            entry->path, path_len);

        GATE_FLAG_SET(tar_attribs, GATE_TARHEADER_TUREAD, (GATE_FLAG_ENABLED(entry->access, GATE_FILEENTRY_ACCESS_OWNERREAD)));
        GATE_FLAG_SET(tar_attribs, GATE_TARHEADER_TUWRITE, (GATE_FLAG_ENABLED(entry->access, GATE_FILEENTRY_ACCESS_OWNERWRITE)));
        GATE_FLAG_SET(tar_attribs, GATE_TARHEADER_TUEXEC, (GATE_FLAG_ENABLED(entry->access, GATE_FILEENTRY_ACCESS_OWNEREXECUTE)));
        GATE_FLAG_SET(tar_attribs, GATE_TARHEADER_TGREAD, (GATE_FLAG_ENABLED(entry->access, GATE_FILEENTRY_ACCESS_GROUPREAD)));
        GATE_FLAG_SET(tar_attribs, GATE_TARHEADER_TGWRITE, (GATE_FLAG_ENABLED(entry->access, GATE_FILEENTRY_ACCESS_GROUPWRITE)));
        GATE_FLAG_SET(tar_attribs, GATE_TARHEADER_TGEXEC, (GATE_FLAG_ENABLED(entry->access, GATE_FILEENTRY_ACCESS_GROUPEXECUTE)));
        GATE_FLAG_SET(tar_attribs, GATE_TARHEADER_TOREAD, (GATE_FLAG_ENABLED(entry->access, GATE_FILEENTRY_ACCESS_ALLREAD)));
        GATE_FLAG_SET(tar_attribs, GATE_TARHEADER_TOWRITE, (GATE_FLAG_ENABLED(entry->access, GATE_FILEENTRY_ACCESS_ALLWRITE)));
        GATE_FLAG_SET(tar_attribs, GATE_TARHEADER_TOEXEC, (GATE_FLAG_ENABLED(entry->access, GATE_FILEENTRY_ACCESS_ALLEXECUTE)));
        GATE_FLAG_SET(tar_attribs, GATE_TARHEADER_TSUID, (GATE_FLAG_ENABLED(entry->access, GATE_FILEENTRY_ACCESS_OWNERSETID)));
        GATE_FLAG_SET(tar_attribs, GATE_TARHEADER_TSGID, (GATE_FLAG_ENABLED(entry->access, GATE_FILEENTRY_ACCESS_GROUPSETID)));
        GATE_FLAG_SET(tar_attribs, GATE_TARHEADER_TSVTX, (GATE_FLAG_ENABLED(entry->access, GATE_FILEENTRY_ACCESS_NODELETE)));

        if (tar_attribs == 0)
        {
            tar_attribs = 0600;
        }

        write_octal(tar_attribs, block.header.filemode, sizeof(block.header.filemode));
        write_octal(entry->size, block.header.size, sizeof(block.header.size));

        if (GATE_FLAG_ENABLED(entry->attribs, GATE_FILEENTRY_ATTRIB_DIRECTORY))
        {
            block.header.typeflag = GATE_TARHEADER_DIRTYPE;
            if (block.header.filename[filename_len - 1] != '/')
            {
                if (filename_len < sizeof(block.header.filename) - 1)
                {
                    block.header.filename[filename_len] = '/';
                    ++filename_len;
                    block.header.filename[filename_len] = 0;
                }
            }
        }
        else if (GATE_FLAG_ENABLED(entry->attribs, GATE_FILEENTRY_ATTRIB_FILE))
        {
            block.header.typeflag = GATE_TARHEADER_REGTYPE;
        }
        else
        {
            ret = GATE_RESULT_NOTSUPPORTED;
            break;
        }

        gate_mem_copy(block.header.magic_id, "ustar\0", 6);
        block.header.tar_version[0] = '0';
        block.header.tar_version[1] = '0';

        result = gate_time_to_unix(entry->time_modified, &unix_time);
        if (GATE_FAILED(result))
        {
            unix_time = 0;
        }
        write_octal(unix_time, block.header.modify_time, sizeof(block.header.modify_time));
        write_octal(unix_time, block.header.change_time, sizeof(block.header.change_time));

        result = gate_time_to_unix(entry->time_accessed, &unix_time);
        if (GATE_FAILED(result))
        {
            unix_time = 0;
        }
        write_octal(unix_time, block.header.access_time, sizeof(block.header.access_time));

        write_octal(0 /*entry->owner_id*/, block.header.owner, sizeof(block.header.owner));
        write_octal(entry->group_id, block.header.group, sizeof(block.header.group));
        len = gate_str_length_max(entry->owner_name, sizeof(entry->owner_name));
        gate_str_print_text(block.header.ownername, sizeof(block.header.ownername),
            entry->owner_name, len);

        len = gate_str_length_max(entry->group_name, sizeof(entry->group_name));
        gate_str_print_text(block.header.groupname, sizeof(block.header.groupname),
            entry->group_name, len);

        gate_tarwriter_create_checksum(&block);


        if (path_len >= sizeof(block.header.filename))
        {
            /* current filename in header is truncated, we need to inject
               longlink blocks before our datablock to address this issue
            */
            ret = gate_tarwriter_add_long_name(writer, entry->path, path_len, &block);
            GATE_BREAK_IF_FAILED(ret);
        }

        ret = gate_stream_write_block(writer->stream, block.data, sizeof(block.data), &written);
        GATE_BREAK_IF_FAILED(ret);
        writer->bytes_written += written;

        if ((stream != NULL) && (entry->size > 0))
        {
            ret = gate_stream_transfer_limit(stream, entry->size, writer->stream, &data_written);
            GATE_BREAK_IF_FAILED(ret);
            if (entry->size != data_written)
            {
                ret = GATE_RESULT_INVALIDOUTPUT;
                break;
            }
            writer->bytes_written += data_written;

            diff = (gate_size_t)(entry->size % sizeof(block.data));
            if (diff != 0)
            {
                gate_mem_clear(&block.data, sizeof(block.data));
                ret = gate_stream_write_block(writer->stream, block.data, sizeof(block.data) - diff, &written);
                GATE_BREAK_IF_FAILED(ret);
                writer->bytes_written += written;
            }
        }

    } while (0);
    return ret;
}
gate_result_t gate_tarwriter_add_data(gate_tarwriter_t* writer, gate_tarentry_t const* entry, void const* data)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    gate_memstream_impl_t memstream;
    gate_memstream_create_static_unmanaged_readonly(&memstream, data, (gate_size_t)entry->size, (gate_size_t)entry->size);
    ret = gate_tarwriter_add(writer, entry, (gate_stream_t*)&memstream);
    gate_object_release(&memstream);
    return ret;
}
gate_result_t gate_tarwriter_flush(gate_tarwriter_t* writer)
{
    gate_result_t ret;
    gate_tarblock_t block = GATE_INIT_EMPTY;
    gate_size_t written;

    do
    {
        /* who empty blocks terminate the tar stream */
        ret = gate_stream_write_block(writer->stream, block.data, sizeof(block.data), &written);
        GATE_BREAK_IF_FAILED(ret);
        writer->bytes_written += written;
        ret = gate_stream_write_block(writer->stream, block.data, sizeof(block.data), &written);
        GATE_BREAK_IF_FAILED(ret);
        writer->bytes_written += written;

        ret = gate_stream_flush(writer->stream);

        gate_object_release(writer->stream);
        writer->stream = NULL;
        writer->control_stream = NULL;
    } while (0);
    return ret;
}
gate_result_t gate_tarwriter_destroy(gate_tarwriter_t* writer)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    if (writer)
    {
        if (writer->stream)
        {
            gate_tarwriter_flush(writer);
            if (writer->stream)
            {
                gate_object_release(writer->stream);
            }
        }

        gate_mem_clear(writer, sizeof(gate_tarwriter_t));
        ret = GATE_RESULT_OK;
    }
    return ret;
}



gate_result_t gate_tarreader_create(gate_tarreader_t* reader, gate_stream_t* stream)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    do
    {
        gate_mem_clear(reader, sizeof(gate_tarreader_t));
        if (!stream)
        {
            ret = GATE_RESULT_INVALIDARG;
            break;
        }
        reader->stream = stream;
        gate_object_retain(reader->stream);
        if (gate_object_implements_interface((gate_object_t*)reader->stream, GATE_INTERFACE_NAME_CONTROLSTREAM))
        {
            reader->control_stream = (gate_controlstream_t*)reader->stream;
        }
        reader->bytes_received = 0;
        reader->bytes_written = 0;
        ret = GATE_RESULT_OK;
    } while (0);

    return ret;
}

gate_result_t gate_tarreader_get_first_entry(gate_tarreader_t* reader, gate_tarentry_t* ptr_entry)
{
    gate_result_t result;
    if (reader->control_stream)
    {
        result = gate_stream_seek(reader->control_stream, 0, GATE_STREAM_SEEK_BEGIN, NULL);
        if (GATE_SUCCEEDED(result))
        {
            result = gate_tarreader_get_next_entry(reader, ptr_entry);
        }
    }
    else
    {
        result = GATE_RESULT_NOTSUPPORTED;
    }
    return result;
}

static gate_bool_t gate_tarreader_is_empty_block(gate_tarblock_t const* block)
{
    gate_size_t len = sizeof(block->data);
    char const* ptr = &block->data[0];

    while (len-- != 0)
    {
        if (*ptr != 0) return false;
        ++ptr;
    }
    return true;
}


gate_result_t gate_tarreader_get_next_entry(gate_tarreader_t* reader, gate_tarentry_t* ptr_entry)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    gate_tarblock_t block = GATE_INIT_EMPTY;
    gate_size_t returned = 0;
    gate_size_t len;
    gate_strbuilder_t path_builder = GATE_INIT_EMPTY;
    gate_uint32_t longlink_len = 0;
    gate_size_t longlink_block_count = 0;
    gate_size_t ndx;
    gate_size_t next_len;
    gate_uint32_t tar_attribs = 0;
    gate_uint64_t unix_time = 0;
    gate_size_t diff;

    do
    {
        gate_mem_clear(ptr_entry, sizeof(gate_tarentry_t));

        if (reader->next_block != 0)
        {
            /* there are content bytes to be accessed */
            ret = GATE_RESULT_INVALIDSTATE;
            break;
        }

        ret = gate_stream_read_block(reader->stream, block.data, sizeof(block.data), &returned);
        GATE_BREAK_IF_FAILED(ret);

        if (returned == 0)
        {
            /* end of stream */
            ret = GATE_RESULT_ENDOFSTREAM;
            break;
        }
        if (returned < sizeof(block.data))
        {
            /* stream not complete, cannot read one full header entry */
            ret = GATE_RESULT_INVALIDINPUT;
            break;
        }

        if (gate_tarreader_is_empty_block(&block))
        {
            /* end of stream */
            ret = GATE_RESULT_ENDOFSTREAM;
            break;
        }

        if (!gate_tarreader_verify_checksum(&block))
        {
            ret = GATE_RESULT_INVALIDHEADER;
            break;
        }

        gate_strbuilder_create_static(&path_builder, ptr_entry->path, sizeof(ptr_entry->path), 0);

        len = gate_str_length_max(block.header.filename, sizeof(block.header.filename));
        if ((0 == gate_str_compare(block.header.filename, len, longlink_token, longlink_token_len))
            && (block.header.typeflag == GATE_TARHEADER_LONGLINK))
        {
            /* longlink detected */
            longlink_len = (gate_uint32_t)read_octal(block.header.size, sizeof(block.header.size));
            longlink_block_count = longlink_len / 512;
            if ((longlink_len % 512) != 0)
            {
                ++longlink_block_count;
            }
            for (ndx = 0; ndx != longlink_block_count; ++ndx)
            {
                next_len = (longlink_len >= sizeof(block.data)) ? sizeof(block.data) : longlink_len;
                ret = gate_stream_read_block(reader->stream, block.data, sizeof(block.data), &returned);
                GATE_BREAK_IF_FAILED(ret);
                gate_strbuilder_append_text(&path_builder, block.data, next_len);
                longlink_len -= (gate_uint32_t)next_len;
            }
            GATE_BREAK_IF_FAILED(ret);

            /* now read the real header block */
            ret = gate_stream_read_block(reader->stream, block.data, sizeof(block.data), &returned);
            GATE_BREAK_IF_FAILED(ret);
        }
        else
        {
            /* just extract the filename from the header */
            gate_strbuilder_append_text(&path_builder, block.header.filename, gate_str_length(block.header.filename));
        }
        tar_attribs = (gate_uint32_t)read_octal(block.header.filemode, sizeof(block.header.filemode));

        ptr_entry->attribs = 0;
        ptr_entry->access = 0;

        GATE_FLAG_SET(ptr_entry->access, GATE_FILEENTRY_ACCESS_OWNERREAD, GATE_FLAG_ENABLED(tar_attribs, GATE_TARHEADER_TUREAD));
        GATE_FLAG_SET(ptr_entry->access, GATE_FILEENTRY_ACCESS_OWNERWRITE, GATE_FLAG_ENABLED(tar_attribs, GATE_TARHEADER_TUWRITE));
        GATE_FLAG_SET(ptr_entry->access, GATE_FILEENTRY_ACCESS_OWNEREXECUTE, GATE_FLAG_ENABLED(tar_attribs, GATE_TARHEADER_TUEXEC));
        GATE_FLAG_SET(ptr_entry->access, GATE_FILEENTRY_ACCESS_GROUPREAD, GATE_FLAG_ENABLED(tar_attribs, GATE_TARHEADER_TGREAD));
        GATE_FLAG_SET(ptr_entry->access, GATE_FILEENTRY_ACCESS_GROUPWRITE, GATE_FLAG_ENABLED(tar_attribs, GATE_TARHEADER_TUWRITE));
        GATE_FLAG_SET(ptr_entry->access, GATE_FILEENTRY_ACCESS_GROUPEXECUTE, GATE_FLAG_ENABLED(tar_attribs, GATE_TARHEADER_TUEXEC));
        GATE_FLAG_SET(ptr_entry->access, GATE_FILEENTRY_ACCESS_ALLREAD, GATE_FLAG_ENABLED(tar_attribs, GATE_TARHEADER_TOREAD));
        GATE_FLAG_SET(ptr_entry->access, GATE_FILEENTRY_ACCESS_ALLWRITE, GATE_FLAG_ENABLED(tar_attribs, GATE_TARHEADER_TOWRITE));
        GATE_FLAG_SET(ptr_entry->access, GATE_FILEENTRY_ACCESS_ALLEXECUTE, GATE_FLAG_ENABLED(tar_attribs, GATE_TARHEADER_TOEXEC));
        GATE_FLAG_SET(ptr_entry->access, GATE_FILEENTRY_ACCESS_OWNERSETID, GATE_FLAG_ENABLED(tar_attribs, GATE_TARHEADER_TSUID));
        GATE_FLAG_SET(ptr_entry->access, GATE_FILEENTRY_ACCESS_GROUPSETID, GATE_FLAG_ENABLED(tar_attribs, GATE_TARHEADER_TSGID));
        GATE_FLAG_SET(ptr_entry->access, GATE_FILEENTRY_ACCESS_NODELETE, GATE_FLAG_ENABLED(tar_attribs, GATE_TARHEADER_TSVTX));

        switch (block.header.typeflag)
        {
        case GATE_TARHEADER_AREGTYPE:
        case GATE_TARHEADER_REGTYPE:
            ptr_entry->attribs |= GATE_FILEENTRY_ATTRIB_FILE;
            break;
        case GATE_TARHEADER_DIRTYPE:
            ptr_entry->attribs |= GATE_FILEENTRY_ATTRIB_DIRECTORY;
            break;
        default:
            ret = GATE_RESULT_NOTSUPPORTED;
            break;
        }
        GATE_BREAK_IF_FAILED(ret);

        reader->next_content_length = read_octal(block.header.size, sizeof(block.header.size));
        reader->next_block = reader->next_content_length;
        diff = (gate_size_t)(reader->next_block % 512U);
        if (diff != 0)
        {
            reader->next_block += (512U - diff);
        }
        ptr_entry->size = reader->next_content_length;
        ptr_entry->owner_id = (gate_uint32_t)read_octal(block.header.owner, sizeof(block.header.owner));
        ptr_entry->group_id = (gate_uint32_t)read_octal(block.header.group, sizeof(block.header.group));

        unix_time = read_octal(block.header.modify_time, sizeof(block.header.modify_time));
        gate_time_from_unix((gate_int64_t)unix_time, &ptr_entry->time_modified);

        unix_time = read_octal(block.header.access_time, sizeof(block.header.access_time));
        gate_time_from_unix((gate_int64_t)unix_time, &ptr_entry->time_accessed);

        gate_str_print_text(ptr_entry->owner_name, sizeof(ptr_entry->owner_name),
            block.header.ownername, gate_str_length_max(block.header.ownername, sizeof(block.header.ownername)));

        gate_str_print_text(ptr_entry->group_name, sizeof(ptr_entry->group_name),
            block.header.groupname, gate_str_length_max(block.header.groupname, sizeof(block.header.groupname)));
        ret = GATE_RESULT_OK;
    } while (0);

    return ret;
}
gate_result_t gate_tarreader_find_entry(gate_tarreader_t* reader, gate_string_t const* path, gate_tarentry_t* ptr_entry)
{
    gate_result_t result = GATE_RESULT_OK;
    gate_tarentry_t entry;

    for (;;)
    {
        result = gate_tarreader_get_next_entry(reader, &entry);
        GATE_BREAK_IF_FAILED(result);
        if (gate_string_equals_str(path, entry.path))
        {
            if (ptr_entry)
            {
                gate_mem_copy(ptr_entry, &entry, sizeof(entry));
            }
            result = GATE_RESULT_OK;
            break;
        }
        result = gate_tarreader_skip_content(reader, NULL);
        GATE_BREAK_IF_FAILED(result);
    }
    return result;
}
gate_result_t gate_tarreader_extract_content(gate_tarreader_t* reader, gate_stream_t* output_target, gate_uint64_t* bytes_transferred)
{
    gate_result_t ret = GATE_RESULT_OK;
    gate_uint64_t exported_bytes = 0;

    do
    {
        if (reader->next_content_length != 0)
        {
            ret = gate_stream_transfer_limit(reader->stream, reader->next_content_length, output_target, &exported_bytes);
            GATE_BREAK_IF_FAILED(ret);
            if (exported_bytes < reader->next_content_length)
            {
                ret = GATE_RESULT_INVALIDINPUT;
                break;
            }
            GATE_DEBUG_ASSERT(reader->next_content_length == exported_bytes);
            reader->next_content_length = 0;
            GATE_DEBUG_ASSERT(reader->next_block >= exported_bytes);
            reader->next_block -= exported_bytes;
        }

        if (reader->next_block != 0)
        {
            ret = gate_stream_skip(reader->stream, reader->next_block, NULL);
            GATE_BREAK_IF_FAILED(ret);
            reader->next_block = 0;
        }
    } while (0);

    if (bytes_transferred)
    {
        *bytes_transferred = exported_bytes;
    }

    return ret;
}
gate_result_t gate_tarreader_skip_content(gate_tarreader_t* reader, gate_uint64_t* optional_bytes_skipped)
{
    gate_result_t ret = GATE_RESULT_OK;
    do
    {
        if (reader->next_block != 0)
        {
            ret = gate_stream_skip(reader->stream, reader->next_block, optional_bytes_skipped);
            GATE_BREAK_IF_FAILED(ret);
            reader->next_block = 0;
        }
        else
        {
            if (optional_bytes_skipped)
            {
                *optional_bytes_skipped = 0;
            }
        }
        reader->next_content_length = 0;
        reader->next_block = 0;
    } while (0);
    return ret;
}

gate_result_t gate_tarreader_destroy(gate_tarreader_t* reader)
{
    gate_result_t ret = GATE_RESULT_OK;
    if (reader->stream)
    {
        gate_object_release(reader->stream);
    }
    gate_mem_clear(reader, sizeof(gate_tarreader_t));
    return ret;
}