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 * @lockStart absolute position from where to lock
1016 * @lockEnd absolute position until where to lock
1017 * @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 * @lockStart absolute position from where to unlock
1062 * @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 perm 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, int flags, ...)
1113 struct GNUNET_DISK_FileHandle *ret;
1124 expfn = GNUNET_STRINGS_filename_expand (fn);
1128 if (GNUNET_DISK_OPEN_READWRITE == (flags & GNUNET_DISK_OPEN_READWRITE))
1129 oflags = O_RDWR; /* note: O_RDWR is NOT always O_RDONLY | O_WRONLY */
1130 else if (flags & GNUNET_DISK_OPEN_READ)
1132 else if (flags & GNUNET_DISK_OPEN_WRITE)
1137 GNUNET_free (expfn);
1140 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1141 oflags |= (O_CREAT & O_EXCL);
1142 if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1144 if (flags & GNUNET_DISK_OPEN_APPEND)
1146 if (flags & GNUNET_DISK_OPEN_CREATE)
1153 va_start (arg, flags);
1154 perm = va_arg (arg, int);
1157 if (perm & GNUNET_DISK_PERM_USER_READ)
1159 if (perm & GNUNET_DISK_PERM_USER_WRITE)
1161 if (perm & GNUNET_DISK_PERM_USER_EXEC)
1163 if (perm & GNUNET_DISK_PERM_GROUP_READ)
1165 if (perm & GNUNET_DISK_PERM_GROUP_WRITE)
1167 if (perm & GNUNET_DISK_PERM_GROUP_EXEC)
1169 if (perm & GNUNET_DISK_PERM_OTHER_READ)
1171 if (perm & GNUNET_DISK_PERM_OTHER_WRITE)
1173 if (perm & GNUNET_DISK_PERM_OTHER_EXEC)
1177 fd = open (expfn, oflags | O_LARGEFILE, mode);
1180 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "open", expfn);
1181 GNUNET_free (expfn);
1188 if (GNUNET_DISK_OPEN_READWRITE == (flags & GNUNET_DISK_OPEN_READWRITE))
1189 access = FILE_READ_DATA | FILE_WRITE_DATA;
1190 else if (flags & GNUNET_DISK_OPEN_READ)
1191 access = FILE_READ_DATA;
1192 else if (flags & GNUNET_DISK_OPEN_WRITE)
1193 access = FILE_WRITE_DATA;
1195 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1199 else if (flags & GNUNET_DISK_OPEN_CREATE)
1201 if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1202 disp = CREATE_ALWAYS;
1206 else if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1208 disp = TRUNCATE_EXISTING;
1215 /* TODO: access priviledges? */
1216 h = CreateFile (expfn, access, FILE_SHARE_DELETE | FILE_SHARE_READ
1217 | FILE_SHARE_WRITE, NULL, disp, FILE_ATTRIBUTE_NORMAL, NULL);
1218 if (h == INVALID_HANDLE_VALUE)
1220 SetErrnoFromWinError (GetLastError ());
1221 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "open", expfn);
1222 GNUNET_free (expfn);
1226 if (flags & GNUNET_DISK_OPEN_APPEND)
1227 if (SetFilePointer (h, 0, 0, FILE_END) == INVALID_SET_FILE_POINTER)
1229 SetErrnoFromWinError (GetLastError ());
1230 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "SetFilePointer", expfn);
1232 GNUNET_free (expfn);
1237 ret = GNUNET_malloc(sizeof(struct GNUNET_DISK_FileHandle));
1243 GNUNET_free (expfn);
1248 * Close an open file
1249 * @param h file handle
1250 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1253 GNUNET_DISK_file_close (struct GNUNET_DISK_FileHandle *h)
1258 return GNUNET_SYSERR;
1262 if (!CloseHandle (h->h))
1264 SetErrnoFromWinError (GetLastError ());
1265 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "close");
1267 return GNUNET_SYSERR;
1270 if (close (h->fd) != 0)
1272 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "close");
1274 return GNUNET_SYSERR;
1282 * Construct full path to a file inside of the private
1283 * directory used by GNUnet. Also creates the corresponding
1284 * directory. If the resulting name is supposed to be
1285 * a directory, end the last argument in '/' (or pass
1286 * DIR_SEPARATOR_STR as the last argument before NULL).
1288 * @param cfg configuration to use (determines HOME)
1289 * @param serviceName name of the service
1290 * @param varargs is NULL-terminated list of
1291 * path components to append to the
1292 * private directory name.
1293 * @return the constructed filename
1296 GNUNET_DISK_get_home_filename (const struct GNUNET_CONFIGURATION_Handle *cfg,
1297 const char *serviceName, ...)
1303 unsigned int needed;
1306 GNUNET_CONFIGURATION_get_value_filename (cfg,
1307 serviceName, "HOME", &pfx))
1311 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1312 _("No `%s' specified for service `%s' in configuration.\n"),
1313 "HOME", serviceName);
1316 needed = strlen (pfx) + 2;
1317 if ((pfx[strlen (pfx) - 1] != '/') && (pfx[strlen (pfx) - 1] != '\\'))
1319 va_start (ap, serviceName);
1322 c = va_arg (ap, const char *);
1325 needed += strlen (c);
1326 if ((c[strlen (c) - 1] != '/') && (c[strlen (c) - 1] != '\\'))
1330 ret = GNUNET_malloc (needed);
1333 va_start (ap, serviceName);
1336 c = va_arg (ap, const char *);
1339 if ((c[strlen (c) - 1] != '/') && (c[strlen (c) - 1] != '\\'))
1340 strcat (ret, DIR_SEPARATOR_STR);
1344 if ((ret[strlen (ret) - 1] != '/') && (ret[strlen (ret) - 1] != '\\'))
1345 GNUNET_DISK_directory_create_for_file (ret);
1347 GNUNET_DISK_directory_create (ret);
1351 struct GNUNET_DISK_MapHandle
1363 * Map a file into memory
1364 * @param h open file handle
1365 * @param m handle to the new mapping
1366 * @param access access specification, GNUNET_DISK_MAP_xxx
1367 * @param len size of the mapping
1368 * @return pointer to the mapped memory region, NULL on failure
1371 GNUNET_DISK_file_map (const struct GNUNET_DISK_FileHandle *h, struct GNUNET_DISK_MapHandle **m,
1372 int access, size_t len)
1381 DWORD mapAccess, protect;
1384 if (access & GNUNET_DISK_MAP_READ && access & GNUNET_DISK_MAP_WRITE)
1386 protect = PAGE_READWRITE;
1387 mapAccess = FILE_MAP_ALL_ACCESS;
1389 else if (access & GNUNET_DISK_MAP_READ)
1391 protect = PAGE_READONLY;
1392 mapAccess = FILE_MAP_READ;
1394 else if (access & GNUNET_DISK_MAP_WRITE)
1396 protect = PAGE_READWRITE;
1397 mapAccess = FILE_MAP_WRITE;
1405 *m = GNUNET_malloc (sizeof (struct GNUNET_DISK_MapHandle));
1406 (*m)->h = CreateFileMapping (h->h, NULL, protect, 0, 0, NULL);
1407 if ((*m)->h == INVALID_HANDLE_VALUE)
1409 SetErrnoFromWinError (GetLastError ());
1414 ret = MapViewOfFile ((*m)->h, mapAccess, 0, 0, len);
1417 SetErrnoFromWinError (GetLastError ());
1418 CloseHandle ((*m)->h);
1427 if (access & GNUNET_DISK_MAP_READ)
1429 if (access & GNUNET_DISK_MAP_WRITE)
1431 *m = GNUNET_malloc (sizeof (struct GNUNET_DISK_MapHandle));
1432 (*m)->addr = mmap (NULL, len, prot, MAP_SHARED, h->fd, 0);
1440 * @param h mapping handle
1441 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1444 GNUNET_DISK_file_unmap (struct GNUNET_DISK_MapHandle *h)
1450 return GNUNET_SYSERR;
1454 ret = UnmapViewOfFile (h->h) ? GNUNET_OK : GNUNET_SYSERR;
1455 if (ret != GNUNET_OK)
1456 SetErrnoFromWinError (GetLastError ());
1457 if (!CloseHandle (h->h) && (ret == GNUNET_OK))
1459 ret = GNUNET_SYSERR;
1460 SetErrnoFromWinError (GetLastError ());
1463 ret = munmap (h->addr, h->len) != -1 ? GNUNET_OK : GNUNET_SYSERR;
1471 * Write file changes to disk
1472 * @param h handle to an open file
1473 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1476 GNUNET_DISK_file_sync (const struct GNUNET_DISK_FileHandle *h)
1481 return GNUNET_SYSERR;
1487 ret = FlushFileBuffers (h->h) ? GNUNET_OK : GNUNET_SYSERR;
1488 if (ret != GNUNET_OK)
1489 SetErrnoFromWinError (GetLastError ());
1492 return fdatasync (h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK;
1497 * Creates an interprocess channel
1498 * @param blocking creates an asynchronous pipe if set to GNUNET_NO
1499 * @return handle to the new pipe, NULL on error
1501 struct GNUNET_DISK_PipeHandle *
1502 GNUNET_DISK_pipe (int blocking)
1504 struct GNUNET_DISK_PipeHandle *p;
1508 p = GNUNET_malloc (sizeof (struct GNUNET_DISK_PipeHandle));
1518 p->fd[0].fd = fd[0];
1519 p->fd[1].fd = fd[1];
1523 flags = fcntl (fd[0], F_GETFL);
1524 flags |= O_NONBLOCK;
1525 ret = fcntl (fd[0], F_SETFL, flags);
1528 flags = fcntl (fd[1], F_GETFL);
1529 flags |= O_NONBLOCK;
1530 ret = fcntl (fd[1], F_SETFL, flags);
1534 GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "fcntl");
1546 ret = CreatePipe (&p->fd[0].h, &p->fd[1].h, NULL, 0);
1554 SetNamedPipeHandleState (p->fd[0].h, &mode, NULL, NULL);
1555 SetNamedPipeHandleState (p->fd[1].h, &mode, NULL, NULL);
1556 /* this always fails on Windows 95, so we don't care about error handling */
1563 if (GNUNET_YES == err)
1574 * Closes an interprocess channel
1576 * @param p pipe to close
1577 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1580 GNUNET_DISK_pipe_close (struct GNUNET_DISK_PipeHandle *p)
1582 int ret = GNUNET_OK;
1584 if (!CloseHandle (p->fd[0].h))
1586 SetErrnoFromWinError (GetLastError ());
1587 ret = GNUNET_SYSERR;
1590 if (!CloseHandle (p->fd[1].h))
1592 SetErrnoFromWinError (GetLastError ());
1593 ret = GNUNET_SYSERR;
1598 if (0 != close (p->fd[0].fd))
1600 ret = GNUNET_SYSERR;
1606 if (0 != close (p->fd[1].fd))
1607 ret = GNUNET_SYSERR;
1617 * Get the handle to a particular pipe end
1619 * @param n number of the end
1621 const struct GNUNET_DISK_FileHandle *
1622 GNUNET_DISK_pipe_handle (const struct GNUNET_DISK_PipeHandle *p, int n)
1628 * Retrieve OS file handle
1630 * @param fh GNUnet file descriptor
1631 * @param dst destination buffer
1632 * @param dst_len length of dst
1633 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1636 GNUNET_internal_disk_file_handle (const struct GNUNET_DISK_FileHandle *fh,
1637 void *dst, unsigned int dst_len)
1640 if (dst_len < sizeof (HANDLE))
1641 return GNUNET_SYSERR;
1642 *((HANDLE *) dst) = fh->h;
1644 if (dst_len < sizeof(int))
1645 return GNUNET_SYSERR;
1646 *((int *) dst) = fh->fd;