aboutsummaryrefslogtreecommitdiffstats
path: root/erts/emulator/drivers/ose/ose_efile.c
blob: 9980b07817004dcd75fa75047edbf988d02726d3 (plain) (blame)
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
/*
 * %CopyrightBegin%
 *
 * Copyright Ericsson AB 1997-2012. All Rights Reserved.
 *
 * The contents of this file are subject to the Erlang Public License,
 * Version 1.1, (the "License"); you may not use this file except in
 * compliance with the License. You should have received a copy of the
 * Erlang Public License along with this software. If not, it can be
 * retrieved online at http://www.erlang.org/.
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
 * the License for the specific language governing rights and limitations
 * under the License.
 *
 * %CopyrightEnd%
 */
/*
 * Purpose: Provides file and directory operations for OSE.
 */
#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif
#if defined(HAVE_POSIX_FALLOCATE) && !defined(__sun) && !defined(__sun__)
#define _XOPEN_SOURCE 600
#endif
#if !defined(_GNU_SOURCE) && defined(HAVE_LINUX_FALLOC_H)
#define _GNU_SOURCE
#endif
#include "sys.h"
#include "erl_driver.h"
#include "erl_efile.h"
/*#include <utime.h>*/
#ifdef HAVE_UNISTD_H
#ifndef __OSE__
#include <unistd.h>
#endif
#endif
#ifdef HAVE_SYS_UIO_H
#include <sys/types.h>
#include <sys/uio.h>
#endif
#if defined(HAVE_SENDFILE) && (defined(__linux__) || (defined(__sun) && defined(__SVR4)))
#include <sys/sendfile.h>
#endif

#if defined(__APPLE__) && defined(__MACH__) && !defined(__DARWIN__)
#define DARWIN 1
#endif

#if defined(DARWIN) || defined(HAVE_LINUX_FALLOC_H) || defined(HAVE_POSIX_FALLOCATE)
#include <fcntl.h>
#endif

#ifdef HAVE_LINUX_FALLOC_H
#include <linux/falloc.h>
#endif

#ifdef SUNOS4
#  define getcwd(buf, size) getwd(buf)
#endif

#ifdef __OSE__
#include "ose.h"
#include "unistd.h"
#include "sys/stat.h"
#include "dirent.h"
#include "sys/time.h"
#include "time.h"
#include "heapapi.h"
#endif

/* Find a definition of MAXIOV, that is used in the code later. */
#if defined IOV_MAX
#define MAXIOV IOV_MAX
#elif defined UIO_MAXIOV
#define MAXIOV UIO_MAXIOV
#else
#define MAXIOV 16
#endif


/*
 * Macros for testing file types.
 */

#define ISDIR(st) (((st).st_mode & S_IFMT) == S_IFDIR)
#define ISREG(st) (((st).st_mode & S_IFMT) == S_IFREG)
#define ISDEV(st) \
  (((st).st_mode&S_IFMT) == S_IFCHR || ((st).st_mode&S_IFMT) == S_IFBLK)
#define ISLNK(st) (((st).st_mode & S_IFLNK) == S_IFLNK)
#ifdef NO_UMASK
#define FILE_MODE 0644
#define DIR_MODE  0755
#else
#define FILE_MODE 0666
#define DIR_MODE  0777
#endif

#define IS_DOT_OR_DOTDOT(s) \
    (s[0] == '.' && (s[1] == '\0' || (s[1] == '.' && s[2] == '\0')))


/*
 * Local file descriptor handling, this is needed for filesystems
 * that does not handle seeking outside EOF.
 */

#define L_FD_EXISTS(fd) \
    ((fdm->is_init == 1) && fdm->fd_array[(fd)] != NULL)

#define L_FD_INVALIDATE(fd) \
       fdm->fd_array[(fd)]->valid = 0

#define L_FD_IS_VALID(fd) \
       (fdm->fd_array[(fd)]->valid == 1)

#define L_FD_OFFSET_BEYOND_EOF(fd, offset) \
       (fdm->fd_array[(fd)]->size < offset)

#define L_FD_CUR(fd) \
   (fdm->fd_array[(fd)]->pos)


struct fd_meta
{
   int is_init;
   uint32_t fd_count;
   struct fd_data *fd_array[256];
};

struct fd_data
{
   int pos;
   int whence;
   int valid;
   size_t size;
};

static struct fd_meta *fdm;
static int l_init_local_fd(void);
static int l_pad_file(int fd, off_t offset);
static int l_update_local_fd(int fd, off_t offset, int whence);

static int check_error(int result, Efile_error* errInfo);

static int
l_init_local_fd()
{
   fdm = heap_alloc_private(sizeof(struct fd_meta), __FILE__, __LINE__);
   fdm->fd_count = 0;
   fdm->is_init = 1;

   memset(fdm->fd_array, NULL, sizeof(fdm->fd_array));
   return 1;
}

static int
l_update_local_fd(int fd, off_t offset, int whence)
{
   errno = 0;

   if (fdm->fd_array[fd] == NULL)
   {
      fdm->fd_array[fd] = heap_alloc_private(sizeof(struct fd_data), __FILE__, __LINE__);
      fdm->fd_count++;
   }

   switch (whence)
   {
      case SEEK_CUR:
         fdm->fd_array[fd]->pos = lseek(fd, 0, SEEK_CUR) + offset;
         break;

      case SEEK_END:
         fdm->fd_array[fd]->pos = lseek(fd, 0, SEEK_END) + offset;
         break;

      case SEEK_SET:
         fdm->fd_array[fd]->pos = offset;

      default:
         errno = ENOSYS;
         break;
   }
   fdm->fd_array[fd]->size = lseek(fd, 0, SEEK_END);

   fdm->fd_array[fd]->whence = whence;
   fdm->fd_array[fd]->valid = 1;

   return ((errno != 0) ? -1 : 1);
}

static int
l_pad_file(int fd, off_t offset)
{
   int size_dif;
   char *pad;
   char *cursor;
   int file_size;
   int written = 0;

   if (!L_FD_IS_VALID(fd))
   {
      l_update_local_fd(fd, offset, SEEK_END);
   }

   if (!L_FD_OFFSET_BEYOND_EOF(fd, offset))
   {

      return -1;
   }


   file_size = lseek(fd, 0, SEEK_END);
   size_dif = offset - file_size;
   pad = heap_alloc_private(size_dif, __FILE__, __LINE__);
   cursor = pad;
   memset(pad, '\0', size_dif);

   while (size_dif > 0)
   {
      written = write(fd, cursor, size_dif);

      if (written < 0)
      {
         return -1;
      }
      cursor += written;
      size_dif -= written;
   }

   L_FD_INVALIDATE(fd);
   heap_free_private(pad);

   return ((errno != 0) ? -1 : 1);
}

static int
check_error(int result, Efile_error *errInfo)
{
    if (result < 0) {
	errInfo->posix_errno = errInfo->os_errno = errno;
	return 0;
    }
    return 1;
}

/*
 * public API
 */

int
efile_mkdir(Efile_error* errInfo,	/* Where to return error codes. */
	    char* name)			/* Name of directory to create. */
{
#ifdef NO_MKDIR_MODE
    return check_error(mkdir(name), errInfo);
#else
    int res = mkdir(name, DIR_MODE);
    if (res < 0 && errno == EINVAL) {
      errno = ENOENT;
    }
    return check_error(res, errInfo);
#endif
}

int
efile_rmdir(Efile_error* errInfo,	/* Where to return error codes. */
	    char* name)			/* Name of directory to delete. */
{
    if (rmdir(name) == 0) {
	return 1;
    }
    if (errno == ENOTEMPTY) {
	errno = EEXIST;
    }
    if (errno == EEXIST) {
	int saved_errno = errno;
	struct stat file_stat;
	struct stat cwd_stat;

	/*
	 *  The error code might be wrong if this is the current directory.
	 */

	if (stat(name, &file_stat) == 0 && stat(".", &cwd_stat) == 0 &&
	    file_stat.st_ino == cwd_stat.st_ino &&
	    file_stat.st_dev == cwd_stat.st_dev) {
	    saved_errno = EINVAL;
	}
	errno = saved_errno;
    }
    return check_error(-1, errInfo);
}

int
efile_delete_file(Efile_error* errInfo,	/* Where to return error codes. */
		  char* name)		/* Name of file to delete. */
{
    struct stat statbuf;

    /* OSE will accept removal of directories with unlink() */
    if (stat(name, &statbuf) >= 0 && ISDIR(statbuf))
    {
       errno = EPERM;
       return check_error(-1, errInfo);
    }

    if (unlink(name) == 0) {
	return 1;
    }
    if (errno == EISDIR) {	/* Linux sets the wrong error code. */
	errno = EPERM;
    }
    return check_error(-1, errInfo);
}

/*
 *---------------------------------------------------------------------------
 *
 *      Changes the name of an existing file or directory, from src to dst.
 *	If src and dst refer to the same file or directory, does nothing
 *	and returns success.  Otherwise if dst already exists, it will be
 *	deleted and replaced by src subject to the following conditions:
 *	    If src is a directory, dst may be an empty directory.
 *	    If src is a file, dst may be a file.
 *	In any other situation where dst already exists, the rename will
 *	fail.
 *
 * Results:
 *	If the directory was successfully created, returns 1.
 *	Otherwise the return value is 0 and errno is set to
 *	indicate the error.  Some possible values for errno are:
 *
 *	EACCES:     src or dst parent directory can't be read and/or written.
 *	EEXIST:	    dst is a non-empty directory.
 *	EINVAL:	    src is a root directory or dst is a subdirectory of src.
 *	EISDIR:	    dst is a directory, but src is not.
 *	ENOENT:	    src doesn't exist, or src or dst is "".
 *	ENOTDIR:    src is a directory, but dst is not.
 *	EXDEV:	    src and dst are on different filesystems.
 *
 * Side effects:
 *	The implementation of rename may allow cross-filesystem renames,
 *	but the caller should be prepared to emulate it with copy and
 *	delete if errno is EXDEV.
 *
 *---------------------------------------------------------------------------
 */

int
efile_rename(Efile_error* errInfo,	/* Where to return error codes. */
	     char* src,		        /* Original name. */
	     char* dst)			/* New name. */
{

   /* temporary fix AFM does not recognize ./<file name>
    * in destination */

   char *dot_str;
   if (dst != NULL)
   {
      dot_str = strchr(dst, '.');

      if (dot_str && dot_str == dst && dot_str[1] == '/')
      {
         dst = dst+2;
      }
   }

   if (rename(src, dst) == 0) {
	return 1;
    }
    if (errno == ENOTEMPTY) {
	errno = EEXIST;
    }
#if defined (sparc)
    /*
     * SunOS 4.1.4 reports overwriting a non-empty directory with a
     * directory as EINVAL instead of EEXIST (first rule out the correct
     * EINVAL result code for moving a directory into itself).  Must be
     * conditionally compiled because realpath() is only defined on SunOS.
     */

    if (errno == EINVAL) {
	char srcPath[MAXPATHLEN], dstPath[MAXPATHLEN];
	DIR *dirPtr;
	struct dirent *dirEntPtr;

#ifdef PURIFY
	memset(srcPath, '\0', sizeof(srcPath));
	memset(dstPath, '\0', sizeof(dstPath));
#endif

	if ((realpath(src, srcPath) != NULL)
		&& (realpath(dst, dstPath) != NULL)
		&& (strncmp(srcPath, dstPath, strlen(srcPath)) != 0)) {
	    dirPtr = opendir(dst);
	    if (dirPtr != NULL) {
		while ((dirEntPtr = readdir(dirPtr)) != NULL) {
		    if ((strcmp(dirEntPtr->d_name, ".") != 0) &&
			    (strcmp(dirEntPtr->d_name, "..") != 0)) {
			errno = EEXIST;
			closedir(dirPtr);
			return check_error(-1, errInfo);
		    }
		}
		closedir(dirPtr);
	    }
	}
	errno = EINVAL;
    }
#endif	/* sparc */

    if (strcmp(src, "/") == 0) {
	/*
	 * Alpha reports renaming / as EBUSY and Linux reports it as EACCES,
	 * instead of EINVAL.
	 */

	errno = EINVAL;
    }

    /*
     * DEC Alpha OSF1 V3.0 returns EACCES when attempting to move a
     * file across filesystems and the parent directory of that file is
     * not writable.  Most other systems return EXDEV.  Does nothing to
     * correct this behavior.
     */

    return check_error(-1, errInfo);
}

int
efile_chdir(Efile_error* errInfo,   /* Where to return error codes. */
	    char* name)		    /* Name of directory to make current. */
{
    return check_error(chdir(name), errInfo);
}


int
efile_getdcwd(Efile_error* errInfo,	/* Where to return error codes. */
	      int drive,		/* 0 - current, 1 - A, 2 - B etc. */
	      char* buffer,		/* Where to return the current
					   directory. */
	      size_t size)		/* Size of buffer. */
{
    if (drive == 0) {
	if (getcwd(buffer, size) == NULL)
	    return check_error(-1, errInfo);

#ifdef SIMSPARCSOLARIS
	/* We get "host:" prepended to the dirname - remove!. */
	{
	  int i = 0;
	  int j = 0;
	  while ((buffer[i] != ':') && (buffer[i] != '\0')) i++;
	  if (buffer[i] == ':') {
	    i++;
	    while ((buffer[j++] = buffer[i++]) != '\0');
	  }
	}
#endif
	return 1;
    }

    /*
     * Drives other than 0 is not supported on Unix.
     */

    errno = ENOTSUP;
    return check_error(-1, errInfo);
}

int
efile_readdir(Efile_error* errInfo,	/* Where to return error codes. */
	      char* name,		/* Name of directory to open. */
	      EFILE_DIR_HANDLE* p_dir_handle,	/* Pointer to directory
						   handle of
						   open directory.*/
	      char* buffer,		/* Pointer to buffer for
					   one filename. */
	      size_t *size)		/* in-out Size of buffer, length
					   of name. */
{
    DIR *dp;			/* Pointer to directory structure. */
    struct dirent* dirp;	/* Pointer to directory entry. */

    /*
     * If this is the first call, we must open the directory.
     */

    if (*p_dir_handle == NULL) {
	dp = opendir(name);
	if (dp == NULL)
	    return check_error(-1, errInfo);
	*p_dir_handle = (EFILE_DIR_HANDLE) dp;
    }

    /*
     * Retrieve the name of the next file using the directory handle.
     */

    dp = *((DIR **)((void *)p_dir_handle));
    for (;;) {
	dirp = readdir(dp);
	if (dirp == NULL) {
	    closedir(dp);
	    return 0;
	}
	if (IS_DOT_OR_DOTDOT(dirp->d_name))
	    continue;
	buffer[0] = '\0';
	strncat(buffer, dirp->d_name, (*size)-1);
	*size = strlen(dirp->d_name);
	return 1;
    }
}

int
efile_openfile(Efile_error* errInfo,	/* Where to return error codes. */
	       char* name,		/* Name of directory to open. */
	       int flags,		/* Flags to user for opening. */
	       int* pfd,		/* Where to store the file
					   descriptor. */
	       Sint64 *pSize)		/* Where to store the size of the
					   file. */
{
    struct stat statbuf;
    int fd;
    int mode;			/* Open mode. */

    if (stat(name, &statbuf) >= 0 && !ISREG(statbuf)) {
	/*
	 * For UNIX only, here is some ugly code to allow
	 * /dev/null to be opened as a file.
	 *
	 * Assumption: The i-node number for /dev/null cannot be zero.
	 */
	static ino_t dev_null_ino = 0;

	if (dev_null_ino == 0) {
	    struct stat nullstatbuf;

	    if (stat("/dev/null", &nullstatbuf) >= 0) {
		dev_null_ino = nullstatbuf.st_ino;
	    }
	}
	if (!(dev_null_ino && statbuf.st_ino == dev_null_ino)) {
	    errno = EISDIR;
	    return check_error(-1, errInfo);
	}
    }

    switch (flags & (EFILE_MODE_READ|EFILE_MODE_WRITE)) {
    case EFILE_MODE_READ:
	mode = O_RDONLY;
	break;
    case EFILE_MODE_WRITE:
	if (flags & EFILE_NO_TRUNCATE)
	    mode = O_WRONLY | O_CREAT;
	else
	    mode = O_WRONLY | O_CREAT | O_TRUNC;
	break;
    case EFILE_MODE_READ_WRITE:
	mode = O_RDWR | O_CREAT;
	break;
    default:
	errno = EINVAL;
	return check_error(-1, errInfo);
    }


    if (flags & EFILE_MODE_APPEND) {
	mode &= ~O_TRUNC;
	mode |= O_APPEND;
    }

    if (flags & EFILE_MODE_EXCL) {
	mode |= O_EXCL;
    }

    fd = open(name, mode, FILE_MODE);

    if (!check_error(fd, errInfo))
	return 0;

    *pfd = fd;
    if (pSize) {
	*pSize = statbuf.st_size;
    }
    return 1;
}

int
efile_may_openfile(Efile_error* errInfo, char *name) {
    struct stat statbuf;	/* Information about the file */
    int result;

    result = stat(name, &statbuf);
    if (!check_error(result, errInfo))
	return 0;
    if (!ISREG(statbuf)) {
	errno = EISDIR;
	return check_error(-1, errInfo);
    }
    return 1;
}

void
efile_closefile(int fd)
{
   if (L_FD_EXISTS(fd))
   {
      free(fdm->fd_array[fd]);
      fdm->fd_array[fd] = NULL;
   }
   close(fd);
}

int
efile_fdatasync(Efile_error *errInfo, /* Where to return error codes. */
	    int fd)               /* File descriptor for file to sync data. */
{
#ifdef HAVE_FDATASYNC
    return check_error(fdatasync(fd), errInfo);
#else
    return efile_fsync(errInfo, fd);
#endif
}

int
efile_fsync(Efile_error *errInfo, /* Where to return error codes. */
	    int fd)               /* File descriptor for file to sync. */
{
#ifdef NO_FSYNC
  undefined fsync /* XXX: Really? */
#else
#if defined(DARWIN) && defined(F_FULLFSYNC)
    return check_error(fcntl(fd, F_FULLFSYNC), errInfo);
#else
    return check_error(fsync(fd), errInfo);
#endif /* DARWIN */
#endif /* NO_FSYNC */
}

int
efile_fileinfo(Efile_error* errInfo, Efile_info* pInfo,
	       char* name, int info_for_link)
{
    struct stat statbuf;	/* Information about the file */
    int result;

    if (info_for_link) {
#ifndef __OSE__
	result = lstat(name, &statbuf);
#else
	result = stat(name, &statbuf);
#endif
    } else {
	result = stat(name, &statbuf);
    }
    if (!check_error(result, errInfo)) {
	return 0;
    }

#if SIZEOF_OFF_T == 4
    pInfo->size_high = 0;
#else
    pInfo->size_high = (Uint32)(statbuf.st_size >> 32);
#endif
    pInfo->size_low = (Uint32)statbuf.st_size;

#ifdef NO_ACCESS
    /* Just look at read/write access for owner. */

    pInfo->access = ((statbuf.st_mode >> 6) & 07) >> 1;

#else
    pInfo->access = FA_NONE;
    if (access(name, R_OK) == 0)
	pInfo->access |= FA_READ;
    if (access(name, W_OK) == 0)
	pInfo->access |= FA_WRITE;

#endif

    if (ISDEV(statbuf))
	pInfo->type = FT_DEVICE;
    else if (ISDIR(statbuf))
	pInfo->type = FT_DIRECTORY;
    else if (ISREG(statbuf))
	pInfo->type = FT_REGULAR;
    else if (ISLNK(statbuf))
	pInfo->type = FT_SYMLINK;
    else
	pInfo->type = FT_OTHER;

    pInfo->accessTime   = statbuf.st_atime;
    pInfo->modifyTime   = statbuf.st_mtime;
    pInfo->cTime        = statbuf.st_ctime;

    pInfo->mode         = statbuf.st_mode;
    pInfo->links        = statbuf.st_nlink;
    pInfo->major_device = statbuf.st_dev;
#ifndef __OSE__
    pInfo->minor_device = statbuf.st_rdev;
#endif
    pInfo->inode        = statbuf.st_ino;
    pInfo->uid          = statbuf.st_uid;
    pInfo->gid          = statbuf.st_gid;

    return 1;
}

int
efile_write_info(Efile_error *errInfo, Efile_info *pInfo, char *name)
{
/* FIXME, this will be dificult to get to work right with the tests on ose
 * reason being that the info values are sometimes used in different ways, and in
 * some times not used at all. */

#ifndef __OSE__
    struct utimbuf tval;
#endif

    /*
     * On some systems chown will always fail for a non-root user unless
     * POSIX_CHOWN_RESTRICTED is not set.  Others will succeed as long as
     * you don't try to chown a file to someone besides youself.
     */
#ifndef __OSE__
    if (chown(name, pInfo->uid, pInfo->gid) && errno != EPERM) {
	return check_error(-1, errInfo);
    }
#endif

    if (pInfo->mode != -1) {
	mode_t newMode = pInfo->mode & (S_ISUID | S_ISGID |
					S_IRWXU | S_IRWXG | S_IRWXO);
	if (chmod(name, newMode)) {
	    newMode &= ~(S_ISUID | S_ISGID);
	    if (chmod(name, newMode)) {
		return check_error(-1, errInfo);
	    }
	}
    }

#ifndef __OSE__
    tval.actime  = pInfo->accessTime;
    tval.modtime = pInfo->modifyTime;

    return check_error(utime(name, &tval), errInfo);
#else
   return 1;
#endif
}


int
efile_write(Efile_error* errInfo,	/* Where to return error codes. */
	    int flags,			/* Flags given when file was
					   opened. */
	    int fd,			/* File descriptor to write to. */
	    char* buf,			/* Buffer to write. */
	    size_t count)		/* Number of bytes to write. */
{
    ssize_t written;			/* Bytes written in last operation. */

    if (L_FD_EXISTS(fd))
    {
      off_t off;
      off = (L_FD_IS_VALID(fd)) ? L_FD_CUR(fd) : lseek(fd, 0, SEEK_CUR);

      if (L_FD_OFFSET_BEYOND_EOF(fd, off))
      {
         l_pad_file(fd, off);
      }

      L_FD_INVALIDATE(fd);
    }

    while (count > 0)
    {
       if ((written = write(fd, buf, count)) < 0)
       {
          if (errno != EINTR)
          {
             return check_error(-1, errInfo);
          }
	  else
          {
	     written = 0;
          }
       }
       ASSERT(written <= count);
       buf += written;
       count -= written;
    }

    if (L_FD_EXISTS(fd))
    {
      L_FD_INVALIDATE(fd);
    }
    return 1;
}

int
efile_writev(Efile_error* errInfo,   /* Where to return error codes */
	     int flags,              /* Flags given when file was
				      * opened */
	     int fd,                 /* File descriptor to write to */
	     SysIOVec* iov,          /* Vector of buffer structs.
				      * The structs may be changed i.e.
				      * due to incomplete writes */
	     int iovcnt)             /* Number of structs in vector */
{
    int cnt = 0;                     /* Buffers so far written */

    ASSERT(iovcnt >= 0);

    while (cnt < iovcnt) {
	if ((! iov[cnt].iov_base) || (iov[cnt].iov_len <= 0)) {
	    /* Empty buffer - skip */
	    cnt++;
	} else { /* Non-empty buffer */
	    ssize_t w;                   /* Bytes written in this call */
#ifdef HAVE_WRITEV
	    int b = iovcnt - cnt;        /* Buffers to write */
	    /* Use as many buffers as MAXIOV allows */
	    if (b > MAXIOV)
		b = MAXIOV;
	    if (b > 1) {
		do {
		    w = writev(fd, &iov[cnt], b);
		} while (w < 0 && errno == EINTR);
	    } else
		/* Degenerated io vector - use regular write */
#endif
		{
		    do {
			w = write(fd, iov[cnt].iov_base, iov[cnt].iov_len);
		    } while (w < 0 && errno == EINTR);
		    ASSERT(w <= iov[cnt].iov_len || w == -1);
		}
	    if (w < 0) return check_error(-1, errInfo);
	    /* Move forward to next buffer to write */
	    for (; cnt < iovcnt && w > 0; cnt++) {
		if (iov[cnt].iov_base && iov[cnt].iov_len > 0) {
		    if (w < iov[cnt].iov_len) {
			/* Adjust the buffer for next write */
			iov[cnt].iov_len -= w;
			iov[cnt].iov_base += w;
			w = 0;
			break;
		    } else {
			w -= iov[cnt].iov_len;
		    }
		}
	    }
	    ASSERT(w == 0);
	} /* else Non-empty buffer */
    } /* while (cnt< iovcnt) */
    return 1;
}

int
efile_read(Efile_error* errInfo,     /* Where to return error codes. */
	   int flags,		     /* Flags given when file was opened. */
	   int fd,		     /* File descriptor to read from. */
	   char* buf,		     /* Buffer to read into. */
	   size_t count,	     /* Number of bytes to read. */
	   size_t *pBytesRead)	     /* Where to return number of
					bytes read. */
{
    ssize_t n;
   if (L_FD_EXISTS(fd))
   {
      off_t off;
      off = (L_FD_IS_VALID(fd)) ? L_FD_CUR(fd) : lseek(fd, 0, SEEK_CUR);
      if (L_FD_IS_VALID(fd) == 0)
      {
         l_update_local_fd(fd, off, SEEK_SET);
      }

      if (L_FD_OFFSET_BEYOND_EOF(fd, off))
      {
         *pBytesRead = 0;
         return 1;
      }
      /* FIXME .. is this needed? */
      lseek(fd, off, SEEK_SET);
   }

    for (;;)
    {
       if ((n = read(fd, buf, count)) >= 0)
       {
          break;
       }
       else if (errno != EINTR)
       {
          return check_error(-1, errInfo);
       }
    }
    if (n != 0 && L_FD_EXISTS(fd))
    {
       L_FD_INVALIDATE(fd);
    }
    *pBytesRead = (size_t) n;
    return 1;
}


/* pread() and pwrite()                                                   */
/* Some unix systems, notably Solaris has these syscalls                  */
/* It is especially nice for i.e. the dets module to have support         */
/* for this, even if the underlying OS dosn't support it, it is           */
/* reasonably easy to work around by first calling seek, and then         */
/* calling read().                                                        */
/* This later strategy however changes the file pointer, which pread()    */
/* does not do. We choose to ignore this and say that the location        */
/* of the file pointer is undefined after a call to any of the p functions*/


int
efile_pread(Efile_error* errInfo,     /* Where to return error codes. */
	    int fd,		      /* File descriptor to read from. */
	    Sint64 offset,            /* Offset in bytes from BOF. */
	    char* buf,		      /* Buffer to read into. */
	    size_t count,	      /* Number of bytes to read. */
	    size_t *pBytesRead)	      /* Where to return
					 number of bytes read. */
{
#if defined(HAVE_PREAD) && defined(HAVE_PWRITE)
    ssize_t n;
    off_t off = (off_t) offset;
    if (off != offset) {
	errno = EINVAL;
	return check_error(-1, errInfo);
    }
    for (;;) {
	if ((n = pread(fd, buf, count, offset)) >= 0)
	    break;
	else if (errno != EINTR)
	    return check_error(-1, errInfo);
    }
    *pBytesRead = (size_t) n;
    return 1;
#else
    {
	int res = efile_seek(errInfo, fd, offset, EFILE_SEEK_SET, NULL);
	if (res) {
	    return efile_read(errInfo, 0, fd, buf, count, pBytesRead);
	} else {
	    return res;
	}
    }
#endif
}



int
efile_pwrite(Efile_error* errInfo,  /* Where to return error codes. */
	     int fd,		    /* File descriptor to write to. */
	     char* buf,		    /* Buffer to write. */
	     size_t count,	    /* Number of bytes to write. */
	     Sint64 offset)	    /* where to write it */
{
#if defined(HAVE_PREAD) && defined(HAVE_PWRITE)
    ssize_t written;		    /* Bytes written in last operation. */
    off_t off = (off_t) offset;
    if (off != offset) {
	errno = EINVAL;
	return check_error(-1, errInfo);
    }

    while (count > 0) {
	if ((written = pwrite(fd, buf, count, offset)) < 0) {
	    if (errno != EINTR)
		return check_error(-1, errInfo);
	    else
		written = 0;
	}
	ASSERT(written <= count);
	buf += written;
	count -= written;
	offset += written;
    }
    return 1;
#else  /* For unix systems that don't support pread() and pwrite() */
    {
	int res = efile_seek(errInfo, fd, offset, EFILE_SEEK_SET, NULL);

	if (res) {
	    return efile_write(errInfo, 0, fd, buf, count);
	} else {
	    return res;
	}
    }
#endif
}


int
efile_seek(Efile_error* errInfo,      /* Where to return error codes. */
	   int fd,                    /* File descriptor to do the seek on. */
	   Sint64 offset,             /* Offset in bytes from the given
					 origin. */
	   int origin,                /* Origin of seek (SEEK_SET, SEEK_CUR,
				         SEEK_END). */
	   Sint64 *new_location)      /* Resulting new location in file. */
{
    off_t off, result;
    off = (off_t) offset;

    switch (origin) {
    case EFILE_SEEK_SET: origin = SEEK_SET; break;
    case EFILE_SEEK_CUR: origin = SEEK_CUR; break;
    case EFILE_SEEK_END: origin = SEEK_END; break;
    default:
	errno = EINVAL;
	return check_error(-1, errInfo);
    }
    if (off != offset) {
    errno = EINVAL;
    return check_error(-1, errInfo);
    }

    errno = 0;
    result = lseek(fd, off, origin);

    if (result >= 0 && L_FD_EXISTS(fd))
    {
       L_FD_INVALIDATE(fd);
    }

    /*
     * Note that the man page for lseek (on SunOs 5) says:
     *
     * "if fildes is a remote file  descriptor  and  offset  is
     * negative,  lseek()  returns  the  file pointer even if it is
     * negative."
     */

     if (result < 0 && errno == 0)
	 errno = EINVAL;
      if (result < 0)
      {
         /* Some filesystems on OSE does not handle seeking beyond EOF
          * We handle this here, by localy storing offsets. */

         if ((lseek(fd, 0, SEEK_END) < off) && errno == 78)
         {
            if (fdm == NULL) /* first time */
            {
               if (l_init_local_fd() == -1)
               {
                  errno = EINVAL;
                  check_error(-1, errInfo);
               }
            }
            l_update_local_fd(fd, off, origin);
            result = off;
         }
         else if (off < 0 && errno == ENOSYS)
         {
            errno = EINVAL;
            return check_error(-1, errInfo);
         }
         else
         {
	         return check_error(-1, errInfo);
         }
      }
      if (new_location) {
	 *new_location = result;
      }
   return 1;
}


int
efile_truncate_file(Efile_error* errInfo, int *fd, int flags)
{
#ifndef NO_FTRUNCATE
    off_t offset;

    if (L_FD_EXISTS(fileno(fd)))
    {
      L_FD_INVALIDATE(fileno(fd));
    }

    return check_error((offset = lseek(*fd, 0, SEEK_CUR)) >= 0 &&
          ftruncate(*fd, offset) == 0 ? 1 : -1, errInfo);
#else
    return 1;
#endif
}

int
efile_readlink(Efile_error* errInfo, char* name, char* buffer, size_t size)
{
#ifndef __OSE__
    int len;
    ASSERT(size > 0);
    len = readlink(name, buffer, size-1);
    if (len == -1) {
	return check_error(-1, errInfo);
    }
    buffer[len] = '\0';
    return 1;
#else
    errno = ENOTSUP;
    return check_error(-1, errInfo);
#endif
}

int
efile_altname(Efile_error* errInfo, char* name, char* buffer, size_t size)
{
    errno = ENOTSUP;
    return check_error(-1, errInfo);
}

int
efile_link(Efile_error* errInfo, char* old, char* new)
{
#ifndef __OSE__
    return check_error(link(old, new), errInfo);
#else
    errno = ENOTSUP;
    return check_error(-1, errInfo);
#endif
}

int
efile_symlink(Efile_error* errInfo, char* old, char* new)
{
#ifndef __OSE__
    return check_error(symlink(old, new), errInfo);
#else
    errno = ENOTSUP;
    return check_error(-1, errInfo);
#endif
}

int
efile_fadvise(Efile_error* errInfo, int fd, Sint64 offset,
		  Sint64 length, int advise)
{
#ifdef HAVE_POSIX_FADVISE
    return check_error(posix_fadvise(fd, offset, length, advise), errInfo);
#else
    return check_error(0, errInfo);
#endif
}

#ifdef HAVE_SENDFILE
/* For some reason the maximum size_t cannot be used as the max size
   3GB seems to work on all platforms */
#define SENDFILE_CHUNK_SIZE ((1UL << 30) -1)

/*
 * sendfile: The implementation of the sendfile system call varies
 * a lot on different *nix platforms so to make the api similar in all
 * we have to emulate some things in linux and play with variables on
 * bsd/darwin.
 *
 * All of the calls will split a command which tries to send more than
 * SENDFILE_CHUNK_SIZE of data at once.
 *
 * On platforms where *nbytes of 0 does not mean the entire file, this is
 * simulated.
 *
 * It could be possible to implement header/trailer in sendfile. Though
 * you would have to emulate it in linux and on BSD/Darwin some complex
 * calculations have to be made when using a non blocking socket to figure
 * out how much of the header/file/trailer was sent in each command.
 *
 * The semantics of the API is this:
 * Return value: 1 if all data was sent and the function does not need to
 * be called again. 0 if an error occures OR if there is more data which
 * has to be sent (EAGAIN or EINTR will be set appropriately)
 *
 * The amount of data written in a call is returned through nbytes.
 *
 */

int
efile_sendfile(Efile_error* errInfo, int in_fd, int out_fd,
	       off_t *offset, Uint64 *nbytes, struct t_sendfile_hdtl* hdtl)
{
    Uint64 written = 0;
#if defined(__linux__)
    ssize_t retval;
    do {
      /* check if *nbytes is 0 or greater than chunk size */
      if (*nbytes == 0 || *nbytes > SENDFILE_CHUNK_SIZE)
	retval = sendfile(out_fd, in_fd, offset, SENDFILE_CHUNK_SIZE);
      else
	retval = sendfile(out_fd, in_fd, offset, *nbytes);
      if (retval > 0) {
	written += retval;
	*nbytes -= retval;
      }
    } while (retval == SENDFILE_CHUNK_SIZE);
    if (written != 0) {
      /* -1 is not returned by the linux API so we have to simulate it */
      retval = -1;
      errno = EAGAIN;
    }
#elif defined(__sun) && defined(__SVR4) && defined(HAVE_SENDFILEV)
    ssize_t retval;
    size_t len;
    sendfilevec_t fdrec;
    fdrec.sfv_fd = in_fd;
    fdrec.sfv_flag = 0;
    do {
      fdrec.sfv_off = *offset;
      len = 0;
      /* check if *nbytes is 0 or greater than chunk size */
      if (*nbytes == 0 || *nbytes > SENDFILE_CHUNK_SIZE)
	fdrec.sfv_len = SENDFILE_CHUNK_SIZE;
      else
	fdrec.sfv_len = *nbytes;
      retval = sendfilev(out_fd, &fdrec, 1, &len);

      /* Sometimes sendfilev can return -1 and still send data.
         When that happens we just pretend that no error happend. */
      if (retval != -1 || errno == EAGAIN || errno == EINTR ||
	  len != 0) {
        *offset += len;
	*nbytes -= len;
	written += len;
	if (errno != EAGAIN && errno != EINTR && len != 0)
	  retval = len;
      }
    } while (len == SENDFILE_CHUNK_SIZE);
#elif defined(DARWIN)
    int retval;
    off_t len;
    do {
      /* check if *nbytes is 0 or greater than chunk size */
      if(*nbytes > SENDFILE_CHUNK_SIZE)
	len = SENDFILE_CHUNK_SIZE;
      else
	len = *nbytes;
      retval = sendfile(in_fd, out_fd, *offset, &len, NULL, 0);
      if (retval != -1 || errno == EAGAIN || errno == EINTR) {
        *offset += len;
	*nbytes -= len;
	written += len;
      }
    } while (len == SENDFILE_CHUNK_SIZE);
#elif defined(__FreeBSD__) || defined(__DragonFly__)
    off_t len;
    int retval;
    do {
      if (*nbytes > SENDFILE_CHUNK_SIZE)
	retval = sendfile(in_fd, out_fd, *offset, SENDFILE_CHUNK_SIZE,
			  NULL, &len, 0);
      else
	retval = sendfile(in_fd, out_fd, *offset, *nbytes, NULL, &len, 0);
      if (retval != -1 || errno == EAGAIN || errno == EINTR) {
	*offset += len;
	*nbytes -= len;
	written += len;
      }
    } while(len == SENDFILE_CHUNK_SIZE);
#endif
    *nbytes = written;
    return check_error(retval, errInfo);
}
#endif /* HAVE_SENDFILE */

#ifdef HAVE_POSIX_FALLOCATE
static int
call_posix_fallocate(int fd, Sint64 offset, Sint64 length)
{
    int ret;

    /*
     * On Linux and Solaris for example, posix_fallocate() returns
     * a positive error number on error and it does not set errno.
     * On FreeBSD however (9.0 at least), it returns -1 on error
     * and it sets errno.
     */
    do {
        ret = posix_fallocate(fd, (off_t) offset, (off_t) length);
        if (ret > 0) {
            errno = ret;
            ret = -1;
        }
    } while (ret != 0 && errno == EINTR);

    return ret;
}
#endif /* HAVE_POSIX_FALLOCATE */

int
efile_fallocate(Efile_error* errInfo, int fd, Sint64 offset, Sint64 length)
{
#if defined HAVE_FALLOCATE
    /* Linux specific, more efficient than posix_fallocate. */
    int ret;

    do {
        ret = fallocate(fd, FALLOC_FL_KEEP_SIZE, (off_t) offset, (off_t) length);
    } while (ret != 0 && errno == EINTR);

#if defined HAVE_POSIX_FALLOCATE
    /* Fallback to posix_fallocate if available. */
    if (ret != 0) {
        ret = call_posix_fallocate(fd, offset, length);
    }
#endif

    return check_error(ret, errInfo);
#elif defined F_PREALLOCATE
    /* Mac OS X specific, equivalent to posix_fallocate. */
    int ret;
    fstore_t fs;

    memset(&fs, 0, sizeof(fs));
    fs.fst_flags = F_ALLOCATECONTIG;
    fs.fst_posmode = F_VOLPOSMODE;
    fs.fst_offset = (off_t) offset;
    fs.fst_length = (off_t) length;

    ret = fcntl(fd, F_PREALLOCATE, &fs);

    if (-1 == ret) {
        fs.fst_flags = F_ALLOCATEALL;
        ret = fcntl(fd, F_PREALLOCATE, &fs);

#if defined HAVE_POSIX_FALLOCATE
        /* Fallback to posix_fallocate if available. */
        if (-1 == ret) {
            ret = call_posix_fallocate(fd, offset, length);
        }
#endif
    }

    return check_error(ret, errInfo);
#elif defined HAVE_POSIX_FALLOCATE
    /* Other Unixes, use posix_fallocate if available. */
    return check_error(call_posix_fallocate(fd, offset, length), errInfo);
#else
    errno = ENOTSUP;
    return check_error(-1, errInfo);
#endif
}