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 uint32_t * dev, uint64_t * ino)
257 if ((0 == stat (filename, &sbuf)) && (0 == statvfs (filename, &fbuf)))
259 *dev = (uint32_t) fbuf.f_fsid;
260 *ino = (uint64_t) sbuf.st_ino;
264 return GNUNET_SYSERR;
269 * Create an (empty) temporary file on disk.
271 * @param t component to use for the name;
272 * does NOT contain "XXXXXX" or "/tmp/".
273 * @return NULL on error, otherwise name of fresh
274 * file on disk in directory for temporary files
277 GNUNET_DISK_mktemp (const char *t)
284 tmpdir = getenv ("TMPDIR");
285 tmpdir = tmpdir ? tmpdir : "/tmp";
287 GNUNET_asprintf (&tmpl, "%s%s%s%s", tmpdir, DIR_SEPARATOR_STR, t, "XXXXXX");
289 fn = (char *) GNUNET_malloc (MAX_PATH + 1);
290 plibc_conv_to_win_path (tmpl, fn);
298 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "mkstemp", fn);
303 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "close", fn);
309 * Get the number of blocks that are left on the partition that
310 * contains the given file (for normal users).
312 * @param part a file on the partition to check
313 * @return -1 on errors, otherwise the number of free blocks
316 GNUNET_DISK_get_blocks_available (const char *part)
321 if (0 != statvfs (part, &buf))
323 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "statfs", part);
333 path = GNUNET_STRINGS_filename_expand (part);
334 memcpy (szDrive, path, 3);
337 if (!GetDiskFreeSpace (szDrive, &dwDummy, &dwDummy, &dwBlocks, &dwDummy))
339 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
340 _("`%s' failed for drive `%s': %u\n"),
341 "GetDiskFreeSpace", szDrive, GetLastError ());
348 if (0 != statfs (part, &s))
350 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "statfs", part);
359 * Test if "fil" is a directory.
360 * Will not print an error message if the directory
361 * does not exist. Will log errors if GNUNET_SYSERR is
362 * returned (i.e., a file exists with the same name).
364 * @param fil filename to test
365 * @return GNUNET_YES if yes, GNUNET_NO if not, GNUNET_SYSERR if it
369 GNUNET_DISK_directory_test (const char *fil)
371 struct stat filestat;
374 ret = STAT (fil, &filestat);
379 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", fil);
380 return GNUNET_SYSERR;
384 if (!S_ISDIR (filestat.st_mode))
386 if (ACCESS (fil, R_OK | X_OK) < 0)
388 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "access", fil);
389 return GNUNET_SYSERR;
395 * Check that fil corresponds to a filename
396 * (of a file that exists and that is not a directory).
398 * @param fil filename to check
399 * @return GNUNET_YES if yes, GNUNET_NO if not a file, GNUNET_SYSERR if something
400 * else (will print an error message in that case, too).
403 GNUNET_DISK_file_test (const char *fil)
405 struct stat filestat;
409 rdir = GNUNET_STRINGS_filename_expand (fil);
411 return GNUNET_SYSERR;
413 ret = STAT (rdir, &filestat);
418 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", rdir);
420 return GNUNET_SYSERR;
425 if (!S_ISREG (filestat.st_mode))
430 if (ACCESS (rdir, R_OK) < 0)
432 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "access", rdir);
434 return GNUNET_SYSERR;
442 * Implementation of "mkdir -p"
443 * @param dir the directory to create
444 * @returns GNUNET_OK on success, GNUNET_SYSERR on failure
447 GNUNET_DISK_directory_create (const char *dir)
454 rdir = GNUNET_STRINGS_filename_expand (dir);
456 return GNUNET_SYSERR;
460 pos = 1; /* skip heading '/' */
462 /* Local or Network path? */
463 if (strncmp (rdir, "\\\\", 2) == 0)
468 if (rdir[pos] == '\\')
478 pos = 3; /* strlen("C:\\") */
483 if ((rdir[pos] == DIR_SEPARATOR) || (pos == len))
486 ret = GNUNET_DISK_directory_test (rdir);
487 if (ret == GNUNET_SYSERR)
490 return GNUNET_SYSERR;
492 if (ret == GNUNET_NO)
495 ret = mkdir (rdir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); /* 755 */
499 if ((ret != 0) && (errno != EEXIST))
501 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "mkdir",
504 return GNUNET_SYSERR;
507 rdir[pos] = DIR_SEPARATOR;
517 * Create the directory structure for storing
520 * @param filename name of a file in the directory
521 * @returns GNUNET_OK on success,
522 * GNUNET_SYSERR on failure,
523 * GNUNET_NO if the directory
524 * exists but is not writeable for us
527 GNUNET_DISK_directory_create_for_file (const char *filename)
533 rdir = GNUNET_STRINGS_filename_expand (filename);
535 return GNUNET_SYSERR;
537 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
540 ret = GNUNET_DISK_directory_create (rdir);
541 if ((ret == GNUNET_OK) && (0 != ACCESS (rdir, W_OK)))
549 * Read the contents of a binary file into a buffer.
550 * @param h handle to an open file
551 * @param result the buffer to write the result to
552 * @param len the maximum number of bytes to read
553 * @return the number of bytes read on success, GNUNET_SYSERR on failure
556 GNUNET_DISK_file_read (const struct GNUNET_DISK_FileHandle * h, void *result,
562 return GNUNET_SYSERR;
568 if (!ReadFile (h->h, result, len, &bytesRead, NULL))
570 SetErrnoFromWinError (GetLastError ());
571 return GNUNET_SYSERR;
575 return read (h->fd, result, len);
581 * Read the contents of a binary file into a buffer.
583 * @param fn file name
584 * @param result the buffer to write the result to
585 * @param len the maximum number of bytes to read
586 * @return number of bytes read, GNUNET_SYSERR on failure
589 GNUNET_DISK_fn_read (const char *fn, void *result, size_t len)
591 struct GNUNET_DISK_FileHandle *fh;
594 fh = GNUNET_DISK_file_open (fn, GNUNET_DISK_OPEN_READ,
595 GNUNET_DISK_PERM_NONE);
597 return GNUNET_SYSERR;
598 ret = GNUNET_DISK_file_read (fh, result, len);
599 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
606 * Write a buffer to a file.
607 * @param h handle to open file
608 * @param buffer the data to write
609 * @param n number of bytes to write
610 * @return number of bytes written on success, GNUNET_SYSERR on error
613 GNUNET_DISK_file_write (const struct GNUNET_DISK_FileHandle * h,
614 const void *buffer, size_t n)
619 return GNUNET_SYSERR;
625 if (!WriteFile (h->h, buffer, n, &bytesWritten, NULL))
627 SetErrnoFromWinError (GetLastError ());
628 return GNUNET_SYSERR;
632 return write (h->fd, buffer, n);
637 * Write a buffer to a file. If the file is longer than the
638 * number of bytes that will be written, it will be truncated.
640 * @param fn file name
641 * @param buffer the data to write
642 * @param n number of bytes to write
643 * @param mode file permissions
644 * @return number of bytes written on success, GNUNET_SYSERR on error
647 GNUNET_DISK_fn_write (const char *fn, const void *buffer,
648 size_t n, enum GNUNET_DISK_AccessPermissions mode)
650 struct GNUNET_DISK_FileHandle *fh;
653 fh = GNUNET_DISK_file_open (fn,
654 GNUNET_DISK_OPEN_WRITE
655 | GNUNET_DISK_OPEN_TRUNCATE
656 | GNUNET_DISK_OPEN_CREATE, mode);
658 return GNUNET_SYSERR;
659 ret = GNUNET_DISK_file_write (fh, buffer, n);
660 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
665 * Scan a directory for files.
667 * @param dirName the name of the directory
668 * @param callback the method to call for each file,
669 * can be NULL, in that case, we only count
670 * @param callback_cls closure for callback
671 * @return the number of files found, GNUNET_SYSERR on error or
672 * ieration aborted by callback returning GNUNET_SYSERR
675 GNUNET_DISK_directory_scan (const char *dirName,
676 GNUNET_FileNameCallback callback,
680 struct dirent *finfo;
685 unsigned int name_len;
688 GNUNET_assert (dirName != NULL);
689 dname = GNUNET_STRINGS_filename_expand (dirName);
690 while ((strlen (dname) > 0) && (dname[strlen (dname) - 1] == DIR_SEPARATOR))
691 dname[strlen (dname) - 1] = '\0';
692 if (0 != STAT (dname, &istat))
694 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", dname);
696 return GNUNET_SYSERR;
698 if (!S_ISDIR (istat.st_mode))
700 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
701 _("Expected `%s' to be a directory!\n"), dirName);
703 return GNUNET_SYSERR;
706 dinfo = OPENDIR (dname);
707 if ((errno == EACCES) || (dinfo == NULL))
709 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "opendir", dname);
713 return GNUNET_SYSERR;
716 n_size = strlen (dname) + name_len + 2;
717 name = GNUNET_malloc (n_size);
718 while ((finfo = readdir (dinfo)) != NULL)
720 if ((0 == strcmp (finfo->d_name, ".")) ||
721 (0 == strcmp (finfo->d_name, "..")))
723 if (callback != NULL)
725 if (name_len < strlen (finfo->d_name))
728 name_len = strlen (finfo->d_name);
729 n_size = strlen (dname) + name_len + 2;
730 name = GNUNET_malloc (n_size);
732 /* dname can end in "/" only if dname == "/";
733 if dname does not end in "/", we need to add
734 a "/" (otherwise, we must not!) */
735 GNUNET_snprintf (name,
739 (strcmp (dname, DIR_SEPARATOR_STR) ==
740 0) ? "" : DIR_SEPARATOR_STR, finfo->d_name);
741 if (GNUNET_OK != callback (callback_cls, name))
746 return GNUNET_SYSERR;
759 * Opaque handle used for iterating over a directory.
761 struct GNUNET_DISK_DirectoryIterator
766 struct GNUNET_SCHEDULER_Handle *sched;
769 * Function to call on directory entries.
771 GNUNET_DISK_DirectoryIteratorCallback callback;
774 * Closure for callback.
779 * Reference to directory.
789 * Next filename to process.
796 enum GNUNET_SCHEDULER_Priority priority;
802 * Task used by the directory iterator.
805 directory_iterator_task (void *cls,
806 const struct GNUNET_SCHEDULER_TaskContext *tc)
808 struct GNUNET_DISK_DirectoryIterator *iter = cls;
811 name = iter->next_name;
812 GNUNET_assert (name != NULL);
813 iter->next_name = NULL;
814 iter->callback (iter->callback_cls, iter, name, iter->dirname);
820 * This function must be called during the DiskIteratorCallback
821 * (exactly once) to schedule the task to process the next
822 * filename in the directory (if there is one).
824 * @param iter opaque handle for the iterator
825 * @param can set to GNUNET_YES to terminate the iteration early
826 * @return GNUNET_YES if iteration will continue,
827 * GNUNET_NO if this was the last entry (and iteration is complete),
828 * GNUNET_SYSERR if abort was YES
831 GNUNET_DISK_directory_iterator_next (struct GNUNET_DISK_DirectoryIterator
834 struct dirent *finfo;
836 GNUNET_assert (iter->next_name == NULL);
837 if (can == GNUNET_YES)
839 closedir (iter->directory);
840 GNUNET_free (iter->dirname);
842 return GNUNET_SYSERR;
844 while (NULL != (finfo = readdir (iter->directory)))
846 if ((0 == strcmp (finfo->d_name, ".")) ||
847 (0 == strcmp (finfo->d_name, "..")))
849 GNUNET_asprintf (&iter->next_name,
851 iter->dirname, DIR_SEPARATOR_STR, finfo->d_name);
856 GNUNET_DISK_directory_iterator_next (iter, GNUNET_YES);
859 GNUNET_SCHEDULER_add_with_priority (iter->sched,
861 &directory_iterator_task, iter);
867 * Scan a directory for files using the scheduler to run a task for
868 * each entry. The name of the directory must be expanded first (!).
869 * If a scheduler does not need to be used, GNUNET_DISK_directory_scan
870 * may provide a simpler API.
872 * @param sched scheduler to use
873 * @param prio priority to use
874 * @param dirName the name of the directory
875 * @param callback the method to call for each file
876 * @param callback_cls closure for callback
879 GNUNET_DISK_directory_iterator_start (struct GNUNET_SCHEDULER_Handle *sched,
880 enum GNUNET_SCHEDULER_Priority prio,
882 GNUNET_DISK_DirectoryIteratorCallback
883 callback, void *callback_cls)
885 struct GNUNET_DISK_DirectoryIterator *di;
887 di = GNUNET_malloc (sizeof (struct GNUNET_DISK_DirectoryIterator));
889 di->callback = callback;
890 di->callback_cls = callback_cls;
891 di->directory = OPENDIR (dirName);
892 di->dirname = GNUNET_strdup (dirName);
894 GNUNET_DISK_directory_iterator_next (di, GNUNET_NO);
899 * Function that removes the given directory by calling
900 * "GNUNET_DISK_directory_remove".
902 * @param unused not used
903 * @param fn directory to remove
907 remove_helper (void *unused, const char *fn)
909 GNUNET_DISK_directory_remove (fn);
915 * Remove all files in a directory (rm -rf). Call with
919 * @param fileName the file to remove
920 * @return GNUNET_OK on success, GNUNET_SYSERR on error
923 GNUNET_DISK_directory_remove (const char *fileName)
927 if (0 != LSTAT (fileName, &istat))
928 return GNUNET_NO; /* file may not exist... */
929 if (UNLINK (fileName) == 0)
931 if ((errno != EISDIR) &&
932 /* EISDIR is not sufficient in all cases, e.g.
933 sticky /tmp directory may result in EPERM on BSD.
934 So we also explicitly check "isDirectory" */
935 (GNUNET_YES != GNUNET_DISK_directory_test (fileName)))
937 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "rmdir", fileName);
938 return GNUNET_SYSERR;
941 GNUNET_DISK_directory_scan (fileName, &remove_helper, NULL))
942 return GNUNET_SYSERR;
943 if (0 != RMDIR (fileName))
945 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "rmdir", fileName);
946 return GNUNET_SYSERR;
955 * @param src file to copy
956 * @param dst destination file name
957 * @return GNUNET_OK on success, GNUNET_SYSERR on error
960 GNUNET_DISK_file_copy (const char *src, const char *dst)
966 struct GNUNET_DISK_FileHandle *in;
967 struct GNUNET_DISK_FileHandle *out;
969 if (GNUNET_OK != GNUNET_DISK_file_size (src, &size, GNUNET_YES))
970 return GNUNET_SYSERR;
972 in = GNUNET_DISK_file_open (src, GNUNET_DISK_OPEN_READ,
973 GNUNET_DISK_PERM_NONE);
975 return GNUNET_SYSERR;
976 out = GNUNET_DISK_file_open (dst, GNUNET_DISK_OPEN_WRITE
977 | GNUNET_DISK_OPEN_CREATE |
978 GNUNET_DISK_OPEN_FAILIFEXISTS,
979 GNUNET_DISK_PERM_USER_READ |
980 GNUNET_DISK_PERM_USER_WRITE |
981 GNUNET_DISK_PERM_GROUP_READ |
982 GNUNET_DISK_PERM_GROUP_WRITE);
985 GNUNET_DISK_file_close (in);
986 return GNUNET_SYSERR;
988 buf = GNUNET_malloc (COPY_BLK_SIZE);
992 if (len > size - pos)
994 if (len != GNUNET_DISK_file_read (in, buf, len))
996 if (len != GNUNET_DISK_file_write (out, buf, len))
1001 GNUNET_DISK_file_close (in);
1002 GNUNET_DISK_file_close (out);
1006 GNUNET_DISK_file_close (in);
1007 GNUNET_DISK_file_close (out);
1008 return GNUNET_SYSERR;
1013 * @brief Removes special characters as ':' from a filename.
1014 * @param fn the filename to canonicalize
1017 GNUNET_DISK_filename_canonicalize (char *fn)
1027 if (c == '/' || c == '\\' || c == ':' || c == '*' || c == '?' ||
1028 c == '"' || c == '<' || c == '>' || c == '|')
1040 * @brief Change owner of a file
1042 * @param filename name of file to change the owner of
1043 * @param user name of the new owner
1044 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1047 GNUNET_DISK_file_change_owner (const char *filename, const char *user)
1052 pws = getpwnam (user);
1055 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1056 _("Cannot obtain information about user `%s': %s\n"),
1057 user, STRERROR (errno));
1058 return GNUNET_SYSERR;
1060 if (0 != chown (filename, pws->pw_uid, pws->pw_gid))
1061 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "chown", filename);
1068 * Lock a part of a file
1069 * @param fh file handle
1070 * @param lockStart absolute position from where to lock
1071 * @param lockEnd absolute position until where to lock
1072 * @param excl GNUNET_YES for an exclusive lock
1073 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1076 GNUNET_DISK_file_lock (struct GNUNET_DISK_FileHandle *fh, off_t lockStart,
1077 off_t lockEnd, int excl)
1082 return GNUNET_SYSERR;
1088 memset (&fl, 0, sizeof (struct flock));
1089 fl.l_type = excl ? F_WRLCK : F_RDLCK;
1090 fl.l_whence = SEEK_SET;
1091 fl.l_start = lockStart;
1094 return fcntl (fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK;
1098 memset (&o, 0, sizeof (OVERLAPPED));
1099 o.Offset = lockStart;
1101 if (!LockFileEx (fh->h, (excl ? LOCKFILE_EXCLUSIVE_LOCK : 0)
1102 | LOCKFILE_FAIL_IMMEDIATELY, 0, lockEnd - lockStart, 0,
1105 SetErrnoFromWinError (GetLastError ());
1106 return GNUNET_SYSERR;
1115 * Unlock a part of a file
1116 * @param fh file handle
1117 * @param unlockStart absolute position from where to unlock
1118 * @param unlockEnd absolute position until where to unlock
1119 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1122 GNUNET_DISK_file_unlock (struct GNUNET_DISK_FileHandle *fh, off_t unlockStart,
1128 return GNUNET_SYSERR;
1134 memset (&fl, 0, sizeof (struct flock));
1135 fl.l_type = F_UNLCK;
1136 fl.l_whence = SEEK_SET;
1137 fl.l_start = unlockStart;
1138 fl.l_len = unlockEnd;
1140 return fcntl (fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK;
1144 memset (&o, 0, sizeof (OVERLAPPED));
1145 o.Offset = unlockStart;
1147 if (!UnlockFileEx (fh->h, 0, unlockEnd - unlockStart, 0, &o))
1149 SetErrnoFromWinError (GetLastError ());
1150 return GNUNET_SYSERR;
1159 * Open a file. Note that the access permissions will only be
1160 * used if a new file is created and if the underlying operating
1161 * system supports the given permissions.
1163 * @param fn file name to be opened
1164 * @param flags opening flags, a combination of GNUNET_DISK_OPEN_xxx bit flags
1165 * @param perm permissions for the newly created file, use
1166 * GNUNET_DISK_PERM_USER_NONE if a file could not be created by this
1167 * call (because of flags)
1168 * @return IO handle on success, NULL on error
1170 struct GNUNET_DISK_FileHandle *
1171 GNUNET_DISK_file_open (const char *fn,
1172 enum GNUNET_DISK_OpenFlags flags,
1173 enum GNUNET_DISK_AccessPermissions perm)
1176 struct GNUNET_DISK_FileHandle *ret;
1187 expfn = GNUNET_STRINGS_filename_expand (fn);
1191 if (GNUNET_DISK_OPEN_READWRITE == (flags & GNUNET_DISK_OPEN_READWRITE))
1192 oflags = O_RDWR; /* note: O_RDWR is NOT always O_RDONLY | O_WRONLY */
1193 else if (flags & GNUNET_DISK_OPEN_READ)
1195 else if (flags & GNUNET_DISK_OPEN_WRITE)
1200 GNUNET_free (expfn);
1203 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1204 oflags |= (O_CREAT & O_EXCL);
1205 if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1207 if (flags & GNUNET_DISK_OPEN_APPEND)
1209 if (flags & GNUNET_DISK_OPEN_CREATE)
1212 if (perm & GNUNET_DISK_PERM_USER_READ)
1214 if (perm & GNUNET_DISK_PERM_USER_WRITE)
1216 if (perm & GNUNET_DISK_PERM_USER_EXEC)
1218 if (perm & GNUNET_DISK_PERM_GROUP_READ)
1220 if (perm & GNUNET_DISK_PERM_GROUP_WRITE)
1222 if (perm & GNUNET_DISK_PERM_GROUP_EXEC)
1224 if (perm & GNUNET_DISK_PERM_OTHER_READ)
1226 if (perm & GNUNET_DISK_PERM_OTHER_WRITE)
1228 if (perm & GNUNET_DISK_PERM_OTHER_EXEC)
1232 fd = open (expfn, oflags | O_LARGEFILE, mode);
1235 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "open", expfn);
1236 GNUNET_free (expfn);
1243 if (GNUNET_DISK_OPEN_READWRITE == (flags & GNUNET_DISK_OPEN_READWRITE))
1244 access = FILE_READ_DATA | FILE_WRITE_DATA;
1245 else if (flags & GNUNET_DISK_OPEN_READ)
1246 access = FILE_READ_DATA;
1247 else if (flags & GNUNET_DISK_OPEN_WRITE)
1248 access = FILE_WRITE_DATA;
1250 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1254 else if (flags & GNUNET_DISK_OPEN_CREATE)
1256 if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1257 disp = CREATE_ALWAYS;
1261 else if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1263 disp = TRUNCATE_EXISTING;
1270 /* TODO: access priviledges? */
1271 h = CreateFile (expfn, access, FILE_SHARE_DELETE | FILE_SHARE_READ
1272 | FILE_SHARE_WRITE, NULL, disp, FILE_ATTRIBUTE_NORMAL,
1274 if (h == INVALID_HANDLE_VALUE)
1276 SetErrnoFromWinError (GetLastError ());
1277 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "open", expfn);
1278 GNUNET_free (expfn);
1282 if (flags & GNUNET_DISK_OPEN_APPEND)
1283 if (SetFilePointer (h, 0, 0, FILE_END) == INVALID_SET_FILE_POINTER)
1285 SetErrnoFromWinError (GetLastError ());
1286 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "SetFilePointer",
1289 GNUNET_free (expfn);
1294 ret = GNUNET_malloc (sizeof (struct GNUNET_DISK_FileHandle));
1300 GNUNET_free (expfn);
1306 * Close an open file
1307 * @param h file handle
1308 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1311 GNUNET_DISK_file_close (struct GNUNET_DISK_FileHandle *h)
1316 return GNUNET_SYSERR;
1320 if (!CloseHandle (h->h))
1322 SetErrnoFromWinError (GetLastError ());
1323 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "close");
1325 return GNUNET_SYSERR;
1328 if (close (h->fd) != 0)
1330 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "close");
1332 return GNUNET_SYSERR;
1341 * Construct full path to a file inside of the private
1342 * directory used by GNUnet. Also creates the corresponding
1343 * directory. If the resulting name is supposed to be
1344 * a directory, end the last argument in '/' (or pass
1345 * DIR_SEPARATOR_STR as the last argument before NULL).
1347 * @param cfg configuration to use (determines HOME)
1348 * @param serviceName name of the service
1349 * @param ... is NULL-terminated list of
1350 * path components to append to the
1351 * private directory name.
1352 * @return the constructed filename
1355 GNUNET_DISK_get_home_filename (const struct GNUNET_CONFIGURATION_Handle *cfg,
1356 const char *serviceName, ...)
1362 unsigned int needed;
1365 GNUNET_CONFIGURATION_get_value_filename (cfg,
1366 serviceName, "HOME", &pfx))
1370 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1371 _("No `%s' specified for service `%s' in configuration.\n"),
1372 "HOME", serviceName);
1375 needed = strlen (pfx) + 2;
1376 if ((pfx[strlen (pfx) - 1] != '/') && (pfx[strlen (pfx) - 1] != '\\'))
1378 va_start (ap, serviceName);
1381 c = va_arg (ap, const char *);
1384 needed += strlen (c);
1385 if ((c[strlen (c) - 1] != '/') && (c[strlen (c) - 1] != '\\'))
1389 ret = GNUNET_malloc (needed);
1392 va_start (ap, serviceName);
1395 c = va_arg (ap, const char *);
1398 if ((c[strlen (c) - 1] != '/') && (c[strlen (c) - 1] != '\\'))
1399 strcat (ret, DIR_SEPARATOR_STR);
1403 if ((ret[strlen (ret) - 1] != '/') && (ret[strlen (ret) - 1] != '\\'))
1404 GNUNET_DISK_directory_create_for_file (ret);
1406 GNUNET_DISK_directory_create (ret);
1412 * Handle for a memory-mapping operation.
1414 struct GNUNET_DISK_MapHandle
1418 * Underlying OS handle.
1423 * Address where the map is in memory.
1428 * Number of bytes mapped.
1436 * Map a file into memory
1438 * @param h open file handle
1439 * @param m handle to the new mapping
1440 * @param access access specification, GNUNET_DISK_MAP_TYPE_xxx
1441 * @param len size of the mapping
1442 * @return pointer to the mapped memory region, NULL on failure
1445 GNUNET_DISK_file_map (const struct GNUNET_DISK_FileHandle *h,
1446 struct GNUNET_DISK_MapHandle **m,
1447 enum GNUNET_DISK_MapType access, size_t len)
1456 DWORD mapAccess, protect;
1459 if ((access & GNUNET_DISK_MAP_TYPE_READ) &&
1460 (access & GNUNET_DISK_MAP_TYPE_WRITE))
1462 protect = PAGE_READWRITE;
1463 mapAccess = FILE_MAP_ALL_ACCESS;
1465 else if (access & GNUNET_DISK_MAP_TYPE_READ)
1467 protect = PAGE_READONLY;
1468 mapAccess = FILE_MAP_READ;
1470 else if (access & GNUNET_DISK_MAP_TYPE_WRITE)
1472 protect = PAGE_READWRITE;
1473 mapAccess = FILE_MAP_WRITE;
1481 *m = GNUNET_malloc (sizeof (struct GNUNET_DISK_MapHandle));
1482 (*m)->h = CreateFileMapping (h->h, NULL, protect, 0, 0, NULL);
1483 if ((*m)->h == INVALID_HANDLE_VALUE)
1485 SetErrnoFromWinError (GetLastError ());
1490 ret = MapViewOfFile ((*m)->h, mapAccess, 0, 0, len);
1493 SetErrnoFromWinError (GetLastError ());
1494 CloseHandle ((*m)->h);
1503 if (access & GNUNET_DISK_MAP_TYPE_READ)
1505 if (access & GNUNET_DISK_MAP_TYPE_WRITE)
1507 *m = GNUNET_malloc (sizeof (struct GNUNET_DISK_MapHandle));
1508 (*m)->addr = mmap (NULL, len, prot, MAP_SHARED, h->fd, 0);
1516 * @param h mapping handle
1517 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1520 GNUNET_DISK_file_unmap (struct GNUNET_DISK_MapHandle *h)
1526 return GNUNET_SYSERR;
1530 ret = UnmapViewOfFile (h->h) ? GNUNET_OK : GNUNET_SYSERR;
1531 if (ret != GNUNET_OK)
1532 SetErrnoFromWinError (GetLastError ());
1533 if (!CloseHandle (h->h) && (ret == GNUNET_OK))
1535 ret = GNUNET_SYSERR;
1536 SetErrnoFromWinError (GetLastError ());
1539 ret = munmap (h->addr, h->len) != -1 ? GNUNET_OK : GNUNET_SYSERR;
1547 * Write file changes to disk
1548 * @param h handle to an open file
1549 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1552 GNUNET_DISK_file_sync (const struct GNUNET_DISK_FileHandle *h)
1557 return GNUNET_SYSERR;
1563 ret = FlushFileBuffers (h->h) ? GNUNET_OK : GNUNET_SYSERR;
1564 if (ret != GNUNET_OK)
1565 SetErrnoFromWinError (GetLastError ());
1567 #elif defined(FREEBSD) || defined(OPENBSD) || defined(DARWIN)
1568 return fsync (h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK;
1570 return fdatasync (h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK;
1575 * Creates an interprocess channel
1577 * @param blocking creates an asynchronous pipe if set to GNUNET_NO
1578 * @return handle to the new pipe, NULL on error
1580 struct GNUNET_DISK_PipeHandle *
1581 GNUNET_DISK_pipe (int blocking)
1583 struct GNUNET_DISK_PipeHandle *p;
1584 struct GNUNET_DISK_FileHandle *fds;
1587 GNUNET_malloc (sizeof (struct GNUNET_DISK_PipeHandle) +
1588 2 * sizeof (struct GNUNET_DISK_FileHandle));
1589 fds = (struct GNUNET_DISK_FileHandle *) &p[1];
1606 p->fd[0]->fd = fd[0];
1607 p->fd[1]->fd = fd[1];
1610 flags = fcntl (fd[0], F_GETFL);
1611 flags |= O_NONBLOCK;
1612 ret = fcntl (fd[0], F_SETFL, flags);
1615 flags = fcntl (fd[1], F_GETFL);
1616 flags |= O_NONBLOCK;
1617 ret = fcntl (fd[1], F_SETFL, flags);
1622 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "fcntl");
1623 GNUNET_break (0 == close (p->fd[0]->fd));
1624 GNUNET_break (0 == close (p->fd[1]->fd));
1633 ret = CreatePipe (&p->fd[0]->h, &p->fd[1]->h, NULL, 0);
1637 SetErrnoFromWinError (GetLastError ());
1645 p->fd[0] = GNUNET_malloc (sizeof (struct GNUNET_DISK_FileHandle));
1646 p->fd[1] = GNUNET_malloc (sizeof (struct GNUNET_DISK_FileHandle));
1647 SetNamedPipeHandleState (p->fd[0]->h, &mode, NULL, NULL);
1648 SetNamedPipeHandleState (p->fd[1]->h, &mode, NULL, NULL);
1649 /* this always fails on Windows 95, so we don't care about error handling */
1657 * Closes an interprocess channel
1659 * @param p pipe to close
1660 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1663 GNUNET_DISK_pipe_close (struct GNUNET_DISK_PipeHandle *p)
1665 int ret = GNUNET_OK;
1669 if (!CloseHandle (p->fd[0]->h))
1671 SetErrnoFromWinError (GetLastError ());
1672 ret = GNUNET_SYSERR;
1674 if (!CloseHandle (p->fd[1]->h))
1676 SetErrnoFromWinError (GetLastError ());
1677 ret = GNUNET_SYSERR;
1682 if (0 != close (p->fd[0]->fd))
1684 ret = GNUNET_SYSERR;
1687 if (0 != close (p->fd[1]->fd))
1689 ret = GNUNET_SYSERR;
1700 * Get the handle to a particular pipe end
1702 * @param n end to access
1704 const struct GNUNET_DISK_FileHandle *
1705 GNUNET_DISK_pipe_handle (const struct GNUNET_DISK_PipeHandle *p,
1706 enum GNUNET_DISK_PipeEnd n)
1710 case GNUNET_DISK_PIPE_END_READ:
1711 case GNUNET_DISK_PIPE_END_WRITE:
1721 * Retrieve OS file handle
1723 * @param fh GNUnet file descriptor
1724 * @param dst destination buffer
1725 * @param dst_len length of dst
1726 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1729 GNUNET_DISK_internal_file_handle_ (const struct GNUNET_DISK_FileHandle *fh,
1730 void *dst, size_t dst_len)
1733 if (dst_len < sizeof (HANDLE))
1734 return GNUNET_SYSERR;
1735 *((HANDLE *) dst) = fh->h;
1737 if (dst_len < sizeof (int))
1738 return GNUNET_SYSERR;
1739 *((int *) dst) = fh->fd;