2 This file is part of GNUnet.
3 (C) 2001, 2002, 2005, 2006, 2009 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
23 * @brief disk IO convenience methods
24 * @author Christian Grothoff
29 #include "gnunet_common.h"
30 #include "gnunet_directories.h"
31 #include "gnunet_disk_lib.h"
32 #include "gnunet_scheduler_lib.h"
33 #include "gnunet_strings_lib.h"
38 * Block size for IO for copying files.
40 #define COPY_BLK_SIZE 65536
44 #if defined(LINUX) || defined(CYGWIN)
47 #if defined(SOMEBSD) || defined(DARWIN)
48 #include <sys/param.h>
49 #include <sys/mount.h>
52 #include <sys/types.h>
53 #include <sys/statvfs.h>
56 #define _IFMT 0170000 /* type of file */
57 #define _IFLNK 0120000 /* symbolic link */
58 #define S_ISLNK(m) (((m)&_IFMT) == _IFLNK)
60 #error PORT-ME: need to port statfs (how much space is left on the drive?)
66 #if !defined(SOMEBSD) && !defined(DARWIN) && !defined(WINDOWS)
70 #include <sys/statvfs.h>
75 * Handle used to manage a pipe.
77 struct GNUNET_DISK_PipeHandle
80 * File descriptors for the pipe.
82 struct GNUNET_DISK_FileHandle *fd[2];
87 * Closure for the recursion to determine the file size
90 struct GetFileSizeData
93 * Set to the total file size.
98 * GNUNET_YES if symbolic links should be included.
100 int include_sym_links;
105 * Iterate over all files in the given directory and
106 * accumulate their size.
108 * @param cls closure of type "struct GetFileSizeData"
109 * @param fn current filename we are looking at
110 * @return GNUNET_SYSERR on serious errors, otherwise GNUNET_OK
113 getSizeRec (void *cls, const char *fn)
115 struct GetFileSizeData *gfsd = cls;
123 if (0 != STAT64 (fn, &buf))
125 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat64", fn);
126 return GNUNET_SYSERR;
129 if (0 != STAT (fn, &buf))
131 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", fn);
132 return GNUNET_SYSERR;
135 if ((!S_ISLNK (buf.st_mode)) || (gfsd->include_sym_links == GNUNET_YES))
136 gfsd->total += buf.st_size;
137 if ((S_ISDIR (buf.st_mode)) &&
138 (0 == ACCESS (fn, X_OK)) &&
139 ((!S_ISLNK (buf.st_mode)) || (gfsd->include_sym_links == GNUNET_YES)))
141 if (GNUNET_SYSERR == GNUNET_DISK_directory_scan (fn, &getSizeRec, gfsd))
142 return GNUNET_SYSERR;
149 * Checks whether a handle is invalid
151 * @param h handle to check
152 * @return GNUNET_YES if invalid, GNUNET_NO if valid
155 GNUNET_DISK_handle_invalid (const struct GNUNET_DISK_FileHandle *h)
158 return ((!h) || (h->h == INVALID_HANDLE_VALUE)) ? GNUNET_YES : GNUNET_NO;
160 return ((!h) || (h->fd == -1)) ? GNUNET_YES : GNUNET_NO;
166 * Move the read/write pointer in a file
168 * @param h handle of an open file
169 * @param offset position to move to
170 * @param whence specification to which position the offset parameter relates to
171 * @return the new position on success, GNUNET_SYSERR otherwise
174 GNUNET_DISK_file_seek (const struct GNUNET_DISK_FileHandle * h, off_t offset,
175 enum GNUNET_DISK_Seek whence)
180 return GNUNET_SYSERR;
185 static DWORD t[] = {[GNUNET_DISK_SEEK_SET] = FILE_BEGIN,
186 [GNUNET_DISK_SEEK_CUR] = FILE_CURRENT,[GNUNET_DISK_SEEK_END] = FILE_END
189 ret = SetFilePointer (h->h, offset, NULL, t[whence]);
190 if (ret == INVALID_SET_FILE_POINTER)
192 SetErrnoFromWinError (GetLastError ());
193 return GNUNET_SYSERR;
197 static int t[] = {[GNUNET_DISK_SEEK_SET] = SEEK_SET,
198 [GNUNET_DISK_SEEK_CUR] = SEEK_CUR,[GNUNET_DISK_SEEK_END] = SEEK_END
201 return lseek (h->fd, offset, t[whence]);
207 * Get the size of the file (or directory) of the given file (in
210 * @param filename name of the file or directory
211 * @param size set to the size of the file (or,
212 * in the case of directories, the sum
213 * of all sizes of files in the directory)
214 * @param includeSymLinks should symbolic links be
216 * @return GNUNET_SYSERR on error, GNUNET_OK on success
219 GNUNET_DISK_file_size (const char *filename,
220 uint64_t * size, int includeSymLinks)
222 struct GetFileSizeData gfsd;
225 GNUNET_assert (size != NULL);
227 gfsd.include_sym_links = includeSymLinks;
228 ret = getSizeRec (&gfsd, filename);
235 * Obtain some unique identifiers for the given file
236 * that can be used to identify it in the local system.
237 * This function is used between GNUnet processes to
238 * quickly check if two files with the same absolute path
239 * are actually identical. The two processes represent
240 * the same peer but may communicate over the network
241 * (and the file may be on an NFS volume). This function
242 * may not be supported on all operating systems.
244 * @param filename name of the file
245 * @param dev set to the device ID
246 * @param ino set to the inode ID
247 * @return GNUNET_OK on success
250 GNUNET_DISK_file_get_identifiers (const char *filename,
251 uint64_t * dev, uint64_t * ino)
257 if ((0 == stat (filename, &sbuf)) && (0 == statvfs (filename, &fbuf)))
259 *dev = (uint64_t) fbuf.f_fsid;
260 *ino = (uint64_t) sbuf.st_ino;
267 if ( (0 == stat (filename, &sbuf)) &&
268 (0 == statfs (filename, &fbuf) ) )
270 *dev = ((uint64_t) fbuf.f_fsid.val[0]) << 32 || ((uint64_t) fbuf.f_fsid.val[1]);
271 *ino = (uint64_t) sbuf.st_ino;
275 // FIXME NILS: test this
276 struct GNUNET_DISK_FileHandle *fh;
277 BY_HANDLE_FILE_INFORMATION info;
280 fh = GNUNET_DISK_file_open(filename, GNUNET_DISK_OPEN_READ, 0);
282 return GNUNET_SYSERR;
283 succ = GetFileInformationByHandle(fh->h, &info);
284 GNUNET_DISK_file_close(fh);
287 *dev = info.dwVolumeSerialNumber;
288 *ino = ((info.nFileIndexHigh << sizeof(DWORD)) | info.nFileIndexLow);
292 return GNUNET_SYSERR;
295 return GNUNET_SYSERR;
300 * Create an (empty) temporary file on disk. If the given name is not
301 * an absolute path, the current 'TMPDIR' will be prepended. In any case,
302 * 6 random characters will be appended to the name to create a unique
305 * @param t component to use for the name;
306 * does NOT contain "XXXXXX" or "/tmp/".
307 * @return NULL on error, otherwise name of fresh
308 * file on disk in directory for temporary files
311 GNUNET_DISK_mktemp (const char *t)
318 if ( (t[0] != '/') &&
321 tmpdir = getenv ("TMPDIR");
322 tmpdir = tmpdir ? tmpdir : "/tmp";
323 GNUNET_asprintf (&tmpl, "%s/%s%s", tmpdir, t, "XXXXXX");
327 GNUNET_asprintf (&tmpl, "%s%s", t, "XXXXXX");
330 fn = (char *) GNUNET_malloc (MAX_PATH + 1);
331 if (ERROR_SUCCESS != plibc_conv_to_win_path (tmpl, fn))
344 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "mkstemp", fn);
349 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "close", fn);
355 * Get the number of blocks that are left on the partition that
356 * contains the given file (for normal users).
358 * @param part a file on the partition to check
359 * @return -1 on errors, otherwise the number of free blocks
362 GNUNET_DISK_get_blocks_available (const char *part)
367 if (0 != statvfs (part, &buf))
369 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "statfs", part);
379 path = GNUNET_STRINGS_filename_expand (part);
382 memcpy (szDrive, path, 3);
385 if (!GetDiskFreeSpace (szDrive, &dwDummy, &dwDummy, &dwBlocks, &dwDummy))
387 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
388 _("`%s' failed for drive `%s': %u\n"),
389 "GetDiskFreeSpace", szDrive, GetLastError ());
396 if (0 != statfs (part, &s))
398 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "statfs", part);
407 * Test if "fil" is a directory.
408 * Will not print an error message if the directory
409 * does not exist. Will log errors if GNUNET_SYSERR is
410 * returned (i.e., a file exists with the same name).
412 * @param fil filename to test
413 * @return GNUNET_YES if yes, GNUNET_NO if not, GNUNET_SYSERR if it
417 GNUNET_DISK_directory_test (const char *fil)
419 struct stat filestat;
422 ret = STAT (fil, &filestat);
427 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", fil);
428 return GNUNET_SYSERR;
432 if (!S_ISDIR (filestat.st_mode))
434 if (ACCESS (fil, R_OK | X_OK) < 0)
436 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "access", fil);
437 return GNUNET_SYSERR;
443 * Check that fil corresponds to a filename
444 * (of a file that exists and that is not a directory).
446 * @param fil filename to check
447 * @return GNUNET_YES if yes, GNUNET_NO if not a file, GNUNET_SYSERR if something
448 * else (will print an error message in that case, too).
451 GNUNET_DISK_file_test (const char *fil)
453 struct stat filestat;
457 rdir = GNUNET_STRINGS_filename_expand (fil);
459 return GNUNET_SYSERR;
461 ret = STAT (rdir, &filestat);
466 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", rdir);
468 return GNUNET_SYSERR;
473 if (!S_ISREG (filestat.st_mode))
478 if (ACCESS (rdir, R_OK) < 0)
480 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "access", rdir);
482 return GNUNET_SYSERR;
490 * Implementation of "mkdir -p"
491 * @param dir the directory to create
492 * @returns GNUNET_OK on success, GNUNET_SYSERR on failure
495 GNUNET_DISK_directory_create (const char *dir)
502 rdir = GNUNET_STRINGS_filename_expand (dir);
504 return GNUNET_SYSERR;
508 pos = 1; /* skip heading '/' */
510 /* Local or Network path? */
511 if (strncmp (rdir, "\\\\", 2) == 0)
516 if (rdir[pos] == '\\')
526 pos = 3; /* strlen("C:\\") */
531 if ((rdir[pos] == DIR_SEPARATOR) || (pos == len))
534 ret = GNUNET_DISK_directory_test (rdir);
535 if (ret == GNUNET_SYSERR)
538 return GNUNET_SYSERR;
540 if (ret == GNUNET_NO)
543 ret = mkdir (rdir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); /* 755 */
547 if ((ret != 0) && (errno != EEXIST))
549 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "mkdir",
552 return GNUNET_SYSERR;
555 rdir[pos] = DIR_SEPARATOR;
565 * Create the directory structure for storing
568 * @param filename name of a file in the directory
569 * @returns GNUNET_OK on success,
570 * GNUNET_SYSERR on failure,
571 * GNUNET_NO if the directory
572 * exists but is not writeable for us
575 GNUNET_DISK_directory_create_for_file (const char *filename)
581 rdir = GNUNET_STRINGS_filename_expand (filename);
583 return GNUNET_SYSERR;
585 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
588 ret = GNUNET_DISK_directory_create (rdir);
589 if ((ret == GNUNET_OK) && (0 != ACCESS (rdir, W_OK)))
597 * Read the contents of a binary file into a buffer.
598 * @param h handle to an open file
599 * @param result the buffer to write the result to
600 * @param len the maximum number of bytes to read
601 * @return the number of bytes read on success, GNUNET_SYSERR on failure
604 GNUNET_DISK_file_read (const struct GNUNET_DISK_FileHandle * h, void *result,
610 return GNUNET_SYSERR;
616 if (!ReadFile (h->h, result, len, &bytesRead, NULL))
618 SetErrnoFromWinError (GetLastError ());
619 return GNUNET_SYSERR;
623 return read (h->fd, result, len);
629 * Read the contents of a binary file into a buffer.
631 * @param fn file name
632 * @param result the buffer to write the result to
633 * @param len the maximum number of bytes to read
634 * @return number of bytes read, GNUNET_SYSERR on failure
637 GNUNET_DISK_fn_read (const char *fn, void *result, size_t len)
639 struct GNUNET_DISK_FileHandle *fh;
642 fh = GNUNET_DISK_file_open (fn, GNUNET_DISK_OPEN_READ,
643 GNUNET_DISK_PERM_NONE);
645 return GNUNET_SYSERR;
646 ret = GNUNET_DISK_file_read (fh, result, len);
647 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
654 * Write a buffer to a file.
655 * @param h handle to open file
656 * @param buffer the data to write
657 * @param n number of bytes to write
658 * @return number of bytes written on success, GNUNET_SYSERR on error
661 GNUNET_DISK_file_write (const struct GNUNET_DISK_FileHandle * h,
662 const void *buffer, size_t n)
667 return GNUNET_SYSERR;
673 if (!WriteFile (h->h, buffer, n, &bytesWritten, NULL))
675 SetErrnoFromWinError (GetLastError ());
676 return GNUNET_SYSERR;
680 return write (h->fd, buffer, n);
685 * Write a buffer to a file. If the file is longer than the
686 * number of bytes that will be written, it will be truncated.
688 * @param fn file name
689 * @param buffer the data to write
690 * @param n number of bytes to write
691 * @param mode file permissions
692 * @return number of bytes written on success, GNUNET_SYSERR on error
695 GNUNET_DISK_fn_write (const char *fn, const void *buffer,
696 size_t n, enum GNUNET_DISK_AccessPermissions mode)
698 struct GNUNET_DISK_FileHandle *fh;
701 fh = GNUNET_DISK_file_open (fn,
702 GNUNET_DISK_OPEN_WRITE
703 | GNUNET_DISK_OPEN_TRUNCATE
704 | GNUNET_DISK_OPEN_CREATE, mode);
706 return GNUNET_SYSERR;
707 ret = GNUNET_DISK_file_write (fh, buffer, n);
708 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
713 * Scan a directory for files.
715 * @param dirName the name of the directory
716 * @param callback the method to call for each file,
717 * can be NULL, in that case, we only count
718 * @param callback_cls closure for callback
719 * @return the number of files found, GNUNET_SYSERR on error or
720 * ieration aborted by callback returning GNUNET_SYSERR
723 GNUNET_DISK_directory_scan (const char *dirName,
724 GNUNET_FileNameCallback callback,
728 struct dirent *finfo;
733 unsigned int name_len;
736 GNUNET_assert (dirName != NULL);
737 dname = GNUNET_STRINGS_filename_expand (dirName);
739 return GNUNET_SYSERR;
740 while ((strlen (dname) > 0) && (dname[strlen (dname) - 1] == DIR_SEPARATOR))
741 dname[strlen (dname) - 1] = '\0';
742 if (0 != STAT (dname, &istat))
744 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", dname);
746 return GNUNET_SYSERR;
748 if (!S_ISDIR (istat.st_mode))
750 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
751 _("Expected `%s' to be a directory!\n"), dirName);
753 return GNUNET_SYSERR;
756 dinfo = OPENDIR (dname);
757 if ((errno == EACCES) || (dinfo == NULL))
759 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "opendir", dname);
763 return GNUNET_SYSERR;
766 n_size = strlen (dname) + name_len + 2;
767 name = GNUNET_malloc (n_size);
768 while ((finfo = readdir (dinfo)) != NULL)
770 if ((0 == strcmp (finfo->d_name, ".")) ||
771 (0 == strcmp (finfo->d_name, "..")))
773 if (callback != NULL)
775 if (name_len < strlen (finfo->d_name))
778 name_len = strlen (finfo->d_name);
779 n_size = strlen (dname) + name_len + 2;
780 name = GNUNET_malloc (n_size);
782 /* dname can end in "/" only if dname == "/";
783 if dname does not end in "/", we need to add
784 a "/" (otherwise, we must not!) */
785 GNUNET_snprintf (name,
789 (strcmp (dname, DIR_SEPARATOR_STR) ==
790 0) ? "" : DIR_SEPARATOR_STR, finfo->d_name);
791 if (GNUNET_OK != callback (callback_cls, name))
796 return GNUNET_SYSERR;
809 * Opaque handle used for iterating over a directory.
811 struct GNUNET_DISK_DirectoryIterator
816 struct GNUNET_SCHEDULER_Handle *sched;
819 * Function to call on directory entries.
821 GNUNET_DISK_DirectoryIteratorCallback callback;
824 * Closure for callback.
829 * Reference to directory.
839 * Next filename to process.
846 enum GNUNET_SCHEDULER_Priority priority;
852 * Task used by the directory iterator.
855 directory_iterator_task (void *cls,
856 const struct GNUNET_SCHEDULER_TaskContext *tc)
858 struct GNUNET_DISK_DirectoryIterator *iter = cls;
861 name = iter->next_name;
862 GNUNET_assert (name != NULL);
863 iter->next_name = NULL;
864 iter->callback (iter->callback_cls, iter, name, iter->dirname);
870 * This function must be called during the DiskIteratorCallback
871 * (exactly once) to schedule the task to process the next
872 * filename in the directory (if there is one).
874 * @param iter opaque handle for the iterator
875 * @param can set to GNUNET_YES to terminate the iteration early
876 * @return GNUNET_YES if iteration will continue,
877 * GNUNET_NO if this was the last entry (and iteration is complete),
878 * GNUNET_SYSERR if abort was YES
881 GNUNET_DISK_directory_iterator_next (struct GNUNET_DISK_DirectoryIterator
884 struct dirent *finfo;
886 GNUNET_assert (iter->next_name == NULL);
887 if (can == GNUNET_YES)
889 closedir (iter->directory);
890 GNUNET_free (iter->dirname);
892 return GNUNET_SYSERR;
894 while (NULL != (finfo = readdir (iter->directory)))
896 if ((0 == strcmp (finfo->d_name, ".")) ||
897 (0 == strcmp (finfo->d_name, "..")))
899 GNUNET_asprintf (&iter->next_name,
901 iter->dirname, DIR_SEPARATOR_STR, finfo->d_name);
906 GNUNET_DISK_directory_iterator_next (iter, GNUNET_YES);
909 GNUNET_SCHEDULER_add_with_priority (iter->sched,
911 &directory_iterator_task, iter);
917 * Scan a directory for files using the scheduler to run a task for
918 * each entry. The name of the directory must be expanded first (!).
919 * If a scheduler does not need to be used, GNUNET_DISK_directory_scan
920 * may provide a simpler API.
922 * @param sched scheduler to use
923 * @param prio priority to use
924 * @param dirName the name of the directory
925 * @param callback the method to call for each file
926 * @param callback_cls closure for callback
929 GNUNET_DISK_directory_iterator_start (struct GNUNET_SCHEDULER_Handle *sched,
930 enum GNUNET_SCHEDULER_Priority prio,
932 GNUNET_DISK_DirectoryIteratorCallback
933 callback, void *callback_cls)
935 struct GNUNET_DISK_DirectoryIterator *di;
937 di = GNUNET_malloc (sizeof (struct GNUNET_DISK_DirectoryIterator));
939 di->callback = callback;
940 di->callback_cls = callback_cls;
941 di->directory = OPENDIR (dirName);
942 if (di->directory == NULL)
945 callback (callback_cls, NULL, NULL, NULL);
948 di->dirname = GNUNET_strdup (dirName);
950 GNUNET_DISK_directory_iterator_next (di, GNUNET_NO);
955 * Function that removes the given directory by calling
956 * "GNUNET_DISK_directory_remove".
958 * @param unused not used
959 * @param fn directory to remove
963 remove_helper (void *unused, const char *fn)
965 (void) GNUNET_DISK_directory_remove (fn);
971 * Remove all files in a directory (rm -rf). Call with
975 * @param fileName the file to remove
976 * @return GNUNET_OK on success, GNUNET_SYSERR on error
979 GNUNET_DISK_directory_remove (const char *fileName)
983 if (0 != LSTAT (fileName, &istat))
984 return GNUNET_NO; /* file may not exist... */
985 if (UNLINK (fileName) == 0)
987 if ((errno != EISDIR) &&
988 /* EISDIR is not sufficient in all cases, e.g.
989 sticky /tmp directory may result in EPERM on BSD.
990 So we also explicitly check "isDirectory" */
991 (GNUNET_YES != GNUNET_DISK_directory_test (fileName)))
993 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "rmdir", fileName);
994 return GNUNET_SYSERR;
997 GNUNET_DISK_directory_scan (fileName, &remove_helper, NULL))
998 return GNUNET_SYSERR;
999 if (0 != RMDIR (fileName))
1001 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "rmdir", fileName);
1002 return GNUNET_SYSERR;
1011 * @param src file to copy
1012 * @param dst destination file name
1013 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1016 GNUNET_DISK_file_copy (const char *src, const char *dst)
1022 struct GNUNET_DISK_FileHandle *in;
1023 struct GNUNET_DISK_FileHandle *out;
1025 if (GNUNET_OK != GNUNET_DISK_file_size (src, &size, GNUNET_YES))
1026 return GNUNET_SYSERR;
1028 in = GNUNET_DISK_file_open (src, GNUNET_DISK_OPEN_READ,
1029 GNUNET_DISK_PERM_NONE);
1031 return GNUNET_SYSERR;
1032 out = GNUNET_DISK_file_open (dst, GNUNET_DISK_OPEN_WRITE
1033 | GNUNET_DISK_OPEN_CREATE |
1034 GNUNET_DISK_OPEN_FAILIFEXISTS,
1035 GNUNET_DISK_PERM_USER_READ |
1036 GNUNET_DISK_PERM_USER_WRITE |
1037 GNUNET_DISK_PERM_GROUP_READ |
1038 GNUNET_DISK_PERM_GROUP_WRITE);
1041 GNUNET_DISK_file_close (in);
1042 return GNUNET_SYSERR;
1044 buf = GNUNET_malloc (COPY_BLK_SIZE);
1047 len = COPY_BLK_SIZE;
1048 if (len > size - pos)
1050 if (len != GNUNET_DISK_file_read (in, buf, len))
1052 if (len != GNUNET_DISK_file_write (out, buf, len))
1057 GNUNET_DISK_file_close (in);
1058 GNUNET_DISK_file_close (out);
1062 GNUNET_DISK_file_close (in);
1063 GNUNET_DISK_file_close (out);
1064 return GNUNET_SYSERR;
1069 * @brief Removes special characters as ':' from a filename.
1070 * @param fn the filename to canonicalize
1073 GNUNET_DISK_filename_canonicalize (char *fn)
1083 if (c == '/' || c == '\\' || c == ':' || c == '*' || c == '?' ||
1084 c == '"' || c == '<' || c == '>' || c == '|')
1096 * @brief Change owner of a file
1098 * @param filename name of file to change the owner of
1099 * @param user name of the new owner
1100 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1103 GNUNET_DISK_file_change_owner (const char *filename, const char *user)
1108 pws = getpwnam (user);
1111 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1112 _("Cannot obtain information about user `%s': %s\n"),
1113 user, STRERROR (errno));
1114 return GNUNET_SYSERR;
1116 if (0 != chown (filename, pws->pw_uid, pws->pw_gid))
1117 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "chown", filename);
1124 * Lock a part of a file
1125 * @param fh file handle
1126 * @param lockStart absolute position from where to lock
1127 * @param lockEnd absolute position until where to lock
1128 * @param excl GNUNET_YES for an exclusive lock
1129 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1132 GNUNET_DISK_file_lock (struct GNUNET_DISK_FileHandle *fh, off_t lockStart,
1133 off_t lockEnd, int excl)
1138 return GNUNET_SYSERR;
1144 memset (&fl, 0, sizeof (struct flock));
1145 fl.l_type = excl ? F_WRLCK : F_RDLCK;
1146 fl.l_whence = SEEK_SET;
1147 fl.l_start = lockStart;
1150 return fcntl (fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK;
1154 memset (&o, 0, sizeof (OVERLAPPED));
1155 o.Offset = lockStart;
1157 if (!LockFileEx (fh->h, (excl ? LOCKFILE_EXCLUSIVE_LOCK : 0)
1158 | LOCKFILE_FAIL_IMMEDIATELY, 0, lockEnd - lockStart, 0,
1161 SetErrnoFromWinError (GetLastError ());
1162 return GNUNET_SYSERR;
1171 * Unlock a part of a file
1172 * @param fh file handle
1173 * @param unlockStart absolute position from where to unlock
1174 * @param unlockEnd absolute position until where to unlock
1175 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1178 GNUNET_DISK_file_unlock (struct GNUNET_DISK_FileHandle *fh, off_t unlockStart,
1184 return GNUNET_SYSERR;
1190 memset (&fl, 0, sizeof (struct flock));
1191 fl.l_type = F_UNLCK;
1192 fl.l_whence = SEEK_SET;
1193 fl.l_start = unlockStart;
1194 fl.l_len = unlockEnd;
1196 return fcntl (fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK;
1200 memset (&o, 0, sizeof (OVERLAPPED));
1201 o.Offset = unlockStart;
1203 if (!UnlockFileEx (fh->h, 0, unlockEnd - unlockStart, 0, &o))
1205 SetErrnoFromWinError (GetLastError ());
1206 return GNUNET_SYSERR;
1215 * Open a file. Note that the access permissions will only be
1216 * used if a new file is created and if the underlying operating
1217 * system supports the given permissions.
1219 * @param fn file name to be opened
1220 * @param flags opening flags, a combination of GNUNET_DISK_OPEN_xxx bit flags
1221 * @param perm permissions for the newly created file, use
1222 * GNUNET_DISK_PERM_USER_NONE if a file could not be created by this
1223 * call (because of flags)
1224 * @return IO handle on success, NULL on error
1226 struct GNUNET_DISK_FileHandle *
1227 GNUNET_DISK_file_open (const char *fn,
1228 enum GNUNET_DISK_OpenFlags flags,
1229 enum GNUNET_DISK_AccessPermissions perm)
1232 struct GNUNET_DISK_FileHandle *ret;
1243 expfn = GNUNET_STRINGS_filename_expand (fn);
1248 if (GNUNET_DISK_OPEN_READWRITE == (flags & GNUNET_DISK_OPEN_READWRITE))
1249 oflags = O_RDWR; /* note: O_RDWR is NOT always O_RDONLY | O_WRONLY */
1250 else if (flags & GNUNET_DISK_OPEN_READ)
1252 else if (flags & GNUNET_DISK_OPEN_WRITE)
1257 GNUNET_free (expfn);
1260 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1261 oflags |= (O_CREAT | O_EXCL);
1262 if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1264 if (flags & GNUNET_DISK_OPEN_APPEND)
1266 if (flags & GNUNET_DISK_OPEN_CREATE)
1268 (void) GNUNET_DISK_directory_create_for_file (expfn);
1270 if (perm & GNUNET_DISK_PERM_USER_READ)
1272 if (perm & GNUNET_DISK_PERM_USER_WRITE)
1274 if (perm & GNUNET_DISK_PERM_USER_EXEC)
1276 if (perm & GNUNET_DISK_PERM_GROUP_READ)
1278 if (perm & GNUNET_DISK_PERM_GROUP_WRITE)
1280 if (perm & GNUNET_DISK_PERM_GROUP_EXEC)
1282 if (perm & GNUNET_DISK_PERM_OTHER_READ)
1284 if (perm & GNUNET_DISK_PERM_OTHER_WRITE)
1286 if (perm & GNUNET_DISK_PERM_OTHER_EXEC)
1290 fd = open (expfn, oflags | O_LARGEFILE, mode);
1293 if (0 == (flags & GNUNET_DISK_OPEN_FAILIFEXISTS))
1294 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "open", expfn);
1296 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_DEBUG, "open", expfn);
1297 GNUNET_free (expfn);
1304 if (GNUNET_DISK_OPEN_READWRITE == (flags & GNUNET_DISK_OPEN_READWRITE))
1305 access = FILE_READ_DATA | FILE_WRITE_DATA;
1306 else if (flags & GNUNET_DISK_OPEN_READ)
1307 access = FILE_READ_DATA;
1308 else if (flags & GNUNET_DISK_OPEN_WRITE)
1309 access = FILE_WRITE_DATA;
1311 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1315 else if (flags & GNUNET_DISK_OPEN_CREATE)
1317 if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1318 disp = CREATE_ALWAYS;
1322 else if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1324 disp = TRUNCATE_EXISTING;
1328 disp = OPEN_EXISTING;
1331 /* TODO: access priviledges? */
1332 h = CreateFile (expfn, access, FILE_SHARE_DELETE | FILE_SHARE_READ
1333 | FILE_SHARE_WRITE, NULL, disp, FILE_ATTRIBUTE_NORMAL,
1335 if (h == INVALID_HANDLE_VALUE)
1337 SetErrnoFromWinError (GetLastError ());
1338 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "open", expfn);
1339 GNUNET_free (expfn);
1343 if (flags & GNUNET_DISK_OPEN_APPEND)
1344 if (SetFilePointer (h, 0, 0, FILE_END) == INVALID_SET_FILE_POINTER)
1346 SetErrnoFromWinError (GetLastError ());
1347 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "SetFilePointer",
1350 GNUNET_free (expfn);
1355 ret = GNUNET_malloc (sizeof (struct GNUNET_DISK_FileHandle));
1361 GNUNET_free (expfn);
1367 * Close an open file
1368 * @param h file handle
1369 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1372 GNUNET_DISK_file_close (struct GNUNET_DISK_FileHandle *h)
1377 return GNUNET_SYSERR;
1381 if (!CloseHandle (h->h))
1383 SetErrnoFromWinError (GetLastError ());
1384 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "close");
1386 return GNUNET_SYSERR;
1389 if (close (h->fd) != 0)
1391 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "close");
1393 return GNUNET_SYSERR;
1402 * Construct full path to a file inside of the private
1403 * directory used by GNUnet. Also creates the corresponding
1404 * directory. If the resulting name is supposed to be
1405 * a directory, end the last argument in '/' (or pass
1406 * DIR_SEPARATOR_STR as the last argument before NULL).
1408 * @param cfg configuration to use (determines HOME)
1409 * @param serviceName name of the service
1410 * @param ... is NULL-terminated list of
1411 * path components to append to the
1412 * private directory name.
1413 * @return the constructed filename
1416 GNUNET_DISK_get_home_filename (const struct GNUNET_CONFIGURATION_Handle *cfg,
1417 const char *serviceName, ...)
1423 unsigned int needed;
1426 GNUNET_CONFIGURATION_get_value_filename (cfg,
1427 serviceName, "HOME", &pfx))
1431 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1432 _("No `%s' specified for service `%s' in configuration.\n"),
1433 "HOME", serviceName);
1436 needed = strlen (pfx) + 2;
1437 if ((pfx[strlen (pfx) - 1] != '/') && (pfx[strlen (pfx) - 1] != '\\'))
1439 va_start (ap, serviceName);
1442 c = va_arg (ap, const char *);
1445 needed += strlen (c);
1446 if ((c[strlen (c) - 1] != '/') && (c[strlen (c) - 1] != '\\'))
1450 ret = GNUNET_malloc (needed);
1453 va_start (ap, serviceName);
1456 c = va_arg (ap, const char *);
1459 if ((c[strlen (c) - 1] != '/') && (c[strlen (c) - 1] != '\\'))
1460 strcat (ret, DIR_SEPARATOR_STR);
1464 if ((ret[strlen (ret) - 1] != '/') && (ret[strlen (ret) - 1] != '\\'))
1465 GNUNET_DISK_directory_create_for_file (ret);
1467 GNUNET_DISK_directory_create (ret);
1473 * Handle for a memory-mapping operation.
1475 struct GNUNET_DISK_MapHandle
1479 * Underlying OS handle.
1484 * Address where the map is in memory.
1489 * Number of bytes mapped.
1497 #define MAP_FAILED ((void *) -1)
1501 * Map a file into memory
1503 * @param h open file handle
1504 * @param m handle to the new mapping
1505 * @param access access specification, GNUNET_DISK_MAP_TYPE_xxx
1506 * @param len size of the mapping
1507 * @return pointer to the mapped memory region, NULL on failure
1510 GNUNET_DISK_file_map (const struct GNUNET_DISK_FileHandle *h,
1511 struct GNUNET_DISK_MapHandle **m,
1512 enum GNUNET_DISK_MapType access, size_t len)
1521 DWORD mapAccess, protect;
1524 if ((access & GNUNET_DISK_MAP_TYPE_READ) &&
1525 (access & GNUNET_DISK_MAP_TYPE_WRITE))
1527 protect = PAGE_READWRITE;
1528 mapAccess = FILE_MAP_ALL_ACCESS;
1530 else if (access & GNUNET_DISK_MAP_TYPE_READ)
1532 protect = PAGE_READONLY;
1533 mapAccess = FILE_MAP_READ;
1535 else if (access & GNUNET_DISK_MAP_TYPE_WRITE)
1537 protect = PAGE_READWRITE;
1538 mapAccess = FILE_MAP_WRITE;
1546 *m = GNUNET_malloc (sizeof (struct GNUNET_DISK_MapHandle));
1547 (*m)->h = CreateFileMapping (h->h, NULL, protect, 0, 0, NULL);
1548 if ((*m)->h == INVALID_HANDLE_VALUE)
1550 SetErrnoFromWinError (GetLastError ());
1555 ret = MapViewOfFile ((*m)->h, mapAccess, 0, 0, len);
1558 SetErrnoFromWinError (GetLastError ());
1559 CloseHandle ((*m)->h);
1568 if (access & GNUNET_DISK_MAP_TYPE_READ)
1570 if (access & GNUNET_DISK_MAP_TYPE_WRITE)
1572 *m = GNUNET_malloc (sizeof (struct GNUNET_DISK_MapHandle));
1573 (*m)->addr = mmap (NULL, len, prot, MAP_SHARED, h->fd, 0);
1574 GNUNET_assert (NULL != (*m)->addr);
1575 if (MAP_FAILED == (*m)->addr)
1587 * @param h mapping handle
1588 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1591 GNUNET_DISK_file_unmap (struct GNUNET_DISK_MapHandle *h)
1597 return GNUNET_SYSERR;
1601 ret = UnmapViewOfFile (h->h) ? GNUNET_OK : GNUNET_SYSERR;
1602 if (ret != GNUNET_OK)
1603 SetErrnoFromWinError (GetLastError ());
1604 if (!CloseHandle (h->h) && (ret == GNUNET_OK))
1606 ret = GNUNET_SYSERR;
1607 SetErrnoFromWinError (GetLastError ());
1610 ret = munmap (h->addr, h->len) != -1 ? GNUNET_OK : GNUNET_SYSERR;
1618 * Write file changes to disk
1619 * @param h handle to an open file
1620 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1623 GNUNET_DISK_file_sync (const struct GNUNET_DISK_FileHandle *h)
1628 return GNUNET_SYSERR;
1634 ret = FlushFileBuffers (h->h) ? GNUNET_OK : GNUNET_SYSERR;
1635 if (ret != GNUNET_OK)
1636 SetErrnoFromWinError (GetLastError ());
1638 #elif defined(FREEBSD) || defined(OPENBSD) || defined(DARWIN)
1639 return fsync (h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK;
1641 return fdatasync (h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK;
1647 * Creates an interprocess channel
1649 * @param blocking creates an asynchronous pipe if set to GNUNET_NO
1650 * @param inherit_read inherit the parent processes stdin (only for windows)
1651 * @param inherit_write inherit the parent processes stdout (only for windows)
1653 * @return handle to the new pipe, NULL on error
1655 struct GNUNET_DISK_PipeHandle *
1656 GNUNET_DISK_pipe (int blocking, int inherit_read, int inherit_write)
1658 struct GNUNET_DISK_PipeHandle *p;
1659 struct GNUNET_DISK_FileHandle *fds;
1662 GNUNET_malloc (sizeof (struct GNUNET_DISK_PipeHandle) +
1663 2 * sizeof (struct GNUNET_DISK_FileHandle));
1664 fds = (struct GNUNET_DISK_FileHandle *) &p[1];
1677 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "pipe");
1682 p->fd[0]->fd = fd[0];
1683 p->fd[1]->fd = fd[1];
1685 flags = fcntl (fd[0], F_GETFL);
1687 flags |= O_NONBLOCK;
1688 if (0 > fcntl (fd[0], F_SETFL, flags))
1690 flags = fcntl (fd[0], F_GETFD);
1691 flags |= FD_CLOEXEC;
1692 if (0 > fcntl (fd[0], F_SETFD, flags))
1695 flags = fcntl (fd[1], F_GETFL);
1697 flags |= O_NONBLOCK;
1698 if (0 > fcntl (fd[1], F_SETFL, flags))
1700 flags = fcntl (fd[1], F_GETFD);
1701 flags |= FD_CLOEXEC;
1702 if (0 > fcntl (fd[1], F_SETFD, flags))
1707 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "fcntl");
1708 GNUNET_break (0 == close (p->fd[0]->fd));
1709 GNUNET_break (0 == close (p->fd[1]->fd));
1718 ret = CreatePipe (&p->fd[0]->h, &p->fd[1]->h, NULL, 0);
1722 SetErrnoFromWinError (GetLastError ());
1725 if (!DuplicateHandle (GetCurrentProcess (), p->fd[0]->h,
1726 GetCurrentProcess (), &tmp_handle, 0, inherit_read == GNUNET_YES ? TRUE : FALSE,
1727 DUPLICATE_SAME_ACCESS))
1729 SetErrnoFromWinError (GetLastError ());
1730 CloseHandle (p->fd[0]->h);
1731 CloseHandle (p->fd[1]->h);
1735 CloseHandle (p->fd[0]->h);
1736 p->fd[0]->h = tmp_handle;
1738 if (!DuplicateHandle (GetCurrentProcess (), p->fd[1]->h,
1739 GetCurrentProcess (), &tmp_handle, 0, inherit_write == GNUNET_YES ? TRUE : FALSE,
1740 DUPLICATE_SAME_ACCESS))
1742 SetErrnoFromWinError (GetLastError ());
1743 CloseHandle (p->fd[0]->h);
1744 CloseHandle (p->fd[1]->h);
1748 CloseHandle (p->fd[1]->h);
1749 p->fd[1]->h = tmp_handle;
1755 SetNamedPipeHandleState (p->fd[0]->h, &mode, NULL, NULL);
1756 SetNamedPipeHandleState (p->fd[1]->h, &mode, NULL, NULL);
1757 /* this always fails on Windows 95, so we don't care about error handling */
1765 * Closes an interprocess channel
1767 * @param p pipe to close
1768 * @param end which end of the pipe to close
1769 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1772 GNUNET_DISK_pipe_close_end (struct GNUNET_DISK_PipeHandle *p,
1773 enum GNUNET_DISK_PipeEnd end)
1775 int ret = GNUNET_OK;
1779 if (end == GNUNET_DISK_PIPE_END_READ)
1781 if (!CloseHandle (p->fd[0]->h))
1783 SetErrnoFromWinError (GetLastError ());
1784 ret = GNUNET_SYSERR;
1786 p->fd[0]->h = INVALID_HANDLE_VALUE;
1788 else if (end == GNUNET_DISK_PIPE_END_WRITE)
1790 if (!CloseHandle (p->fd[1]->h))
1792 SetErrnoFromWinError (GetLastError ());
1793 ret = GNUNET_SYSERR;
1795 p->fd[1]->h = INVALID_HANDLE_VALUE;
1800 if (end == GNUNET_DISK_PIPE_END_READ)
1802 if (0 != close (p->fd[0]->fd))
1804 ret = GNUNET_SYSERR;
1809 else if (end == GNUNET_DISK_PIPE_END_WRITE)
1811 if (0 != close (p->fd[1]->fd))
1813 ret = GNUNET_SYSERR;
1824 * Closes an interprocess channel
1826 * @param p pipe to close
1827 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1830 GNUNET_DISK_pipe_close (struct GNUNET_DISK_PipeHandle *p)
1832 int ret = GNUNET_OK;
1836 if (!CloseHandle (p->fd[0]->h))
1838 SetErrnoFromWinError (GetLastError ());
1839 ret = GNUNET_SYSERR;
1841 if (!CloseHandle (p->fd[1]->h))
1843 SetErrnoFromWinError (GetLastError ());
1844 ret = GNUNET_SYSERR;
1849 if (p->fd[0]->fd != -1)
1851 if (0 != close (p->fd[0]->fd))
1853 ret = GNUNET_SYSERR;
1858 if (p->fd[1]->fd != -1)
1860 if (0 != close (p->fd[1]->fd))
1862 ret = GNUNET_SYSERR;
1874 * Get the handle to a particular pipe end
1877 * @param n end to access
1878 * @return handle for the respective end
1880 const struct GNUNET_DISK_FileHandle *
1881 GNUNET_DISK_pipe_handle (const struct GNUNET_DISK_PipeHandle *p,
1882 enum GNUNET_DISK_PipeEnd n)
1886 case GNUNET_DISK_PIPE_END_READ:
1887 case GNUNET_DISK_PIPE_END_WRITE:
1897 * Retrieve OS file handle
1899 * @param fh GNUnet file descriptor
1900 * @param dst destination buffer
1901 * @param dst_len length of dst
1902 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1905 GNUNET_DISK_internal_file_handle_ (const struct GNUNET_DISK_FileHandle *fh,
1906 void *dst, size_t dst_len)
1909 if (dst_len < sizeof (HANDLE))
1910 return GNUNET_SYSERR;
1911 *((HANDLE *) dst) = fh->h;
1913 if (dst_len < sizeof (int))
1914 return GNUNET_SYSERR;
1915 *((int *) dst) = fh->fd;