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", tmpdir, t, "XXXXXX");
289 fn = (char *) GNUNET_malloc (MAX_PATH + 1);
290 if (ERROR_SUCCESS != plibc_conv_to_win_path (tmpl, fn))
303 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "mkstemp", fn);
308 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "close", fn);
314 * Get the number of blocks that are left on the partition that
315 * contains the given file (for normal users).
317 * @param part a file on the partition to check
318 * @return -1 on errors, otherwise the number of free blocks
321 GNUNET_DISK_get_blocks_available (const char *part)
326 if (0 != statvfs (part, &buf))
328 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "statfs", part);
338 path = GNUNET_STRINGS_filename_expand (part);
339 memcpy (szDrive, path, 3);
342 if (!GetDiskFreeSpace (szDrive, &dwDummy, &dwDummy, &dwBlocks, &dwDummy))
344 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
345 _("`%s' failed for drive `%s': %u\n"),
346 "GetDiskFreeSpace", szDrive, GetLastError ());
353 if (0 != statfs (part, &s))
355 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "statfs", part);
364 * Test if "fil" is a directory.
365 * Will not print an error message if the directory
366 * does not exist. Will log errors if GNUNET_SYSERR is
367 * returned (i.e., a file exists with the same name).
369 * @param fil filename to test
370 * @return GNUNET_YES if yes, GNUNET_NO if not, GNUNET_SYSERR if it
374 GNUNET_DISK_directory_test (const char *fil)
376 struct stat filestat;
379 ret = STAT (fil, &filestat);
384 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", fil);
385 return GNUNET_SYSERR;
389 if (!S_ISDIR (filestat.st_mode))
391 if (ACCESS (fil, R_OK | X_OK) < 0)
393 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "access", fil);
394 return GNUNET_SYSERR;
400 * Check that fil corresponds to a filename
401 * (of a file that exists and that is not a directory).
403 * @param fil filename to check
404 * @return GNUNET_YES if yes, GNUNET_NO if not a file, GNUNET_SYSERR if something
405 * else (will print an error message in that case, too).
408 GNUNET_DISK_file_test (const char *fil)
410 struct stat filestat;
414 rdir = GNUNET_STRINGS_filename_expand (fil);
416 return GNUNET_SYSERR;
418 ret = STAT (rdir, &filestat);
423 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", rdir);
425 return GNUNET_SYSERR;
430 if (!S_ISREG (filestat.st_mode))
435 if (ACCESS (rdir, R_OK) < 0)
437 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "access", rdir);
439 return GNUNET_SYSERR;
447 * Implementation of "mkdir -p"
448 * @param dir the directory to create
449 * @returns GNUNET_OK on success, GNUNET_SYSERR on failure
452 GNUNET_DISK_directory_create (const char *dir)
459 rdir = GNUNET_STRINGS_filename_expand (dir);
461 return GNUNET_SYSERR;
465 pos = 1; /* skip heading '/' */
467 /* Local or Network path? */
468 if (strncmp (rdir, "\\\\", 2) == 0)
473 if (rdir[pos] == '\\')
483 pos = 3; /* strlen("C:\\") */
488 if ((rdir[pos] == DIR_SEPARATOR) || (pos == len))
491 ret = GNUNET_DISK_directory_test (rdir);
492 if (ret == GNUNET_SYSERR)
495 return GNUNET_SYSERR;
497 if (ret == GNUNET_NO)
500 ret = mkdir (rdir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); /* 755 */
504 if ((ret != 0) && (errno != EEXIST))
506 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "mkdir",
509 return GNUNET_SYSERR;
512 rdir[pos] = DIR_SEPARATOR;
522 * Create the directory structure for storing
525 * @param filename name of a file in the directory
526 * @returns GNUNET_OK on success,
527 * GNUNET_SYSERR on failure,
528 * GNUNET_NO if the directory
529 * exists but is not writeable for us
532 GNUNET_DISK_directory_create_for_file (const char *filename)
538 rdir = GNUNET_STRINGS_filename_expand (filename);
540 return GNUNET_SYSERR;
542 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
545 ret = GNUNET_DISK_directory_create (rdir);
546 if ((ret == GNUNET_OK) && (0 != ACCESS (rdir, W_OK)))
554 * Read the contents of a binary file into a buffer.
555 * @param h handle to an open file
556 * @param result the buffer to write the result to
557 * @param len the maximum number of bytes to read
558 * @return the number of bytes read on success, GNUNET_SYSERR on failure
561 GNUNET_DISK_file_read (const struct GNUNET_DISK_FileHandle * h, void *result,
567 return GNUNET_SYSERR;
573 if (!ReadFile (h->h, result, len, &bytesRead, NULL))
575 SetErrnoFromWinError (GetLastError ());
576 return GNUNET_SYSERR;
580 return read (h->fd, result, len);
586 * Read the contents of a binary file into a buffer.
588 * @param fn file name
589 * @param result the buffer to write the result to
590 * @param len the maximum number of bytes to read
591 * @return number of bytes read, GNUNET_SYSERR on failure
594 GNUNET_DISK_fn_read (const char *fn, void *result, size_t len)
596 struct GNUNET_DISK_FileHandle *fh;
599 fh = GNUNET_DISK_file_open (fn, GNUNET_DISK_OPEN_READ,
600 GNUNET_DISK_PERM_NONE);
602 return GNUNET_SYSERR;
603 ret = GNUNET_DISK_file_read (fh, result, len);
604 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
611 * Write a buffer to a file.
612 * @param h handle to open file
613 * @param buffer the data to write
614 * @param n number of bytes to write
615 * @return number of bytes written on success, GNUNET_SYSERR on error
618 GNUNET_DISK_file_write (const struct GNUNET_DISK_FileHandle * h,
619 const void *buffer, size_t n)
624 return GNUNET_SYSERR;
630 if (!WriteFile (h->h, buffer, n, &bytesWritten, NULL))
632 SetErrnoFromWinError (GetLastError ());
633 return GNUNET_SYSERR;
637 return write (h->fd, buffer, n);
642 * Write a buffer to a file. If the file is longer than the
643 * number of bytes that will be written, it will be truncated.
645 * @param fn file name
646 * @param buffer the data to write
647 * @param n number of bytes to write
648 * @param mode file permissions
649 * @return number of bytes written on success, GNUNET_SYSERR on error
652 GNUNET_DISK_fn_write (const char *fn, const void *buffer,
653 size_t n, enum GNUNET_DISK_AccessPermissions mode)
655 struct GNUNET_DISK_FileHandle *fh;
658 fh = GNUNET_DISK_file_open (fn,
659 GNUNET_DISK_OPEN_WRITE
660 | GNUNET_DISK_OPEN_TRUNCATE
661 | GNUNET_DISK_OPEN_CREATE, mode);
663 return GNUNET_SYSERR;
664 ret = GNUNET_DISK_file_write (fh, buffer, n);
665 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
670 * Scan a directory for files.
672 * @param dirName the name of the directory
673 * @param callback the method to call for each file,
674 * can be NULL, in that case, we only count
675 * @param callback_cls closure for callback
676 * @return the number of files found, GNUNET_SYSERR on error or
677 * ieration aborted by callback returning GNUNET_SYSERR
680 GNUNET_DISK_directory_scan (const char *dirName,
681 GNUNET_FileNameCallback callback,
685 struct dirent *finfo;
690 unsigned int name_len;
693 GNUNET_assert (dirName != NULL);
694 dname = GNUNET_STRINGS_filename_expand (dirName);
695 while ((strlen (dname) > 0) && (dname[strlen (dname) - 1] == DIR_SEPARATOR))
696 dname[strlen (dname) - 1] = '\0';
697 if (0 != STAT (dname, &istat))
699 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", dname);
701 return GNUNET_SYSERR;
703 if (!S_ISDIR (istat.st_mode))
705 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
706 _("Expected `%s' to be a directory!\n"), dirName);
708 return GNUNET_SYSERR;
711 dinfo = OPENDIR (dname);
712 if ((errno == EACCES) || (dinfo == NULL))
714 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "opendir", dname);
718 return GNUNET_SYSERR;
721 n_size = strlen (dname) + name_len + 2;
722 name = GNUNET_malloc (n_size);
723 while ((finfo = readdir (dinfo)) != NULL)
725 if ((0 == strcmp (finfo->d_name, ".")) ||
726 (0 == strcmp (finfo->d_name, "..")))
728 if (callback != NULL)
730 if (name_len < strlen (finfo->d_name))
733 name_len = strlen (finfo->d_name);
734 n_size = strlen (dname) + name_len + 2;
735 name = GNUNET_malloc (n_size);
737 /* dname can end in "/" only if dname == "/";
738 if dname does not end in "/", we need to add
739 a "/" (otherwise, we must not!) */
740 GNUNET_snprintf (name,
744 (strcmp (dname, DIR_SEPARATOR_STR) ==
745 0) ? "" : DIR_SEPARATOR_STR, finfo->d_name);
746 if (GNUNET_OK != callback (callback_cls, name))
751 return GNUNET_SYSERR;
764 * Opaque handle used for iterating over a directory.
766 struct GNUNET_DISK_DirectoryIterator
771 struct GNUNET_SCHEDULER_Handle *sched;
774 * Function to call on directory entries.
776 GNUNET_DISK_DirectoryIteratorCallback callback;
779 * Closure for callback.
784 * Reference to directory.
794 * Next filename to process.
801 enum GNUNET_SCHEDULER_Priority priority;
807 * Task used by the directory iterator.
810 directory_iterator_task (void *cls,
811 const struct GNUNET_SCHEDULER_TaskContext *tc)
813 struct GNUNET_DISK_DirectoryIterator *iter = cls;
816 name = iter->next_name;
817 GNUNET_assert (name != NULL);
818 iter->next_name = NULL;
819 iter->callback (iter->callback_cls, iter, name, iter->dirname);
825 * This function must be called during the DiskIteratorCallback
826 * (exactly once) to schedule the task to process the next
827 * filename in the directory (if there is one).
829 * @param iter opaque handle for the iterator
830 * @param can set to GNUNET_YES to terminate the iteration early
831 * @return GNUNET_YES if iteration will continue,
832 * GNUNET_NO if this was the last entry (and iteration is complete),
833 * GNUNET_SYSERR if abort was YES
836 GNUNET_DISK_directory_iterator_next (struct GNUNET_DISK_DirectoryIterator
839 struct dirent *finfo;
841 GNUNET_assert (iter->next_name == NULL);
842 if (can == GNUNET_YES)
844 closedir (iter->directory);
845 GNUNET_free (iter->dirname);
847 return GNUNET_SYSERR;
849 while (NULL != (finfo = readdir (iter->directory)))
851 if ((0 == strcmp (finfo->d_name, ".")) ||
852 (0 == strcmp (finfo->d_name, "..")))
854 GNUNET_asprintf (&iter->next_name,
856 iter->dirname, DIR_SEPARATOR_STR, finfo->d_name);
861 GNUNET_DISK_directory_iterator_next (iter, GNUNET_YES);
864 GNUNET_SCHEDULER_add_with_priority (iter->sched,
866 &directory_iterator_task, iter);
872 * Scan a directory for files using the scheduler to run a task for
873 * each entry. The name of the directory must be expanded first (!).
874 * If a scheduler does not need to be used, GNUNET_DISK_directory_scan
875 * may provide a simpler API.
877 * @param sched scheduler to use
878 * @param prio priority to use
879 * @param dirName the name of the directory
880 * @param callback the method to call for each file
881 * @param callback_cls closure for callback
884 GNUNET_DISK_directory_iterator_start (struct GNUNET_SCHEDULER_Handle *sched,
885 enum GNUNET_SCHEDULER_Priority prio,
887 GNUNET_DISK_DirectoryIteratorCallback
888 callback, void *callback_cls)
890 struct GNUNET_DISK_DirectoryIterator *di;
892 di = GNUNET_malloc (sizeof (struct GNUNET_DISK_DirectoryIterator));
894 di->callback = callback;
895 di->callback_cls = callback_cls;
896 di->directory = OPENDIR (dirName);
897 di->dirname = GNUNET_strdup (dirName);
899 GNUNET_DISK_directory_iterator_next (di, GNUNET_NO);
904 * Function that removes the given directory by calling
905 * "GNUNET_DISK_directory_remove".
907 * @param unused not used
908 * @param fn directory to remove
912 remove_helper (void *unused, const char *fn)
914 GNUNET_DISK_directory_remove (fn);
920 * Remove all files in a directory (rm -rf). Call with
924 * @param fileName the file to remove
925 * @return GNUNET_OK on success, GNUNET_SYSERR on error
928 GNUNET_DISK_directory_remove (const char *fileName)
932 if (0 != LSTAT (fileName, &istat))
933 return GNUNET_NO; /* file may not exist... */
934 if (UNLINK (fileName) == 0)
936 if ((errno != EISDIR) &&
937 /* EISDIR is not sufficient in all cases, e.g.
938 sticky /tmp directory may result in EPERM on BSD.
939 So we also explicitly check "isDirectory" */
940 (GNUNET_YES != GNUNET_DISK_directory_test (fileName)))
942 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "rmdir", fileName);
943 return GNUNET_SYSERR;
946 GNUNET_DISK_directory_scan (fileName, &remove_helper, NULL))
947 return GNUNET_SYSERR;
948 if (0 != RMDIR (fileName))
950 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "rmdir", fileName);
951 return GNUNET_SYSERR;
960 * @param src file to copy
961 * @param dst destination file name
962 * @return GNUNET_OK on success, GNUNET_SYSERR on error
965 GNUNET_DISK_file_copy (const char *src, const char *dst)
971 struct GNUNET_DISK_FileHandle *in;
972 struct GNUNET_DISK_FileHandle *out;
974 if (GNUNET_OK != GNUNET_DISK_file_size (src, &size, GNUNET_YES))
975 return GNUNET_SYSERR;
977 in = GNUNET_DISK_file_open (src, GNUNET_DISK_OPEN_READ,
978 GNUNET_DISK_PERM_NONE);
980 return GNUNET_SYSERR;
981 out = GNUNET_DISK_file_open (dst, GNUNET_DISK_OPEN_WRITE
982 | GNUNET_DISK_OPEN_CREATE |
983 GNUNET_DISK_OPEN_FAILIFEXISTS,
984 GNUNET_DISK_PERM_USER_READ |
985 GNUNET_DISK_PERM_USER_WRITE |
986 GNUNET_DISK_PERM_GROUP_READ |
987 GNUNET_DISK_PERM_GROUP_WRITE);
990 GNUNET_DISK_file_close (in);
991 return GNUNET_SYSERR;
993 buf = GNUNET_malloc (COPY_BLK_SIZE);
997 if (len > size - pos)
999 if (len != GNUNET_DISK_file_read (in, buf, len))
1001 if (len != GNUNET_DISK_file_write (out, buf, len))
1006 GNUNET_DISK_file_close (in);
1007 GNUNET_DISK_file_close (out);
1011 GNUNET_DISK_file_close (in);
1012 GNUNET_DISK_file_close (out);
1013 return GNUNET_SYSERR;
1018 * @brief Removes special characters as ':' from a filename.
1019 * @param fn the filename to canonicalize
1022 GNUNET_DISK_filename_canonicalize (char *fn)
1032 if (c == '/' || c == '\\' || c == ':' || c == '*' || c == '?' ||
1033 c == '"' || c == '<' || c == '>' || c == '|')
1045 * @brief Change owner of a file
1047 * @param filename name of file to change the owner of
1048 * @param user name of the new owner
1049 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1052 GNUNET_DISK_file_change_owner (const char *filename, const char *user)
1057 pws = getpwnam (user);
1060 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1061 _("Cannot obtain information about user `%s': %s\n"),
1062 user, STRERROR (errno));
1063 return GNUNET_SYSERR;
1065 if (0 != chown (filename, pws->pw_uid, pws->pw_gid))
1066 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "chown", filename);
1073 * Lock a part of a file
1074 * @param fh file handle
1075 * @param lockStart absolute position from where to lock
1076 * @param lockEnd absolute position until where to lock
1077 * @param excl GNUNET_YES for an exclusive lock
1078 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1081 GNUNET_DISK_file_lock (struct GNUNET_DISK_FileHandle *fh, off_t lockStart,
1082 off_t lockEnd, int excl)
1087 return GNUNET_SYSERR;
1093 memset (&fl, 0, sizeof (struct flock));
1094 fl.l_type = excl ? F_WRLCK : F_RDLCK;
1095 fl.l_whence = SEEK_SET;
1096 fl.l_start = lockStart;
1099 return fcntl (fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK;
1103 memset (&o, 0, sizeof (OVERLAPPED));
1104 o.Offset = lockStart;
1106 if (!LockFileEx (fh->h, (excl ? LOCKFILE_EXCLUSIVE_LOCK : 0)
1107 | LOCKFILE_FAIL_IMMEDIATELY, 0, lockEnd - lockStart, 0,
1110 SetErrnoFromWinError (GetLastError ());
1111 return GNUNET_SYSERR;
1120 * Unlock a part of a file
1121 * @param fh file handle
1122 * @param unlockStart absolute position from where to unlock
1123 * @param unlockEnd absolute position until where to unlock
1124 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1127 GNUNET_DISK_file_unlock (struct GNUNET_DISK_FileHandle *fh, off_t unlockStart,
1133 return GNUNET_SYSERR;
1139 memset (&fl, 0, sizeof (struct flock));
1140 fl.l_type = F_UNLCK;
1141 fl.l_whence = SEEK_SET;
1142 fl.l_start = unlockStart;
1143 fl.l_len = unlockEnd;
1145 return fcntl (fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK;
1149 memset (&o, 0, sizeof (OVERLAPPED));
1150 o.Offset = unlockStart;
1152 if (!UnlockFileEx (fh->h, 0, unlockEnd - unlockStart, 0, &o))
1154 SetErrnoFromWinError (GetLastError ());
1155 return GNUNET_SYSERR;
1164 * Open a file. Note that the access permissions will only be
1165 * used if a new file is created and if the underlying operating
1166 * system supports the given permissions.
1168 * @param fn file name to be opened
1169 * @param flags opening flags, a combination of GNUNET_DISK_OPEN_xxx bit flags
1170 * @param perm permissions for the newly created file, use
1171 * GNUNET_DISK_PERM_USER_NONE if a file could not be created by this
1172 * call (because of flags)
1173 * @return IO handle on success, NULL on error
1175 struct GNUNET_DISK_FileHandle *
1176 GNUNET_DISK_file_open (const char *fn,
1177 enum GNUNET_DISK_OpenFlags flags,
1178 enum GNUNET_DISK_AccessPermissions perm)
1181 struct GNUNET_DISK_FileHandle *ret;
1192 expfn = GNUNET_STRINGS_filename_expand (fn);
1198 if (GNUNET_DISK_OPEN_READWRITE == (flags & GNUNET_DISK_OPEN_READWRITE))
1199 oflags = O_RDWR; /* note: O_RDWR is NOT always O_RDONLY | O_WRONLY */
1200 else if (flags & GNUNET_DISK_OPEN_READ)
1202 else if (flags & GNUNET_DISK_OPEN_WRITE)
1207 GNUNET_free (expfn);
1210 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1211 oflags |= (O_CREAT & O_EXCL);
1212 if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1214 if (flags & GNUNET_DISK_OPEN_APPEND)
1216 if (flags & GNUNET_DISK_OPEN_CREATE)
1219 if (perm & GNUNET_DISK_PERM_USER_READ)
1221 if (perm & GNUNET_DISK_PERM_USER_WRITE)
1223 if (perm & GNUNET_DISK_PERM_USER_EXEC)
1225 if (perm & GNUNET_DISK_PERM_GROUP_READ)
1227 if (perm & GNUNET_DISK_PERM_GROUP_WRITE)
1229 if (perm & GNUNET_DISK_PERM_GROUP_EXEC)
1231 if (perm & GNUNET_DISK_PERM_OTHER_READ)
1233 if (perm & GNUNET_DISK_PERM_OTHER_WRITE)
1235 if (perm & GNUNET_DISK_PERM_OTHER_EXEC)
1239 fd = open (expfn, oflags | O_LARGEFILE, mode);
1242 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "open", expfn);
1243 GNUNET_free (expfn);
1250 if (GNUNET_DISK_OPEN_READWRITE == (flags & GNUNET_DISK_OPEN_READWRITE))
1251 access = FILE_READ_DATA | FILE_WRITE_DATA;
1252 else if (flags & GNUNET_DISK_OPEN_READ)
1253 access = FILE_READ_DATA;
1254 else if (flags & GNUNET_DISK_OPEN_WRITE)
1255 access = FILE_WRITE_DATA;
1257 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1261 else if (flags & GNUNET_DISK_OPEN_CREATE)
1263 if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1264 disp = CREATE_ALWAYS;
1268 else if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1270 disp = TRUNCATE_EXISTING;
1277 /* TODO: access priviledges? */
1278 h = CreateFile (expfn, access, FILE_SHARE_DELETE | FILE_SHARE_READ
1279 | FILE_SHARE_WRITE, NULL, disp, FILE_ATTRIBUTE_NORMAL,
1281 if (h == INVALID_HANDLE_VALUE)
1283 SetErrnoFromWinError (GetLastError ());
1284 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "open", expfn);
1285 GNUNET_free (expfn);
1289 if (flags & GNUNET_DISK_OPEN_APPEND)
1290 if (SetFilePointer (h, 0, 0, FILE_END) == INVALID_SET_FILE_POINTER)
1292 SetErrnoFromWinError (GetLastError ());
1293 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "SetFilePointer",
1296 GNUNET_free (expfn);
1301 ret = GNUNET_malloc (sizeof (struct GNUNET_DISK_FileHandle));
1307 GNUNET_free (expfn);
1313 * Close an open file
1314 * @param h file handle
1315 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1318 GNUNET_DISK_file_close (struct GNUNET_DISK_FileHandle *h)
1323 return GNUNET_SYSERR;
1327 if (!CloseHandle (h->h))
1329 SetErrnoFromWinError (GetLastError ());
1330 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "close");
1332 return GNUNET_SYSERR;
1335 if (close (h->fd) != 0)
1337 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "close");
1339 return GNUNET_SYSERR;
1348 * Construct full path to a file inside of the private
1349 * directory used by GNUnet. Also creates the corresponding
1350 * directory. If the resulting name is supposed to be
1351 * a directory, end the last argument in '/' (or pass
1352 * DIR_SEPARATOR_STR as the last argument before NULL).
1354 * @param cfg configuration to use (determines HOME)
1355 * @param serviceName name of the service
1356 * @param ... is NULL-terminated list of
1357 * path components to append to the
1358 * private directory name.
1359 * @return the constructed filename
1362 GNUNET_DISK_get_home_filename (const struct GNUNET_CONFIGURATION_Handle *cfg,
1363 const char *serviceName, ...)
1369 unsigned int needed;
1372 GNUNET_CONFIGURATION_get_value_filename (cfg,
1373 serviceName, "HOME", &pfx))
1377 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1378 _("No `%s' specified for service `%s' in configuration.\n"),
1379 "HOME", serviceName);
1382 needed = strlen (pfx) + 2;
1383 if ((pfx[strlen (pfx) - 1] != '/') && (pfx[strlen (pfx) - 1] != '\\'))
1385 va_start (ap, serviceName);
1388 c = va_arg (ap, const char *);
1391 needed += strlen (c);
1392 if ((c[strlen (c) - 1] != '/') && (c[strlen (c) - 1] != '\\'))
1396 ret = GNUNET_malloc (needed);
1399 va_start (ap, serviceName);
1402 c = va_arg (ap, const char *);
1405 if ((c[strlen (c) - 1] != '/') && (c[strlen (c) - 1] != '\\'))
1406 strcat (ret, DIR_SEPARATOR_STR);
1410 if ((ret[strlen (ret) - 1] != '/') && (ret[strlen (ret) - 1] != '\\'))
1411 GNUNET_DISK_directory_create_for_file (ret);
1413 GNUNET_DISK_directory_create (ret);
1419 * Handle for a memory-mapping operation.
1421 struct GNUNET_DISK_MapHandle
1425 * Underlying OS handle.
1430 * Address where the map is in memory.
1435 * Number of bytes mapped.
1443 #define MAP_FAILED ((void *) -1)
1447 * Map a file into memory
1449 * @param h open file handle
1450 * @param m handle to the new mapping
1451 * @param access access specification, GNUNET_DISK_MAP_TYPE_xxx
1452 * @param len size of the mapping
1453 * @return pointer to the mapped memory region, NULL on failure
1456 GNUNET_DISK_file_map (const struct GNUNET_DISK_FileHandle *h,
1457 struct GNUNET_DISK_MapHandle **m,
1458 enum GNUNET_DISK_MapType access, size_t len)
1467 DWORD mapAccess, protect;
1470 if ((access & GNUNET_DISK_MAP_TYPE_READ) &&
1471 (access & GNUNET_DISK_MAP_TYPE_WRITE))
1473 protect = PAGE_READWRITE;
1474 mapAccess = FILE_MAP_ALL_ACCESS;
1476 else if (access & GNUNET_DISK_MAP_TYPE_READ)
1478 protect = PAGE_READONLY;
1479 mapAccess = FILE_MAP_READ;
1481 else if (access & GNUNET_DISK_MAP_TYPE_WRITE)
1483 protect = PAGE_READWRITE;
1484 mapAccess = FILE_MAP_WRITE;
1492 *m = GNUNET_malloc (sizeof (struct GNUNET_DISK_MapHandle));
1493 (*m)->h = CreateFileMapping (h->h, NULL, protect, 0, 0, NULL);
1494 if ((*m)->h == INVALID_HANDLE_VALUE)
1496 SetErrnoFromWinError (GetLastError ());
1501 ret = MapViewOfFile ((*m)->h, mapAccess, 0, 0, len);
1504 SetErrnoFromWinError (GetLastError ());
1505 CloseHandle ((*m)->h);
1515 if (access & GNUNET_DISK_MAP_TYPE_READ)
1517 if (access & GNUNET_DISK_MAP_TYPE_WRITE)
1519 *m = GNUNET_malloc (sizeof (struct GNUNET_DISK_MapHandle));
1520 (*m)->addr = mmap (NULL, len, prot, MAP_SHARED, h->fd, 0);
1521 GNUNET_assert (NULL != (*m)->addr);
1522 if (MAP_FAILED == (*m)->addr)
1536 * @param h mapping handle
1537 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1540 GNUNET_DISK_file_unmap (struct GNUNET_DISK_MapHandle *h)
1546 return GNUNET_SYSERR;
1550 ret = UnmapViewOfFile (h->h) ? GNUNET_OK : GNUNET_SYSERR;
1551 if (ret != GNUNET_OK)
1552 SetErrnoFromWinError (GetLastError ());
1553 if (!CloseHandle (h->h) && (ret == GNUNET_OK))
1555 ret = GNUNET_SYSERR;
1556 SetErrnoFromWinError (GetLastError ());
1559 ret = munmap (h->addr, h->len) != -1 ? GNUNET_OK : GNUNET_SYSERR;
1567 * Write file changes to disk
1568 * @param h handle to an open file
1569 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1572 GNUNET_DISK_file_sync (const struct GNUNET_DISK_FileHandle *h)
1577 return GNUNET_SYSERR;
1583 ret = FlushFileBuffers (h->h) ? GNUNET_OK : GNUNET_SYSERR;
1584 if (ret != GNUNET_OK)
1585 SetErrnoFromWinError (GetLastError ());
1587 #elif defined(FREEBSD) || defined(OPENBSD) || defined(DARWIN)
1588 return fsync (h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK;
1590 return fdatasync (h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK;
1595 * Creates an interprocess channel
1597 * @param blocking creates an asynchronous pipe if set to GNUNET_NO
1598 * @return handle to the new pipe, NULL on error
1600 struct GNUNET_DISK_PipeHandle *
1601 GNUNET_DISK_pipe (int blocking)
1603 struct GNUNET_DISK_PipeHandle *p;
1604 struct GNUNET_DISK_FileHandle *fds;
1607 GNUNET_malloc (sizeof (struct GNUNET_DISK_PipeHandle) +
1608 2 * sizeof (struct GNUNET_DISK_FileHandle));
1609 fds = (struct GNUNET_DISK_FileHandle *) &p[1];
1626 p->fd[0]->fd = fd[0];
1627 p->fd[1]->fd = fd[1];
1630 flags = fcntl (fd[0], F_GETFL);
1631 flags |= O_NONBLOCK;
1632 ret = fcntl (fd[0], F_SETFL, flags);
1635 flags = fcntl (fd[1], F_GETFL);
1636 flags |= O_NONBLOCK;
1637 ret = fcntl (fd[1], F_SETFL, flags);
1642 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "fcntl");
1643 GNUNET_break (0 == close (p->fd[0]->fd));
1644 GNUNET_break (0 == close (p->fd[1]->fd));
1653 ret = CreatePipe (&p->fd[0]->h, &p->fd[1]->h, NULL, 0);
1657 SetErrnoFromWinError (GetLastError ());
1665 SetNamedPipeHandleState (p->fd[0]->h, &mode, NULL, NULL);
1666 SetNamedPipeHandleState (p->fd[1]->h, &mode, NULL, NULL);
1667 /* this always fails on Windows 95, so we don't care about error handling */
1675 * Closes an interprocess channel
1677 * @param p pipe to close
1678 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1681 GNUNET_DISK_pipe_close (struct GNUNET_DISK_PipeHandle *p)
1683 int ret = GNUNET_OK;
1687 if (!CloseHandle (p->fd[0]->h))
1689 SetErrnoFromWinError (GetLastError ());
1690 ret = GNUNET_SYSERR;
1692 if (!CloseHandle (p->fd[1]->h))
1694 SetErrnoFromWinError (GetLastError ());
1695 ret = GNUNET_SYSERR;
1700 if (0 != close (p->fd[0]->fd))
1702 ret = GNUNET_SYSERR;
1705 if (0 != close (p->fd[1]->fd))
1707 ret = GNUNET_SYSERR;
1718 * Get the handle to a particular pipe end
1720 * @param n end to access
1722 const struct GNUNET_DISK_FileHandle *
1723 GNUNET_DISK_pipe_handle (const struct GNUNET_DISK_PipeHandle *p,
1724 enum GNUNET_DISK_PipeEnd n)
1728 case GNUNET_DISK_PIPE_END_READ:
1729 case GNUNET_DISK_PIPE_END_WRITE:
1739 * Retrieve OS file handle
1741 * @param fh GNUnet file descriptor
1742 * @param dst destination buffer
1743 * @param dst_len length of dst
1744 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1747 GNUNET_DISK_internal_file_handle_ (const struct GNUNET_DISK_FileHandle *fh,
1748 void *dst, size_t dst_len)
1751 if (dst_len < sizeof (HANDLE))
1752 return GNUNET_SYSERR;
1753 *((HANDLE *) dst) = fh->h;
1755 if (dst_len < sizeof (int))
1756 return GNUNET_SYSERR;
1757 *((int *) dst) = fh->fd;