~n-muench/ubuntu/precise/open-vm-tools/open-vm-tools.raring-precise.backport

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
/*********************************************************
 * Copyright (C) 1998 VMware, Inc. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA.
 *
 *********************************************************/

/*
 * fileIO.c --
 *
 *    Basic (non internationalized) implementation of error messages for the
 *    Files library.
 *
 *    File locking/unlocking routines.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

#include "vmware.h"
#include "util.h"
#include "fileIO.h"
#include "fileLock.h"
#include "fileInt.h"
#include "msg.h"
#include "unicodeOperations.h"
#include "hostType.h"
#if defined(_WIN32)
#include <io.h>
#else
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#if defined(VMX86_SERVER)
#include "fs_public.h"
#endif


/*
 *----------------------------------------------------------------------
 *
 * FileIO_ErrorEnglish --
 *
 *      Return the message associated with a status code
 *
 * Results:
 *      The message
 *
 * Side effects:
 *      None
 *
 *----------------------------------------------------------------------
 */

const char *
FileIO_ErrorEnglish(FileIOResult status) // IN
{
   return Msg_StripMSGID(FileIO_MsgError(status));
}


/*
 *----------------------------------------------------------------------
 *
 * FileIO_MsgError --
 *
 *      Return the message associated with a status code
 *
 * Results:
 *      The message.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

const char *
FileIO_MsgError(FileIOResult status) // IN
{
   const char *result = NULL;

   switch (status) {
   case FILEIO_SUCCESS:
      /*
       * Most of the time, you don't call this function with this value
       * because there is no error
       */
      result = MSGID(fileio.success) "Success";
      break;

   case FILEIO_CANCELLED:
      /*
       * Most of the time, you don't call this function with this value
       * because you don't want to display error messages after a user has
       * cancelled an operation.
       */
      result = MSGID(fileio.cancel) "The operation was canceled by the user";
      break;

   case FILEIO_ERROR:
      /*
       * Most of the time, you don't call this function with this value
       * because you can call your native function to retrieve a more
       * accurate message.
       */
      result = MSGID(fileio.generic) "Error";
      break;

   case FILEIO_OPEN_ERROR_EXIST:
      result = MSGID(fileio.exists) "The file already exists";
      break;

   case FILEIO_LOCK_FAILED:
      result = MSGID(fileio.lock) "Failed to lock the file";
      break;

   case FILEIO_READ_ERROR_EOF:
      result = MSGID(fileio.eof) "Tried to read beyond the end of the file";
      break;

   case FILEIO_FILE_NOT_FOUND:
      result = MSGID(fileio.notfound) "Could not find the file";
      break;

   case FILEIO_NO_PERMISSION:
      result = MSGID(fileio.noPerm) "Insufficient permission to access the file";
      break;

   case FILEIO_FILE_NAME_TOO_LONG:
      result = MSGID(fileio.namelong) "The file name is too long";
      break;

   case FILEIO_WRITE_ERROR_FBIG:
      result = MSGID(fileio.fBig) "The file is too large";
      break;

   case FILEIO_WRITE_ERROR_NOSPC:
      result = MSGID(fileio.noSpc) "There is no space left on the device";
      break;

   case FILEIO_WRITE_ERROR_DQUOT:
      result = MSGID(fileio.dQuot) "There is no space left on the device";
      break;

   case FILEIO_ERROR_LAST:
      NOT_IMPLEMENTED();
      break;

      /*
       * We do not provide a default case on purpose, so that the compiler can
       * detect changes in the error set and reminds us to implement the
       * associated messages --hpreg
       */
   }

   if (!result) {
      Warning("%s: bad code %d\n", __FUNCTION__, status);
      ASSERT(0);
      result = MSGID(fileio.unknown) "Unknown error";
   }

   return result;
}


/*
 *----------------------------------------------------------------------
 *
 * FileIO_Init --
 *
 *      Initialize invalid FileIODescriptor.  Expects that caller
 *	prepared structure with FileIO_Invalidate.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None
 *
 *----------------------------------------------------------------------
 */

void
FileIO_Init(FileIODescriptor *fd,   // IN/OUT:
            ConstUnicode pathName)  // IN:
{
   ASSERT(fd);
   ASSERT(pathName);

   fd->fileName = Unicode_Duplicate(pathName);
}


/*
 *----------------------------------------------------------------------
 *
 * FileIO_Cleanup --
 *
 *      Undo resource allocation done by FileIO_Init.  You do not want to
 *	call this function directly, you most probably want FileIO_Close.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None
 *
 *----------------------------------------------------------------------
 */

void
FileIO_Cleanup(FileIODescriptor *fd)  // IN/OUT:
{
   ASSERT(fd);

   if (fd->fileName) {
      Unicode_Free(fd->fileName);
      fd->fileName = NULL;
   }
}


/*
 *----------------------------------------------------------------------
 *
 * FileIOResolveLockBits --
 *
 *      Resolve the multitude of lock bits from historical public names
 *      to newer internal names.
 *
 *      Input flags: FILEIO_OPEN_LOCKED a.k.a. FILEIO_OPEN_LOCK_BEST,
 *                   FILEIO_OPEN_EXCLUSIVE_LOCK
 *      Output flags: FILEIO_OPEN_LOCK_MANDATORY, FILEIO_OPEN_LOCK_ADVISORY
 *
 * Results:
 *      None
 *
 * Side effects:
 *      Only output flags are set in *access.
 *
 *----------------------------------------------------------------------
 */

void
FileIOResolveLockBits(int *access)  // IN/OUT: FILEIO_OPEN_* bits
{
   /*
    * Lock types:
    *    none: no locking at all
    *    advisory: open() ignores lock, FileIO_ respects lock.
    *    mandatory: open() and FileIO_ respect lock.
    *    "best": downgrades to advisory or mandatory based on OS support
    */
   if ((*access & FILEIO_OPEN_EXCLUSIVE_LOCK) != 0) {
      *access &= ~FILEIO_OPEN_EXCLUSIVE_LOCK;
      *access |= FILEIO_OPEN_LOCK_MANDATORY;
   }
   if ((*access & FILEIO_OPEN_LOCK_BEST) != 0) {
      /* "Best effort" bit: mandatory if OS supports, advisory otherwise */
      *access &= ~FILEIO_OPEN_LOCK_BEST;
      if (HostType_OSIsVMK()) {
         *access |= FILEIO_OPEN_LOCK_MANDATORY;
      } else {
         *access |= FILEIO_OPEN_LOCK_ADVISORY;
      }
   }

   /* Only one lock type (or none at all) allowed */
   ASSERT(((*access & FILEIO_OPEN_LOCK_ADVISORY) == 0) ||
          ((*access & FILEIO_OPEN_LOCK_MANDATORY) == 0));
}


/*
 *----------------------------------------------------------------------
 *
 * FileIO_Lock --
 *
 *      Call the FileLock module to lock the given file.
 *
 * Results:
 *      FILEIO_ERROR               A serious error occured.
 *      FILEIO_SUCCESS             All is well
 *      FILEIO_LOCK_FAILED         Requested lock on file was not acquired
 *      FILEIO_FILE_NOT_FOUND      Unable to find the specified file
 *      FILEIO_NO_PERMISSION       Permissions issues
 *      FILEIO_FILE_NAME_TOO_LONG  The path name is too long
 *
 * Side effects:
 *      None
 *
 *----------------------------------------------------------------------
 */

FileIOResult
FileIO_Lock(FileIODescriptor *file,  // IN/OUT:
            int access)              // IN:
{
   FileIOResult ret = FILEIO_SUCCESS;

   /*
    * Lock the file if necessary.
    */

   ASSERT(file);
   ASSERT(file->lockToken == NULL);

   FileIOResolveLockBits(&access);
   ASSERT((access & FILEIO_OPEN_LOCKED) == 0);

#if !defined(__FreeBSD__) && !defined(sun)
   if ((access & FILEIO_OPEN_LOCK_MANDATORY) != 0) {
      /* Mandatory file locks are available only when opening a file */
      ret = FILEIO_LOCK_FAILED;
   } else if ((access & FILEIO_OPEN_LOCK_ADVISORY) != 0) {
      int err = 0;

      file->lockToken = FileLock_Lock(file->fileName,
                                      (access & FILEIO_OPEN_ACCESS_WRITE) == 0,
                                      FILELOCK_DEFAULT_WAIT,
                                      &err,
                                      NULL);

      if (file->lockToken == NULL) {
         /* Describe the lock not acquired situation in detail */
         Warning(LGPFX" %s on '%s' failed: %s\n",
                 __FUNCTION__, UTF8(file->fileName),
                 (err == 0) ? "Lock timed out" : strerror(err));

         /* Return a serious failure status if the locking code did */
         switch (err) {
         case 0:             // File is currently locked
         case EROFS:         // Attempt to lock for write on RO FS
            ret = FILEIO_LOCK_FAILED;
            break;
         case ENAMETOOLONG:  // Path is too long
            ret = FILEIO_FILE_NAME_TOO_LONG;
            break;
         case ENOENT:        // No such file or directory
            ret = FILEIO_FILE_NOT_FOUND;
            break;
         case EACCES:       // Permissions issues
            ret = FILEIO_NO_PERMISSION;
            break;
         default:            // Some sort of locking error
            ret = FILEIO_ERROR;
         }
      }
   }
#endif // !__FreeBSD__ && !sun

   return ret;
}


/*
 *----------------------------------------------------------------------
 *
 * FileIO_UnLock --
 *
 *      Call the FileLock module to unlock the given file.
 *
 * Results:
 *      FILEIO_SUCCESS  All is well
 *      FILEIO_ERROR    A serious error occured.
 *
 * Side effects:
 *      None
 *
 *----------------------------------------------------------------------
 */

FileIOResult
FileIO_Unlock(FileIODescriptor *file)  // IN/OUT:
{
   FileIOResult ret = FILEIO_SUCCESS;

   ASSERT(file);

#if !defined(__FreeBSD__) && !defined(sun)
   if (file->lockToken != NULL) {
      int err = 0;

      if (!FileLock_Unlock(file->lockToken, &err, NULL)) {
         Warning(LGPFX" %s on '%s' failed: %s\n",
                 __FUNCTION__, UTF8(file->fileName), strerror(err));

         ret = FILEIO_ERROR;
      }

      file->lockToken = NULL;
   }
#else
   ASSERT(file->lockToken == NULL);
#endif // !__FreeBSD__ && !sun

   return ret;
}


/*
 *----------------------------------------------------------------------
 *
 * FileIO_GetSize --
 *
 *      Get size of file.
 *
 * Results:
 *      Size of file or -1.
 *
 * Side effects:
 *      errno is set on error.
 *
 *----------------------------------------------------------------------
 */

int64
FileIO_GetSize(const FileIODescriptor *fd)  // IN:
{
   int64 logicalBytes;

   return (FileIO_GetAllocSize(fd, &logicalBytes, NULL) != FILEIO_SUCCESS) ?
      -1 : logicalBytes;
}


/*
 *----------------------------------------------------------------------
 *
 * FileIO_GetSizeByPath --
 *
 *      Get size of a file specified by path. 
 *
 * Results:
 *      Size of file or -1.
 *
 * Side effects:
 *      errno is set on error
 *
 *----------------------------------------------------------------------
 */

int64
FileIO_GetSizeByPath(ConstUnicode pathName)  // IN:
{
   int64 logicalBytes;

   return (FileIO_GetAllocSizeByPath(pathName, &logicalBytes, NULL) !=
      FILEIO_SUCCESS) ? -1 : logicalBytes;
}


/*
 *----------------------------------------------------------------------
 *
 * FileIO_Filename --
 *
 *      Returns the filename that was used to open a FileIODescriptor
 *
 * Results:
 *      Filename. You DON'T own the memory - use Unicode_Duplicate if
 *      you want to keep it for yourself. In particular, if the file
 *      gets closed the string will almost certainly become invalid.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

ConstUnicode
FileIO_Filename(FileIODescriptor *fd)  // IN:
{
   ASSERT(fd);

   return fd->fileName;
}


/*
 *----------------------------------------------------------------------
 *
 * FileIO_CloseAndUnlink
 *
 *      Closes and unlinks the file associated with a FileIODescriptor.
 *
 * Results:
 *      TRUE: An error occurred.
 *      FALSE: The file was closed and unlinked.
 *
 * Side effects:
 *      File is probably closed and unlinked.
 *
 *----------------------------------------------------------------------
 */

Bool
FileIO_CloseAndUnlink(FileIODescriptor *fd)  // IN:
{
   Unicode path;
   Bool ret;

   ASSERT(fd);
   ASSERT(FileIO_IsValid(fd));

   path = Unicode_Duplicate(fd->fileName);
   ret = FileIO_Close(fd) || File_Unlink(path);
   Unicode_Free(path);

   return ret;
}


#if defined(_WIN32) || defined(__linux__) || defined(__APPLE__) || \
    defined(__FreeBSD__) || defined(sun)
/*
 *----------------------------------------------------------------------
 *
 * FileIO_Pread --
 *
 *      Reads from a file starting at a specified offset.
 *
 *      Note: This function may update the file pointer so you will need to
 *      call FileIO_Seek before calling FileIO_Read/Write afterwards.
 *
 * Results:
 *      FILEIO_SUCCESS, FILEIO_ERROR
 *
 * Side effects:
 *      None
 *
 *----------------------------------------------------------------------
 */

FileIOResult
FileIO_Pread(FileIODescriptor *fd,  // IN: File descriptor
             void *buf,             // IN: Buffer to read into
             size_t len,            // IN: Length of the buffer
             uint64 offset)         // IN: Offset to start reading
{
   struct iovec iov;

   ASSERT(fd);

   iov.iov_base = buf;
   iov.iov_len = len;

   return FileIO_Preadv(fd, &iov, 1, offset, len);
}


/*
 *----------------------------------------------------------------------
 *
 * FileIO_Pwrite --
 *
 *      Writes to a file starting at a specified offset.
 *
 *      Note: This function may update the file pointer so you will need to
 *      call FileIO_Seek before calling FileIO_Read/Write afterwards.
 *
 * Results:
 *      FILEIO_SUCCESS, FILEIO_ERROR
 *
 * Side effects:
 *      None
 *
 *----------------------------------------------------------------------
 */

FileIOResult
FileIO_Pwrite(FileIODescriptor *fd,  // IN: File descriptor
              void const *buf,       // IN: Buffer to write from
              size_t len,            // IN: Length of the buffer
              uint64 offset)         // IN: Offset to start writing
{
   struct iovec iov;

   ASSERT(fd);

   /* The cast is safe because FileIO_Pwritev() will not write to '*buf'. */
   iov.iov_base = (void *)buf;
   iov.iov_len = len;

   return FileIO_Pwritev(fd, &iov, 1, offset, len);
}
#endif


#if defined(sun) && __GNUC__ < 3
/*
 *-----------------------------------------------------------------------------
 *
 * FileIO_IsSuccess --
 *
 *      XXX: See comment in fileIO.h.  For reasonable compilers, this
 *      function is implemented as "static inline" in fileIO.h; for
 *      unreasonable compilers, it can't be static so we implement it here.
 *
 * Results:
 *      TRUE if the input indicates success.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

Bool
FileIO_IsSuccess(FileIOResult res)  // IN:
{
   return res == FILEIO_SUCCESS;
}
#endif


/*
 *-----------------------------------------------------------------------------
 *
 * FileIOAtomicTempPath
 *
 *      Return a temp path name in the same directory as the argument file.
 *      The path is the full path of the source file with a '~' appended.
 *      The caller must free the path when done.
 *
 * Results:
 *      Unicode path if successful, NULL on failure.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static Unicode 
FileIOAtomicTempPath(FileIODescriptor *fileFD)  // IN:
{
   Unicode path;
   Unicode srcPath;

   ASSERT(FileIO_IsValid(fileFD));

   srcPath = File_FullPath(FileIO_Filename(fileFD));
   if (!srcPath) {
      Log("%s: File_FullPath of '%s' failed.\n", __FUNCTION__,
          FileIO_Filename(fileFD));
      return NULL;
   }
   path = Unicode_Join(srcPath, "~", NULL);
   Unicode_Free(srcPath);

   return path;
}


/*
 *-----------------------------------------------------------------------------
 *
 * FileIO_AtomicTempFile
 *
 *      Create a temp file in the same directory as the argument file. 
 *      On non-Windows attempts to create the temp file with the same
 *      permissions and owner/group as the argument file.
 *
 * Results:
 *      FileIOResult of call that failed or FILEIO_SUCCESS
 *
 * Side effects:
 *      Creates a new file.
 *
 *-----------------------------------------------------------------------------
 */

FileIOResult
FileIO_AtomicTempFile(FileIODescriptor *fileFD,  // IN:
                      FileIODescriptor *tempFD)  // OUT:
{
   Unicode tempPath = NULL;
   int permissions;
   FileIOResult status;
#if !defined(_WIN32)
   int ret;
   struct stat stbuf;
#endif

   ASSERT(FileIO_IsValid(fileFD));
   ASSERT(tempFD && !FileIO_IsValid(tempFD));

   tempPath = FileIOAtomicTempPath(fileFD);
   if (!tempPath) {
      status = FILEIO_ERROR;
      goto bail;
   }

#if defined(_WIN32)
   permissions = 0;
   File_UnlinkIfExists(tempPath);
#else
   if (fstat(fileFD->posix, &stbuf)) {
      Log("%s: Failed to fstat '%s', errno: %d.\n", __FUNCTION__,
          FileIO_Filename(fileFD), errno);
      ASSERT(!vmx86_server); // For APD, hosted can fall-back and write directly
      status = FILEIO_ERROR;
      goto bail;
   }
   permissions = stbuf.st_mode;

   /* Do a "cleanup" unlink in case some previous process left a temp file around */
   ret = Posix_Unlink(tempPath);
   if (ret != 0 && errno != ENOENT) { /* ENOENT is expected, file should not exist */
      Log("%s: Failed to unlink temporary file, errno: %d\n",
          __FUNCTION__, errno);
      /* Fall through; FileIO_Create will report the actual error */
   }
#endif

   status = FileIO_Create(tempFD, tempPath,
                          FILEIO_ACCESS_READ | FILEIO_ACCESS_WRITE,
                          FILEIO_OPEN_CREATE_SAFE, permissions);
   if (!FileIO_IsSuccess(status)) {
      Log("%s: Failed to create temporary file, err: %d\n", __FUNCTION__,
          Err_Errno());
      goto bail;
   }

#if !defined(_WIN32)
   /*
    * On ESX we always use the vmkernel atomic file swap primitive, so
    * there's no need to set the permissions and owner of the temp file.
    */

   if (!HostType_OSIsVMK()) {
      if (fchmod(tempFD->posix, stbuf.st_mode)) {
         Log("%s: Failed to chmod temporary file, errno: %d\n",
             __FUNCTION__, errno);
         status = FILEIO_ERROR;
         goto bail;
      }
      if (fchown(tempFD->posix, stbuf.st_uid, stbuf.st_gid)) {
         Log("%s: Failed to chown temporary file, errno: %d\n",
             __FUNCTION__, errno);
         status = FILEIO_ERROR;
         goto bail;
      }
   }
#endif

   Unicode_Free(tempPath);
   return FILEIO_SUCCESS;

bail:
   ASSERT(!FileIO_IsSuccess(status));
   if (FileIO_IsValid(tempFD)) {
      FileIO_Close(tempFD);
#if defined(_WIN32)
      File_UnlinkIfExists(tempPath);
#else
      ret = Posix_Unlink(tempPath);
      if (ret != 0) {
         Log("%s: Failed to clean up temporary file, errno: %d\n",
             __FUNCTION__, errno);
      }
      ASSERT(ret == 0);
#endif
   }
   Unicode_Free(tempPath);
   return status;
}


/*
 *-----------------------------------------------------------------------------
 *
 * FileIO_AtomicUpdate --
 *
 *      On ESX when the target files reside on vmfs, exchanges the contents
 *      of two files using code modeled from VmkfsLib_SwapFiles.  Both "curr"
 *      and "new" are left open.
 *
 *      On ESX when the target files reside on NFS, and on hosted products,
 *      uses rename to swap files, so "new" becomes "curr", and path to "new"
 *      no longer exists on success.
 *
 *      On success the caller must call FileIO_IsValid on newFD to verify it
 *	is still open before using it again.
 *
 * Results:
 *      TRUE if successful, FALSE on failure.
 *
 * Side effects:
 *      Disk I/O.
 *
 *-----------------------------------------------------------------------------
 */


Bool
FileIO_AtomicUpdate(FileIODescriptor *newFD,   // IN/OUT: file IO descriptor
                    FileIODescriptor *currFD)  // IN/OUT: file IO descriptor
{
   char *currPath;
   char *newPath;
   uint32 currAccess;
   uint32 newAccess;
   Bool ret = FALSE;
   FileIOResult status;

   ASSERT(FileIO_IsValid(newFD));
   ASSERT(FileIO_IsValid(currFD));

   if (HostType_OSIsVMK()) {
#if defined(VMX86_SERVER)
      FS_SwapFilesArgs *args = NULL;
      char *dirName = NULL;
      char *fileName = NULL;
      char *dstDirName = NULL;
      char *dstFileName = NULL;
      int savedErrno;
      int fd;

      currPath = File_FullPath(FileIO_Filename(currFD));
      newPath = File_FullPath(FileIO_Filename(newFD));

      ASSERT(currPath);
      ASSERT(newPath);

      File_GetPathName(newPath, &dirName, &fileName);
      File_GetPathName(currPath, &dstDirName, &dstFileName);

      ASSERT(dirName && *dirName);
      ASSERT(fileName && *fileName);
      ASSERT(dstDirName && *dstDirName);
      ASSERT(dstFileName && *dstFileName);
      ASSERT(!strcmp(dirName, dstDirName));

      args = (FS_SwapFilesArgs *) Util_SafeCalloc(1, sizeof(*args));
      if (Str_Snprintf(args->srcFile, sizeof(args->srcFile), "%s",
                       fileName) < 0) {
         Log("%s: Path too long \"%s\".\n", __FUNCTION__, fileName);
         goto swapdone;
      }
      if (Str_Snprintf(args->dstFilePath, sizeof(args->dstFilePath), "%s/%s",
                       dstDirName, dstFileName) < 0) {
         Log("%s: Path too long \"%s\".\n", __FUNCTION__, dstFileName);
         goto swapdone;
      }

      /*
       * Issue the ioctl on the directory rather than on the file,
       * because the file could be open.
       */

      fd = Posix_Open(dirName, O_RDONLY);
      if (fd < 0) {
         Log("%s: Open failed \"%s\" %d.\n", __FUNCTION__, dirName,
             errno);
         ASSERT_BUG_DEBUGONLY(615124, errno != EBUSY);
         goto swapdone;
      }

      savedErrno = 0;
      if (ioctl(fd, IOCTLCMD_VMFS_SWAP_FILES, args) != 0) {
         savedErrno = errno;
         if (errno != ENOSYS) {
            Log("%s: ioctl failed %d.\n", __FUNCTION__, errno);
            ASSERT_BUG_DEBUGONLY(615124, errno != EBUSY);
         }
      } else {
         ret = TRUE;
      }

      close(fd);

      /*
       * Did we fail because we are on NFS?
       */
      if (savedErrno == ENOSYS) {
         /*
          * NFS allows renames of locked files, even if both files
          * are locked.  The file lock follows the file handle, not
          * the name, so after the rename we can swap the underlying
          * file descriptors instead of closing and reopening the
          * target file.
          *
          * This is different than the hosted path below because
          * ESX uses native file locks and hosted does not.
          */

         if (File_Rename(newPath, currPath)) {
            Log("%s: rename of '%s' to '%s' failed %d.\n",
                newPath, currPath, __FUNCTION__, errno);
            goto swapdone;
         }
         ret = TRUE;
         fd = newFD->posix;
         newFD->posix = currFD->posix;
         currFD->posix = fd;
         FileIO_Close(newFD);
      }

swapdone:
      free(args);
      free(dirName);
      free(fileName);
      free(dstDirName);
      free(dstFileName);
      free(currPath);
      free(newPath);

      return ret;
#else
      NOT_REACHED();
#endif
   }

   currPath = Unicode_Duplicate(FileIO_Filename(currFD));
   newPath = Unicode_Duplicate(FileIO_Filename(newFD));

   newAccess = newFD->flags;
   currAccess = currFD->flags;

   FileIO_Close(newFD);

   /*
    * The current file needs to be closed and reopened,
    * but we don't want to drop the file lock by calling 
    * FileIO_Close() on it.  Instead, use native close primitives.
    * We'll reopen it later with a temp FileIODescriptor, and
    * swap the file descriptor/handle.  Set the descriptor/handle
    * to an invalid value while we're in the middle of transferring
    * ownership.
    */

#if defined(_WIN32)
   CloseHandle(currFD->win32);
   currFD->win32 = INVALID_HANDLE_VALUE;
#else
   close(currFD->posix);
   currFD->posix = -1;
#endif
   if (File_RenameRetry(newPath, currPath, 10)) {
      goto bail;
   }

   ret = TRUE;
   
bail:

   /*
    * XXX - We shouldn't drop the file lock here.
    *       Need to implement FileIO_Reopen to close
    *       and reopen without dropping the lock.
    */

   FileIO_Close(currFD);  // XXX - PR 769296

   status = FileIO_Open(currFD, currPath, currAccess, 0);
   if (!FileIO_IsSuccess(status)) {
      Panic("Failed to reopen dictionary file.\n");
   }

   Unicode_Free(currPath);
   Unicode_Free(newPath);
   return ret;
}