Rely on Gnulib for <unistd.h>.
[bpt/guile.git] / libguile / filesys.c
1 /* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2004, 2006,
2 * 2009, 2010, 2011, 2012, 2013, 2014 Free Software Foundation, Inc.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public License
6 * as published by the Free Software Foundation; either version 3 of
7 * the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17 * 02110-1301 USA
18 */
19
20
21 \f
22 /* This file contains POSIX file system access procedures. Procedures
23 essential to the compiler and run-time (`stat', `canonicalize-path',
24 etc.) are compiled even with `--disable-posix'. */
25
26
27 /* See stime.c for comments on why _POSIX_C_SOURCE is not always defined. */
28 #define _LARGEFILE64_SOURCE /* ask for stat64 etc */
29 #ifdef __hpux
30 #define _POSIX_C_SOURCE 199506L /* for readdir_r */
31 #endif
32
33 #ifdef HAVE_CONFIG_H
34 # include <config.h>
35 #endif
36
37 #include <alloca.h>
38
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <errno.h>
42
43 #include "libguile/_scm.h"
44 #include "libguile/smob.h"
45 #include "libguile/feature.h"
46 #include "libguile/fports.h"
47 #include "libguile/private-gc.h" /* for SCM_MAX */
48 #include "libguile/strings.h"
49 #include "libguile/vectors.h"
50 #include "libguile/dynwind.h"
51
52 #include "libguile/validate.h"
53 #include "libguile/filesys.h"
54
55 \f
56 #ifdef HAVE_IO_H
57 #include <io.h>
58 #endif
59
60 #ifdef HAVE_DIRECT_H
61 #include <direct.h>
62 #endif
63
64 #ifdef TIME_WITH_SYS_TIME
65 # include <sys/time.h>
66 # include <time.h>
67 #else
68 # if HAVE_SYS_TIME_H
69 # include <sys/time.h>
70 # else
71 # include <time.h>
72 # endif
73 #endif
74
75 #include <unistd.h>
76
77 #ifdef LIBC_H_WITH_UNISTD_H
78 #include <libc.h>
79 #endif
80
81 #include <sys/select.h>
82
83 #ifdef HAVE_STRING_H
84 #include <string.h>
85 #endif
86
87 #include <sys/types.h>
88 #include <sys/stat.h>
89 #include <fcntl.h>
90
91 #ifdef HAVE_PWD_H
92 #include <pwd.h>
93 #endif
94
95 #include <dirent.h>
96
97 #define NAMLEN(dirent) strlen ((dirent)->d_name)
98
99 #ifdef HAVE_SYS_SENDFILE_H
100 # include <sys/sendfile.h>
101 #endif
102
103 /* Glibc's `sendfile' function. */
104 #define sendfile_or_sendfile64 \
105 CHOOSE_LARGEFILE (sendfile, sendfile64)
106
107 #include <full-read.h>
108 #include <full-write.h>
109
110
111 \f
112
113 /* Two helper macros for an often used pattern */
114
115 #define STRING_SYSCALL(str,cstr,code) \
116 do { \
117 int eno; \
118 char *cstr = scm_to_locale_string (str); \
119 SCM_SYSCALL (code); \
120 eno = errno; free (cstr); errno = eno; \
121 } while (0)
122
123 #define STRING2_SYSCALL(str1,cstr1,str2,cstr2,code) \
124 do { \
125 int eno; \
126 char *cstr1, *cstr2; \
127 scm_dynwind_begin (0); \
128 cstr1 = scm_to_locale_string (str1); \
129 scm_dynwind_free (cstr1); \
130 cstr2 = scm_to_locale_string (str2); \
131 scm_dynwind_free (cstr2); \
132 SCM_SYSCALL (code); \
133 eno = errno; scm_dynwind_end (); errno = eno; \
134 } while (0)
135
136 \f
137
138 #ifdef HAVE_POSIX
139
140 /* {Permissions}
141 */
142
143 #ifdef HAVE_CHOWN
144 SCM_DEFINE (scm_chown, "chown", 3, 0, 0,
145 (SCM object, SCM owner, SCM group),
146 "Change the ownership and group of the file referred to by @var{object} to\n"
147 "the integer values @var{owner} and @var{group}. @var{object} can be\n"
148 "a string containing a file name or, if the platform\n"
149 "supports fchown, a port or integer file descriptor\n"
150 "which is open on the file. The return value\n"
151 "is unspecified.\n\n"
152 "If @var{object} is a symbolic link, either the\n"
153 "ownership of the link or the ownership of the referenced file will be\n"
154 "changed depending on the operating system (lchown is\n"
155 "unsupported at present). If @var{owner} or @var{group} is specified\n"
156 "as @code{-1}, then that ID is not changed.")
157 #define FUNC_NAME s_scm_chown
158 {
159 int rv;
160
161 object = SCM_COERCE_OUTPORT (object);
162
163 #ifdef HAVE_FCHOWN
164 if (scm_is_integer (object) || (SCM_OPFPORTP (object)))
165 {
166 int fdes = (SCM_OPFPORTP (object)?
167 SCM_FPORT_FDES (object) : scm_to_int (object));
168
169 SCM_SYSCALL (rv = fchown (fdes, scm_to_int (owner), scm_to_int (group)));
170 }
171 else
172 #endif
173 {
174 STRING_SYSCALL (object, c_object,
175 rv = chown (c_object,
176 scm_to_int (owner), scm_to_int (group)));
177 }
178 if (rv == -1)
179 SCM_SYSERROR;
180 return SCM_UNSPECIFIED;
181 }
182 #undef FUNC_NAME
183 #endif /* HAVE_CHOWN */
184
185 \f
186
187 SCM_DEFINE (scm_open_fdes, "open-fdes", 2, 1, 0,
188 (SCM path, SCM flags, SCM mode),
189 "Similar to @code{open} but return a file descriptor instead of\n"
190 "a port.")
191 #define FUNC_NAME s_scm_open_fdes
192 {
193 int fd;
194 int iflags;
195 int imode;
196
197 iflags = SCM_NUM2INT (2, flags);
198 imode = SCM_NUM2INT_DEF (3, mode, 0666);
199 STRING_SYSCALL (path, c_path, fd = open_or_open64 (c_path, iflags, imode));
200 if (fd == -1)
201 SCM_SYSERROR;
202 return scm_from_int (fd);
203 }
204 #undef FUNC_NAME
205
206 SCM_DEFINE (scm_open, "open", 2, 1, 0,
207 (SCM path, SCM flags, SCM mode),
208 "Open the file named by @var{path} for reading and/or writing.\n"
209 "@var{flags} is an integer specifying how the file should be opened.\n"
210 "@var{mode} is an integer specifying the permission bits of the file, if\n"
211 "it needs to be created, before the umask is applied. The default is 666\n"
212 "(Unix itself has no default).\n\n"
213 "@var{flags} can be constructed by combining variables using @code{logior}.\n"
214 "Basic flags are:\n\n"
215 "@defvar O_RDONLY\n"
216 "Open the file read-only.\n"
217 "@end defvar\n"
218 "@defvar O_WRONLY\n"
219 "Open the file write-only.\n"
220 "@end defvar\n"
221 "@defvar O_RDWR\n"
222 "Open the file read/write.\n"
223 "@end defvar\n"
224 "@defvar O_APPEND\n"
225 "Append to the file instead of truncating.\n"
226 "@end defvar\n"
227 "@defvar O_CREAT\n"
228 "Create the file if it does not already exist.\n"
229 "@end defvar\n\n"
230 "See the Unix documentation of the @code{open} system call\n"
231 "for additional flags.")
232 #define FUNC_NAME s_scm_open
233 {
234 SCM newpt;
235 char *port_mode;
236 int fd;
237 int iflags;
238
239 fd = scm_to_int (scm_open_fdes (path, flags, mode));
240 iflags = SCM_NUM2INT (2, flags);
241
242 if ((iflags & O_RDWR) == O_RDWR)
243 {
244 /* Opened read-write. */
245 if (iflags & O_APPEND)
246 port_mode = "a+";
247 else if (iflags & O_CREAT)
248 port_mode = "w+";
249 else
250 port_mode = "r+";
251 }
252 else
253 {
254 /* Opened read-only or write-only. */
255 if (iflags & O_APPEND)
256 port_mode = "a";
257 else if (iflags & O_WRONLY)
258 port_mode = "w";
259 else
260 port_mode = "r";
261 }
262
263 newpt = scm_fdes_to_port (fd, port_mode, path);
264 return newpt;
265 }
266 #undef FUNC_NAME
267
268 SCM_DEFINE (scm_close, "close", 1, 0, 0,
269 (SCM fd_or_port),
270 "Similar to close-port (@pxref{Closing, close-port}),\n"
271 "but also works on file descriptors. A side\n"
272 "effect of closing a file descriptor is that any ports using that file\n"
273 "descriptor are moved to a different file descriptor and have\n"
274 "their revealed counts set to zero.")
275 #define FUNC_NAME s_scm_close
276 {
277 int rv;
278 int fd;
279
280 fd_or_port = SCM_COERCE_OUTPORT (fd_or_port);
281
282 if (SCM_PORTP (fd_or_port))
283 return scm_close_port (fd_or_port);
284 fd = scm_to_int (fd_or_port);
285 scm_evict_ports (fd); /* see scsh manual. */
286 SCM_SYSCALL (rv = close (fd));
287 /* following scsh, closing an already closed file descriptor is
288 not an error. */
289 if (rv < 0 && errno != EBADF)
290 SCM_SYSERROR;
291 return scm_from_bool (rv >= 0);
292 }
293 #undef FUNC_NAME
294
295 SCM_DEFINE (scm_close_fdes, "close-fdes", 1, 0, 0,
296 (SCM fd),
297 "A simple wrapper for the @code{close} system call.\n"
298 "Close file descriptor @var{fd}, which must be an integer.\n"
299 "Unlike close (@pxref{Ports and File Descriptors, close}),\n"
300 "the file descriptor will be closed even if a port is using it.\n"
301 "The return value is unspecified.")
302 #define FUNC_NAME s_scm_close_fdes
303 {
304 int c_fd;
305 int rv;
306
307 c_fd = scm_to_int (fd);
308 SCM_SYSCALL (rv = close (c_fd));
309 if (rv < 0)
310 SCM_SYSERROR;
311 return SCM_UNSPECIFIED;
312 }
313 #undef FUNC_NAME
314
315 #endif /* HAVE_POSIX */
316
317 \f
318 /* {Files}
319 */
320
321 SCM_SYMBOL (scm_sym_regular, "regular");
322 SCM_SYMBOL (scm_sym_directory, "directory");
323 #ifdef S_ISLNK
324 SCM_SYMBOL (scm_sym_symlink, "symlink");
325 #endif
326 SCM_SYMBOL (scm_sym_block_special, "block-special");
327 SCM_SYMBOL (scm_sym_char_special, "char-special");
328 SCM_SYMBOL (scm_sym_fifo, "fifo");
329 SCM_SYMBOL (scm_sym_sock, "socket");
330 SCM_SYMBOL (scm_sym_unknown, "unknown");
331
332 static SCM
333 scm_stat2scm (struct stat_or_stat64 *stat_temp)
334 {
335 SCM ans = scm_c_make_vector (18, SCM_UNSPECIFIED);
336
337 SCM_SIMPLE_VECTOR_SET(ans, 0, scm_from_ulong (stat_temp->st_dev));
338 SCM_SIMPLE_VECTOR_SET(ans, 1, scm_from_ino_t_or_ino64_t (stat_temp->st_ino));
339 SCM_SIMPLE_VECTOR_SET(ans, 2, scm_from_ulong (stat_temp->st_mode));
340 SCM_SIMPLE_VECTOR_SET(ans, 3, scm_from_ulong (stat_temp->st_nlink));
341 SCM_SIMPLE_VECTOR_SET(ans, 4, scm_from_ulong (stat_temp->st_uid));
342 SCM_SIMPLE_VECTOR_SET(ans, 5, scm_from_ulong (stat_temp->st_gid));
343 #ifdef HAVE_STRUCT_STAT_ST_RDEV
344 SCM_SIMPLE_VECTOR_SET(ans, 6, scm_from_ulong (stat_temp->st_rdev));
345 #else
346 SCM_SIMPLE_VECTOR_SET(ans, 6, SCM_BOOL_F);
347 #endif
348 SCM_SIMPLE_VECTOR_SET(ans, 7, scm_from_off_t_or_off64_t (stat_temp->st_size));
349 SCM_SIMPLE_VECTOR_SET(ans, 8, scm_from_ulong (stat_temp->st_atime));
350 SCM_SIMPLE_VECTOR_SET(ans, 9, scm_from_ulong (stat_temp->st_mtime));
351 SCM_SIMPLE_VECTOR_SET(ans, 10, scm_from_ulong (stat_temp->st_ctime));
352 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
353 SCM_SIMPLE_VECTOR_SET(ans, 11, scm_from_ulong (stat_temp->st_blksize));
354 #else
355 SCM_SIMPLE_VECTOR_SET(ans, 11, scm_from_ulong (4096L));
356 #endif
357 #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
358 SCM_SIMPLE_VECTOR_SET(ans, 12, scm_from_blkcnt_t_or_blkcnt64_t (stat_temp->st_blocks));
359 #else
360 SCM_SIMPLE_VECTOR_SET(ans, 12, SCM_BOOL_F);
361 #endif
362 {
363 int mode = stat_temp->st_mode;
364
365 if (S_ISREG (mode))
366 SCM_SIMPLE_VECTOR_SET(ans, 13, scm_sym_regular);
367 else if (S_ISDIR (mode))
368 SCM_SIMPLE_VECTOR_SET(ans, 13, scm_sym_directory);
369 #ifdef S_ISLNK
370 /* systems without symlinks probably don't have S_ISLNK */
371 else if (S_ISLNK (mode))
372 SCM_SIMPLE_VECTOR_SET(ans, 13, scm_sym_symlink);
373 #endif
374 else if (S_ISBLK (mode))
375 SCM_SIMPLE_VECTOR_SET(ans, 13, scm_sym_block_special);
376 else if (S_ISCHR (mode))
377 SCM_SIMPLE_VECTOR_SET(ans, 13, scm_sym_char_special);
378 else if (S_ISFIFO (mode))
379 SCM_SIMPLE_VECTOR_SET(ans, 13, scm_sym_fifo);
380 #ifdef S_ISSOCK
381 else if (S_ISSOCK (mode))
382 SCM_SIMPLE_VECTOR_SET(ans, 13, scm_sym_sock);
383 #endif
384 else
385 SCM_SIMPLE_VECTOR_SET(ans, 13, scm_sym_unknown);
386
387 SCM_SIMPLE_VECTOR_SET(ans, 14, scm_from_int ((~S_IFMT) & mode));
388
389 /* the layout of the bits in ve[14] is intended to be portable.
390 If there are systems that don't follow the usual convention,
391 the following could be used:
392
393 tmp = 0;
394 if (S_ISUID & mode) tmp += 1;
395 tmp <<= 1;
396 if (S_IRGRP & mode) tmp += 1;
397 tmp <<= 1;
398 if (S_ISVTX & mode) tmp += 1;
399 tmp <<= 1;
400 if (S_IRUSR & mode) tmp += 1;
401 tmp <<= 1;
402 if (S_IWUSR & mode) tmp += 1;
403 tmp <<= 1;
404 if (S_IXUSR & mode) tmp += 1;
405 tmp <<= 1;
406 if (S_IWGRP & mode) tmp += 1;
407 tmp <<= 1;
408 if (S_IXGRP & mode) tmp += 1;
409 tmp <<= 1;
410 if (S_IROTH & mode) tmp += 1;
411 tmp <<= 1;
412 if (S_IWOTH & mode) tmp += 1;
413 tmp <<= 1;
414 if (S_IXOTH & mode) tmp += 1;
415
416 SCM_SIMPLE_VECTOR_SET(ans, 14, scm_from_int (tmp));
417
418 */
419 }
420 #ifdef HAVE_STRUCT_STAT_ST_ATIM
421 SCM_SIMPLE_VECTOR_SET(ans, 15, scm_from_long (stat_temp->st_atim.tv_nsec));
422 #else
423 SCM_SIMPLE_VECTOR_SET(ans, 15, SCM_I_MAKINUM (0));
424 #endif
425 #ifdef HAVE_STRUCT_STAT_ST_MTIM
426 SCM_SIMPLE_VECTOR_SET(ans, 16, scm_from_long (stat_temp->st_mtim.tv_nsec));
427 #else
428 SCM_SIMPLE_VECTOR_SET(ans, 16, SCM_I_MAKINUM (0));
429 #endif
430 #ifdef HAVE_STRUCT_STAT_ST_CTIM
431 SCM_SIMPLE_VECTOR_SET(ans, 17, scm_from_ulong (stat_temp->st_ctim.tv_sec));
432 #else
433 SCM_SIMPLE_VECTOR_SET(ans, 17, SCM_I_MAKINUM (0));
434 #endif
435
436 return ans;
437 }
438
439 static int
440 is_file_name_separator (SCM c)
441 {
442 if (scm_is_eq (c, SCM_MAKE_CHAR ('/')))
443 return 1;
444 #ifdef __MINGW32__
445 if (scm_is_eq (c, SCM_MAKE_CHAR ('\\')))
446 return 1;
447 #endif
448 return 0;
449 }
450
451 SCM_DEFINE (scm_stat, "stat", 1, 1, 0,
452 (SCM object, SCM exception_on_error),
453 "Return an object containing various information about the file\n"
454 "determined by @var{object}. @var{object} can be a string containing\n"
455 "a file name or a port or integer file descriptor which is open\n"
456 "on a file (in which case @code{fstat} is used as the underlying\n"
457 "system call).\n"
458 "\n"
459 "If the optional @var{exception_on_error} argument is true, which\n"
460 "is the default, an exception will be raised if the underlying\n"
461 "system call returns an error, for example if the file is not\n"
462 "found or is not readable. Otherwise, an error will cause\n"
463 "@code{stat} to return @code{#f}."
464 "\n"
465 "The object returned by a successful call to @code{stat} can be\n"
466 "passed as a single parameter to the following procedures, all of\n"
467 "which return integers:\n"
468 "\n"
469 "@table @code\n"
470 "@item stat:dev\n"
471 "The device containing the file.\n"
472 "@item stat:ino\n"
473 "The file serial number, which distinguishes this file from all\n"
474 "other files on the same device.\n"
475 "@item stat:mode\n"
476 "The mode of the file. This includes file type information and\n"
477 "the file permission bits. See @code{stat:type} and\n"
478 "@code{stat:perms} below.\n"
479 "@item stat:nlink\n"
480 "The number of hard links to the file.\n"
481 "@item stat:uid\n"
482 "The user ID of the file's owner.\n"
483 "@item stat:gid\n"
484 "The group ID of the file.\n"
485 "@item stat:rdev\n"
486 "Device ID; this entry is defined only for character or block\n"
487 "special files.\n"
488 "@item stat:size\n"
489 "The size of a regular file in bytes.\n"
490 "@item stat:atime\n"
491 "The last access time for the file.\n"
492 "@item stat:mtime\n"
493 "The last modification time for the file.\n"
494 "@item stat:ctime\n"
495 "The last modification time for the attributes of the file.\n"
496 "@item stat:blksize\n"
497 "The optimal block size for reading or writing the file, in\n"
498 "bytes.\n"
499 "@item stat:blocks\n"
500 "The amount of disk space that the file occupies measured in\n"
501 "units of 512 byte blocks.\n"
502 "@end table\n"
503 "\n"
504 "In addition, the following procedures return the information\n"
505 "from stat:mode in a more convenient form:\n"
506 "\n"
507 "@table @code\n"
508 "@item stat:type\n"
509 "A symbol representing the type of file. Possible values are\n"
510 "regular, directory, symlink, block-special, char-special, fifo,\n"
511 "socket and unknown\n"
512 "@item stat:perms\n"
513 "An integer representing the access permission bits.\n"
514 "@end table")
515 #define FUNC_NAME s_scm_stat
516 {
517 int rv;
518 int fdes;
519 struct stat_or_stat64 stat_temp;
520
521 if (scm_is_integer (object))
522 {
523 SCM_SYSCALL (rv = fstat_or_fstat64 (scm_to_int (object), &stat_temp));
524 }
525 else if (scm_is_string (object))
526 {
527 char *file = scm_to_locale_string (object);
528 SCM_SYSCALL (rv = stat_or_stat64 (file, &stat_temp));
529 free (file);
530 }
531 else
532 {
533 object = SCM_COERCE_OUTPORT (object);
534 SCM_VALIDATE_OPFPORT (1, object);
535 fdes = SCM_FPORT_FDES (object);
536 SCM_SYSCALL (rv = fstat_or_fstat64 (fdes, &stat_temp));
537 }
538
539 if (rv == -1)
540 {
541 if (SCM_UNBNDP (exception_on_error) || scm_is_true (exception_on_error))
542 {
543 int en = errno;
544 SCM_SYSERROR_MSG ("~A: ~S",
545 scm_list_2 (scm_strerror (scm_from_int (en)),
546 object),
547 en);
548 }
549 else
550 return SCM_BOOL_F;
551 }
552 return scm_stat2scm (&stat_temp);
553 }
554 #undef FUNC_NAME
555
556 SCM_DEFINE (scm_lstat, "lstat", 1, 0, 0,
557 (SCM str),
558 "Similar to @code{stat}, but does not follow symbolic links, i.e.,\n"
559 "it will return information about a symbolic link itself, not the\n"
560 "file it points to. @var{str} must be a string.")
561 #define FUNC_NAME s_scm_lstat
562 {
563 int rv;
564 struct stat_or_stat64 stat_temp;
565
566 STRING_SYSCALL (str, c_str, rv = lstat_or_lstat64 (c_str, &stat_temp));
567 if (rv != 0)
568 {
569 int en = errno;
570
571 SCM_SYSERROR_MSG ("~A: ~S",
572 scm_list_2 (scm_strerror (scm_from_int (en)), str),
573 en);
574 }
575 return scm_stat2scm (&stat_temp);
576 }
577 #undef FUNC_NAME
578
579 \f
580 #ifdef HAVE_POSIX
581
582 /* {Modifying Directories}
583 */
584
585 SCM_DEFINE (scm_link, "link", 2, 0, 0,
586 (SCM oldpath, SCM newpath),
587 "Creates a new name @var{newpath} in the file system for the\n"
588 "file named by @var{oldpath}. If @var{oldpath} is a symbolic\n"
589 "link, the link may or may not be followed depending on the\n"
590 "system.")
591 #define FUNC_NAME s_scm_link
592 {
593 int val;
594
595 STRING2_SYSCALL (oldpath, c_oldpath,
596 newpath, c_newpath,
597 val = link (c_oldpath, c_newpath));
598 if (val != 0)
599 SCM_SYSERROR;
600 return SCM_UNSPECIFIED;
601 }
602 #undef FUNC_NAME
603
604 \f
605 /* {Navigating Directories}
606 */
607
608
609 SCM_DEFINE (scm_chdir, "chdir", 1, 0, 0,
610 (SCM str),
611 "Change the current working directory to @var{str}.\n"
612 "The return value is unspecified.")
613 #define FUNC_NAME s_scm_chdir
614 {
615 int ans;
616
617 STRING_SYSCALL (str, c_str, ans = chdir (c_str));
618 if (ans != 0)
619 SCM_SYSERROR;
620 return SCM_UNSPECIFIED;
621 }
622 #undef FUNC_NAME
623
624 \f
625
626 /* check that element is a port or file descriptor. if it's a port
627 and its buffer is ready for use, add it to the ports_ready list.
628 otherwise add its file descriptor to *set. the type of list can be
629 determined from pos: SCM_ARG1 for reads, SCM_ARG2 for writes,
630 SCM_ARG3 for excepts. */
631 static int
632 set_element (fd_set *set, SCM *ports_ready, SCM element, int pos)
633 {
634 int fd;
635
636 if (scm_is_integer (element))
637 {
638 fd = scm_to_int (element);
639 }
640 else
641 {
642 int use_buf = 0;
643
644 element = SCM_COERCE_OUTPORT (element);
645 SCM_ASSERT (SCM_OPFPORTP (element), element, pos, "select");
646 if (pos == SCM_ARG1)
647 {
648 /* check whether port has buffered input. */
649 scm_t_port *pt = SCM_PTAB_ENTRY (element);
650
651 if (pt->read_pos < pt->read_end)
652 use_buf = 1;
653 }
654 else if (pos == SCM_ARG2)
655 {
656 /* check whether port's output buffer has room. */
657 scm_t_port *pt = SCM_PTAB_ENTRY (element);
658
659 /* > 1 since writing the last byte in the buffer causes flush. */
660 if (pt->write_end - pt->write_pos > 1)
661 use_buf = 1;
662 }
663 fd = use_buf ? -1 : SCM_FPORT_FDES (element);
664 }
665 if (fd == -1)
666 *ports_ready = scm_cons (element, *ports_ready);
667 else
668 FD_SET (fd, set);
669 return fd;
670 }
671
672 /* check list_or_vec, a list or vector of ports or file descriptors,
673 adding each member to either the ports_ready list (if it's a port
674 with a usable buffer) or to *set. the kind of list_or_vec can be
675 determined from pos: SCM_ARG1 for reads, SCM_ARG2 for writes,
676 SCM_ARG3 for excepts. */
677 static int
678 fill_select_type (fd_set *set, SCM *ports_ready, SCM list_or_vec, int pos)
679 {
680 int max_fd = 0;
681
682 if (scm_is_simple_vector (list_or_vec))
683 {
684 int i = SCM_SIMPLE_VECTOR_LENGTH (list_or_vec);
685
686 while (--i >= 0)
687 {
688 int fd = set_element (set, ports_ready,
689 SCM_SIMPLE_VECTOR_REF (list_or_vec, i), pos);
690
691 if (fd > max_fd)
692 max_fd = fd;
693 }
694 }
695 else
696 {
697 while (!SCM_NULL_OR_NIL_P (list_or_vec))
698 {
699 int fd = set_element (set, ports_ready, SCM_CAR (list_or_vec), pos);
700
701 if (fd > max_fd)
702 max_fd = fd;
703 list_or_vec = SCM_CDR (list_or_vec);
704 }
705 }
706
707 return max_fd;
708 }
709
710 /* if element (a file descriptor or port) appears in *set, cons it to
711 list. return list. */
712 static SCM
713 get_element (fd_set *set, SCM element, SCM list)
714 {
715 int fd;
716
717 if (scm_is_integer (element))
718 {
719 fd = scm_to_int (element);
720 }
721 else
722 {
723 fd = SCM_FPORT_FDES (SCM_COERCE_OUTPORT (element));
724 }
725 if (FD_ISSET (fd, set))
726 list = scm_cons (element, list);
727 return list;
728 }
729
730 /* construct component of scm_select return value.
731 set: pointer to set of file descriptors found by select to be ready
732 ports_ready: ports ready due to buffering
733 list_or_vec: original list/vector handed to scm_select.
734 the return value is a list/vector of ready ports/file descriptors.
735 works by finding the objects in list which correspond to members of
736 *set and appending them to ports_ready. result is converted to a
737 vector if list_or_vec is a vector. */
738 static SCM
739 retrieve_select_type (fd_set *set, SCM ports_ready, SCM list_or_vec)
740 {
741 SCM answer_list = ports_ready;
742
743 if (scm_is_simple_vector (list_or_vec))
744 {
745 int i = SCM_SIMPLE_VECTOR_LENGTH (list_or_vec);
746
747 while (--i >= 0)
748 {
749 answer_list = get_element (set,
750 SCM_SIMPLE_VECTOR_REF (list_or_vec, i),
751 answer_list);
752 }
753 return scm_vector (answer_list);
754 }
755 else
756 {
757 /* list_or_vec must be a list. */
758 while (!SCM_NULL_OR_NIL_P (list_or_vec))
759 {
760 answer_list = get_element (set, SCM_CAR (list_or_vec), answer_list);
761 list_or_vec = SCM_CDR (list_or_vec);
762 }
763 return answer_list;
764 }
765 }
766
767 /* Static helper functions above refer to s_scm_select directly as s_select */
768 SCM_DEFINE (scm_select, "select", 3, 2, 0,
769 (SCM reads, SCM writes, SCM excepts, SCM secs, SCM usecs),
770 "This procedure has a variety of uses: waiting for the ability\n"
771 "to provide input, accept output, or the existence of\n"
772 "exceptional conditions on a collection of ports or file\n"
773 "descriptors, or waiting for a timeout to occur.\n"
774 "It also returns if interrupted by a signal.\n\n"
775 "@var{reads}, @var{writes} and @var{excepts} can be lists or\n"
776 "vectors, with each member a port or a file descriptor.\n"
777 "The value returned is a list of three corresponding\n"
778 "lists or vectors containing only the members which meet the\n"
779 "specified requirement. The ability of port buffers to\n"
780 "provide input or accept output is taken into account.\n"
781 "Ordering of the input lists or vectors is not preserved.\n\n"
782 "The optional arguments @var{secs} and @var{usecs} specify the\n"
783 "timeout. Either @var{secs} can be specified alone, as\n"
784 "either an integer or a real number, or both @var{secs} and\n"
785 "@var{usecs} can be specified as integers, in which case\n"
786 "@var{usecs} is an additional timeout expressed in\n"
787 "microseconds. If @var{secs} is omitted or is @code{#f} then\n"
788 "select will wait for as long as it takes for one of the other\n"
789 "conditions to be satisfied.\n\n"
790 "The scsh version of @code{select} differs as follows:\n"
791 "Only vectors are accepted for the first three arguments.\n"
792 "The @var{usecs} argument is not supported.\n"
793 "Multiple values are returned instead of a list.\n"
794 "Duplicates in the input vectors appear only once in output.\n"
795 "An additional @code{select!} interface is provided.")
796 #define FUNC_NAME s_scm_select
797 {
798 struct timeval timeout;
799 struct timeval * time_ptr;
800 fd_set read_set;
801 fd_set write_set;
802 fd_set except_set;
803 int read_count;
804 int write_count;
805 int except_count;
806 /* these lists accumulate ports which are ready due to buffering.
807 their file descriptors don't need to be added to the select sets. */
808 SCM read_ports_ready = SCM_EOL;
809 SCM write_ports_ready = SCM_EOL;
810 int max_fd;
811
812 if (scm_is_simple_vector (reads))
813 {
814 read_count = SCM_SIMPLE_VECTOR_LENGTH (reads);
815 }
816 else
817 {
818 read_count = scm_ilength (reads);
819 SCM_ASSERT (read_count >= 0, reads, SCM_ARG1, FUNC_NAME);
820 }
821 if (scm_is_simple_vector (writes))
822 {
823 write_count = SCM_SIMPLE_VECTOR_LENGTH (writes);
824 }
825 else
826 {
827 write_count = scm_ilength (writes);
828 SCM_ASSERT (write_count >= 0, writes, SCM_ARG2, FUNC_NAME);
829 }
830 if (scm_is_simple_vector (excepts))
831 {
832 except_count = SCM_SIMPLE_VECTOR_LENGTH (excepts);
833 }
834 else
835 {
836 except_count = scm_ilength (excepts);
837 SCM_ASSERT (except_count >= 0, excepts, SCM_ARG3, FUNC_NAME);
838 }
839
840 FD_ZERO (&read_set);
841 FD_ZERO (&write_set);
842 FD_ZERO (&except_set);
843
844 max_fd = fill_select_type (&read_set, &read_ports_ready, reads, SCM_ARG1);
845
846 {
847 int write_max = fill_select_type (&write_set, &write_ports_ready,
848 writes, SCM_ARG2);
849 int except_max = fill_select_type (&except_set, NULL,
850 excepts, SCM_ARG3);
851
852 if (write_max > max_fd)
853 max_fd = write_max;
854 if (except_max > max_fd)
855 max_fd = except_max;
856 }
857
858 /* if there's a port with a ready buffer, don't block, just
859 check for ready file descriptors. */
860 if (!scm_is_null (read_ports_ready) || !scm_is_null (write_ports_ready))
861 {
862 timeout.tv_sec = 0;
863 timeout.tv_usec = 0;
864 time_ptr = &timeout;
865 }
866 else if (SCM_UNBNDP (secs) || scm_is_false (secs))
867 time_ptr = 0;
868 else
869 {
870 if (scm_is_unsigned_integer (secs, 0, ULONG_MAX))
871 {
872 timeout.tv_sec = scm_to_ulong (secs);
873 if (SCM_UNBNDP (usecs))
874 timeout.tv_usec = 0;
875 else
876 timeout.tv_usec = scm_to_long (usecs);
877 }
878 else
879 {
880 double fl = scm_to_double (secs);
881
882 if (!SCM_UNBNDP (usecs))
883 SCM_WRONG_TYPE_ARG (4, secs);
884 if (fl > LONG_MAX)
885 SCM_OUT_OF_RANGE (4, secs);
886 timeout.tv_sec = (long) fl;
887 timeout.tv_usec = (long) ((fl - timeout.tv_sec) * 1000000);
888 }
889 time_ptr = &timeout;
890 }
891
892 {
893 int rv = select (max_fd + 1,
894 &read_set, &write_set, &except_set,
895 time_ptr);
896 if (rv < 0)
897 SCM_SYSERROR;
898 }
899 return scm_list_3 (retrieve_select_type (&read_set, read_ports_ready, reads),
900 retrieve_select_type (&write_set, write_ports_ready, writes),
901 retrieve_select_type (&except_set, SCM_EOL, excepts));
902 }
903 #undef FUNC_NAME
904
905 \f
906
907 #ifdef HAVE_FCNTL
908 SCM_DEFINE (scm_fcntl, "fcntl", 2, 1, 0,
909 (SCM object, SCM cmd, SCM value),
910 "Apply @var{cmd} to the specified file descriptor or the underlying\n"
911 "file descriptor of the specified port. @var{value} is an optional\n"
912 "integer argument.\n\n"
913 "Values for @var{cmd} are:\n\n"
914 "@table @code\n"
915 "@item F_DUPFD\n"
916 "Duplicate a file descriptor\n"
917 "@item F_GETFD\n"
918 "Get flags associated with the file descriptor.\n"
919 "@item F_SETFD\n"
920 "Set flags associated with the file descriptor to @var{value}.\n"
921 "@item F_GETFL\n"
922 "Get flags associated with the open file.\n"
923 "@item F_SETFL\n"
924 "Set flags associated with the open file to @var{value}\n"
925 "@item F_GETOWN\n"
926 "Get the process ID of a socket's owner, for @code{SIGIO} signals.\n"
927 "@item F_SETOWN\n"
928 "Set the process that owns a socket to @var{value}, for @code{SIGIO} signals.\n"
929 "@item FD_CLOEXEC\n"
930 "The value used to indicate the \"close on exec\" flag with @code{F_GETFL} or\n"
931 "@code{F_SETFL}.\n"
932 "@end table")
933 #define FUNC_NAME s_scm_fcntl
934 {
935 int rv;
936 int fdes;
937 int ivalue;
938
939 object = SCM_COERCE_OUTPORT (object);
940
941 if (SCM_OPFPORTP (object))
942 fdes = SCM_FPORT_FDES (object);
943 else
944 fdes = scm_to_int (object);
945
946 if (SCM_UNBNDP (value))
947 ivalue = 0;
948 else
949 ivalue = scm_to_int (value);
950
951 SCM_SYSCALL (rv = fcntl (fdes, scm_to_int (cmd), ivalue));
952 if (rv == -1)
953 SCM_SYSERROR;
954 return scm_from_int (rv);
955 }
956 #undef FUNC_NAME
957 #endif /* HAVE_FCNTL */
958
959 SCM_DEFINE (scm_fsync, "fsync", 1, 0, 0,
960 (SCM object),
961 "Copies any unwritten data for the specified output file\n"
962 "descriptor to disk. If @var{object} is a port, its buffer is\n"
963 "flushed before the underlying file descriptor is fsync'd.\n"
964 "The return value is unspecified.")
965 #define FUNC_NAME s_scm_fsync
966 {
967 int fdes;
968
969 object = SCM_COERCE_OUTPORT (object);
970
971 if (SCM_OPFPORTP (object))
972 {
973 scm_flush (object);
974 fdes = SCM_FPORT_FDES (object);
975 }
976 else
977 fdes = scm_to_int (object);
978
979 if (fsync (fdes) == -1)
980 SCM_SYSERROR;
981 return SCM_UNSPECIFIED;
982 }
983 #undef FUNC_NAME
984
985 #ifdef HAVE_SYMLINK
986 SCM_DEFINE (scm_symlink, "symlink", 2, 0, 0,
987 (SCM oldpath, SCM newpath),
988 "Create a symbolic link named @var{oldpath} with the value\n"
989 "(i.e., pointing to) @var{newpath}. The return value is\n"
990 "unspecified.")
991 #define FUNC_NAME s_scm_symlink
992 {
993 int val;
994
995 STRING2_SYSCALL (oldpath, c_oldpath,
996 newpath, c_newpath,
997 val = symlink (c_oldpath, c_newpath));
998 if (val != 0)
999 SCM_SYSERROR;
1000 return SCM_UNSPECIFIED;
1001 }
1002 #undef FUNC_NAME
1003 #endif /* HAVE_SYMLINK */
1004
1005 SCM_DEFINE (scm_readlink, "readlink", 1, 0, 0,
1006 (SCM path),
1007 "Return the value of the symbolic link named by @var{path} (a\n"
1008 "string), i.e., the file that the link points to.")
1009 #define FUNC_NAME s_scm_readlink
1010 {
1011 int rv;
1012 int size = 100;
1013 char *buf;
1014 SCM result;
1015 char *c_path;
1016
1017 scm_dynwind_begin (0);
1018
1019 c_path = scm_to_locale_string (path);
1020 scm_dynwind_free (c_path);
1021
1022 buf = scm_malloc (size);
1023
1024 while ((rv = readlink (c_path, buf, size)) == size)
1025 {
1026 free (buf);
1027 size *= 2;
1028 buf = scm_malloc (size);
1029 }
1030 if (rv == -1)
1031 {
1032 int save_errno = errno;
1033 free (buf);
1034 errno = save_errno;
1035 SCM_SYSERROR;
1036 }
1037 result = scm_take_locale_stringn (buf, rv);
1038
1039 scm_dynwind_end ();
1040 return result;
1041 }
1042 #undef FUNC_NAME
1043
1044 SCM_DEFINE (scm_copy_file, "copy-file", 2, 0, 0,
1045 (SCM oldfile, SCM newfile),
1046 "Copy the file specified by @var{oldfile} to @var{newfile}.\n"
1047 "The return value is unspecified.")
1048 #define FUNC_NAME s_scm_copy_file
1049 {
1050 char *c_oldfile, *c_newfile;
1051 int oldfd, newfd;
1052 int n, rv;
1053 char buf[BUFSIZ];
1054 struct stat_or_stat64 oldstat;
1055
1056 scm_dynwind_begin (0);
1057
1058 c_oldfile = scm_to_locale_string (oldfile);
1059 scm_dynwind_free (c_oldfile);
1060 c_newfile = scm_to_locale_string (newfile);
1061 scm_dynwind_free (c_newfile);
1062
1063 oldfd = open_or_open64 (c_oldfile, O_RDONLY | O_BINARY);
1064 if (oldfd == -1)
1065 SCM_SYSERROR;
1066
1067 SCM_SYSCALL (rv = fstat_or_fstat64 (oldfd, &oldstat));
1068 if (rv == -1)
1069 goto err_close_oldfd;
1070
1071 /* use POSIX flags instead of 07777?. */
1072 newfd = open_or_open64 (c_newfile, O_WRONLY | O_CREAT | O_TRUNC,
1073 oldstat.st_mode & 07777);
1074 if (newfd == -1)
1075 {
1076 err_close_oldfd:
1077 close (oldfd);
1078 SCM_SYSERROR;
1079 }
1080
1081 while ((n = read (oldfd, buf, sizeof buf)) > 0)
1082 if (write (newfd, buf, n) != n)
1083 {
1084 close (oldfd);
1085 close (newfd);
1086 SCM_SYSERROR;
1087 }
1088 close (oldfd);
1089 if (close (newfd) == -1)
1090 SCM_SYSERROR;
1091
1092 scm_dynwind_end ();
1093 return SCM_UNSPECIFIED;
1094 }
1095 #undef FUNC_NAME
1096
1097 SCM_DEFINE (scm_sendfile, "sendfile", 3, 1, 0,
1098 (SCM out, SCM in, SCM count, SCM offset),
1099 "Send @var{count} bytes from @var{in} to @var{out}, both of which "
1100 "must be either open file ports or file descriptors. When "
1101 "@var{offset} is omitted, start reading from @var{in}'s current "
1102 "position; otherwise, start reading at @var{offset}. Return "
1103 "the number of bytes actually sent.")
1104 #define FUNC_NAME s_scm_sendfile
1105 {
1106 #define VALIDATE_FD_OR_PORT(cvar, svar, pos) \
1107 if (scm_is_integer (svar)) \
1108 cvar = scm_to_int (svar); \
1109 else \
1110 { \
1111 SCM_VALIDATE_OPFPORT (pos, svar); \
1112 scm_flush (svar); \
1113 cvar = SCM_FPORT_FDES (svar); \
1114 }
1115
1116 ssize_t result SCM_UNUSED;
1117 size_t c_count, total = 0;
1118 scm_t_off c_offset;
1119 int in_fd, out_fd;
1120
1121 VALIDATE_FD_OR_PORT (out_fd, out, 1);
1122 VALIDATE_FD_OR_PORT (in_fd, in, 2);
1123 c_count = scm_to_size_t (count);
1124 c_offset = SCM_UNBNDP (offset) ? 0 : scm_to_off_t (offset);
1125
1126 #if defined HAVE_SYS_SENDFILE_H && defined HAVE_SENDFILE
1127 /* The Linux-style sendfile(2), which is different from the BSD-style. */
1128
1129 {
1130 off_t *offset_ptr;
1131
1132 offset_ptr = SCM_UNBNDP (offset) ? NULL : &c_offset;
1133
1134 /* On Linux, when OUT_FD is a file, everything is transferred at once and
1135 RESULT == C_COUNT. However, when OUT_FD is a pipe or other "slow"
1136 device, fewer bytes may be transferred, hence the loop. RESULT == 0
1137 means EOF on IN_FD, so leave the loop in that case. */
1138 do
1139 {
1140 result = sendfile_or_sendfile64 (out_fd, in_fd, offset_ptr,
1141 c_count - total);
1142 if (result > 0)
1143 /* At this point, either OFFSET_PTR is non-NULL and it has been
1144 updated to the current offset in IN_FD, or it is NULL and IN_FD's
1145 offset has been updated. */
1146 total += result;
1147 else if (result < 0 && (errno == EINTR || errno == EAGAIN))
1148 /* Keep going. */
1149 result = 1;
1150 }
1151 while (total < c_count && result > 0);
1152 }
1153
1154 /* Quoting the Linux man page: "In Linux kernels before 2.6.33, out_fd
1155 must refer to a socket. Since Linux 2.6.33 it can be any file."
1156 Fall back to read(2) and write(2) when such an error occurs. */
1157 if (result < 0 && errno != EINVAL && errno != ENOSYS)
1158 SCM_SYSERROR;
1159 else if (result < 0)
1160 #endif
1161 {
1162 char buf[8192];
1163 size_t left;
1164 int reached_eof = 0;
1165
1166 if (!SCM_UNBNDP (offset))
1167 {
1168 if (SCM_PORTP (in))
1169 scm_seek (in, scm_from_off_t (c_offset), scm_from_int (SEEK_SET));
1170 else
1171 {
1172 if (lseek_or_lseek64 (in_fd, c_offset, SEEK_SET) < 0)
1173 SCM_SYSERROR;
1174 }
1175 }
1176
1177 for (total = 0, left = c_count; total < c_count && !reached_eof; )
1178 {
1179 size_t asked, obtained, written;
1180
1181 asked = SCM_MIN (sizeof buf, left);
1182 obtained = full_read (in_fd, buf, asked);
1183 if (obtained < asked)
1184 {
1185 if (errno == 0)
1186 reached_eof = 1;
1187 else
1188 SCM_SYSERROR;
1189 }
1190
1191 left -= obtained;
1192
1193 written = full_write (out_fd, buf, obtained);
1194 if (written < obtained)
1195 SCM_SYSERROR;
1196
1197 total += written;
1198 }
1199
1200 }
1201
1202 return scm_from_size_t (total);
1203
1204 #undef VALIDATE_FD_OR_PORT
1205 }
1206 #undef FUNC_NAME
1207
1208 #endif /* HAVE_POSIX */
1209
1210 \f
1211 /* Essential procedures used in (system base compile). */
1212
1213 #ifdef HAVE_GETCWD
1214 SCM_DEFINE (scm_getcwd, "getcwd", 0, 0, 0,
1215 (),
1216 "Return the name of the current working directory.")
1217 #define FUNC_NAME s_scm_getcwd
1218 {
1219 char *rv;
1220 size_t size = 100;
1221 char *wd;
1222 SCM result;
1223
1224 wd = scm_malloc (size);
1225 while ((rv = getcwd (wd, size)) == 0 && errno == ERANGE)
1226 {
1227 free (wd);
1228 size *= 2;
1229 wd = scm_malloc (size);
1230 }
1231 if (rv == 0)
1232 {
1233 int save_errno = errno;
1234 free (wd);
1235 errno = save_errno;
1236 SCM_SYSERROR;
1237 }
1238 result = scm_from_locale_stringn (wd, strlen (wd));
1239 free (wd);
1240 return result;
1241 }
1242 #undef FUNC_NAME
1243 #endif /* HAVE_GETCWD */
1244
1245 SCM_DEFINE (scm_mkdir, "mkdir", 1, 1, 0,
1246 (SCM path, SCM mode),
1247 "Create a new directory named by @var{path}. If @var{mode} is omitted\n"
1248 "then the permissions of the directory file are set using the current\n"
1249 "umask. Otherwise they are set to the decimal value specified with\n"
1250 "@var{mode}. The return value is unspecified.")
1251 #define FUNC_NAME s_scm_mkdir
1252 {
1253 int rv;
1254 mode_t mask;
1255
1256 if (SCM_UNBNDP (mode))
1257 {
1258 mask = umask (0);
1259 umask (mask);
1260 STRING_SYSCALL (path, c_path, rv = mkdir (c_path, 0777 ^ mask));
1261 }
1262 else
1263 {
1264 STRING_SYSCALL (path, c_path, rv = mkdir (c_path, scm_to_uint (mode)));
1265 }
1266 if (rv != 0)
1267 SCM_SYSERROR;
1268 return SCM_UNSPECIFIED;
1269 }
1270 #undef FUNC_NAME
1271
1272 SCM_DEFINE (scm_rmdir, "rmdir", 1, 0, 0,
1273 (SCM path),
1274 "Remove the existing directory named by @var{path}. The directory must\n"
1275 "be empty for this to succeed. The return value is unspecified.")
1276 #define FUNC_NAME s_scm_rmdir
1277 {
1278 int val;
1279
1280 STRING_SYSCALL (path, c_path, val = rmdir (c_path));
1281 if (val != 0)
1282 SCM_SYSERROR;
1283 return SCM_UNSPECIFIED;
1284 }
1285 #undef FUNC_NAME
1286
1287 SCM_DEFINE (scm_rename, "rename-file", 2, 0, 0,
1288 (SCM oldname, SCM newname),
1289 "Renames the file specified by @var{oldname} to @var{newname}.\n"
1290 "The return value is unspecified.")
1291 #define FUNC_NAME s_scm_rename
1292 {
1293 int rv;
1294
1295 STRING2_SYSCALL (oldname, c_oldname,
1296 newname, c_newname,
1297 rv = rename (c_oldname, c_newname));
1298 if (rv != 0)
1299 SCM_SYSERROR;
1300 return SCM_UNSPECIFIED;
1301 }
1302 #undef FUNC_NAME
1303
1304
1305 SCM_DEFINE (scm_delete_file, "delete-file", 1, 0, 0,
1306 (SCM str),
1307 "Deletes (or \"unlinks\") the file specified by @var{str}.")
1308 #define FUNC_NAME s_scm_delete_file
1309 {
1310 int ans;
1311 STRING_SYSCALL (str, c_str, ans = unlink (c_str));
1312 if (ans != 0)
1313 SCM_SYSERROR;
1314 return SCM_UNSPECIFIED;
1315 }
1316 #undef FUNC_NAME
1317
1318 SCM_DEFINE (scm_access, "access?", 2, 0, 0,
1319 (SCM path, SCM how),
1320 "Test accessibility of a file under the real UID and GID of the\n"
1321 "calling process. The return is @code{#t} if @var{path} exists\n"
1322 "and the permissions requested by @var{how} are all allowed, or\n"
1323 "@code{#f} if not.\n"
1324 "\n"
1325 "@var{how} is an integer which is one of the following values,\n"
1326 "or a bitwise-OR (@code{logior}) of multiple values.\n"
1327 "\n"
1328 "@defvar R_OK\n"
1329 "Test for read permission.\n"
1330 "@end defvar\n"
1331 "@defvar W_OK\n"
1332 "Test for write permission.\n"
1333 "@end defvar\n"
1334 "@defvar X_OK\n"
1335 "Test for execute permission.\n"
1336 "@end defvar\n"
1337 "@defvar F_OK\n"
1338 "Test for existence of the file. This is implied by each of the\n"
1339 "other tests, so there's no need to combine it with them.\n"
1340 "@end defvar\n"
1341 "\n"
1342 "It's important to note that @code{access?} does not simply\n"
1343 "indicate what will happen on attempting to read or write a\n"
1344 "file. In normal circumstances it does, but in a set-UID or\n"
1345 "set-GID program it doesn't because @code{access?} tests the\n"
1346 "real ID, whereas an open or execute attempt uses the effective\n"
1347 "ID.\n"
1348 "\n"
1349 "A program which will never run set-UID/GID can ignore the\n"
1350 "difference between real and effective IDs, but for maximum\n"
1351 "generality, especially in library functions, it's best not to\n"
1352 "use @code{access?} to predict the result of an open or execute,\n"
1353 "instead simply attempt that and catch any exception.\n"
1354 "\n"
1355 "The main use for @code{access?} is to let a set-UID/GID program\n"
1356 "determine what the invoking user would have been allowed to do,\n"
1357 "without the greater (or perhaps lesser) privileges afforded by\n"
1358 "the effective ID. For more on this, see ``Testing File\n"
1359 "Access'' in The GNU C Library Reference Manual.")
1360 #define FUNC_NAME s_scm_access
1361 {
1362 int rv;
1363 char *c_path;
1364
1365 c_path = scm_to_locale_string (path);
1366 rv = access (c_path, scm_to_int (how));
1367 free (c_path);
1368
1369 return scm_from_bool (!rv);
1370 }
1371 #undef FUNC_NAME
1372
1373 SCM_DEFINE (scm_chmod, "chmod", 2, 0, 0,
1374 (SCM object, SCM mode),
1375 "Changes the permissions of the file referred to by\n"
1376 "@var{object}. @var{object} can be a string containing a file\n"
1377 "name or a port or integer file descriptor which is open on a\n"
1378 "file (in which case @code{fchmod} is used as the underlying\n"
1379 "system call). @var{mode} specifies the new permissions as a\n"
1380 "decimal number, e.g., @code{(chmod \"foo\" #o755)}.\n"
1381 "The return value is unspecified.")
1382 #define FUNC_NAME s_scm_chmod
1383 {
1384 int rv;
1385
1386 object = SCM_COERCE_OUTPORT (object);
1387
1388 #if HAVE_FCHMOD
1389 if (scm_is_integer (object) || SCM_OPFPORTP (object))
1390 {
1391 int fdes;
1392 if (scm_is_integer (object))
1393 fdes = scm_to_int (object);
1394 else
1395 fdes = SCM_FPORT_FDES (object);
1396 SCM_SYSCALL (rv = fchmod (fdes, scm_to_int (mode)));
1397 }
1398 else
1399 #endif
1400 {
1401 STRING_SYSCALL (object, c_object,
1402 rv = chmod (c_object, scm_to_int (mode)));
1403 }
1404 if (rv == -1)
1405 SCM_SYSERROR;
1406 return SCM_UNSPECIFIED;
1407 }
1408 #undef FUNC_NAME
1409
1410 SCM_DEFINE (scm_umask, "umask", 0, 1, 0,
1411 (SCM mode),
1412 "If @var{mode} is omitted, returns a decimal number representing the current\n"
1413 "file creation mask. Otherwise the file creation mask is set to\n"
1414 "@var{mode} and the previous value is returned.\n\n"
1415 "E.g., @code{(umask #o022)} sets the mask to octal 22, decimal 18.")
1416 #define FUNC_NAME s_scm_umask
1417 {
1418 mode_t mask;
1419 if (SCM_UNBNDP (mode))
1420 {
1421 mask = umask (0);
1422 umask (mask);
1423 }
1424 else
1425 {
1426 mask = umask (scm_to_uint (mode));
1427 }
1428 return scm_from_uint (mask);
1429 }
1430 #undef FUNC_NAME
1431
1432 SCM_DEFINE (scm_mkstemp, "mkstemp!", 1, 0, 0,
1433 (SCM tmpl),
1434 "Create a new unique file in the file system and return a new\n"
1435 "buffered port open for reading and writing to the file.\n"
1436 "\n"
1437 "@var{tmpl} is a string specifying where the file should be\n"
1438 "created: it must end with @samp{XXXXXX} and those @samp{X}s\n"
1439 "will be changed in the string to return the name of the file.\n"
1440 "(@code{port-filename} on the port also gives the name.)\n"
1441 "\n"
1442 "POSIX doesn't specify the permissions mode of the file, on GNU\n"
1443 "and most systems it's @code{#o600}. An application can use\n"
1444 "@code{chmod} to relax that if desired. For example\n"
1445 "@code{#o666} less @code{umask}, which is usual for ordinary\n"
1446 "file creation,\n"
1447 "\n"
1448 "@example\n"
1449 "(let ((port (mkstemp! (string-copy \"/tmp/myfile-XXXXXX\"))))\n"
1450 " (chmod port (logand #o666 (lognot (umask))))\n"
1451 " ...)\n"
1452 "@end example")
1453 #define FUNC_NAME s_scm_mkstemp
1454 {
1455 char *c_tmpl;
1456 int rv;
1457
1458 scm_dynwind_begin (0);
1459
1460 c_tmpl = scm_to_locale_string (tmpl);
1461 scm_dynwind_free (c_tmpl);
1462
1463 SCM_SYSCALL (rv = mkstemp (c_tmpl));
1464 if (rv == -1)
1465 SCM_SYSERROR;
1466
1467 scm_substring_move_x (scm_from_locale_string (c_tmpl),
1468 SCM_INUM0, scm_string_length (tmpl),
1469 tmpl, SCM_INUM0);
1470
1471 scm_dynwind_end ();
1472 return scm_fdes_to_port (rv, "w+", tmpl);
1473 }
1474 #undef FUNC_NAME
1475
1476 \f
1477 /* Filename manipulation */
1478
1479 SCM scm_dot_string;
1480
1481 #ifdef __MINGW32__
1482 SCM_SYMBOL (sym_file_name_convention, "windows");
1483 #else
1484 SCM_SYMBOL (sym_file_name_convention, "posix");
1485 #endif
1486
1487 SCM_INTERNAL SCM scm_system_file_name_convention (void);
1488
1489 SCM_DEFINE (scm_system_file_name_convention,
1490 "system-file-name-convention", 0, 0, 0, (void),
1491 "Return either @code{posix} or @code{windows}, depending on\n"
1492 "what kind of system this Guile is running on.")
1493 #define FUNC_NAME s_scm_system_file_name_convention
1494 {
1495 return sym_file_name_convention;
1496 }
1497 #undef FUNC_NAME
1498
1499 SCM_DEFINE (scm_dirname, "dirname", 1, 0, 0,
1500 (SCM filename),
1501 "Return the directory name component of the file name\n"
1502 "@var{filename}. If @var{filename} does not contain a directory\n"
1503 "component, @code{.} is returned.")
1504 #define FUNC_NAME s_scm_dirname
1505 {
1506 long int i;
1507 unsigned long int len;
1508
1509 SCM_VALIDATE_STRING (1, filename);
1510
1511 len = scm_i_string_length (filename);
1512
1513 i = len - 1;
1514
1515 while (i >= 0 && is_file_name_separator (scm_c_string_ref (filename, i)))
1516 --i;
1517 while (i >= 0 && !is_file_name_separator (scm_c_string_ref (filename, i)))
1518 --i;
1519 while (i >= 0 && is_file_name_separator (scm_c_string_ref (filename, i)))
1520 --i;
1521
1522 if (i < 0)
1523 {
1524 if (len > 0 && is_file_name_separator (scm_c_string_ref (filename, 0)))
1525 return scm_c_substring (filename, 0, 1);
1526 else
1527 return scm_dot_string;
1528 }
1529 else
1530 return scm_c_substring (filename, 0, i + 1);
1531 }
1532 #undef FUNC_NAME
1533
1534 SCM_DEFINE (scm_basename, "basename", 1, 1, 0,
1535 (SCM filename, SCM suffix),
1536 "Return the base name of the file name @var{filename}. The\n"
1537 "base name is the file name without any directory components.\n"
1538 "If @var{suffix} is provided, and is equal to the end of\n"
1539 "@var{filename}, it is removed also.")
1540 #define FUNC_NAME s_scm_basename
1541 {
1542 int i, j, len, end;
1543
1544 SCM_VALIDATE_STRING (1, filename);
1545 len = scm_i_string_length (filename);
1546
1547 if (SCM_UNBNDP (suffix))
1548 j = -1;
1549 else
1550 {
1551 SCM_VALIDATE_STRING (2, suffix);
1552 j = scm_i_string_length (suffix) - 1;
1553 }
1554 i = len - 1;
1555 while (i >= 0 && is_file_name_separator (scm_c_string_ref (filename, i)))
1556 --i;
1557 end = i;
1558 while (i >= 0 && j >= 0
1559 && (scm_i_string_ref (filename, i)
1560 == scm_i_string_ref (suffix, j)))
1561 {
1562 --i;
1563 --j;
1564 }
1565 if (j == -1)
1566 end = i;
1567 while (i >= 0 && !is_file_name_separator (scm_c_string_ref (filename, i)))
1568 --i;
1569 if (i == end)
1570 {
1571 if (len > 0 && is_file_name_separator (scm_c_string_ref (filename, 0)))
1572 return scm_c_substring (filename, 0, 1);
1573 else
1574 return scm_dot_string;
1575 }
1576 else
1577 return scm_c_substring (filename, i+1, end+1);
1578 }
1579 #undef FUNC_NAME
1580
1581 SCM_DEFINE (scm_canonicalize_path, "canonicalize-path", 1, 0, 0,
1582 (SCM path),
1583 "Return the canonical path of @var{path}. A canonical path has\n"
1584 "no @code{.} or @code{..} components, nor any repeated path\n"
1585 "separators (@code{/}) nor symlinks.\n\n"
1586 "Raises an error if any component of @var{path} does not exist.")
1587 #define FUNC_NAME s_scm_canonicalize_path
1588 {
1589 char *str, *canon;
1590
1591 SCM_VALIDATE_STRING (1, path);
1592
1593 str = scm_to_locale_string (path);
1594 canon = canonicalize_file_name (str);
1595 free (str);
1596
1597 if (canon)
1598 return scm_take_locale_string (canon);
1599 else
1600 SCM_SYSERROR;
1601 }
1602 #undef FUNC_NAME
1603
1604 SCM
1605 scm_i_relativize_path (SCM path, SCM in_path)
1606 {
1607 char *str, *canon;
1608 SCM scanon;
1609
1610 str = scm_to_locale_string (path);
1611 canon = canonicalize_file_name (str);
1612 free (str);
1613
1614 if (!canon)
1615 return SCM_BOOL_F;
1616
1617 scanon = scm_take_locale_string (canon);
1618
1619 for (; scm_is_pair (in_path); in_path = scm_cdr (in_path))
1620 {
1621 SCM dir = scm_car (in_path);
1622 size_t len = scm_c_string_length (dir);
1623
1624 /* When DIR is empty, it means "current working directory". We
1625 could set DIR to (getcwd) in that case, but then the
1626 canonicalization would depend on the current directory, which
1627 is not what we want in the context of `compile-file', for
1628 instance. */
1629 if (len > 0
1630 && scm_is_true (scm_string_prefix_p (dir, scanon,
1631 SCM_UNDEFINED, SCM_UNDEFINED,
1632 SCM_UNDEFINED, SCM_UNDEFINED)))
1633 {
1634 /* DIR either has a trailing delimiter or doesn't. SCANON
1635 will be delimited by single delimiters. When DIR does not
1636 have a trailing delimiter, add one to the length to strip
1637 off the delimiter within SCANON. */
1638 if (!is_file_name_separator (scm_c_string_ref (dir, len - 1)))
1639 len++;
1640
1641 if (scm_c_string_length (scanon) > len)
1642 return scm_substring (scanon, scm_from_size_t (len), SCM_UNDEFINED);
1643 else
1644 return SCM_BOOL_F;
1645 }
1646 }
1647
1648 return SCM_BOOL_F;
1649 }
1650
1651 \f
1652 /* Examining directories. These procedures are used by `check-guile'
1653 and thus compiled unconditionally. */
1654
1655 scm_t_bits scm_tc16_dir;
1656
1657
1658 SCM_DEFINE (scm_directory_stream_p, "directory-stream?", 1, 0, 0,
1659 (SCM obj),
1660 "Return a boolean indicating whether @var{obj} is a directory\n"
1661 "stream as returned by @code{opendir}.")
1662 #define FUNC_NAME s_scm_directory_stream_p
1663 {
1664 return scm_from_bool (SCM_DIRP (obj));
1665 }
1666 #undef FUNC_NAME
1667
1668
1669 SCM_DEFINE (scm_opendir, "opendir", 1, 0, 0,
1670 (SCM dirname),
1671 "Open the directory specified by @var{dirname} and return a directory\n"
1672 "stream.")
1673 #define FUNC_NAME s_scm_opendir
1674 {
1675 DIR *ds;
1676 STRING_SYSCALL (dirname, c_dirname, ds = opendir (c_dirname));
1677 if (ds == NULL)
1678 SCM_SYSERROR;
1679 SCM_RETURN_NEWSMOB (scm_tc16_dir | (SCM_DIR_FLAG_OPEN<<16), ds);
1680 }
1681 #undef FUNC_NAME
1682
1683
1684 /* FIXME: The glibc manual has a portability note that readdir_r may not
1685 null-terminate its return string. The circumstances outlined for this
1686 are not clear, nor is it clear what should be done about it. Lets use
1687 NAMLEN and worry about what else should be done if/when someone can
1688 figure it out. */
1689
1690 SCM_DEFINE (scm_readdir, "readdir", 1, 0, 0,
1691 (SCM port),
1692 "Return (as a string) the next directory entry from the directory stream\n"
1693 "@var{port}. If there is no remaining entry to be read then the\n"
1694 "end of file object is returned.")
1695 #define FUNC_NAME s_scm_readdir
1696 {
1697 struct dirent_or_dirent64 *rdent;
1698
1699 SCM_VALIDATE_DIR (1, port);
1700 if (!SCM_DIR_OPEN_P (port))
1701 SCM_MISC_ERROR ("Directory ~S is not open.", scm_list_1 (port));
1702
1703 #if HAVE_READDIR_R
1704 /* As noted in the glibc manual, on various systems (such as Solaris) the
1705 d_name[] field is only 1 char and you're expected to size the dirent
1706 buffer for readdir_r based on NAME_MAX. The SCM_MAX expressions below
1707 effectively give either sizeof(d_name) or NAME_MAX+1, whichever is
1708 bigger.
1709
1710 On solaris 10 there's no NAME_MAX constant, it's necessary to use
1711 pathconf(). We prefer NAME_MAX though, since it should be a constant
1712 and will therefore save a system call. We also prefer it since dirfd()
1713 is not available everywhere.
1714
1715 An alternative to dirfd() would be to open() the directory and then use
1716 fdopendir(), if the latter is available. That'd let us hold the fd
1717 somewhere in the smob, or just the dirent size calculated once. */
1718 {
1719 struct dirent_or_dirent64 de; /* just for sizeof */
1720 DIR *ds = (DIR *) SCM_SMOB_DATA_1 (port);
1721 #ifdef NAME_MAX
1722 char buf [SCM_MAX (sizeof (de),
1723 sizeof (de) - sizeof (de.d_name) + NAME_MAX + 1)];
1724 #else
1725 char *buf;
1726 long name_max = fpathconf (dirfd (ds), _PC_NAME_MAX);
1727 if (name_max == -1)
1728 SCM_SYSERROR;
1729 buf = alloca (SCM_MAX (sizeof (de),
1730 sizeof (de) - sizeof (de.d_name) + name_max + 1));
1731 #endif
1732
1733 errno = 0;
1734 SCM_SYSCALL (readdir_r_or_readdir64_r (ds, (struct dirent_or_dirent64 *) buf, &rdent));
1735 if (errno != 0)
1736 SCM_SYSERROR;
1737 if (! rdent)
1738 return SCM_EOF_VAL;
1739
1740 return (rdent ? scm_from_locale_stringn (rdent->d_name, NAMLEN (rdent))
1741 : SCM_EOF_VAL);
1742 }
1743 #else
1744 {
1745 SCM ret;
1746 scm_dynwind_begin (0);
1747 scm_i_dynwind_pthread_mutex_lock (&scm_i_misc_mutex);
1748
1749 errno = 0;
1750 SCM_SYSCALL (rdent = readdir_or_readdir64 ((DIR *) SCM_SMOB_DATA_1 (port)));
1751 if (errno != 0)
1752 SCM_SYSERROR;
1753
1754 ret = (rdent ? scm_from_locale_stringn (rdent->d_name, NAMLEN (rdent))
1755 : SCM_EOF_VAL);
1756
1757 scm_dynwind_end ();
1758 return ret;
1759 }
1760 #endif
1761 }
1762 #undef FUNC_NAME
1763
1764
1765 SCM_DEFINE (scm_rewinddir, "rewinddir", 1, 0, 0,
1766 (SCM port),
1767 "Reset the directory port @var{port} so that the next call to\n"
1768 "@code{readdir} will return the first directory entry.")
1769 #define FUNC_NAME s_scm_rewinddir
1770 {
1771 SCM_VALIDATE_DIR (1, port);
1772 if (!SCM_DIR_OPEN_P (port))
1773 SCM_MISC_ERROR ("Directory ~S is not open.", scm_list_1 (port));
1774
1775 rewinddir ((DIR *) SCM_SMOB_DATA_1 (port));
1776
1777 return SCM_UNSPECIFIED;
1778 }
1779 #undef FUNC_NAME
1780
1781
1782 SCM_DEFINE (scm_closedir, "closedir", 1, 0, 0,
1783 (SCM port),
1784 "Close the directory stream @var{port}.\n"
1785 "The return value is unspecified.")
1786 #define FUNC_NAME s_scm_closedir
1787 {
1788 SCM_VALIDATE_DIR (1, port);
1789
1790 if (SCM_DIR_OPEN_P (port))
1791 {
1792 int sts;
1793
1794 SCM_SYSCALL (sts = closedir ((DIR *) SCM_SMOB_DATA_1 (port)));
1795 if (sts != 0)
1796 SCM_SYSERROR;
1797
1798 SCM_SET_SMOB_DATA_0 (port, scm_tc16_dir);
1799 }
1800
1801 return SCM_UNSPECIFIED;
1802 }
1803 #undef FUNC_NAME
1804
1805
1806 #ifdef HAVE_POSIX
1807 static int
1808 scm_dir_print (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
1809 {
1810 scm_puts ("#<", port);
1811 if (!SCM_DIR_OPEN_P (exp))
1812 scm_puts ("closed: ", port);
1813 scm_puts ("directory stream ", port);
1814 scm_uintprint (SCM_SMOB_DATA_1 (exp), 16, port);
1815 scm_putc ('>', port);
1816 return 1;
1817 }
1818
1819
1820 static size_t
1821 scm_dir_free (SCM p)
1822 {
1823 if (SCM_DIR_OPEN_P (p))
1824 closedir ((DIR *) SCM_SMOB_DATA_1 (p));
1825 return 0;
1826 }
1827 #endif
1828
1829 \f
1830
1831 void
1832 scm_init_filesys ()
1833 {
1834 #ifdef HAVE_POSIX
1835 scm_tc16_dir = scm_make_smob_type ("directory", 0);
1836 scm_set_smob_free (scm_tc16_dir, scm_dir_free);
1837 scm_set_smob_print (scm_tc16_dir, scm_dir_print);
1838
1839 #ifdef O_RDONLY
1840 scm_c_define ("O_RDONLY", scm_from_int (O_RDONLY));
1841 #endif
1842 #ifdef O_WRONLY
1843 scm_c_define ("O_WRONLY", scm_from_int (O_WRONLY));
1844 #endif
1845 #ifdef O_RDWR
1846 scm_c_define ("O_RDWR", scm_from_int (O_RDWR));
1847 #endif
1848 #ifdef O_CREAT
1849 scm_c_define ("O_CREAT", scm_from_int (O_CREAT));
1850 #endif
1851 #ifdef O_EXCL
1852 scm_c_define ("O_EXCL", scm_from_int (O_EXCL));
1853 #endif
1854 #ifdef O_NOCTTY
1855 scm_c_define ("O_NOCTTY", scm_from_int (O_NOCTTY));
1856 #endif
1857 #ifdef O_TRUNC
1858 scm_c_define ("O_TRUNC", scm_from_int (O_TRUNC));
1859 #endif
1860 #ifdef O_APPEND
1861 scm_c_define ("O_APPEND", scm_from_int (O_APPEND));
1862 #endif
1863 #ifdef O_NONBLOCK
1864 scm_c_define ("O_NONBLOCK", scm_from_int (O_NONBLOCK));
1865 #endif
1866 #ifdef O_NDELAY
1867 scm_c_define ("O_NDELAY", scm_from_int (O_NDELAY));
1868 #endif
1869 #ifdef O_SYNC
1870 scm_c_define ("O_SYNC", scm_from_int (O_SYNC));
1871 #endif
1872 #ifdef O_LARGEFILE
1873 scm_c_define ("O_LARGEFILE", scm_from_int (O_LARGEFILE));
1874 #endif
1875 #ifdef O_NOTRANS
1876 scm_c_define ("O_NOTRANS", scm_from_int (O_NOTRANS));
1877 #endif
1878
1879 #ifdef F_DUPFD
1880 scm_c_define ("F_DUPFD", scm_from_int (F_DUPFD));
1881 #endif
1882 #ifdef F_GETFD
1883 scm_c_define ("F_GETFD", scm_from_int (F_GETFD));
1884 #endif
1885 #ifdef F_SETFD
1886 scm_c_define ("F_SETFD", scm_from_int (F_SETFD));
1887 #endif
1888 #ifdef F_GETFL
1889 scm_c_define ("F_GETFL", scm_from_int (F_GETFL));
1890 #endif
1891 #ifdef F_SETFL
1892 scm_c_define ("F_SETFL", scm_from_int (F_SETFL));
1893 #endif
1894 #ifdef F_GETOWN
1895 scm_c_define ("F_GETOWN", scm_from_int (F_GETOWN));
1896 #endif
1897 #ifdef F_SETOWN
1898 scm_c_define ("F_SETOWN", scm_from_int (F_SETOWN));
1899 #endif
1900 #ifdef FD_CLOEXEC
1901 scm_c_define ("FD_CLOEXEC", scm_from_int (FD_CLOEXEC));
1902 #endif
1903 #endif /* HAVE_POSIX */
1904
1905 /* `access' symbols. */
1906 scm_c_define ("R_OK", scm_from_int (R_OK));
1907 scm_c_define ("W_OK", scm_from_int (W_OK));
1908 scm_c_define ("X_OK", scm_from_int (X_OK));
1909 scm_c_define ("F_OK", scm_from_int (F_OK));
1910
1911 scm_dot_string = scm_from_locale_string (".");
1912
1913 #include "libguile/filesys.x"
1914 }
1915
1916 /*
1917 Local Variables:
1918 c-file-style: "gnu"
1919 End:
1920 */