summaryrefslogtreecommitdiff
path: root/tarfs.c
blob: 459f9d64fa9a4096b0460ad5d16c02b2d3324439 (plain)
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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
/* tarfs - A GNU tar filesystem for the Hurd.
   Copyright (C) 2002, 2003  Ludovic Courtès <ludo@chbouib.org>
 
   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.
 
   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.
 
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
   USA */

#include <hurd.h>
#include <hurd/netfs.h>

#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <error.h>
#include <sys/mman.h>
#include <dirent.h>
#include <fcntl.h>
#include <limits.h>
#include <argp.h>
#include <argz.h>

#include "backend.h"
#include "tarfs.h"
#include "fs.h"
#include "cache.h"
#include "zipstores.h"
#include "debug.h"

/* New netfs variables */
char *netfs_server_name = "tarfs";
char *netfs_server_version = "(rw-alpha)";

/* Filesystem options */
struct tarfs_opts tarfs_options;
const char *argp_program_version =
  "tarfs(rw-alpha) for the GNU Hurd (compiled: " __DATE__ ")";

/* Argp data */
const char *argp_program_bug_address = "Ludovic Courtès <ludo@chbouib.org>";
const char *args_doc = "ARCHIVE";
const char *doc = "Hurd tar filesystem:\n"
   "parses a tar archive and creates the corresponding filesystem\n";

const struct argp_option fs_options[] =
{
#ifdef DEBUG
  { "debug",        'D', "FILE", 0, "Print debug output to FILE" },
#endif
  { "gzip",         'z', NULL, 0, "Archive file is gzipped" },
  { "bzip2",        'j', NULL, 0, "Archive file is bzip2'd" },
  { "no-timeout",   't', NULL, 0, "Parse file in a separate thread "
				  "(thus avoiding startup timeouts)" },
  { "readonly",     'r', NULL, 0, "Start tarfs read-only" },
  { "writable",     'w', NULL, 0, "Start tarfs writable (default)" },
  { "volatile",     'v', NULL, 0, "Start tarfs volatile "
  				  "(ie writable but not synced)" },
  { "create",       'c', NULL, 0, "Create tar file if not there" },
#if 0
  { "sync",         's', "INTERVAL", 0, "Sync all data not actually written "
				  "to disk every INTERVAL seconds (by "
				  "default, the data is *not* synced unless "
				  "explicitely requested)" },
#endif
  { 0 }
};

/* Tar file store & lock.  */
static struct store *tar_file;
static pthread_mutex_t  tar_file_lock;

/* Archive parsing hook (see tar.c) */
extern int (* tar_header_hook) (tar_record_t *, struct archive *);

/* List of tar items for this file */
static struct tar_list tar_list;

/* Data used by netfs_get_dirents() */
static struct node *curr_dir;
static struct node *curr_node;
static int    curr_entry = 0;

/* A convenience macro */
#define IF_RWFS \
  if (tarfs_options.readonly) \
    return EROFS;


#define D(_s) strdup(_s)

/* Open the tar file STORE according to TARFS_OPTIONS.  Assumes the
   store is already locked.  */
static error_t
open_store ()
{
  error_t err;
  int     flags = tarfs_options.readonly || tarfs_options.volatil
 		  ? STORE_READONLY
 		  : 0;

  switch (tarfs_options.compress)
  {
    case COMPRESS_NONE:
      err = store_file_open (tarfs_options.file_name, flags, &tar_file);
      break;
    case COMPRESS_GZIP:
      err = store_gzip_open (tarfs_options.file_name, flags, &tar_file);
      break;
    case COMPRESS_BZIP2:
      err = store_bzip2_open (tarfs_options.file_name, flags, &tar_file);
      break;
    default:
      error (1, EINVAL, "Compression method not implemented (yet)");
  }

  return err;
}

/* Close the tar file assuming that it is already locked.  */
static void
close_store ()
{
  store_free (tar_file);
  tar_file = NULL;
}

/* Reads NODE from file.  This is called by the cache backend.  */
static error_t
read_from_file (struct node *node, off_t offset, size_t howmuch,
                size_t *actually_read, void *data)
{
  error_t err = 0;
  store_offset_t start = NODE_INFO(node)->tar->offset;
  void *d = data;

  pthread_mutex_lock (&tar_file_lock);

  if (!tar_file)
    err = open_store ();

  if (!err)
    err = store_read (tar_file,
		      start + offset,
		      howmuch,
		      &d,
		      actually_read);

  pthread_mutex_unlock (&tar_file_lock);

  if (err)
    return err;

  assert (*actually_read <= howmuch);

  /* Checks whether store_read() has allocated a new buffer.  */
  if (data != d)
  {
    memcpy (data, d, *actually_read);
    munmap (d, *actually_read);
  }

  return 0;
}


/* Argp options parser.  */
error_t
tarfs_parse_opts (int key, char *arg, struct argp_state *state)
{
  switch (key)
  {
#ifdef DEBUG
    case 'D':
      debug_set_file (arg);
      break;
#endif
    case 'c':
      tarfs_options.create = 1;
      break;
    case 'v':
      tarfs_options.volatil = 1;
      break;
    case 'r':
      tarfs_options.readonly = 1;
      break;
    case 'w':
      tarfs_options.readonly = 0;
      break;
    case 't':
      tarfs_options.threaded = 1;
      break;
    case 'z':
      tarfs_options.compress = COMPRESS_GZIP;
      break;
    case 'j':
      tarfs_options.compress = COMPRESS_BZIP2;
      break;
    case 's':
      tarfs_options.interval = atoi (arg);
      break;
    case ARGP_KEY_ARG:
      tarfs_options.file_name = strdup (arg);
      if (!tarfs_options.file_name || !strlen (tarfs_options.file_name))
	argp_error (state, "No archive specified.");
  }

  return 0;
}

/* Returns the tarfs' struct argp.  */
void
tarfs_get_argp (struct argp *a)
{
  bzero (a, sizeof (struct argp));
  a->options  = fs_options;
  a->parser   = tarfs_parse_opts;
  a->args_doc = args_doc;
  a->doc      = doc;
}

/* Append to the malloced string *ARGZ of len *ARGZ_LEN a NULL-separated list
   of arguments.  */
error_t
tarfs_get_args (char **argz, unsigned *argz_len)
{
  error_t err = 0;
  
  if (!err && tarfs_options.volatil)
    err = argz_add (argz, argz_len, "--volatile");
  else
  {
    if (tarfs_options.readonly)
      err = argz_add (argz, argz_len, "--readonly");
    else
      err = argz_add (argz, argz_len, "--writable");
  }

  if (err)
    return err;

  switch (tarfs_options.compress)
  {
    case COMPRESS_GZIP:
      err = argz_add (argz, argz_len, "--gzip");
      break;
    case COMPRESS_BZIP2:
      err = argz_add (argz, argz_len, "--bzip2");
      break;
  }

  if (err)
    return err;

  err = argz_add (argz, argz_len, tarfs_options.file_name);
  
  return err;
}

/* A basic set_options (). Only runtime options can be changed (using
   fsysopts): for instance, --no-timeout won't work (it doesn't make
   sense when tarfs is already running).  */
error_t
tarfs_set_options (const char *argz, size_t argz_len)
{
  error_t err = 0;

  /* If going readonly (resp. read-write) while the store is currently
     opened read-write (resp. read-only) then close it first.  */

  if (!strcmp (argz, "-r") || !strcmp (argz, "--readonly"))
  {
    if (!tarfs_options.readonly)
    {
      pthread_mutex_lock (&tar_file_lock);
      tarfs_options.readonly = 1;
      close_store ();
      err = open_store ();
      pthread_mutex_unlock (&tar_file_lock);

      if (err)
	tarfs_options.readonly = 0;
      else
        tarfs_options.volatil  = 0;
    }
  }
  else if (!strcmp (argz, "-w") || !strcmp (argz, "--writable"))
  {
    if (tarfs_options.readonly)
    {
      pthread_mutex_lock (&tar_file_lock);
      tarfs_options.readonly = 0;
      close_store ();
      err = open_store ();
      pthread_mutex_unlock (&tar_file_lock);

      if (err)
	tarfs_options.readonly = 1;
      else
        tarfs_options.volatil  = 0;
    }
  }
  else if (!strcmp (argz, "-v") || !strcmp (argz, "--volatile"))
    tarfs_options.readonly = 0, tarfs_options.volatil = 1;
  else
    err = EINVAL;

  return err;
}



error_t tarfs_create_node (struct node **newnode, struct node *dir,
			   const char *name, mode_t mode);

/* This function is called every time a header has been successfully parsed.
   It simply creates the node corresponding to the header.
   OFFSET denotes the offset of the header in the archive.  */
int
tarfs_add_header (tar_record_t *hdr, struct archive *archive)
{
  error_t err;
  static struct tar_item *last_item = NULL;
  struct node *dir, *new = NULL;
  char *name, *notfound, *retry;
  char arch_name[NAMSIZ + 1];
  
  assert (hdr != NULL);

  dir = netfs_root_node;

  memcpy (arch_name, hdr->header.arch_name, NAMSIZ);
  arch_name[NAMSIZ] = '\0';
  name = strdup (arch_name);
  assert (name);
  debug (("name = %s", name));

  /* Find the new node's parent directory.  */
  do
  {
    err = fs_find_node_path (&dir, &retry, &notfound, name);

    /* If a subdirectory wasn't found, then complain, create it and go on.
       eg.: if we wan't to create "/foo/bar" and "/foo" does not exist
            yet, then create "/foo" first and then continue with "bar".  */
    if (retry)
    {
      error (0, 0, "Inconsistent tar archive "
		   "(directory \"%s\" not found)", notfound);
      err = tarfs_create_node (&new, dir, notfound, S_IFDIR | 755);
      assert_perror (err);
      /*fs_make_subdir (&new, dir, notfound);
      NEW_NODE_INFO (new);*/
      free (name);
      name = retry;
      dir = new;
    }
  }
  while (retry);

  if (!notfound)
  {
    /* Means that this node is already here: do nothing.  Complain only
       if the node we found is not the root dir ("tar cf x ." creates
       './' as the first tar entry).  */
    if (dir != netfs_root_node)
      error (0, 0, "Warning: node \"%s\" already exists", name);

    return 0;
  }

  /* Now, go ahead and create the node.  */
  name = notfound;
  assert (strlen (name) > 0);

  switch (hdr->header.linkflag)
  {
    /* Hard link.  */
    case LF_LINK:
    {
      char *tgname;
      struct node *target;

      debug (("Hard linking \"%s\"", name));

      /* Get the target's node first. */
      tgname = malloc (NAMSIZ + 1);
      memcpy (tgname, hdr->header.arch_linkname, NAMSIZ);
      tgname [NAMSIZ] = '\0';
      target = netfs_root_node;
      fs_find_node_path (&target, &retry, &notfound, tgname);

      if ((!retry) && (!notfound))
      {
	/* FIXME: Call tarfs_create_node () and tarfs_link_node instead */
	fs_hard_link_node (&new, dir, name, target->nn_stat.st_mode, target);

	/* Update node info & stats */
	if (new)
	{
	  NEW_NODE_INFO (new);

          /* No need to create a cache for hard links.  */

	  /* Add the tar item into the list.  */
	  err = tar_make_item (&NODE_INFO(new)->tar, new,
			       0, archive->current_tar_position);
	  assert_perror (err);
	}
      }
      else
	error (0, 0, "Hard link target not found (%s -> %s)", name, tgname);

      break;
    }

    /* Other node types.  */
    default:
      err = fs_make_node (&new, dir, name, 0);
      assert_perror (err);

      /* Update node info & stats */
      if (new)
      {
	NEW_NODE_INFO (new);
	tar_fill_stat (archive, &new->nn_stat, hdr);

	/* Create a cache for the new node.  */
	err = cache_create (new);
	if (err)
	  error (1, err, "An error occured while creating the filesystem");

	/* Add the tar item into the list.  */
	err = tar_make_item (&NODE_INFO(new)->tar, new,
			     new->nn_stat.st_size, archive->current_tar_position);
	assert_perror (err);
      }
  }

  if (!new || err)
    error (1, err, "Filesystem could not be built");

  tar_insert_item (&tar_list, last_item, NODE_INFO(new)->tar);
  last_item = NODE_INFO(new)->tar;

#if 0
  debug (("%s: Created node \"%s\" (size=%li)\n",
          __FUNCTION__, name, new->nn_stat.st_size));
#endif

  /* Symlinks handling */
  if (S_ISLNK (new->nn_stat.st_mode))
  {
    if (hdr->header.arch_linkname[0])
      fs_link_node_path (new, strdup (hdr->header.arch_linkname));
    else
    {
      error (0, 0, "Warning: empty symlink target for node \"%s\"",
	     new->nn->name);
      fs_link_node_path (new, strdup (""));
    }
  }

  /* Directories */
  if (S_ISDIR (new->nn_stat.st_mode))
  {
    new->nn_stat.st_nlink = 2;
    new->nn->dir->nn_stat.st_nlink++;
  }

  return 0;
}


error_t
tarfs_init (struct node **root, struct iouser *user)
{
  error_t err = 0;
  io_statbuf_t st;
  int    flags;
  file_t tarfile;
  mode_t mode = 0644;

  /* Sync the archive.  */
  void
  sync_archive ()
  {
    error_t tarfs_sync_fs (int wait);

    while (1)
    {
      sleep (tarfs_options.interval);

      if (!tarfs_options.readonly)
	tarfs_sync_fs (0);
    }
  }

  /* Reads and parses a tar archive, possibly in a separate thread.  */
  void
  read_archive ()
  {
    error_t err;

    /* Go ahead: parse and build.  */
    pthread_mutex_lock (&tar_file_lock);
    err = tar_open_archive (tar_file);
    pthread_mutex_unlock (&tar_file_lock);

    if (err)
      error (1, 0, "Invalid tar archive (%s)", tarfs_options.file_name);
#if 0
    else
      {
        pthread_t t;
        pthread_create (&t, NULL, (void*(*)(void*)) sync_archive, NULL);
      }
#endif
  }


  /* Init. */
  if ((! tarfs_options.file_name) || (! strlen (tarfs_options.file_name)))
    error (1, 0, "No file specified");
  if (tarfs_options.create)
    tarfs_options.readonly = 0, flags = O_CREAT | O_READ | O_WRITE;
  else
    flags = tarfs_options.readonly || tarfs_options.volatil
            ? O_READ
            : O_READ | O_WRITE;

  /* Get the tarfile's stat.  */
  tarfile = file_name_lookup (tarfs_options.file_name, flags, mode);
  if (tarfile != MACH_PORT_NULL)
  {
    /* Check permissions */
    err = io_stat (tarfile, &st);

    if (!err && (flags & O_READ))
      err = fshelp_access (&st, S_IREAD, user);
    if (!err && (flags & O_WRITE))
      err = fshelp_access (&st, S_IWRITE, user);
  }
  else
    err = errno;

  if (err)
  {
    error (1, err, "%s", tarfs_options.file_name);
    return err;
  }
  mach_port_deallocate (mach_task_self (), tarfile);

  err = fs_init ();
  if (err)
    return err;

  /* Create root node */
  st.st_mode &= ~S_IFMT;
  st.st_mode |= S_IFDIR | S_IROOT | S_IATRANS;
  err = fs_make_node (&netfs_root_node, NULL, NULL, st.st_mode);
  if (err)
    return err;

  /* Parse the archive and build the filesystem */
  cache_init (read_from_file);
  tar_header_hook = tarfs_add_header;
  tar_list_init (&tar_list);

  /* Open the corresponding store */
  err = open_store ();
  if (err)
    error (1, err, "%s", tarfs_options.file_name);

  assert (tar_file);

  /* We make the following assumption because this is the way it's gotta
     be with these stores.  */
  assert (tar_file->block_size == 1);

  if (st.st_size)
  {
    if (tarfs_options.threaded)
      {
        pthread_t t;
        pthread_create(&t, NULL, (void*(*)(void*)) read_archive, NULL);
      }
    else
      read_archive ();
  }

  return 0;
}


int
tarfs_set_cd (struct node *dir)
{
  curr_dir = dir;
  curr_node = dir->nn->entries;

  /* Skip anonymous nodes (created by dir_mkfile ()).  */
  while (curr_node && (! curr_node->nn->name))
    curr_node = curr_node->next;

  curr_entry = 0;
  return 0;
}

int
tarfs_skip_entries (int n)
{
  assert (n >= 0);

  /* Skip N first DIR entries. */
  curr_node = curr_dir->nn->entries;

  if (n > 2)
  {
    /* Skip more than `.' and `..' */
    curr_entry = 2;
    while ((curr_entry < n) && (curr_node))
    {
      /* Skip anonymous nodes (created by dir_mkfile ()).  */
      do
	curr_node = curr_node->next;
      while (curr_node && (! curr_node->nn->name));

      curr_entry++;
    }
  }
  else
    curr_entry = n;
  
  /* Returns non-null if could not skip N entries. */
  return (curr_entry<=n)?0:1;
}

static inline int
_new_dirent (struct dirent** e, const struct node *n, const char* nodename)
{
  size_t namelen;
  char*  name;

  assert (nodename != NULL);

  /* N==NULL means that we are considering the node on which the
     translator is set.  */
  namelen = (n) ? strlen (nodename) : 2;

  /* Allocate it. */
  *e = mmap (NULL, sizeof (struct dirent) + namelen,
	     PROT_READ|PROT_WRITE, MAP_ANONYMOUS, 0, 0);
  assert (*e != NULL);
  
  /* Copy node name */
  name = &(*e)->d_name[0];

  if (n == NULL)
  {
    /* `..' */
    memcpy (name, nodename, 3);
    namelen = 2;
    (*e)->d_type = DT_DIR;
    (*e)->d_ino  = netfs_root_node->nn_stat.st_ino;
  }
  else
  {
    memcpy (name, nodename, namelen);

    /* Set the type corresponding to n->nn_stat.st_mode */
    if (n->nn_stat.st_mode & S_IFREG)
      (*e)->d_type = DT_REG;
    else if (n->nn_stat.st_mode & S_IFDIR)
      (*e)->d_type = DT_DIR;
    else if (n->nn_stat.st_mode & S_IFLNK)
      (*e)->d_type = DT_LNK;
    else
      (*e)->d_type = DT_UNKNOWN;

    /* if FILENO==0 then the node won't appear. */
    (*e)->d_fileno = n->nn_stat.st_ino;
  }

  assert (namelen != 0);

  (*e)->d_namlen = namelen;
  (*e)->d_reclen = sizeof (struct dirent) + namelen;

  return 0;
}

int
tarfs_get_next_entry (struct dirent **entry)
{
  switch (curr_entry++)
  {
    case 0:
      _new_dirent (entry, curr_dir, ".");
      break;
    case 1:
      _new_dirent (entry, curr_dir->nn->dir, "..");
      break;
    default:
      if (!curr_node)
	return 1;	/* no more entries */
      else
      {
	_new_dirent (entry, curr_node, curr_node->nn->name);

	/* Skip anonymous nodes (created by dir_mkfile ()).  */
	do
	  curr_node = curr_node->next;
	while (curr_node && (! curr_node->nn->name));
      }
      break;
  }

  return 0;
}

/* Looks up node named NAME and returns the result in NODE.  */
error_t
tarfs_lookup_node (struct node** node, struct node* dir, const char* name)
{
  struct node *n = dir->nn->entries;

  /* Look for NAME in DIR entries. */
  while (n)
  {
    char *this = n->nn->name;

    if (this)
      if (!strcmp (this, name))
        break;

    n = n->next;
  }

  *node = n;

  if (!n)
    return ENOENT;

  return 0;
}

error_t
tarfs_read_node (struct node *node, off_t offset, size_t *len, void* data)
{
  if (S_ISDIR (node->nn_stat.st_mode))
  {
    *len = 0;
    return EISDIR;
  }
  else
    return cache_read (node, offset, *len, data, len);
}


/* Write to NODE through its cache.  */
error_t
tarfs_write_node (struct node *node, off_t offset, size_t *len, const void *data)
{
  IF_RWFS;

  if (S_ISDIR (node->nn_stat.st_mode))
  {
    *len = 0;
    return EISDIR;
  }
  else
  {
    error_t err;
    /* Checks whether we need to actually write to another node.
       (hard links are not handled by cache_write ()).  */
    struct node *what = node->nn->hardlink ? node->nn->hardlink : node;
    
    err = cache_write (node, offset, data, *len, len);

    /* Synchronize stat with hard link's target.  */
    if ((! err) && (what != node))
      node->nn_stat.st_size = what->nn_stat.st_size;

    return err;
  }
}

/* Update NODE stat structure and mark it as dirty.  */
error_t
tarfs_change_stat (struct node *node, const io_statbuf_t *st)
{
  error_t err = 0;
  struct node *what = node->nn->hardlink ? node->nn->hardlink : node;

  IF_RWFS;

  if (st->st_size != what->nn_stat.st_size)
    /* Update the cache size */
    err = cache_set_size (what, st->st_size);

  if (!err)
  {
    what->nn_stat = *st;
    NODE_INFO(what)->stat_changed = 1;

    /* Synchronize NODE with its TARGET if it's a hard link.  */
    if (what != node)
    {
      node->nn_stat = what->nn_stat;
      NODE_INFO(node)->stat_changed = 1;
    }
  }

  return err;
}


/* Create a node named NAME in directory DIR. If NEWNODE is non-zero then
   it will point to the new node.  NAME is duplicated.  */
error_t
tarfs_create_node (struct node **newnode, struct node *dir,
		   const char *name, mode_t mode)
{
  error_t err;
  struct node *new = NULL;

  IF_RWFS;

  /* Allow anonymous (nameless) nodes (created by dir_mkfile ()).  */
  if (name)
  {
    /* NODE's path has to be at most NAMSIZ long. */
    char *path = fs_get_path_from_root (netfs_root_node, dir);
    if (strlen (name) + strlen (path) + 1 > NAMSIZ)
      return ENAMETOOLONG;

    debug (("Creating node %s", name));
  }
  else
  {
    debug (("Creating anonymous node", dir->nn->name));

    /* Don't add anonymous nodes into the tar list.  */
    err = fs_make_node (&new, dir, NULL, mode);

    if (!err && new)
      NEW_NODE_INFO (new);

    *newnode = new;

    err = cache_create (new);

    return err;
  }

  err = fs_make_node (&new, dir, strdup (name), mode);
  if (!err && new)
  {
    struct tar_item *tar, *prev_tar;

    NEW_NODE_INFO (new);
    err = cache_create (new);

    if (!err)
    {
      /* Insert a corresponding tar item into the list.
	 Offset `-1' denotes a note that does not exist inside the tar file.  */
      err = tar_make_item (&tar, new, 0, -1);
      assert_perror (err);

      /* Find a place to put TAR.  */
      tar_put_item (&prev_tar, tar);
      tar_insert_item (&tar_list, prev_tar, tar);
    }
  }

  if (newnode)
    *newnode = new;

  return err;
}

/* Unlink NODE.  NODE's tar_item will remain in the list until the filesystem
   is linked, *except* if its offset is `-1' (new node).  */
error_t
tarfs_unlink_node (struct node *node)
{
  error_t err = 0;
  struct tar_item *tar = NODE_INFO(node)->tar;

  IF_RWFS;

  debug (("Unlinking %s", node->nn->name));

  /* Delete NODE.  */
  err = fs_unlink_node (node);
  if (err)
    return err;

  /* If NODE has never existed inside the tar file, then remove its tar_item
     from the list.  */
  if (tar->offset == -1)
    tar_unlink_item (&tar_list, tar);

  return err;
}


void
tarfs_free_node (struct node *node)
{
  struct tar_item *tar = NODE_INFO (node)->tar;

  /* Free all related resources */
  cache_free (node);
  free (NODE_INFO (node));
  fs_free_node (node);
  tar->node = NULL;
}


/* Tries to create a hard link named NAME in DIR to file NODE.  */
error_t
tarfs_link_node (struct node *dir, struct node *target,
		 const char *name, int excl)
{
  error_t err = 0;
  struct tar_item *prev_tar, *tar;
  struct node *new;

  if (fs_find_node (dir, name))
    return excl ? EEXIST : 0;

  /* If the link's target is anonymous (nameless), then don't create
     a new node, just change its name.  */
  if (!target->nn->name)
  {
    new = target;
    new->nn->name = strdup (name);

    /* Insert NEW into the tar list */
    err = tar_make_item (&tar, new, 0, -1);
    if (!err)
      tar_put_item (&prev_tar, tar);
  }
  else
  {
    err = fs_hard_link_node (&new, dir, strdup (name),
			     target->nn_stat.st_mode, target);
    if (! err && new)
    {
      struct tar_item *t;
      NEW_NODE_INFO (new);

      /* Insert NEW into the tar list */
      err = tar_make_item (&tar, new, 0, -1);
      if (!err)
      {
	tar_put_item (&prev_tar, tar);

	/* Since NEW must appear after TARGET in the tar list,
	   Make sure that PREV_TAR comes *before* TARGET's tar, otherwise
	   set PREV_TAR to be TARGET's tar item.  */
	for (t = NODE_INFO(target)->tar;
	     t && (t != prev_tar);
	     t = t->next);

	if (!t)
	  prev_tar = NODE_INFO(new)->tar;
      }
    }
  }

  if (!err)
  {
    tar_insert_item (&tar_list, prev_tar, tar);
    NODE_INFO(new)->tar = tar;
  }

  return err;
}

/* Tries to turn NODE into a symlink to TARGET.  */
error_t
tarfs_symlink_node (struct node *node, const char *target)
{
  error_t err;

  err = fs_link_node_path (node, target);

  return err;
}

/* Tries to turn NODE into a device of type TYPE (either S_IFBLK or S_IFCHR).
 */
error_t
tarfs_mkdev_node (struct node *node, mode_t type, dev_t indexes)
{
  debug (("Not implemented"));
  return EOPNOTSUPP;
}


/* Rounds SIZE to the upper RECORDSIZE.  */
static inline size_t
round_size (size_t s)
{
   return  (RECORDSIZE * ( (s / RECORDSIZE) \
      			    + ((s % RECORDSIZE) ? 1 : 0 )) );
}

/* Cache nodes ahead CURR_TAR whose data reside in the region
   [OFFS, OFFS+SIZE] of the tar file.  */
static inline error_t
cache_ahead (struct tar_item *curr_tar, off_t offs, size_t size)
{
  error_t err = 0;
  struct node *node;	/* Corresponding node */
  size_t node_size;	/* Node size          */
  off_t  node_offs;	/* Node offset        */

  assert (size);

  do
  {
    /* Looks for an item available in the tar file.  */
    while (curr_tar)
      if ((curr_tar->offset != -1) && (curr_tar->node))
	break;
      else
        curr_tar = curr_tar->next;

    if (curr_tar)
    {
      node = curr_tar->node;
      node_offs = curr_tar->offset;
      node_size = node->nn_stat.st_size;

      /* If we are beyond NODE's boundary, assume it's already cached.  */
      if ( (offs < node_offs + node_size)
           && (offs + size > node_offs) )
      {
	/* Cache either the whole node or just what we need.  */
	size_t how_much;
	how_much = (offs + size > node_offs + node_size)
	           ? node_size
	           : offs + size - node_offs;

	debug (("Caching %i bytes from \"%s\"", how_much, node->nn->name));
	err = cache_cache (node, how_much);
	if (err)
	  return err;
      }

      curr_tar = curr_tar->next;
    }
  }
  while (curr_tar && (node_offs < offs + size));

  return err;
}

/* Store the filesystem into the tar file.  */
error_t
tarfs_sync_fs (int wait)
{
  error_t err = 0;
  char buf[RECORDSIZE];
  off_t  file_offs = 0; /* Current offset in the tar file */
  size_t orig_size = 0;	/* Total original tar file size */
  int need_trailing_block = 0; /* Do we need an additional block at the end? */
  struct tar_item *tar;

  /* Dump BUF to the tar file's store, enlarging it if necessary.  */
  error_t
  tar_write (off_t offset, void *buf, size_t len, size_t *amount)
  {
    error_t err = 0;
    int cnt = 0;

    while (1)
    {
      pthread_mutex_lock (&tar_file_lock);

      if (!tar_file)
	err = open_store ();

      if (!err)
	err = store_write (tar_file, offset, buf, len, amount);

      pthread_mutex_unlock (&tar_file_lock);

      cnt++;

      if (! err)
        break;
      if (cnt > 1)
        break;

      if (err == EIO)
      {
        /* Try to enlarge the file.  */
        debug (("Enlarging file from %lli to %lli",
               tar_file->size, offset + len));
        err = store_set_size (tar_file, offset + len);
        if (err)
          break;
      }
    }

    if (err)
      error (0, err,
	     "Could not write to file (offs="OFF_FMT")", file_offs);

    return err;
  }


  /* Traverse the tar items list and sync them.  */
  tar_list_lock (&tar_list);

  for (tar = tar_list_head (&tar_list);
       tar;
       /* TAR is incremented inside the loop */ )
  {
    struct node *node = tar->node;

    /* Compute the original tar file size.  */
    if (tar->offset != -1)
      orig_size += round_size (tar->orig_size) + RECORDSIZE;

    if (node)
    {
      int have_to_sync;
      char *path;
      size_t size;

      /* Lock the node first */
      pthread_mutex_lock (&node->lock);
      have_to_sync = (tar->offset != file_offs + RECORDSIZE);
      path = fs_get_path_from_root (netfs_root_node, node);
      size = node->nn_stat.st_size;

      /* Round SIZE.  */
      size = round_size (size);

      /* Synchronize NODE's stat.  */
      if ((NODE_INFO(node)->stat_changed) ||
	  (node->nn_stat.st_size != tar->orig_size) ||
	  (have_to_sync))
      {
	size_t amount;
	char *target;

	debug (("%s: syncing stat", path));

	/* Cache all the nodes that would have been overwritten otherwise.  */
	err = cache_ahead (tar, file_offs, RECORDSIZE);
	if (err)
	  break;

	target = node->nn->hardlink
		 ? fs_get_path_from_root (netfs_root_node, node->nn->hardlink)
		 : NULL;

	/* Create and write the corresponding tar header.  */
	tar_make_header ((tar_record_t *)buf, &node->nn_stat,
			 path, node->nn->symlink, target);

	err = tar_write (file_offs, buf, RECORDSIZE, &amount);
	if (err)
	  break;

	assert (amount == RECORDSIZE);

	/* Never finish the tar file with a stat record.  */
	need_trailing_block = 1;
      }
      file_offs  += RECORDSIZE;

      /* Synchronize NODE's contents except if it's a directory/link.  */
      if ((! S_ISDIR (node->nn_stat.st_mode))
          && (! node->nn->symlink)
          && (! node->nn->hardlink)
	  && ((! cache_synced (node)) || (have_to_sync)) )
      {
	off_t  start = file_offs; /* NODE's start */
	off_t  offs = 0; /* Offset in NODE */

	/* We don't need to cache_ahead () if we already are more than
	   one block behind the original item since we write only
	   RECORDSIZE bytes record.  */
	int ahead = (tar->offset - (long)start < RECORDSIZE);

	debug (("%s: syncing contents (%i bytes)", path, size));

	/* Write RECORDSIZE-long blocks.  */
	while (offs < size)
	{
	  size_t amount;
	  
	  if (ahead)
	  {
	    /* Cache everything that will be overlapped.  */
	    err = cache_ahead (tar, file_offs, RECORDSIZE);
	    if (err)
	      break;
	  }

	  err = cache_read (node, offs, RECORDSIZE, buf, &amount);
	  assert_perror (err);

	  /* Last block: fill it with zeros if necessary.  */
	  if (amount < RECORDSIZE)
	  {
	    assert (offs + RECORDSIZE == size);
	    bzero (&buf[amount], RECORDSIZE - amount);
	  }

	  /* Write the whole record, regardless of the amount of data
	     actually read.  */
	  err = tar_write (file_offs, buf, RECORDSIZE, &amount);
	  if (err)
	    break;

	  assert (amount == RECORDSIZE);

	  offs += RECORDSIZE;
	  file_offs += RECORDSIZE;
	}

	if (err)
	  break;

	/* Update NODE's offset *after* cache_ahead () !  */
	tar->offset = start;

	/* Update the original item size.  */
	tar->orig_size = node->nn_stat.st_size;

	/* If this is the last tar item, tell whether we need an additional
	   trailing block: if NODE's size is a RECORDSIZE multiple then we
	   need one.  */
	need_trailing_block = ! (tar->orig_size % RECORDSIZE);
      }
      else
      {
	/* Update NODE's offset.  */
	tar->offset = file_offs;

        /* Skip record anyway.  */
        file_offs += RECORDSIZE * ((node->nn_stat.st_size / RECORDSIZE)
                     + ( (node->nn_stat.st_size % RECORDSIZE) ? 1 : 0 ));
      }

      cache_free (node);
      free (path);
      pthread_mutex_unlock (&node->lock);

      /* Go to next item.  */
      tar = tar->next;
    }
    else
    {
      struct tar_item *next = tar->next;
      debug (("Node removed (size=%i)", tar->orig_size));
      tar_unlink_item_safe (&tar_list, tar);

      /* Go to next item.  */
      tar = next;
    }
  }

  tar_list_unlock (&tar_list);


  /* Add an empty record (FIXME: GNU tar added several of them) */
  if (!err)
  {
    size_t amount;

    if (!file_offs)
      error (0, 0, "Warning: archive is empty");

    bzero (buf, RECORDSIZE);
    err = tar_write (file_offs, buf, RECORDSIZE, &amount);

    if (err || (amount < RECORDSIZE))
    {
      if (!err)
        err = EIO;
    }

    file_offs += amount;
  }

  /* Checks whether the tar file needs to be truncated.  */
  if (!err && (file_offs < orig_size))
  {
    debug (("Truncating tar file from %u to "OFF_FMT" bytes",
            orig_size, file_offs));

    err = store_set_size (tar_file, file_offs);
    if (err)
      error (0, err, "Cannot truncate \"%s\"", tarfs_options.file_name);
  }


  if (!err)
  {
    /* Call store_free () to commit the changes. This is actually only useful
       for zip stores.  */
    close_store ();
  }

  return err;
}

/* Tarfs destructor.  */
error_t
tarfs_go_away ()
{
  error_t err;

  if (!tarfs_options.readonly && !tarfs_options.volatil)
  {
    err = tarfs_sync_fs (0);
    if (err)
      error (0, err, "Syncing failed");
  }

  if (tar_file)
    store_close_source (tar_file);

  debug (("Bye!"));

  return 0;
}


/* Defines the filesystem backend. */
struct fs_backend tarfs_backend =
{
  tarfs_init,
  tarfs_get_argp,
  tarfs_get_args,
  tarfs_set_options,
  tarfs_set_cd,
  tarfs_skip_entries,
  tarfs_get_next_entry,
  tarfs_lookup_node,
  tarfs_read_node,

  /* Write support */
  tarfs_write_node,
  tarfs_change_stat,
  tarfs_create_node,
  tarfs_unlink_node,

  tarfs_link_node,
  tarfs_symlink_node,
  tarfs_mkdev_node,

  tarfs_free_node,

  tarfs_sync_fs,
  tarfs_go_away
};