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. If the given name is not
270 * an absolute path, the current 'TMPDIR' will be prepended. In any case,
271 * 6 random characters will be appended to the name to create a unique
274 * @param t component to use for the name;
275 * does NOT contain "XXXXXX" or "/tmp/".
276 * @return NULL on error, otherwise name of fresh
277 * file on disk in directory for temporary files
280 GNUNET_DISK_mktemp (const char *t)
287 if ( (t[0] != '/') &&
290 tmpdir = getenv ("TMPDIR");
291 tmpdir = tmpdir ? tmpdir : "/tmp";
292 GNUNET_asprintf (&tmpl, "%s/%s%s", tmpdir, t, "XXXXXX");
296 GNUNET_asprintf (&tmpl, "%s%s", t, "XXXXXX");
299 fn = (char *) GNUNET_malloc (MAX_PATH + 1);
300 if (ERROR_SUCCESS != plibc_conv_to_win_path (tmpl, fn))
313 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "mkstemp", fn);
318 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "close", fn);
324 * Get the number of blocks that are left on the partition that
325 * contains the given file (for normal users).
327 * @param part a file on the partition to check
328 * @return -1 on errors, otherwise the number of free blocks
331 GNUNET_DISK_get_blocks_available (const char *part)
336 if (0 != statvfs (part, &buf))
338 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "statfs", part);
348 path = GNUNET_STRINGS_filename_expand (part);
349 memcpy (szDrive, path, 3);
352 if (!GetDiskFreeSpace (szDrive, &dwDummy, &dwDummy, &dwBlocks, &dwDummy))
354 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
355 _("`%s' failed for drive `%s': %u\n"),
356 "GetDiskFreeSpace", szDrive, GetLastError ());
363 if (0 != statfs (part, &s))
365 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "statfs", part);
374 * Test if "fil" is a directory.
375 * Will not print an error message if the directory
376 * does not exist. Will log errors if GNUNET_SYSERR is
377 * returned (i.e., a file exists with the same name).
379 * @param fil filename to test
380 * @return GNUNET_YES if yes, GNUNET_NO if not, GNUNET_SYSERR if it
384 GNUNET_DISK_directory_test (const char *fil)
386 struct stat filestat;
389 ret = STAT (fil, &filestat);
394 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", fil);
395 return GNUNET_SYSERR;
399 if (!S_ISDIR (filestat.st_mode))
401 if (ACCESS (fil, R_OK | X_OK) < 0)
403 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "access", fil);
404 return GNUNET_SYSERR;
410 * Check that fil corresponds to a filename
411 * (of a file that exists and that is not a directory).
413 * @param fil filename to check
414 * @return GNUNET_YES if yes, GNUNET_NO if not a file, GNUNET_SYSERR if something
415 * else (will print an error message in that case, too).
418 GNUNET_DISK_file_test (const char *fil)
420 struct stat filestat;
424 rdir = GNUNET_STRINGS_filename_expand (fil);
426 return GNUNET_SYSERR;
428 ret = STAT (rdir, &filestat);
433 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", rdir);
435 return GNUNET_SYSERR;
440 if (!S_ISREG (filestat.st_mode))
445 if (ACCESS (rdir, R_OK) < 0)
447 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "access", rdir);
449 return GNUNET_SYSERR;
457 * Implementation of "mkdir -p"
458 * @param dir the directory to create
459 * @returns GNUNET_OK on success, GNUNET_SYSERR on failure
462 GNUNET_DISK_directory_create (const char *dir)
469 rdir = GNUNET_STRINGS_filename_expand (dir);
471 return GNUNET_SYSERR;
475 pos = 1; /* skip heading '/' */
477 /* Local or Network path? */
478 if (strncmp (rdir, "\\\\", 2) == 0)
483 if (rdir[pos] == '\\')
493 pos = 3; /* strlen("C:\\") */
498 if ((rdir[pos] == DIR_SEPARATOR) || (pos == len))
501 ret = GNUNET_DISK_directory_test (rdir);
502 if (ret == GNUNET_SYSERR)
505 return GNUNET_SYSERR;
507 if (ret == GNUNET_NO)
510 ret = mkdir (rdir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); /* 755 */
514 if ((ret != 0) && (errno != EEXIST))
516 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "mkdir",
519 return GNUNET_SYSERR;
522 rdir[pos] = DIR_SEPARATOR;
532 * Create the directory structure for storing
535 * @param filename name of a file in the directory
536 * @returns GNUNET_OK on success,
537 * GNUNET_SYSERR on failure,
538 * GNUNET_NO if the directory
539 * exists but is not writeable for us
542 GNUNET_DISK_directory_create_for_file (const char *filename)
548 rdir = GNUNET_STRINGS_filename_expand (filename);
550 return GNUNET_SYSERR;
552 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
555 ret = GNUNET_DISK_directory_create (rdir);
556 if ((ret == GNUNET_OK) && (0 != ACCESS (rdir, W_OK)))
564 * Read the contents of a binary file into a buffer.
565 * @param h handle to an open file
566 * @param result the buffer to write the result to
567 * @param len the maximum number of bytes to read
568 * @return the number of bytes read on success, GNUNET_SYSERR on failure
571 GNUNET_DISK_file_read (const struct GNUNET_DISK_FileHandle * h, void *result,
577 return GNUNET_SYSERR;
583 if (!ReadFile (h->h, result, len, &bytesRead, NULL))
585 SetErrnoFromWinError (GetLastError ());
586 return GNUNET_SYSERR;
590 return read (h->fd, result, len);
596 * Read the contents of a binary file into a buffer.
598 * @param fn file name
599 * @param result the buffer to write the result to
600 * @param len the maximum number of bytes to read
601 * @return number of bytes read, GNUNET_SYSERR on failure
604 GNUNET_DISK_fn_read (const char *fn, void *result, size_t len)
606 struct GNUNET_DISK_FileHandle *fh;
609 fh = GNUNET_DISK_file_open (fn, GNUNET_DISK_OPEN_READ,
610 GNUNET_DISK_PERM_NONE);
612 return GNUNET_SYSERR;
613 ret = GNUNET_DISK_file_read (fh, result, len);
614 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
621 * Write a buffer to a file.
622 * @param h handle to open file
623 * @param buffer the data to write
624 * @param n number of bytes to write
625 * @return number of bytes written on success, GNUNET_SYSERR on error
628 GNUNET_DISK_file_write (const struct GNUNET_DISK_FileHandle * h,
629 const void *buffer, size_t n)
634 return GNUNET_SYSERR;
640 if (!WriteFile (h->h, buffer, n, &bytesWritten, NULL))
642 SetErrnoFromWinError (GetLastError ());
643 return GNUNET_SYSERR;
647 return write (h->fd, buffer, n);
652 * Write a buffer to a file. If the file is longer than the
653 * number of bytes that will be written, it will be truncated.
655 * @param fn file name
656 * @param buffer the data to write
657 * @param n number of bytes to write
658 * @param mode file permissions
659 * @return number of bytes written on success, GNUNET_SYSERR on error
662 GNUNET_DISK_fn_write (const char *fn, const void *buffer,
663 size_t n, enum GNUNET_DISK_AccessPermissions mode)
665 struct GNUNET_DISK_FileHandle *fh;
668 fh = GNUNET_DISK_file_open (fn,
669 GNUNET_DISK_OPEN_WRITE
670 | GNUNET_DISK_OPEN_TRUNCATE
671 | GNUNET_DISK_OPEN_CREATE, mode);
673 return GNUNET_SYSERR;
674 ret = GNUNET_DISK_file_write (fh, buffer, n);
675 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
680 * Scan a directory for files.
682 * @param dirName the name of the directory
683 * @param callback the method to call for each file,
684 * can be NULL, in that case, we only count
685 * @param callback_cls closure for callback
686 * @return the number of files found, GNUNET_SYSERR on error or
687 * ieration aborted by callback returning GNUNET_SYSERR
690 GNUNET_DISK_directory_scan (const char *dirName,
691 GNUNET_FileNameCallback callback,
695 struct dirent *finfo;
700 unsigned int name_len;
703 GNUNET_assert (dirName != NULL);
704 dname = GNUNET_STRINGS_filename_expand (dirName);
705 while ((strlen (dname) > 0) && (dname[strlen (dname) - 1] == DIR_SEPARATOR))
706 dname[strlen (dname) - 1] = '\0';
707 if (0 != STAT (dname, &istat))
709 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", dname);
711 return GNUNET_SYSERR;
713 if (!S_ISDIR (istat.st_mode))
715 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
716 _("Expected `%s' to be a directory!\n"), dirName);
718 return GNUNET_SYSERR;
721 dinfo = OPENDIR (dname);
722 if ((errno == EACCES) || (dinfo == NULL))
724 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "opendir", dname);
728 return GNUNET_SYSERR;
731 n_size = strlen (dname) + name_len + 2;
732 name = GNUNET_malloc (n_size);
733 while ((finfo = readdir (dinfo)) != NULL)
735 if ((0 == strcmp (finfo->d_name, ".")) ||
736 (0 == strcmp (finfo->d_name, "..")))
738 if (callback != NULL)
740 if (name_len < strlen (finfo->d_name))
743 name_len = strlen (finfo->d_name);
744 n_size = strlen (dname) + name_len + 2;
745 name = GNUNET_malloc (n_size);
747 /* dname can end in "/" only if dname == "/";
748 if dname does not end in "/", we need to add
749 a "/" (otherwise, we must not!) */
750 GNUNET_snprintf (name,
754 (strcmp (dname, DIR_SEPARATOR_STR) ==
755 0) ? "" : DIR_SEPARATOR_STR, finfo->d_name);
756 if (GNUNET_OK != callback (callback_cls, name))
761 return GNUNET_SYSERR;
774 * Opaque handle used for iterating over a directory.
776 struct GNUNET_DISK_DirectoryIterator
781 struct GNUNET_SCHEDULER_Handle *sched;
784 * Function to call on directory entries.
786 GNUNET_DISK_DirectoryIteratorCallback callback;
789 * Closure for callback.
794 * Reference to directory.
804 * Next filename to process.
811 enum GNUNET_SCHEDULER_Priority priority;
817 * Task used by the directory iterator.
820 directory_iterator_task (void *cls,
821 const struct GNUNET_SCHEDULER_TaskContext *tc)
823 struct GNUNET_DISK_DirectoryIterator *iter = cls;
826 name = iter->next_name;
827 GNUNET_assert (name != NULL);
828 iter->next_name = NULL;
829 iter->callback (iter->callback_cls, iter, name, iter->dirname);
835 * This function must be called during the DiskIteratorCallback
836 * (exactly once) to schedule the task to process the next
837 * filename in the directory (if there is one).
839 * @param iter opaque handle for the iterator
840 * @param can set to GNUNET_YES to terminate the iteration early
841 * @return GNUNET_YES if iteration will continue,
842 * GNUNET_NO if this was the last entry (and iteration is complete),
843 * GNUNET_SYSERR if abort was YES
846 GNUNET_DISK_directory_iterator_next (struct GNUNET_DISK_DirectoryIterator
849 struct dirent *finfo;
851 GNUNET_assert (iter->next_name == NULL);
852 if (can == GNUNET_YES)
854 closedir (iter->directory);
855 GNUNET_free (iter->dirname);
857 return GNUNET_SYSERR;
859 while (NULL != (finfo = readdir (iter->directory)))
861 if ((0 == strcmp (finfo->d_name, ".")) ||
862 (0 == strcmp (finfo->d_name, "..")))
864 GNUNET_asprintf (&iter->next_name,
866 iter->dirname, DIR_SEPARATOR_STR, finfo->d_name);
871 GNUNET_DISK_directory_iterator_next (iter, GNUNET_YES);
874 GNUNET_SCHEDULER_add_with_priority (iter->sched,
876 &directory_iterator_task, iter);
882 * Scan a directory for files using the scheduler to run a task for
883 * each entry. The name of the directory must be expanded first (!).
884 * If a scheduler does not need to be used, GNUNET_DISK_directory_scan
885 * may provide a simpler API.
887 * @param sched scheduler to use
888 * @param prio priority to use
889 * @param dirName the name of the directory
890 * @param callback the method to call for each file
891 * @param callback_cls closure for callback
894 GNUNET_DISK_directory_iterator_start (struct GNUNET_SCHEDULER_Handle *sched,
895 enum GNUNET_SCHEDULER_Priority prio,
897 GNUNET_DISK_DirectoryIteratorCallback
898 callback, void *callback_cls)
900 struct GNUNET_DISK_DirectoryIterator *di;
902 di = GNUNET_malloc (sizeof (struct GNUNET_DISK_DirectoryIterator));
904 di->callback = callback;
905 di->callback_cls = callback_cls;
906 di->directory = OPENDIR (dirName);
907 di->dirname = GNUNET_strdup (dirName);
909 GNUNET_DISK_directory_iterator_next (di, GNUNET_NO);
914 * Function that removes the given directory by calling
915 * "GNUNET_DISK_directory_remove".
917 * @param unused not used
918 * @param fn directory to remove
922 remove_helper (void *unused, const char *fn)
924 (void) GNUNET_DISK_directory_remove (fn);
930 * Remove all files in a directory (rm -rf). Call with
934 * @param fileName the file to remove
935 * @return GNUNET_OK on success, GNUNET_SYSERR on error
938 GNUNET_DISK_directory_remove (const char *fileName)
942 if (0 != LSTAT (fileName, &istat))
943 return GNUNET_NO; /* file may not exist... */
944 if (UNLINK (fileName) == 0)
946 if ((errno != EISDIR) &&
947 /* EISDIR is not sufficient in all cases, e.g.
948 sticky /tmp directory may result in EPERM on BSD.
949 So we also explicitly check "isDirectory" */
950 (GNUNET_YES != GNUNET_DISK_directory_test (fileName)))
952 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "rmdir", fileName);
953 return GNUNET_SYSERR;
956 GNUNET_DISK_directory_scan (fileName, &remove_helper, NULL))
957 return GNUNET_SYSERR;
958 if (0 != RMDIR (fileName))
960 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "rmdir", fileName);
961 return GNUNET_SYSERR;
970 * @param src file to copy
971 * @param dst destination file name
972 * @return GNUNET_OK on success, GNUNET_SYSERR on error
975 GNUNET_DISK_file_copy (const char *src, const char *dst)
981 struct GNUNET_DISK_FileHandle *in;
982 struct GNUNET_DISK_FileHandle *out;
984 if (GNUNET_OK != GNUNET_DISK_file_size (src, &size, GNUNET_YES))
985 return GNUNET_SYSERR;
987 in = GNUNET_DISK_file_open (src, GNUNET_DISK_OPEN_READ,
988 GNUNET_DISK_PERM_NONE);
990 return GNUNET_SYSERR;
991 out = GNUNET_DISK_file_open (dst, GNUNET_DISK_OPEN_WRITE
992 | GNUNET_DISK_OPEN_CREATE |
993 GNUNET_DISK_OPEN_FAILIFEXISTS,
994 GNUNET_DISK_PERM_USER_READ |
995 GNUNET_DISK_PERM_USER_WRITE |
996 GNUNET_DISK_PERM_GROUP_READ |
997 GNUNET_DISK_PERM_GROUP_WRITE);
1000 GNUNET_DISK_file_close (in);
1001 return GNUNET_SYSERR;
1003 buf = GNUNET_malloc (COPY_BLK_SIZE);
1006 len = COPY_BLK_SIZE;
1007 if (len > size - pos)
1009 if (len != GNUNET_DISK_file_read (in, buf, len))
1011 if (len != GNUNET_DISK_file_write (out, buf, len))
1016 GNUNET_DISK_file_close (in);
1017 GNUNET_DISK_file_close (out);
1021 GNUNET_DISK_file_close (in);
1022 GNUNET_DISK_file_close (out);
1023 return GNUNET_SYSERR;
1028 * @brief Removes special characters as ':' from a filename.
1029 * @param fn the filename to canonicalize
1032 GNUNET_DISK_filename_canonicalize (char *fn)
1042 if (c == '/' || c == '\\' || c == ':' || c == '*' || c == '?' ||
1043 c == '"' || c == '<' || c == '>' || c == '|')
1055 * @brief Change owner of a file
1057 * @param filename name of file to change the owner of
1058 * @param user name of the new owner
1059 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1062 GNUNET_DISK_file_change_owner (const char *filename, const char *user)
1067 pws = getpwnam (user);
1070 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1071 _("Cannot obtain information about user `%s': %s\n"),
1072 user, STRERROR (errno));
1073 return GNUNET_SYSERR;
1075 if (0 != chown (filename, pws->pw_uid, pws->pw_gid))
1076 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "chown", filename);
1083 * Lock a part of a file
1084 * @param fh file handle
1085 * @param lockStart absolute position from where to lock
1086 * @param lockEnd absolute position until where to lock
1087 * @param excl GNUNET_YES for an exclusive lock
1088 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1091 GNUNET_DISK_file_lock (struct GNUNET_DISK_FileHandle *fh, off_t lockStart,
1092 off_t lockEnd, int excl)
1097 return GNUNET_SYSERR;
1103 memset (&fl, 0, sizeof (struct flock));
1104 fl.l_type = excl ? F_WRLCK : F_RDLCK;
1105 fl.l_whence = SEEK_SET;
1106 fl.l_start = lockStart;
1109 return fcntl (fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK;
1113 memset (&o, 0, sizeof (OVERLAPPED));
1114 o.Offset = lockStart;
1116 if (!LockFileEx (fh->h, (excl ? LOCKFILE_EXCLUSIVE_LOCK : 0)
1117 | LOCKFILE_FAIL_IMMEDIATELY, 0, lockEnd - lockStart, 0,
1120 SetErrnoFromWinError (GetLastError ());
1121 return GNUNET_SYSERR;
1130 * Unlock a part of a file
1131 * @param fh file handle
1132 * @param unlockStart absolute position from where to unlock
1133 * @param unlockEnd absolute position until where to unlock
1134 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1137 GNUNET_DISK_file_unlock (struct GNUNET_DISK_FileHandle *fh, off_t unlockStart,
1143 return GNUNET_SYSERR;
1149 memset (&fl, 0, sizeof (struct flock));
1150 fl.l_type = F_UNLCK;
1151 fl.l_whence = SEEK_SET;
1152 fl.l_start = unlockStart;
1153 fl.l_len = unlockEnd;
1155 return fcntl (fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK;
1159 memset (&o, 0, sizeof (OVERLAPPED));
1160 o.Offset = unlockStart;
1162 if (!UnlockFileEx (fh->h, 0, unlockEnd - unlockStart, 0, &o))
1164 SetErrnoFromWinError (GetLastError ());
1165 return GNUNET_SYSERR;
1174 * Open a file. Note that the access permissions will only be
1175 * used if a new file is created and if the underlying operating
1176 * system supports the given permissions.
1178 * @param fn file name to be opened
1179 * @param flags opening flags, a combination of GNUNET_DISK_OPEN_xxx bit flags
1180 * @param perm permissions for the newly created file, use
1181 * GNUNET_DISK_PERM_USER_NONE if a file could not be created by this
1182 * call (because of flags)
1183 * @return IO handle on success, NULL on error
1185 struct GNUNET_DISK_FileHandle *
1186 GNUNET_DISK_file_open (const char *fn,
1187 enum GNUNET_DISK_OpenFlags flags,
1188 enum GNUNET_DISK_AccessPermissions perm)
1191 struct GNUNET_DISK_FileHandle *ret;
1202 expfn = GNUNET_STRINGS_filename_expand (fn);
1208 if (GNUNET_DISK_OPEN_READWRITE == (flags & GNUNET_DISK_OPEN_READWRITE))
1209 oflags = O_RDWR; /* note: O_RDWR is NOT always O_RDONLY | O_WRONLY */
1210 else if (flags & GNUNET_DISK_OPEN_READ)
1212 else if (flags & GNUNET_DISK_OPEN_WRITE)
1217 GNUNET_free (expfn);
1220 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1221 oflags |= (O_CREAT | O_EXCL);
1222 if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1224 if (flags & GNUNET_DISK_OPEN_APPEND)
1226 if (flags & GNUNET_DISK_OPEN_CREATE)
1229 if (perm & GNUNET_DISK_PERM_USER_READ)
1231 if (perm & GNUNET_DISK_PERM_USER_WRITE)
1233 if (perm & GNUNET_DISK_PERM_USER_EXEC)
1235 if (perm & GNUNET_DISK_PERM_GROUP_READ)
1237 if (perm & GNUNET_DISK_PERM_GROUP_WRITE)
1239 if (perm & GNUNET_DISK_PERM_GROUP_EXEC)
1241 if (perm & GNUNET_DISK_PERM_OTHER_READ)
1243 if (perm & GNUNET_DISK_PERM_OTHER_WRITE)
1245 if (perm & GNUNET_DISK_PERM_OTHER_EXEC)
1249 fd = open (expfn, oflags | O_LARGEFILE, mode);
1252 if (0 == (flags & GNUNET_DISK_OPEN_FAILIFEXISTS))
1253 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "open", expfn);
1255 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_DEBUG, "open", expfn);
1256 GNUNET_free (expfn);
1263 if (GNUNET_DISK_OPEN_READWRITE == (flags & GNUNET_DISK_OPEN_READWRITE))
1264 access = FILE_READ_DATA | FILE_WRITE_DATA;
1265 else if (flags & GNUNET_DISK_OPEN_READ)
1266 access = FILE_READ_DATA;
1267 else if (flags & GNUNET_DISK_OPEN_WRITE)
1268 access = FILE_WRITE_DATA;
1270 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1274 else if (flags & GNUNET_DISK_OPEN_CREATE)
1276 if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1277 disp = CREATE_ALWAYS;
1281 else if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1283 disp = TRUNCATE_EXISTING;
1287 disp = OPEN_EXISTING;
1290 /* TODO: access priviledges? */
1291 h = CreateFile (expfn, access, FILE_SHARE_DELETE | FILE_SHARE_READ
1292 | FILE_SHARE_WRITE, NULL, disp, FILE_ATTRIBUTE_NORMAL,
1294 if (h == INVALID_HANDLE_VALUE)
1296 SetErrnoFromWinError (GetLastError ());
1297 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "open", expfn);
1298 GNUNET_free (expfn);
1302 if (flags & GNUNET_DISK_OPEN_APPEND)
1303 if (SetFilePointer (h, 0, 0, FILE_END) == INVALID_SET_FILE_POINTER)
1305 SetErrnoFromWinError (GetLastError ());
1306 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "SetFilePointer",
1309 GNUNET_free (expfn);
1314 ret = GNUNET_malloc (sizeof (struct GNUNET_DISK_FileHandle));
1320 GNUNET_free (expfn);
1326 * Close an open file
1327 * @param h file handle
1328 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1331 GNUNET_DISK_file_close (struct GNUNET_DISK_FileHandle *h)
1336 return GNUNET_SYSERR;
1340 if (!CloseHandle (h->h))
1342 SetErrnoFromWinError (GetLastError ());
1343 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "close");
1345 return GNUNET_SYSERR;
1348 if (close (h->fd) != 0)
1350 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "close");
1352 return GNUNET_SYSERR;
1361 * Construct full path to a file inside of the private
1362 * directory used by GNUnet. Also creates the corresponding
1363 * directory. If the resulting name is supposed to be
1364 * a directory, end the last argument in '/' (or pass
1365 * DIR_SEPARATOR_STR as the last argument before NULL).
1367 * @param cfg configuration to use (determines HOME)
1368 * @param serviceName name of the service
1369 * @param ... is NULL-terminated list of
1370 * path components to append to the
1371 * private directory name.
1372 * @return the constructed filename
1375 GNUNET_DISK_get_home_filename (const struct GNUNET_CONFIGURATION_Handle *cfg,
1376 const char *serviceName, ...)
1382 unsigned int needed;
1385 GNUNET_CONFIGURATION_get_value_filename (cfg,
1386 serviceName, "HOME", &pfx))
1390 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1391 _("No `%s' specified for service `%s' in configuration.\n"),
1392 "HOME", serviceName);
1395 needed = strlen (pfx) + 2;
1396 if ((pfx[strlen (pfx) - 1] != '/') && (pfx[strlen (pfx) - 1] != '\\'))
1398 va_start (ap, serviceName);
1401 c = va_arg (ap, const char *);
1404 needed += strlen (c);
1405 if ((c[strlen (c) - 1] != '/') && (c[strlen (c) - 1] != '\\'))
1409 ret = GNUNET_malloc (needed);
1412 va_start (ap, serviceName);
1415 c = va_arg (ap, const char *);
1418 if ((c[strlen (c) - 1] != '/') && (c[strlen (c) - 1] != '\\'))
1419 strcat (ret, DIR_SEPARATOR_STR);
1423 if ((ret[strlen (ret) - 1] != '/') && (ret[strlen (ret) - 1] != '\\'))
1424 GNUNET_DISK_directory_create_for_file (ret);
1426 GNUNET_DISK_directory_create (ret);
1432 * Handle for a memory-mapping operation.
1434 struct GNUNET_DISK_MapHandle
1438 * Underlying OS handle.
1443 * Address where the map is in memory.
1448 * Number of bytes mapped.
1456 #define MAP_FAILED ((void *) -1)
1460 * Map a file into memory
1462 * @param h open file handle
1463 * @param m handle to the new mapping
1464 * @param access access specification, GNUNET_DISK_MAP_TYPE_xxx
1465 * @param len size of the mapping
1466 * @return pointer to the mapped memory region, NULL on failure
1469 GNUNET_DISK_file_map (const struct GNUNET_DISK_FileHandle *h,
1470 struct GNUNET_DISK_MapHandle **m,
1471 enum GNUNET_DISK_MapType access, size_t len)
1480 DWORD mapAccess, protect;
1483 if ((access & GNUNET_DISK_MAP_TYPE_READ) &&
1484 (access & GNUNET_DISK_MAP_TYPE_WRITE))
1486 protect = PAGE_READWRITE;
1487 mapAccess = FILE_MAP_ALL_ACCESS;
1489 else if (access & GNUNET_DISK_MAP_TYPE_READ)
1491 protect = PAGE_READONLY;
1492 mapAccess = FILE_MAP_READ;
1494 else if (access & GNUNET_DISK_MAP_TYPE_WRITE)
1496 protect = PAGE_READWRITE;
1497 mapAccess = FILE_MAP_WRITE;
1505 *m = GNUNET_malloc (sizeof (struct GNUNET_DISK_MapHandle));
1506 (*m)->h = CreateFileMapping (h->h, NULL, protect, 0, 0, NULL);
1507 if ((*m)->h == INVALID_HANDLE_VALUE)
1509 SetErrnoFromWinError (GetLastError ());
1514 ret = MapViewOfFile ((*m)->h, mapAccess, 0, 0, len);
1517 SetErrnoFromWinError (GetLastError ());
1518 CloseHandle ((*m)->h);
1528 if (access & GNUNET_DISK_MAP_TYPE_READ)
1530 if (access & GNUNET_DISK_MAP_TYPE_WRITE)
1532 *m = GNUNET_malloc (sizeof (struct GNUNET_DISK_MapHandle));
1533 (*m)->addr = mmap (NULL, len, prot, MAP_SHARED, h->fd, 0);
1534 GNUNET_assert (NULL != (*m)->addr);
1535 if (MAP_FAILED == (*m)->addr)
1549 * @param h mapping handle
1550 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1553 GNUNET_DISK_file_unmap (struct GNUNET_DISK_MapHandle *h)
1559 return GNUNET_SYSERR;
1563 ret = UnmapViewOfFile (h->h) ? GNUNET_OK : GNUNET_SYSERR;
1564 if (ret != GNUNET_OK)
1565 SetErrnoFromWinError (GetLastError ());
1566 if (!CloseHandle (h->h) && (ret == GNUNET_OK))
1568 ret = GNUNET_SYSERR;
1569 SetErrnoFromWinError (GetLastError ());
1572 ret = munmap (h->addr, h->len) != -1 ? GNUNET_OK : GNUNET_SYSERR;
1580 * Write file changes to disk
1581 * @param h handle to an open file
1582 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1585 GNUNET_DISK_file_sync (const struct GNUNET_DISK_FileHandle *h)
1590 return GNUNET_SYSERR;
1596 ret = FlushFileBuffers (h->h) ? GNUNET_OK : GNUNET_SYSERR;
1597 if (ret != GNUNET_OK)
1598 SetErrnoFromWinError (GetLastError ());
1600 #elif defined(FREEBSD) || defined(OPENBSD) || defined(DARWIN)
1601 return fsync (h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK;
1603 return fdatasync (h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK;
1608 * Creates an interprocess channel
1610 * @param blocking creates an asynchronous pipe if set to GNUNET_NO
1611 * @return handle to the new pipe, NULL on error
1613 struct GNUNET_DISK_PipeHandle *
1614 GNUNET_DISK_pipe (int blocking)
1616 struct GNUNET_DISK_PipeHandle *p;
1617 struct GNUNET_DISK_FileHandle *fds;
1620 GNUNET_malloc (sizeof (struct GNUNET_DISK_PipeHandle) +
1621 2 * sizeof (struct GNUNET_DISK_FileHandle));
1622 fds = (struct GNUNET_DISK_FileHandle *) &p[1];
1639 p->fd[0]->fd = fd[0];
1640 p->fd[1]->fd = fd[1];
1643 flags = fcntl (fd[0], F_GETFL);
1644 flags |= O_NONBLOCK;
1645 ret = fcntl (fd[0], F_SETFL, flags);
1648 flags = fcntl (fd[1], F_GETFL);
1649 flags |= O_NONBLOCK;
1650 ret = fcntl (fd[1], F_SETFL, flags);
1655 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "fcntl");
1656 GNUNET_break (0 == close (p->fd[0]->fd));
1657 GNUNET_break (0 == close (p->fd[1]->fd));
1666 ret = CreatePipe (&p->fd[0]->h, &p->fd[1]->h, NULL, 0);
1670 SetErrnoFromWinError (GetLastError ());
1678 SetNamedPipeHandleState (p->fd[0]->h, &mode, NULL, NULL);
1679 SetNamedPipeHandleState (p->fd[1]->h, &mode, NULL, NULL);
1680 /* this always fails on Windows 95, so we don't care about error handling */
1688 * Closes an interprocess channel
1690 * @param p pipe to close
1691 * @param end which end of the pipe to close
1692 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1695 GNUNET_DISK_pipe_close_end (struct GNUNET_DISK_PipeHandle *p,
1696 enum GNUNET_DISK_PipeEnd end)
1698 int ret = GNUNET_OK;
1702 if (end == GNUNET_DISK_PIPE_END_READ)
1704 if (!CloseHandle (p->fd[0]->h))
1706 SetErrnoFromWinError (GetLastError ());
1707 ret = GNUNET_SYSERR;
1709 p->fd[0]->h = INVALID_HANDLE_VALUE;
1711 else if (end == GNUNET_DISK_PIPE_END_WRITE)
1713 if (!CloseHandle (p->fd[1]->h))
1715 SetErrnoFromWinError (GetLastError ());
1716 ret = GNUNET_SYSERR;
1718 p->fd[1]->h = INVALID_HANDLE_VALUE;
1723 if (end == GNUNET_DISK_PIPE_END_READ)
1725 if (0 != close (p->fd[0]->fd))
1727 ret = GNUNET_SYSERR;
1732 else if (end == GNUNET_DISK_PIPE_END_WRITE)
1734 if (0 != close (p->fd[1]->fd))
1736 ret = GNUNET_SYSERR;
1747 * Closes an interprocess channel
1749 * @param p pipe to close
1750 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1753 GNUNET_DISK_pipe_close (struct GNUNET_DISK_PipeHandle *p)
1755 int ret = GNUNET_OK;
1759 if (!CloseHandle (p->fd[0]->h))
1761 SetErrnoFromWinError (GetLastError ());
1762 ret = GNUNET_SYSERR;
1764 if (!CloseHandle (p->fd[1]->h))
1766 SetErrnoFromWinError (GetLastError ());
1767 ret = GNUNET_SYSERR;
1772 if (p->fd[0]->fd != -1)
1774 if (0 != close (p->fd[0]->fd))
1776 ret = GNUNET_SYSERR;
1781 if (p->fd[1]->fd != -1)
1783 if (0 != close (p->fd[1]->fd))
1785 ret = GNUNET_SYSERR;
1797 * Get the handle to a particular pipe end
1800 * @param n end to access
1801 * @return handle for the respective end
1803 const struct GNUNET_DISK_FileHandle *
1804 GNUNET_DISK_pipe_handle (const struct GNUNET_DISK_PipeHandle *p,
1805 enum GNUNET_DISK_PipeEnd n)
1809 case GNUNET_DISK_PIPE_END_READ:
1810 case GNUNET_DISK_PIPE_END_WRITE:
1820 * Retrieve OS file handle
1822 * @param fh GNUnet file descriptor
1823 * @param dst destination buffer
1824 * @param dst_len length of dst
1825 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1828 GNUNET_DISK_internal_file_handle_ (const struct GNUNET_DISK_FileHandle *fh,
1829 void *dst, size_t dst_len)
1832 if (dst_len < sizeof (HANDLE))
1833 return GNUNET_SYSERR;
1834 *((HANDLE *) dst) = fh->h;
1836 if (dst_len < sizeof (int))
1837 return GNUNET_SYSERR;
1838 *((int *) dst) = fh->fd;