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"
41 #include <sys/param.h>
42 #include <sys/mount.h>
45 #include <sys/param.h>
46 #include <sys/mount.h>
49 #include <sys/types.h>
50 #include <sys/statvfs.h>
53 #define _IFMT 0170000 /* type of file */
54 #define _IFLNK 0120000 /* symbolic link */
55 #define S_ISLNK(m) (((m)&_IFMT) == _IFLNK)
57 #error PORT-ME: need to port statfs (how much space is left on the drive?)
75 int include_sym_links;
78 struct GNUNET_DISK_PipeHandle
80 struct GNUNET_DISK_FileHandle fd[2];
84 getSizeRec (void *ptr, const char *fn)
86 GetFileSizeData *gfsd = ptr;
94 if (0 != STAT64 (fn, &buf))
96 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat64", fn);
100 if (0 != STAT (fn, &buf))
102 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", fn);
103 return GNUNET_SYSERR;
106 if ((!S_ISLNK (buf.st_mode)) || (gfsd->include_sym_links == GNUNET_YES))
107 gfsd->total += buf.st_size;
108 if ((S_ISDIR (buf.st_mode)) &&
109 (0 == ACCESS (fn, X_OK)) &&
110 ((!S_ISLNK (buf.st_mode)) || (gfsd->include_sym_links == GNUNET_YES)))
112 if (GNUNET_SYSERR == GNUNET_DISK_directory_scan (fn, &getSizeRec, gfsd))
113 return GNUNET_SYSERR;
119 * Checks whether a handle is invalid
120 * @param h handle to check
121 * @return GNUNET_YES if invalid, GNUNET_NO if valid
124 GNUNET_DISK_handle_invalid (const struct GNUNET_DISK_FileHandle *h)
127 return !h || h->h == INVALID_HANDLE_VALUE ? GNUNET_YES : GNUNET_NO;
129 return !h || h->fd == -1 ? GNUNET_YES : GNUNET_NO;
135 * Move the read/write pointer in a file
136 * @param h handle of an open file
137 * @param offset position to move to
138 * @param whence specification to which position the offset parameter relates to
139 * @return the new position on success, GNUNET_SYSERR otherwise
142 GNUNET_DISK_file_seek (const struct GNUNET_DISK_FileHandle *h, off_t offset,
143 enum GNUNET_DISK_Seek whence)
148 return GNUNET_SYSERR;
153 static DWORD t[] = { [GNUNET_DISK_SEEK_SET] = FILE_BEGIN,
154 [GNUNET_DISK_SEEK_CUR] = FILE_CURRENT, [GNUNET_DISK_SEEK_END] = FILE_END };
156 ret = SetFilePointer (h->h, offset, NULL, t[whence]);
157 if (ret == INVALID_SET_FILE_POINTER)
159 SetErrnoFromWinError (GetLastError ());
160 return GNUNET_SYSERR;
164 static int t[] = { [GNUNET_DISK_SEEK_SET] = SEEK_SET,
165 [GNUNET_DISK_SEEK_CUR] = SEEK_CUR, [GNUNET_DISK_SEEK_END] = SEEK_END };
167 return lseek (h->fd, offset, t[whence]);
172 * Get the size of the file (or directory)
173 * of the given file (in bytes).
175 * @return GNUNET_SYSERR on error, GNUNET_OK on success
178 GNUNET_DISK_file_size (const char *filename,
182 GetFileSizeData gfsd;
185 GNUNET_assert (size != NULL);
187 gfsd.include_sym_links = includeSymLinks;
188 ret = getSizeRec (&gfsd, filename);
196 #include <sys/statvfs.h>
204 * @param filename name of the file
205 * @param dev set to the device ID
206 * @param ino set to the inode ID
207 * @return GNUNET_OK on success
209 int GNUNET_DISK_file_get_identifiers (const char *filename,
217 if ( (0 == stat(filename,
219 (0 == statvfs (filename,
222 *dev = (uint32_t) fbuf.f_fsid;
223 *ino = (uint64_t) sbuf.st_ino;
226 return GNUNET_SYSERR;
231 * Create an (empty) temporary file on disk.
233 * @param template component to use for the name;
234 * does NOT contain "XXXXXX" or "/tmp/".
235 * @return NULL on error, otherwise name of fresh
236 * file on disk in directory for temporary files
239 GNUNET_DISK_mktemp (const char *t)
246 tmpdir = getenv ("TMPDIR");
247 tmpdir = tmpdir ? tmpdir : "/tmp";
249 GNUNET_asprintf (&tmpl,
256 fn = (char *) GNUNET_malloc (MAX_PATH + 1);
257 plibc_conv_to_win_path (tmpl, fn);
265 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
272 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
280 * Get the number of blocks that are left on the partition that
281 * contains the given file (for normal users).
283 * @param part a file on the partition to check
284 * @return -1 on errors, otherwise the number of free blocks
287 GNUNET_DISK_get_blocks_available (const char *part)
292 if (0 != statvfs (part, &buf))
294 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "statfs", part);
304 path = GNUNET_STRINGS_filename_expand (part);
305 memcpy (szDrive, path, 3);
308 if (!GetDiskFreeSpace (szDrive, &dwDummy, &dwDummy, &dwBlocks, &dwDummy))
310 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
311 _("`%s' failed for drive `%s': %u\n"),
312 "GetDiskFreeSpace", szDrive, GetLastError ());
319 if (0 != statfs (part, &s))
321 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "statfs", part);
329 * Test if fil is a directory.
331 * @return GNUNET_YES if yes, GNUNET_NO if not, GNUNET_SYSERR if it
335 GNUNET_DISK_directory_test (const char *fil)
337 struct stat filestat;
340 ret = STAT (fil, &filestat);
345 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", fil);
346 return GNUNET_SYSERR;
350 if (!S_ISDIR (filestat.st_mode))
352 if (ACCESS (fil, R_OK | X_OK) < 0)
354 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "access", fil);
355 return GNUNET_SYSERR;
361 * Check that fil corresponds to a filename
362 * (of a file that exists and that is not a directory).
363 * @returns GNUNET_YES if yes, GNUNET_NO if not a file, GNUNET_SYSERR if something
364 * else (will print an error message in that case, too).
367 GNUNET_DISK_file_test (const char *fil)
369 struct stat filestat;
373 rdir = GNUNET_STRINGS_filename_expand (fil);
375 return GNUNET_SYSERR;
377 ret = STAT (rdir, &filestat);
382 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", rdir);
384 return GNUNET_SYSERR;
389 if (!S_ISREG (filestat.st_mode))
394 if (ACCESS (rdir, R_OK) < 0)
396 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "access", rdir);
398 return GNUNET_SYSERR;
405 * Implementation of "mkdir -p"
406 * @param dir the directory to create
407 * @returns GNUNET_OK on success, GNUNET_SYSERR on failure
410 GNUNET_DISK_directory_create (const char *dir)
417 rdir = GNUNET_STRINGS_filename_expand (dir);
419 return GNUNET_SYSERR;
423 pos = 1; /* skip heading '/' */
425 /* Local or Network path? */
426 if (strncmp (rdir, "\\\\", 2) == 0)
431 if (rdir[pos] == '\\')
441 pos = 3; /* strlen("C:\\") */
446 if ((rdir[pos] == DIR_SEPARATOR) || (pos == len))
449 ret = GNUNET_DISK_directory_test (rdir);
450 if (ret == GNUNET_SYSERR)
453 return GNUNET_SYSERR;
455 if (ret == GNUNET_NO)
458 ret = mkdir (rdir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); /* 755 */
462 if ((ret != 0) && (errno != EEXIST))
464 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "mkdir",
467 return GNUNET_SYSERR;
470 rdir[pos] = DIR_SEPARATOR;
480 * Create the directory structure for storing
483 * @param filename name of a file in the directory
484 * @returns GNUNET_OK on success,
485 * GNUNET_SYSERR on failure,
486 * GNUNET_NO if the directory
487 * exists but is not writeable for us
490 GNUNET_DISK_directory_create_for_file (const char *dir)
496 rdir = GNUNET_STRINGS_filename_expand (dir);
498 return GNUNET_SYSERR;
500 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
503 ret = GNUNET_DISK_directory_create (rdir);
504 if ((ret == GNUNET_OK) && (0 != ACCESS (rdir, W_OK)))
511 * Read the contents of a binary file into a buffer.
512 * @param h handle to an open file
513 * @param result the buffer to write the result to
514 * @param len the maximum number of bytes to read
515 * @return the number of bytes read on success, GNUNET_SYSERR on failure
518 GNUNET_DISK_file_read (const struct GNUNET_DISK_FileHandle *h, void *result,
524 return GNUNET_SYSERR;
530 if (!ReadFile (h->h, result, len, &bytesRead, NULL))
532 SetErrnoFromWinError (GetLastError ());
533 return GNUNET_SYSERR;
537 return read (h->fd, result, len);
543 * Read the contents of a binary file into a buffer.
545 * @param fn file name
546 * @param result the buffer to write the result to
547 * @param len the maximum number of bytes to read
548 * @return number of bytes read, GNUNET_SYSERR on failure
551 GNUNET_DISK_fn_read (const char * const fn,
555 struct GNUNET_DISK_FileHandle *fh;
558 fh = GNUNET_DISK_file_open (fn, GNUNET_DISK_OPEN_READ);
560 return GNUNET_SYSERR;
561 ret = GNUNET_DISK_file_read (fh, result, len);
562 GNUNET_assert(GNUNET_OK == GNUNET_DISK_file_close(fh));
569 * Write a buffer to a file.
570 * @param h handle to open file
571 * @param buffer the data to write
572 * @param n number of bytes to write
573 * @return number of bytes written on success, GNUNET_SYSERR on error
576 GNUNET_DISK_file_write (const struct GNUNET_DISK_FileHandle *h, const void *buffer,
582 return GNUNET_SYSERR;
588 if (!WriteFile (h->h, buffer, n, &bytesWritten, NULL))
590 SetErrnoFromWinError (GetLastError ());
591 return GNUNET_SYSERR;
595 return write (h->fd, buffer, n);
600 * Write a buffer to a file. If the file is longer than the
601 * number of bytes that will be written, iit will be truncated.
603 * @param fn file name
604 * @param buffer the data to write
605 * @param n number of bytes to write
606 * @return GNUNET_OK on success, GNUNET_SYSERR on error
609 GNUNET_DISK_fn_write (const char * const fn, const void *buffer,
612 struct GNUNET_DISK_FileHandle *fh;
615 fh = GNUNET_DISK_file_open (fn,
616 GNUNET_DISK_OPEN_WRITE
617 | GNUNET_DISK_OPEN_TRUNCATE
618 | GNUNET_DISK_OPEN_CREATE, mode);
620 return GNUNET_SYSERR;
621 ret = (n == GNUNET_DISK_file_write (fh, buffer, n)) ? GNUNET_OK : GNUNET_SYSERR;
622 GNUNET_assert(GNUNET_OK == GNUNET_DISK_file_close(fh));
628 * Scan a directory for files. The name of the directory
629 * must be expanded first (!).
630 * @param dirName the name of the directory
631 * @param callback the method to call for each file,
632 * can be NULL, in that case, we only count
633 * @param data argument to pass to callback
634 * @return the number of files found, GNUNET_SYSERR on error or
635 * ieration aborted by callback returning GNUNET_SYSERR
638 GNUNET_DISK_directory_scan (const char *dirName,
639 GNUNET_FileNameCallback callback, void *data)
642 struct dirent *finfo;
647 unsigned int name_len;
650 GNUNET_assert (dirName != NULL);
651 dname = GNUNET_STRINGS_filename_expand (dirName);
652 while ((strlen (dname) > 0) && (dname[strlen (dname) - 1] == DIR_SEPARATOR))
653 dname[strlen (dname) - 1] = '\0';
654 if (0 != STAT (dname, &istat))
656 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", dname);
658 return GNUNET_SYSERR;
660 if (!S_ISDIR (istat.st_mode))
662 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
663 _("Expected `%s' to be a directory!\n"), dirName);
665 return GNUNET_SYSERR;
668 dinfo = OPENDIR (dname);
669 if ((errno == EACCES) || (dinfo == NULL))
671 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "opendir", dname);
675 return GNUNET_SYSERR;
678 n_size = strlen (dname) + name_len + 2;
679 name = GNUNET_malloc (n_size);
680 while ((finfo = readdir (dinfo)) != NULL)
682 if ((0 == strcmp (finfo->d_name, ".")) ||
683 (0 == strcmp (finfo->d_name, "..")))
685 if (callback != NULL)
687 if (name_len < strlen (finfo->d_name))
690 name_len = strlen (finfo->d_name);
691 n_size = strlen (dname) + name_len + 2;
692 name = GNUNET_malloc (n_size);
694 /* dname can end in "/" only if dname == "/";
695 if dname does not end in "/", we need to add
696 a "/" (otherwise, we must not!) */
697 GNUNET_snprintf (name,
701 (strcmp (dname, DIR_SEPARATOR_STR) ==
702 0) ? "" : DIR_SEPARATOR_STR, finfo->d_name);
703 if (GNUNET_OK != callback (data, name))
708 return GNUNET_SYSERR;
721 * Opaque handle used for iterating over a directory.
723 struct GNUNET_DISK_DirectoryIterator
728 struct GNUNET_SCHEDULER_Handle *sched;
731 * Function to call on directory entries.
733 GNUNET_DISK_DirectoryIteratorCallback callback;
736 * Closure for callback.
741 * Reference to directory.
751 * Next filename to process.
758 enum GNUNET_SCHEDULER_Priority priority;
764 * Task used by the directory iterator.
767 directory_iterator_task (void *cls,
768 const struct GNUNET_SCHEDULER_TaskContext *tc)
770 struct GNUNET_DISK_DirectoryIterator *iter = cls;
773 name = iter->next_name;
774 GNUNET_assert (name != NULL);
775 iter->next_name = NULL;
776 iter->callback (iter->callback_cls, iter, name, iter->dirname);
782 * This function must be called during the DiskIteratorCallback
783 * (exactly once) to schedule the task to process the next
784 * filename in the directory (if there is one).
786 * @param iter opaque handle for the iterator
787 * @param can set to GNUNET_YES to terminate the iteration early
788 * @return GNUNET_YES if iteration will continue,
789 * GNUNET_NO if this was the last entry (and iteration is complete),
790 * GNUNET_SYSERR if abort was YES
793 GNUNET_DISK_directory_iterator_next (struct GNUNET_DISK_DirectoryIterator
796 struct dirent *finfo;
798 GNUNET_assert (iter->next_name == NULL);
799 if (can == GNUNET_YES)
801 closedir (iter->directory);
802 GNUNET_free (iter->dirname);
804 return GNUNET_SYSERR;
806 while (NULL != (finfo = readdir (iter->directory)))
808 if ((0 == strcmp (finfo->d_name, ".")) ||
809 (0 == strcmp (finfo->d_name, "..")))
811 GNUNET_asprintf (&iter->next_name,
813 iter->dirname, DIR_SEPARATOR_STR, finfo->d_name);
818 GNUNET_DISK_directory_iterator_next (iter, GNUNET_YES);
821 GNUNET_SCHEDULER_add_after (iter->sched,
824 GNUNET_SCHEDULER_NO_TASK,
825 &directory_iterator_task, iter);
831 * Scan a directory for files using the scheduler to run a task for
832 * each entry. The name of the directory must be expanded first (!).
833 * If a scheduler does not need to be used, GNUNET_DISK_directory_scan
834 * may provide a simpler API.
836 * @param sched scheduler to use
837 * @param prio priority to use
838 * @param dirName the name of the directory
839 * @param callback the method to call for each file
840 * @param callback_cls closure for callback
843 GNUNET_DISK_directory_iterator_start (struct GNUNET_SCHEDULER_Handle *sched,
844 enum GNUNET_SCHEDULER_Priority prio,
846 GNUNET_DISK_DirectoryIteratorCallback
847 callback, void *callback_cls)
849 struct GNUNET_DISK_DirectoryIterator *di;
851 di = GNUNET_malloc (sizeof (struct GNUNET_DISK_DirectoryIterator));
853 di->callback = callback;
854 di->callback_cls = callback_cls;
855 di->directory = OPENDIR (dirName);
856 di->dirname = GNUNET_strdup (dirName);
858 GNUNET_DISK_directory_iterator_next (di, GNUNET_NO);
863 remove_helper (void *unused, const char *fn)
865 GNUNET_DISK_directory_remove (fn);
870 * Remove all files in a directory (rm -rf). Call with
874 * @param fileName the file to remove
875 * @return GNUNET_OK on success, GNUNET_SYSERR on error
878 GNUNET_DISK_directory_remove (const char *fileName)
882 if (0 != LSTAT (fileName, &istat))
883 return GNUNET_NO; /* file may not exist... */
884 if (UNLINK (fileName) == 0)
886 if ((errno != EISDIR) &&
887 /* EISDIR is not sufficient in all cases, e.g.
888 sticky /tmp directory may result in EPERM on BSD.
889 So we also explicitly check "isDirectory" */
890 (GNUNET_YES != GNUNET_DISK_directory_test (fileName)))
892 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "rmdir", fileName);
893 return GNUNET_SYSERR;
896 GNUNET_DISK_directory_scan (fileName, remove_helper, NULL))
897 return GNUNET_SYSERR;
898 if (0 != RMDIR (fileName))
900 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "rmdir", fileName);
901 return GNUNET_SYSERR;
906 #define COPY_BLK_SIZE 65536
910 * @return GNUNET_OK on success, GNUNET_SYSERR on error
913 GNUNET_DISK_file_copy (const char *src, const char *dst)
919 struct GNUNET_DISK_FileHandle *in;
920 struct GNUNET_DISK_FileHandle *out;
922 if (GNUNET_OK != GNUNET_DISK_file_size (src, &size, GNUNET_YES))
923 return GNUNET_SYSERR;
925 in = GNUNET_DISK_file_open (src, GNUNET_DISK_OPEN_READ);
927 return GNUNET_SYSERR;
928 out = GNUNET_DISK_file_open (dst, GNUNET_DISK_OPEN_WRITE
929 | GNUNET_DISK_OPEN_CREATE | GNUNET_DISK_OPEN_FAILIFEXISTS,
930 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
931 | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_GROUP_WRITE);
934 GNUNET_DISK_file_close (in);
935 return GNUNET_SYSERR;
937 buf = GNUNET_malloc (COPY_BLK_SIZE);
941 if (len > size - pos)
943 if (len != GNUNET_DISK_file_read (in, buf, len))
945 if (len != GNUNET_DISK_file_write (out, buf, len))
950 GNUNET_DISK_file_close (in);
951 GNUNET_DISK_file_close (out);
955 GNUNET_DISK_file_close (in);
956 GNUNET_DISK_file_close (out);
957 return GNUNET_SYSERR;
962 * @brief Removes special characters as ':' from a filename.
963 * @param fn the filename to canonicalize
966 GNUNET_DISK_filename_canonicalize (char *fn)
976 if (c == '/' || c == '\\' || c == ':' || c == '*' || c == '?' ||
977 c == '"' || c == '<' || c == '>' || c == '|')
989 * @brief Change owner of a file
992 GNUNET_DISK_file_change_owner (const char *filename, const char *user)
997 pws = getpwnam (user);
1000 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1001 _("Cannot obtain information about user `%s': %s\n"),
1002 user, STRERROR (errno));
1003 return GNUNET_SYSERR;
1005 if (0 != chown (filename, pws->pw_uid, pws->pw_gid))
1006 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "chown", filename);
1013 * Lock a part of a file
1014 * @param fh file handle
1015 * @param lockStart absolute position from where to lock
1016 * @param lockEnd absolute position until where to lock
1017 * @param excl GNUNET_YES for an exclusive lock
1018 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1021 GNUNET_DISK_file_lock (struct GNUNET_DISK_FileHandle *fh, off_t lockStart,
1022 off_t lockEnd, int excl)
1027 return GNUNET_SYSERR;
1033 memset (&fl, 0, sizeof(struct flock));
1034 fl.l_type = excl ? F_WRLCK : F_RDLCK;
1035 fl.l_whence = SEEK_SET;
1036 fl.l_start = lockStart;
1039 return fcntl (fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK;
1043 memset (&o, 0, sizeof(OVERLAPPED));
1044 o.Offset = lockStart;
1046 if (!LockFileEx (fh->h, (excl ? LOCKFILE_EXCLUSIVE_LOCK : 0)
1047 | LOCKFILE_FAIL_IMMEDIATELY, 0, lockEnd - lockStart, 0, &o))
1049 SetErrnoFromWinError (GetLastError ());
1050 return GNUNET_SYSERR;
1059 * Unlock a part of a file
1060 * @param fh file handle
1061 * @param lockStart absolute position from where to unlock
1062 * @param lockEnd absolute position until where to unlock
1063 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1066 GNUNET_DISK_file_unlock (struct GNUNET_DISK_FileHandle *fh, off_t unlockStart,
1072 return GNUNET_SYSERR;
1078 memset (&fl, 0, sizeof(struct flock));
1079 fl.l_type = F_UNLCK;
1080 fl.l_whence = SEEK_SET;
1081 fl.l_start = unlockStart;
1082 fl.l_len = unlockEnd;
1084 return fcntl (fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK;
1088 memset (&o, 0, sizeof(OVERLAPPED));
1089 o.Offset = unlockStart;
1091 if (!UnlockFileEx (fh->h, 0, unlockEnd - unlockStart, 0, &o))
1093 SetErrnoFromWinError (GetLastError ());
1094 return GNUNET_SYSERR;
1104 * @param fn file name to be opened
1105 * @param flags opening flags, a combination of GNUNET_DISK_OPEN_xxx bit flags
1106 * @param ... permissions for the newly created file
1107 * @return IO handle on success, NULL on error
1109 struct GNUNET_DISK_FileHandle *
1110 GNUNET_DISK_file_open (const char *fn,
1111 enum GNUNET_DISK_OpenFlags flags,
1115 struct GNUNET_DISK_FileHandle *ret;
1126 expfn = GNUNET_STRINGS_filename_expand (fn);
1130 if (GNUNET_DISK_OPEN_READWRITE == (flags & GNUNET_DISK_OPEN_READWRITE))
1131 oflags = O_RDWR; /* note: O_RDWR is NOT always O_RDONLY | O_WRONLY */
1132 else if (flags & GNUNET_DISK_OPEN_READ)
1134 else if (flags & GNUNET_DISK_OPEN_WRITE)
1139 GNUNET_free (expfn);
1142 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1143 oflags |= (O_CREAT & O_EXCL);
1144 if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1146 if (flags & GNUNET_DISK_OPEN_APPEND)
1148 if (flags & GNUNET_DISK_OPEN_CREATE)
1155 va_start (arg, flags);
1156 perm = va_arg (arg, int);
1159 if (perm & GNUNET_DISK_PERM_USER_READ)
1161 if (perm & GNUNET_DISK_PERM_USER_WRITE)
1163 if (perm & GNUNET_DISK_PERM_USER_EXEC)
1165 if (perm & GNUNET_DISK_PERM_GROUP_READ)
1167 if (perm & GNUNET_DISK_PERM_GROUP_WRITE)
1169 if (perm & GNUNET_DISK_PERM_GROUP_EXEC)
1171 if (perm & GNUNET_DISK_PERM_OTHER_READ)
1173 if (perm & GNUNET_DISK_PERM_OTHER_WRITE)
1175 if (perm & GNUNET_DISK_PERM_OTHER_EXEC)
1179 fd = open (expfn, oflags | O_LARGEFILE, mode);
1182 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "open", expfn);
1183 GNUNET_free (expfn);
1190 if (GNUNET_DISK_OPEN_READWRITE == (flags & GNUNET_DISK_OPEN_READWRITE))
1191 access = FILE_READ_DATA | FILE_WRITE_DATA;
1192 else if (flags & GNUNET_DISK_OPEN_READ)
1193 access = FILE_READ_DATA;
1194 else if (flags & GNUNET_DISK_OPEN_WRITE)
1195 access = FILE_WRITE_DATA;
1197 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1201 else if (flags & GNUNET_DISK_OPEN_CREATE)
1203 if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1204 disp = CREATE_ALWAYS;
1208 else if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1210 disp = TRUNCATE_EXISTING;
1217 /* TODO: access priviledges? */
1218 h = CreateFile (expfn, access, FILE_SHARE_DELETE | FILE_SHARE_READ
1219 | FILE_SHARE_WRITE, NULL, disp, FILE_ATTRIBUTE_NORMAL, NULL);
1220 if (h == INVALID_HANDLE_VALUE)
1222 SetErrnoFromWinError (GetLastError ());
1223 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "open", expfn);
1224 GNUNET_free (expfn);
1228 if (flags & GNUNET_DISK_OPEN_APPEND)
1229 if (SetFilePointer (h, 0, 0, FILE_END) == INVALID_SET_FILE_POINTER)
1231 SetErrnoFromWinError (GetLastError ());
1232 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "SetFilePointer", expfn);
1234 GNUNET_free (expfn);
1239 ret = GNUNET_malloc(sizeof(struct GNUNET_DISK_FileHandle));
1245 GNUNET_free (expfn);
1250 * Close an open file
1251 * @param h file handle
1252 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1255 GNUNET_DISK_file_close (struct GNUNET_DISK_FileHandle *h)
1260 return GNUNET_SYSERR;
1264 if (!CloseHandle (h->h))
1266 SetErrnoFromWinError (GetLastError ());
1267 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "close");
1269 return GNUNET_SYSERR;
1272 if (close (h->fd) != 0)
1274 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "close");
1276 return GNUNET_SYSERR;
1284 * Construct full path to a file inside of the private
1285 * directory used by GNUnet. Also creates the corresponding
1286 * directory. If the resulting name is supposed to be
1287 * a directory, end the last argument in '/' (or pass
1288 * DIR_SEPARATOR_STR as the last argument before NULL).
1290 * @param cfg configuration to use (determines HOME)
1291 * @param serviceName name of the service
1292 * @param varargs is NULL-terminated list of
1293 * path components to append to the
1294 * private directory name.
1295 * @return the constructed filename
1298 GNUNET_DISK_get_home_filename (const struct GNUNET_CONFIGURATION_Handle *cfg,
1299 const char *serviceName, ...)
1305 unsigned int needed;
1308 GNUNET_CONFIGURATION_get_value_filename (cfg,
1309 serviceName, "HOME", &pfx))
1313 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1314 _("No `%s' specified for service `%s' in configuration.\n"),
1315 "HOME", serviceName);
1318 needed = strlen (pfx) + 2;
1319 if ((pfx[strlen (pfx) - 1] != '/') && (pfx[strlen (pfx) - 1] != '\\'))
1321 va_start (ap, serviceName);
1324 c = va_arg (ap, const char *);
1327 needed += strlen (c);
1328 if ((c[strlen (c) - 1] != '/') && (c[strlen (c) - 1] != '\\'))
1332 ret = GNUNET_malloc (needed);
1335 va_start (ap, serviceName);
1338 c = va_arg (ap, const char *);
1341 if ((c[strlen (c) - 1] != '/') && (c[strlen (c) - 1] != '\\'))
1342 strcat (ret, DIR_SEPARATOR_STR);
1346 if ((ret[strlen (ret) - 1] != '/') && (ret[strlen (ret) - 1] != '\\'))
1347 GNUNET_DISK_directory_create_for_file (ret);
1349 GNUNET_DISK_directory_create (ret);
1353 struct GNUNET_DISK_MapHandle
1365 * Map a file into memory
1366 * @param h open file handle
1367 * @param m handle to the new mapping
1368 * @param access access specification, GNUNET_DISK_MAP_TYPE_xxx
1369 * @param len size of the mapping
1370 * @return pointer to the mapped memory region, NULL on failure
1373 GNUNET_DISK_file_map (const struct GNUNET_DISK_FileHandle *h, struct GNUNET_DISK_MapHandle **m,
1374 enum GNUNET_DISK_MapType access, size_t len)
1383 DWORD mapAccess, protect;
1386 if ((access & GNUNET_DISK_MAP_TYPE_READ) &&
1387 (access & GNUNET_DISK_MAP_TYPE_WRITE))
1389 protect = PAGE_READWRITE;
1390 mapAccess = FILE_MAP_ALL_ACCESS;
1392 else if (access & GNUNET_DISK_MAP_TYPE_READ)
1394 protect = PAGE_READONLY;
1395 mapAccess = FILE_MAP_READ;
1397 else if (access & GNUNET_DISK_MAP_TYPE_WRITE)
1399 protect = PAGE_READWRITE;
1400 mapAccess = FILE_MAP_WRITE;
1408 *m = GNUNET_malloc (sizeof (struct GNUNET_DISK_MapHandle));
1409 (*m)->h = CreateFileMapping (h->h, NULL, protect, 0, 0, NULL);
1410 if ((*m)->h == INVALID_HANDLE_VALUE)
1412 SetErrnoFromWinError (GetLastError ());
1417 ret = MapViewOfFile ((*m)->h, mapAccess, 0, 0, len);
1420 SetErrnoFromWinError (GetLastError ());
1421 CloseHandle ((*m)->h);
1430 if (access & GNUNET_DISK_MAP_TYPE_READ)
1432 if (access & GNUNET_DISK_MAP_TYPE_WRITE)
1434 *m = GNUNET_malloc (sizeof (struct GNUNET_DISK_MapHandle));
1435 (*m)->addr = mmap (NULL, len, prot, MAP_SHARED, h->fd, 0);
1443 * @param h mapping handle
1444 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1447 GNUNET_DISK_file_unmap (struct GNUNET_DISK_MapHandle *h)
1453 return GNUNET_SYSERR;
1457 ret = UnmapViewOfFile (h->h) ? GNUNET_OK : GNUNET_SYSERR;
1458 if (ret != GNUNET_OK)
1459 SetErrnoFromWinError (GetLastError ());
1460 if (!CloseHandle (h->h) && (ret == GNUNET_OK))
1462 ret = GNUNET_SYSERR;
1463 SetErrnoFromWinError (GetLastError ());
1466 ret = munmap (h->addr, h->len) != -1 ? GNUNET_OK : GNUNET_SYSERR;
1474 * Write file changes to disk
1475 * @param h handle to an open file
1476 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1479 GNUNET_DISK_file_sync (const struct GNUNET_DISK_FileHandle *h)
1484 return GNUNET_SYSERR;
1490 ret = FlushFileBuffers (h->h) ? GNUNET_OK : GNUNET_SYSERR;
1491 if (ret != GNUNET_OK)
1492 SetErrnoFromWinError (GetLastError ());
1494 #elif FREEBSD || OPENBSD
1495 return fsync (h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK;
1497 return fdatasync (h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK;
1502 * Creates an interprocess channel
1503 * @param blocking creates an asynchronous pipe if set to GNUNET_NO
1504 * @return handle to the new pipe, NULL on error
1506 struct GNUNET_DISK_PipeHandle *
1507 GNUNET_DISK_pipe (int blocking)
1509 struct GNUNET_DISK_PipeHandle *p;
1513 p = GNUNET_malloc (sizeof (struct GNUNET_DISK_PipeHandle));
1523 p->fd[0].fd = fd[0];
1524 p->fd[1].fd = fd[1];
1528 flags = fcntl (fd[0], F_GETFL);
1529 flags |= O_NONBLOCK;
1530 ret = fcntl (fd[0], F_SETFL, flags);
1533 flags = fcntl (fd[1], F_GETFL);
1534 flags |= O_NONBLOCK;
1535 ret = fcntl (fd[1], F_SETFL, flags);
1539 GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "fcntl");
1551 ret = CreatePipe (&p->fd[0].h, &p->fd[1].h, NULL, 0);
1559 SetNamedPipeHandleState (p->fd[0].h, &mode, NULL, NULL);
1560 SetNamedPipeHandleState (p->fd[1].h, &mode, NULL, NULL);
1561 /* this always fails on Windows 95, so we don't care about error handling */
1568 if (GNUNET_YES == err)
1579 * Closes an interprocess channel
1581 * @param p pipe to close
1582 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1585 GNUNET_DISK_pipe_close (struct GNUNET_DISK_PipeHandle *p)
1587 int ret = GNUNET_OK;
1589 if (!CloseHandle (p->fd[0].h))
1591 SetErrnoFromWinError (GetLastError ());
1592 ret = GNUNET_SYSERR;
1595 if (!CloseHandle (p->fd[1].h))
1597 SetErrnoFromWinError (GetLastError ());
1598 ret = GNUNET_SYSERR;
1603 if (0 != close (p->fd[0].fd))
1605 ret = GNUNET_SYSERR;
1611 if (0 != close (p->fd[1].fd))
1612 ret = GNUNET_SYSERR;
1622 * Get the handle to a particular pipe end
1624 * @param n number of the end
1626 const struct GNUNET_DISK_FileHandle *
1627 GNUNET_DISK_pipe_handle (const struct GNUNET_DISK_PipeHandle *p, int n)
1633 * Retrieve OS file handle
1635 * @param fh GNUnet file descriptor
1636 * @param dst destination buffer
1637 * @param dst_len length of dst
1638 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1641 GNUNET_internal_disk_file_handle (const struct GNUNET_DISK_FileHandle *fh,
1642 void *dst, unsigned int dst_len)
1645 if (dst_len < sizeof (HANDLE))
1646 return GNUNET_SYSERR;
1647 *((HANDLE *) dst) = fh->h;
1649 if (dst_len < sizeof(int))
1650 return GNUNET_SYSERR;
1651 *((int *) dst) = fh->fd;