cdd9ae73c11dcfcd159808cf4478afaab1975789
[bpt/guile.git] / libguile / filesys.c
1 /* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2004, 2006,
2 * 2009, 2010, 2011, 2012 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/iselect.h"
49 #include "libguile/strings.h"
50 #include "libguile/vectors.h"
51 #include "libguile/dynwind.h"
52
53 #include "libguile/validate.h"
54 #include "libguile/filesys.h"
55
56 \f
57 #ifdef HAVE_IO_H
58 #include <io.h>
59 #endif
60
61 #ifdef HAVE_DIRECT_H
62 #include <direct.h>
63 #endif
64
65 #ifdef TIME_WITH_SYS_TIME
66 # include <sys/time.h>
67 # include <time.h>
68 #else
69 # if HAVE_SYS_TIME_H
70 # include <sys/time.h>
71 # else
72 # include <time.h>
73 # endif
74 #endif
75
76 #ifdef HAVE_UNISTD_H
77 #include <unistd.h>
78 #endif
79
80 #ifdef LIBC_H_WITH_UNISTD_H
81 #include <libc.h>
82 #endif
83
84 #ifdef HAVE_SYS_SELECT_H
85 #include <sys/select.h>
86 #endif
87
88 #ifdef HAVE_STRING_H
89 #include <string.h>
90 #endif
91
92 #include <sys/types.h>
93 #include <sys/stat.h>
94 #include <fcntl.h>
95
96 #ifdef HAVE_PWD_H
97 #include <pwd.h>
98 #endif
99
100 #include <dirent.h>
101
102 #define NAMLEN(dirent) strlen ((dirent)->d_name)
103
104 /* Some more definitions for the native Windows port. */
105 #ifdef __MINGW32__
106 # define fsync(fd) _commit (fd)
107 # define fchmod(fd, mode) (-1)
108 #endif /* __MINGW32__ */
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 #ifdef __MINGW32__
440 /*
441 * Try getting the appropiate stat buffer for a given file descriptor
442 * under Windows. It differentiates between file, pipe and socket
443 * descriptors.
444 */
445 static int fstat_Win32 (int fdes, struct stat *buf)
446 {
447 int error, optlen = sizeof (int);
448
449 memset (buf, 0, sizeof (struct stat));
450
451 /* Is this a socket ? */
452 if (getsockopt (fdes, SOL_SOCKET, SO_ERROR, (void *) &error, &optlen) >= 0)
453 {
454 buf->st_mode = _S_IREAD | _S_IWRITE | _S_IEXEC;
455 buf->st_nlink = 1;
456 buf->st_atime = buf->st_ctime = buf->st_mtime = time (NULL);
457 return 0;
458 }
459 /* Maybe a regular file or pipe ? */
460 return fstat (fdes, buf);
461 }
462 #endif /* __MINGW32__ */
463
464 SCM_DEFINE (scm_stat, "stat", 1, 1, 0,
465 (SCM object, SCM exception_on_error),
466 "Return an object containing various information about the file\n"
467 "determined by @var{object}. @var{object} can be a string containing\n"
468 "a file name or a port or integer file descriptor which is open\n"
469 "on a file (in which case @code{fstat} is used as the underlying\n"
470 "system call).\n"
471 "\n"
472 "If the optional @var{exception_on_error} argument is true, which\n"
473 "is the default, an exception will be raised if the underlying\n"
474 "system call returns an error, for example if the file is not\n"
475 "found or is not readable. Otherwise, an error will cause\n"
476 "@code{stat} to return @code{#f}."
477 "\n"
478 "The object returned by a successful call to @code{stat} can be\n"
479 "passed as a single parameter to the following procedures, all of\n"
480 "which return integers:\n"
481 "\n"
482 "@table @code\n"
483 "@item stat:dev\n"
484 "The device containing the file.\n"
485 "@item stat:ino\n"
486 "The file serial number, which distinguishes this file from all\n"
487 "other files on the same device.\n"
488 "@item stat:mode\n"
489 "The mode of the file. This includes file type information and\n"
490 "the file permission bits. See @code{stat:type} and\n"
491 "@code{stat:perms} below.\n"
492 "@item stat:nlink\n"
493 "The number of hard links to the file.\n"
494 "@item stat:uid\n"
495 "The user ID of the file's owner.\n"
496 "@item stat:gid\n"
497 "The group ID of the file.\n"
498 "@item stat:rdev\n"
499 "Device ID; this entry is defined only for character or block\n"
500 "special files.\n"
501 "@item stat:size\n"
502 "The size of a regular file in bytes.\n"
503 "@item stat:atime\n"
504 "The last access time for the file.\n"
505 "@item stat:mtime\n"
506 "The last modification time for the file.\n"
507 "@item stat:ctime\n"
508 "The last modification time for the attributes of the file.\n"
509 "@item stat:blksize\n"
510 "The optimal block size for reading or writing the file, in\n"
511 "bytes.\n"
512 "@item stat:blocks\n"
513 "The amount of disk space that the file occupies measured in\n"
514 "units of 512 byte blocks.\n"
515 "@end table\n"
516 "\n"
517 "In addition, the following procedures return the information\n"
518 "from stat:mode in a more convenient form:\n"
519 "\n"
520 "@table @code\n"
521 "@item stat:type\n"
522 "A symbol representing the type of file. Possible values are\n"
523 "regular, directory, symlink, block-special, char-special, fifo,\n"
524 "socket and unknown\n"
525 "@item stat:perms\n"
526 "An integer representing the access permission bits.\n"
527 "@end table")
528 #define FUNC_NAME s_scm_stat
529 {
530 int rv;
531 int fdes;
532 struct stat_or_stat64 stat_temp;
533
534 if (scm_is_integer (object))
535 {
536 #ifdef __MINGW32__
537 SCM_SYSCALL (rv = fstat_Win32 (scm_to_int (object), &stat_temp));
538 #else
539 SCM_SYSCALL (rv = fstat_or_fstat64 (scm_to_int (object), &stat_temp));
540 #endif
541 }
542 else if (scm_is_string (object))
543 {
544 char *file = scm_to_locale_string (object);
545 #ifdef __MINGW32__
546 char *p;
547 p = file + strlen (file) - 1;
548 while (p > file && (*p == '/' || *p == '\\'))
549 *p-- = '\0';
550 #endif
551 SCM_SYSCALL (rv = stat_or_stat64 (file, &stat_temp));
552 free (file);
553 }
554 else
555 {
556 object = SCM_COERCE_OUTPORT (object);
557 SCM_VALIDATE_OPFPORT (1, object);
558 fdes = SCM_FPORT_FDES (object);
559 #ifdef __MINGW32__
560 SCM_SYSCALL (rv = fstat_Win32 (fdes, &stat_temp));
561 #else
562 SCM_SYSCALL (rv = fstat_or_fstat64 (fdes, &stat_temp));
563 #endif
564 }
565
566 if (rv == -1)
567 {
568 if (SCM_UNBNDP (exception_on_error) || scm_is_true (exception_on_error))
569 {
570 int en = errno;
571 SCM_SYSERROR_MSG ("~A: ~S",
572 scm_list_2 (scm_strerror (scm_from_int (en)),
573 object),
574 en);
575 }
576 else
577 return SCM_BOOL_F;
578 }
579 return scm_stat2scm (&stat_temp);
580 }
581 #undef FUNC_NAME
582
583 #ifdef HAVE_LSTAT
584 SCM_DEFINE (scm_lstat, "lstat", 1, 0, 0,
585 (SCM str),
586 "Similar to @code{stat}, but does not follow symbolic links, i.e.,\n"
587 "it will return information about a symbolic link itself, not the\n"
588 "file it points to. @var{str} must be a string.")
589 #define FUNC_NAME s_scm_lstat
590 {
591 int rv;
592 struct stat_or_stat64 stat_temp;
593
594 STRING_SYSCALL (str, c_str, rv = lstat_or_lstat64 (c_str, &stat_temp));
595 if (rv != 0)
596 {
597 int en = errno;
598
599 SCM_SYSERROR_MSG ("~A: ~S",
600 scm_list_2 (scm_strerror (scm_from_int (en)), str),
601 en);
602 }
603 return scm_stat2scm (&stat_temp);
604 }
605 #undef FUNC_NAME
606 #endif /* HAVE_LSTAT */
607
608 \f
609 #ifdef HAVE_POSIX
610
611 /* {Modifying Directories}
612 */
613
614 #ifdef HAVE_LINK
615 SCM_DEFINE (scm_link, "link", 2, 0, 0,
616 (SCM oldpath, SCM newpath),
617 "Creates a new name @var{newpath} in the file system for the\n"
618 "file named by @var{oldpath}. If @var{oldpath} is a symbolic\n"
619 "link, the link may or may not be followed depending on the\n"
620 "system.")
621 #define FUNC_NAME s_scm_link
622 {
623 int val;
624
625 STRING2_SYSCALL (oldpath, c_oldpath,
626 newpath, c_newpath,
627 val = link (c_oldpath, c_newpath));
628 if (val != 0)
629 SCM_SYSERROR;
630 return SCM_UNSPECIFIED;
631 }
632 #undef FUNC_NAME
633 #endif /* HAVE_LINK */
634
635 \f
636 /* {Navigating Directories}
637 */
638
639
640 SCM_DEFINE (scm_chdir, "chdir", 1, 0, 0,
641 (SCM str),
642 "Change the current working directory to @var{str}.\n"
643 "The return value is unspecified.")
644 #define FUNC_NAME s_scm_chdir
645 {
646 int ans;
647
648 STRING_SYSCALL (str, c_str, ans = chdir (c_str));
649 if (ans != 0)
650 SCM_SYSERROR;
651 return SCM_UNSPECIFIED;
652 }
653 #undef FUNC_NAME
654
655 \f
656
657 #ifdef HAVE_SELECT
658
659 /* check that element is a port or file descriptor. if it's a port
660 and its buffer is ready for use, add it to the ports_ready list.
661 otherwise add its file descriptor to *set. the type of list can be
662 determined from pos: SCM_ARG1 for reads, SCM_ARG2 for writes,
663 SCM_ARG3 for excepts. */
664 static int
665 set_element (SELECT_TYPE *set, SCM *ports_ready, SCM element, int pos)
666 {
667 int fd;
668
669 if (scm_is_integer (element))
670 {
671 fd = scm_to_int (element);
672 }
673 else
674 {
675 int use_buf = 0;
676
677 element = SCM_COERCE_OUTPORT (element);
678 SCM_ASSERT (SCM_OPFPORTP (element), element, pos, "select");
679 if (pos == SCM_ARG1)
680 {
681 /* check whether port has buffered input. */
682 scm_t_port *pt = SCM_PTAB_ENTRY (element);
683
684 if (pt->read_pos < pt->read_end)
685 use_buf = 1;
686 }
687 else if (pos == SCM_ARG2)
688 {
689 /* check whether port's output buffer has room. */
690 scm_t_port *pt = SCM_PTAB_ENTRY (element);
691
692 /* > 1 since writing the last byte in the buffer causes flush. */
693 if (pt->write_end - pt->write_pos > 1)
694 use_buf = 1;
695 }
696 fd = use_buf ? -1 : SCM_FPORT_FDES (element);
697 }
698 if (fd == -1)
699 *ports_ready = scm_cons (element, *ports_ready);
700 else
701 FD_SET (fd, set);
702 return fd;
703 }
704
705 /* check list_or_vec, a list or vector of ports or file descriptors,
706 adding each member to either the ports_ready list (if it's a port
707 with a usable buffer) or to *set. the kind of list_or_vec can be
708 determined from pos: SCM_ARG1 for reads, SCM_ARG2 for writes,
709 SCM_ARG3 for excepts. */
710 static int
711 fill_select_type (SELECT_TYPE *set, SCM *ports_ready, SCM list_or_vec, int pos)
712 {
713 int max_fd = 0;
714
715 if (scm_is_simple_vector (list_or_vec))
716 {
717 int i = SCM_SIMPLE_VECTOR_LENGTH (list_or_vec);
718
719 while (--i >= 0)
720 {
721 int fd = set_element (set, ports_ready,
722 SCM_SIMPLE_VECTOR_REF (list_or_vec, i), pos);
723
724 if (fd > max_fd)
725 max_fd = fd;
726 }
727 }
728 else
729 {
730 while (!SCM_NULL_OR_NIL_P (list_or_vec))
731 {
732 int fd = set_element (set, ports_ready, SCM_CAR (list_or_vec), pos);
733
734 if (fd > max_fd)
735 max_fd = fd;
736 list_or_vec = SCM_CDR (list_or_vec);
737 }
738 }
739
740 return max_fd;
741 }
742
743 /* if element (a file descriptor or port) appears in *set, cons it to
744 list. return list. */
745 static SCM
746 get_element (SELECT_TYPE *set, SCM element, SCM list)
747 {
748 int fd;
749
750 if (scm_is_integer (element))
751 {
752 fd = scm_to_int (element);
753 }
754 else
755 {
756 fd = SCM_FPORT_FDES (SCM_COERCE_OUTPORT (element));
757 }
758 if (FD_ISSET (fd, set))
759 list = scm_cons (element, list);
760 return list;
761 }
762
763 /* construct component of scm_select return value.
764 set: pointer to set of file descriptors found by select to be ready
765 ports_ready: ports ready due to buffering
766 list_or_vec: original list/vector handed to scm_select.
767 the return value is a list/vector of ready ports/file descriptors.
768 works by finding the objects in list which correspond to members of
769 *set and appending them to ports_ready. result is converted to a
770 vector if list_or_vec is a vector. */
771 static SCM
772 retrieve_select_type (SELECT_TYPE *set, SCM ports_ready, SCM list_or_vec)
773 {
774 SCM answer_list = ports_ready;
775
776 if (scm_is_simple_vector (list_or_vec))
777 {
778 int i = SCM_SIMPLE_VECTOR_LENGTH (list_or_vec);
779
780 while (--i >= 0)
781 {
782 answer_list = get_element (set,
783 SCM_SIMPLE_VECTOR_REF (list_or_vec, i),
784 answer_list);
785 }
786 return scm_vector (answer_list);
787 }
788 else
789 {
790 /* list_or_vec must be a list. */
791 while (!SCM_NULL_OR_NIL_P (list_or_vec))
792 {
793 answer_list = get_element (set, SCM_CAR (list_or_vec), answer_list);
794 list_or_vec = SCM_CDR (list_or_vec);
795 }
796 return answer_list;
797 }
798 }
799
800 /* Static helper functions above refer to s_scm_select directly as s_select */
801 SCM_DEFINE (scm_select, "select", 3, 2, 0,
802 (SCM reads, SCM writes, SCM excepts, SCM secs, SCM usecs),
803 "This procedure has a variety of uses: waiting for the ability\n"
804 "to provide input, accept output, or the existence of\n"
805 "exceptional conditions on a collection of ports or file\n"
806 "descriptors, or waiting for a timeout to occur.\n"
807 "It also returns if interrupted by a signal.\n\n"
808 "@var{reads}, @var{writes} and @var{excepts} can be lists or\n"
809 "vectors, with each member a port or a file descriptor.\n"
810 "The value returned is a list of three corresponding\n"
811 "lists or vectors containing only the members which meet the\n"
812 "specified requirement. The ability of port buffers to\n"
813 "provide input or accept output is taken into account.\n"
814 "Ordering of the input lists or vectors is not preserved.\n\n"
815 "The optional arguments @var{secs} and @var{usecs} specify the\n"
816 "timeout. Either @var{secs} can be specified alone, as\n"
817 "either an integer or a real number, or both @var{secs} and\n"
818 "@var{usecs} can be specified as integers, in which case\n"
819 "@var{usecs} is an additional timeout expressed in\n"
820 "microseconds. If @var{secs} is omitted or is @code{#f} then\n"
821 "select will wait for as long as it takes for one of the other\n"
822 "conditions to be satisfied.\n\n"
823 "The scsh version of @code{select} differs as follows:\n"
824 "Only vectors are accepted for the first three arguments.\n"
825 "The @var{usecs} argument is not supported.\n"
826 "Multiple values are returned instead of a list.\n"
827 "Duplicates in the input vectors appear only once in output.\n"
828 "An additional @code{select!} interface is provided.")
829 #define FUNC_NAME s_scm_select
830 {
831 struct timeval timeout;
832 struct timeval * time_ptr;
833 SELECT_TYPE read_set;
834 SELECT_TYPE write_set;
835 SELECT_TYPE except_set;
836 int read_count;
837 int write_count;
838 int except_count;
839 /* these lists accumulate ports which are ready due to buffering.
840 their file descriptors don't need to be added to the select sets. */
841 SCM read_ports_ready = SCM_EOL;
842 SCM write_ports_ready = SCM_EOL;
843 int max_fd;
844
845 if (scm_is_simple_vector (reads))
846 {
847 read_count = SCM_SIMPLE_VECTOR_LENGTH (reads);
848 }
849 else
850 {
851 read_count = scm_ilength (reads);
852 SCM_ASSERT (read_count >= 0, reads, SCM_ARG1, FUNC_NAME);
853 }
854 if (scm_is_simple_vector (writes))
855 {
856 write_count = SCM_SIMPLE_VECTOR_LENGTH (writes);
857 }
858 else
859 {
860 write_count = scm_ilength (writes);
861 SCM_ASSERT (write_count >= 0, writes, SCM_ARG2, FUNC_NAME);
862 }
863 if (scm_is_simple_vector (excepts))
864 {
865 except_count = SCM_SIMPLE_VECTOR_LENGTH (excepts);
866 }
867 else
868 {
869 except_count = scm_ilength (excepts);
870 SCM_ASSERT (except_count >= 0, excepts, SCM_ARG3, FUNC_NAME);
871 }
872
873 FD_ZERO (&read_set);
874 FD_ZERO (&write_set);
875 FD_ZERO (&except_set);
876
877 max_fd = fill_select_type (&read_set, &read_ports_ready, reads, SCM_ARG1);
878
879 {
880 int write_max = fill_select_type (&write_set, &write_ports_ready,
881 writes, SCM_ARG2);
882 int except_max = fill_select_type (&except_set, NULL,
883 excepts, SCM_ARG3);
884
885 if (write_max > max_fd)
886 max_fd = write_max;
887 if (except_max > max_fd)
888 max_fd = except_max;
889 }
890
891 /* if there's a port with a ready buffer, don't block, just
892 check for ready file descriptors. */
893 if (!scm_is_null (read_ports_ready) || !scm_is_null (write_ports_ready))
894 {
895 timeout.tv_sec = 0;
896 timeout.tv_usec = 0;
897 time_ptr = &timeout;
898 }
899 else if (SCM_UNBNDP (secs) || scm_is_false (secs))
900 time_ptr = 0;
901 else
902 {
903 if (scm_is_unsigned_integer (secs, 0, ULONG_MAX))
904 {
905 timeout.tv_sec = scm_to_ulong (secs);
906 if (SCM_UNBNDP (usecs))
907 timeout.tv_usec = 0;
908 else
909 timeout.tv_usec = scm_to_long (usecs);
910 }
911 else
912 {
913 double fl = scm_to_double (secs);
914
915 if (!SCM_UNBNDP (usecs))
916 SCM_WRONG_TYPE_ARG (4, secs);
917 if (fl > LONG_MAX)
918 SCM_OUT_OF_RANGE (4, secs);
919 timeout.tv_sec = (long) fl;
920 timeout.tv_usec = (long) ((fl - timeout.tv_sec) * 1000000);
921 }
922 time_ptr = &timeout;
923 }
924
925 {
926 int rv = scm_std_select (max_fd + 1,
927 &read_set, &write_set, &except_set,
928 time_ptr);
929 if (rv < 0)
930 SCM_SYSERROR;
931 }
932 return scm_list_3 (retrieve_select_type (&read_set, read_ports_ready, reads),
933 retrieve_select_type (&write_set, write_ports_ready, writes),
934 retrieve_select_type (&except_set, SCM_EOL, excepts));
935 }
936 #undef FUNC_NAME
937 #endif /* HAVE_SELECT */
938
939 \f
940
941 #ifdef HAVE_FCNTL
942 SCM_DEFINE (scm_fcntl, "fcntl", 2, 1, 0,
943 (SCM object, SCM cmd, SCM value),
944 "Apply @var{cmd} to the specified file descriptor or the underlying\n"
945 "file descriptor of the specified port. @var{value} is an optional\n"
946 "integer argument.\n\n"
947 "Values for @var{cmd} are:\n\n"
948 "@table @code\n"
949 "@item F_DUPFD\n"
950 "Duplicate a file descriptor\n"
951 "@item F_GETFD\n"
952 "Get flags associated with the file descriptor.\n"
953 "@item F_SETFD\n"
954 "Set flags associated with the file descriptor to @var{value}.\n"
955 "@item F_GETFL\n"
956 "Get flags associated with the open file.\n"
957 "@item F_SETFL\n"
958 "Set flags associated with the open file to @var{value}\n"
959 "@item F_GETOWN\n"
960 "Get the process ID of a socket's owner, for @code{SIGIO} signals.\n"
961 "@item F_SETOWN\n"
962 "Set the process that owns a socket to @var{value}, for @code{SIGIO} signals.\n"
963 "@item FD_CLOEXEC\n"
964 "The value used to indicate the \"close on exec\" flag with @code{F_GETFL} or\n"
965 "@code{F_SETFL}.\n"
966 "@end table")
967 #define FUNC_NAME s_scm_fcntl
968 {
969 int rv;
970 int fdes;
971 int ivalue;
972
973 object = SCM_COERCE_OUTPORT (object);
974
975 if (SCM_OPFPORTP (object))
976 fdes = SCM_FPORT_FDES (object);
977 else
978 fdes = scm_to_int (object);
979
980 if (SCM_UNBNDP (value))
981 ivalue = 0;
982 else
983 ivalue = scm_to_int (value);
984
985 SCM_SYSCALL (rv = fcntl (fdes, scm_to_int (cmd), ivalue));
986 if (rv == -1)
987 SCM_SYSERROR;
988 return scm_from_int (rv);
989 }
990 #undef FUNC_NAME
991 #endif /* HAVE_FCNTL */
992
993 SCM_DEFINE (scm_fsync, "fsync", 1, 0, 0,
994 (SCM object),
995 "Copies any unwritten data for the specified output file\n"
996 "descriptor to disk. If @var{object} is a port, its buffer is\n"
997 "flushed before the underlying file descriptor is fsync'd.\n"
998 "The return value is unspecified.")
999 #define FUNC_NAME s_scm_fsync
1000 {
1001 int fdes;
1002
1003 object = SCM_COERCE_OUTPORT (object);
1004
1005 if (SCM_OPFPORTP (object))
1006 {
1007 scm_flush (object);
1008 fdes = SCM_FPORT_FDES (object);
1009 }
1010 else
1011 fdes = scm_to_int (object);
1012
1013 if (fsync (fdes) == -1)
1014 SCM_SYSERROR;
1015 return SCM_UNSPECIFIED;
1016 }
1017 #undef FUNC_NAME
1018
1019 #ifdef HAVE_SYMLINK
1020 SCM_DEFINE (scm_symlink, "symlink", 2, 0, 0,
1021 (SCM oldpath, SCM newpath),
1022 "Create a symbolic link named @var{oldpath} with the value\n"
1023 "(i.e., pointing to) @var{newpath}. The return value is\n"
1024 "unspecified.")
1025 #define FUNC_NAME s_scm_symlink
1026 {
1027 int val;
1028
1029 STRING2_SYSCALL (oldpath, c_oldpath,
1030 newpath, c_newpath,
1031 val = symlink (c_oldpath, c_newpath));
1032 if (val != 0)
1033 SCM_SYSERROR;
1034 return SCM_UNSPECIFIED;
1035 }
1036 #undef FUNC_NAME
1037 #endif /* HAVE_SYMLINK */
1038
1039 #ifdef HAVE_READLINK
1040 SCM_DEFINE (scm_readlink, "readlink", 1, 0, 0,
1041 (SCM path),
1042 "Return the value of the symbolic link named by @var{path} (a\n"
1043 "string), i.e., the file that the link points to.")
1044 #define FUNC_NAME s_scm_readlink
1045 {
1046 int rv;
1047 int size = 100;
1048 char *buf;
1049 SCM result;
1050 char *c_path;
1051
1052 scm_dynwind_begin (0);
1053
1054 c_path = scm_to_locale_string (path);
1055 scm_dynwind_free (c_path);
1056
1057 buf = scm_malloc (size);
1058
1059 while ((rv = readlink (c_path, buf, size)) == size)
1060 {
1061 free (buf);
1062 size *= 2;
1063 buf = scm_malloc (size);
1064 }
1065 if (rv == -1)
1066 {
1067 int save_errno = errno;
1068 free (buf);
1069 errno = save_errno;
1070 SCM_SYSERROR;
1071 }
1072 result = scm_take_locale_stringn (buf, rv);
1073
1074 scm_dynwind_end ();
1075 return result;
1076 }
1077 #undef FUNC_NAME
1078 #endif /* HAVE_READLINK */
1079
1080 SCM_DEFINE (scm_copy_file, "copy-file", 2, 0, 0,
1081 (SCM oldfile, SCM newfile),
1082 "Copy the file specified by @var{oldfile} to @var{newfile}.\n"
1083 "The return value is unspecified.")
1084 #define FUNC_NAME s_scm_copy_file
1085 {
1086 char *c_oldfile, *c_newfile;
1087 int oldfd, newfd;
1088 int n, rv;
1089 char buf[BUFSIZ];
1090 struct stat_or_stat64 oldstat;
1091
1092 scm_dynwind_begin (0);
1093
1094 c_oldfile = scm_to_locale_string (oldfile);
1095 scm_dynwind_free (c_oldfile);
1096 c_newfile = scm_to_locale_string (newfile);
1097 scm_dynwind_free (c_newfile);
1098
1099 oldfd = open_or_open64 (c_oldfile, O_RDONLY);
1100 if (oldfd == -1)
1101 SCM_SYSERROR;
1102
1103 #ifdef __MINGW32__
1104 SCM_SYSCALL (rv = fstat_Win32 (oldfd, &oldstat));
1105 #else
1106 SCM_SYSCALL (rv = fstat_or_fstat64 (oldfd, &oldstat));
1107 #endif
1108 if (rv == -1)
1109 goto err_close_oldfd;
1110
1111 /* use POSIX flags instead of 07777?. */
1112 newfd = open_or_open64 (c_newfile, O_WRONLY | O_CREAT | O_TRUNC,
1113 oldstat.st_mode & 07777);
1114 if (newfd == -1)
1115 {
1116 err_close_oldfd:
1117 close (oldfd);
1118 SCM_SYSERROR;
1119 }
1120
1121 while ((n = read (oldfd, buf, sizeof buf)) > 0)
1122 if (write (newfd, buf, n) != n)
1123 {
1124 close (oldfd);
1125 close (newfd);
1126 SCM_SYSERROR;
1127 }
1128 close (oldfd);
1129 if (close (newfd) == -1)
1130 SCM_SYSERROR;
1131
1132 scm_dynwind_end ();
1133 return SCM_UNSPECIFIED;
1134 }
1135 #undef FUNC_NAME
1136
1137 #endif /* HAVE_POSIX */
1138
1139 \f
1140 /* Essential procedures used in (system base compile). */
1141
1142 #ifdef HAVE_GETCWD
1143 SCM_DEFINE (scm_getcwd, "getcwd", 0, 0, 0,
1144 (),
1145 "Return the name of the current working directory.")
1146 #define FUNC_NAME s_scm_getcwd
1147 {
1148 char *rv;
1149 size_t size = 100;
1150 char *wd;
1151 SCM result;
1152
1153 wd = scm_malloc (size);
1154 while ((rv = getcwd (wd, size)) == 0 && errno == ERANGE)
1155 {
1156 free (wd);
1157 size *= 2;
1158 wd = scm_malloc (size);
1159 }
1160 if (rv == 0)
1161 {
1162 int save_errno = errno;
1163 free (wd);
1164 errno = save_errno;
1165 SCM_SYSERROR;
1166 }
1167 result = scm_from_locale_stringn (wd, strlen (wd));
1168 free (wd);
1169 return result;
1170 }
1171 #undef FUNC_NAME
1172 #endif /* HAVE_GETCWD */
1173
1174 #ifdef HAVE_MKDIR
1175 SCM_DEFINE (scm_mkdir, "mkdir", 1, 1, 0,
1176 (SCM path, SCM mode),
1177 "Create a new directory named by @var{path}. If @var{mode} is omitted\n"
1178 "then the permissions of the directory file are set using the current\n"
1179 "umask. Otherwise they are set to the decimal value specified with\n"
1180 "@var{mode}. The return value is unspecified.")
1181 #define FUNC_NAME s_scm_mkdir
1182 {
1183 int rv;
1184 mode_t mask;
1185
1186 if (SCM_UNBNDP (mode))
1187 {
1188 mask = umask (0);
1189 umask (mask);
1190 STRING_SYSCALL (path, c_path, rv = mkdir (c_path, 0777 ^ mask));
1191 }
1192 else
1193 {
1194 STRING_SYSCALL (path, c_path, rv = mkdir (c_path, scm_to_uint (mode)));
1195 }
1196 if (rv != 0)
1197 SCM_SYSERROR;
1198 return SCM_UNSPECIFIED;
1199 }
1200 #undef FUNC_NAME
1201 #endif /* HAVE_MKDIR */
1202
1203 #ifdef HAVE_RMDIR
1204 SCM_DEFINE (scm_rmdir, "rmdir", 1, 0, 0,
1205 (SCM path),
1206 "Remove the existing directory named by @var{path}. The directory must\n"
1207 "be empty for this to succeed. The return value is unspecified.")
1208 #define FUNC_NAME s_scm_rmdir
1209 {
1210 int val;
1211
1212 STRING_SYSCALL (path, c_path, val = rmdir (c_path));
1213 if (val != 0)
1214 SCM_SYSERROR;
1215 return SCM_UNSPECIFIED;
1216 }
1217 #undef FUNC_NAME
1218 #endif
1219
1220 #ifdef HAVE_RENAME
1221 #define my_rename rename
1222 #else
1223 static int
1224 my_rename (const char *oldname, const char *newname)
1225 {
1226 int rv;
1227
1228 SCM_SYSCALL (rv = link (oldname, newname));
1229 if (rv == 0)
1230 {
1231 SCM_SYSCALL (rv = unlink (oldname));
1232 if (rv != 0)
1233 /* unlink failed. remove new name */
1234 SCM_SYSCALL (unlink (newname));
1235 }
1236 return rv;
1237 }
1238 #endif
1239
1240 SCM_DEFINE (scm_rename, "rename-file", 2, 0, 0,
1241 (SCM oldname, SCM newname),
1242 "Renames the file specified by @var{oldname} to @var{newname}.\n"
1243 "The return value is unspecified.")
1244 #define FUNC_NAME s_scm_rename
1245 {
1246 int rv;
1247
1248 STRING2_SYSCALL (oldname, c_oldname,
1249 newname, c_newname,
1250 rv = my_rename (c_oldname, c_newname));
1251 if (rv != 0)
1252 SCM_SYSERROR;
1253 return SCM_UNSPECIFIED;
1254 }
1255 #undef FUNC_NAME
1256
1257
1258 SCM_DEFINE (scm_delete_file, "delete-file", 1, 0, 0,
1259 (SCM str),
1260 "Deletes (or \"unlinks\") the file specified by @var{str}.")
1261 #define FUNC_NAME s_scm_delete_file
1262 {
1263 int ans;
1264 STRING_SYSCALL (str, c_str, ans = unlink (c_str));
1265 if (ans != 0)
1266 SCM_SYSERROR;
1267 return SCM_UNSPECIFIED;
1268 }
1269 #undef FUNC_NAME
1270
1271 SCM_DEFINE (scm_access, "access?", 2, 0, 0,
1272 (SCM path, SCM how),
1273 "Test accessibility of a file under the real UID and GID of the\n"
1274 "calling process. The return is @code{#t} if @var{path} exists\n"
1275 "and the permissions requested by @var{how} are all allowed, or\n"
1276 "@code{#f} if not.\n"
1277 "\n"
1278 "@var{how} is an integer which is one of the following values,\n"
1279 "or a bitwise-OR (@code{logior}) of multiple values.\n"
1280 "\n"
1281 "@defvar R_OK\n"
1282 "Test for read permission.\n"
1283 "@end defvar\n"
1284 "@defvar W_OK\n"
1285 "Test for write permission.\n"
1286 "@end defvar\n"
1287 "@defvar X_OK\n"
1288 "Test for execute permission.\n"
1289 "@end defvar\n"
1290 "@defvar F_OK\n"
1291 "Test for existence of the file. This is implied by each of the\n"
1292 "other tests, so there's no need to combine it with them.\n"
1293 "@end defvar\n"
1294 "\n"
1295 "It's important to note that @code{access?} does not simply\n"
1296 "indicate what will happen on attempting to read or write a\n"
1297 "file. In normal circumstances it does, but in a set-UID or\n"
1298 "set-GID program it doesn't because @code{access?} tests the\n"
1299 "real ID, whereas an open or execute attempt uses the effective\n"
1300 "ID.\n"
1301 "\n"
1302 "A program which will never run set-UID/GID can ignore the\n"
1303 "difference between real and effective IDs, but for maximum\n"
1304 "generality, especially in library functions, it's best not to\n"
1305 "use @code{access?} to predict the result of an open or execute,\n"
1306 "instead simply attempt that and catch any exception.\n"
1307 "\n"
1308 "The main use for @code{access?} is to let a set-UID/GID program\n"
1309 "determine what the invoking user would have been allowed to do,\n"
1310 "without the greater (or perhaps lesser) privileges afforded by\n"
1311 "the effective ID. For more on this, see ``Testing File\n"
1312 "Access'' in The GNU C Library Reference Manual.")
1313 #define FUNC_NAME s_scm_access
1314 {
1315 int rv;
1316 char *c_path;
1317
1318 c_path = scm_to_locale_string (path);
1319 rv = access (c_path, scm_to_int (how));
1320 free (c_path);
1321
1322 return scm_from_bool (!rv);
1323 }
1324 #undef FUNC_NAME
1325
1326 SCM_DEFINE (scm_chmod, "chmod", 2, 0, 0,
1327 (SCM object, SCM mode),
1328 "Changes the permissions of the file referred to by\n"
1329 "@var{object}. @var{object} can be a string containing a file\n"
1330 "name or a port or integer file descriptor which is open on a\n"
1331 "file (in which case @code{fchmod} is used as the underlying\n"
1332 "system call). @var{mode} specifies the new permissions as a\n"
1333 "decimal number, e.g., @code{(chmod \"foo\" #o755)}.\n"
1334 "The return value is unspecified.")
1335 #define FUNC_NAME s_scm_chmod
1336 {
1337 int rv;
1338 int fdes;
1339
1340 object = SCM_COERCE_OUTPORT (object);
1341
1342 if (scm_is_integer (object) || SCM_OPFPORTP (object))
1343 {
1344 if (scm_is_integer (object))
1345 fdes = scm_to_int (object);
1346 else
1347 fdes = SCM_FPORT_FDES (object);
1348 SCM_SYSCALL (rv = fchmod (fdes, scm_to_int (mode)));
1349 }
1350 else
1351 {
1352 STRING_SYSCALL (object, c_object,
1353 rv = chmod (c_object, scm_to_int (mode)));
1354 }
1355 if (rv == -1)
1356 SCM_SYSERROR;
1357 return SCM_UNSPECIFIED;
1358 }
1359 #undef FUNC_NAME
1360
1361 SCM_DEFINE (scm_umask, "umask", 0, 1, 0,
1362 (SCM mode),
1363 "If @var{mode} is omitted, returns a decimal number representing the current\n"
1364 "file creation mask. Otherwise the file creation mask is set to\n"
1365 "@var{mode} and the previous value is returned.\n\n"
1366 "E.g., @code{(umask #o022)} sets the mask to octal 22, decimal 18.")
1367 #define FUNC_NAME s_scm_umask
1368 {
1369 mode_t mask;
1370 if (SCM_UNBNDP (mode))
1371 {
1372 mask = umask (0);
1373 umask (mask);
1374 }
1375 else
1376 {
1377 mask = umask (scm_to_uint (mode));
1378 }
1379 return scm_from_uint (mask);
1380 }
1381 #undef FUNC_NAME
1382
1383 #ifndef HAVE_MKSTEMP
1384 extern int mkstemp (char *);
1385 #endif
1386
1387 SCM_DEFINE (scm_mkstemp, "mkstemp!", 1, 0, 0,
1388 (SCM tmpl),
1389 "Create a new unique file in the file system and return a new\n"
1390 "buffered port open for reading and writing to the file.\n"
1391 "\n"
1392 "@var{tmpl} is a string specifying where the file should be\n"
1393 "created: it must end with @samp{XXXXXX} and those @samp{X}s\n"
1394 "will be changed in the string to return the name of the file.\n"
1395 "(@code{port-filename} on the port also gives the name.)\n"
1396 "\n"
1397 "POSIX doesn't specify the permissions mode of the file, on GNU\n"
1398 "and most systems it's @code{#o600}. An application can use\n"
1399 "@code{chmod} to relax that if desired. For example\n"
1400 "@code{#o666} less @code{umask}, which is usual for ordinary\n"
1401 "file creation,\n"
1402 "\n"
1403 "@example\n"
1404 "(let ((port (mkstemp! (string-copy \"/tmp/myfile-XXXXXX\"))))\n"
1405 " (chmod port (logand #o666 (lognot (umask))))\n"
1406 " ...)\n"
1407 "@end example")
1408 #define FUNC_NAME s_scm_mkstemp
1409 {
1410 char *c_tmpl;
1411 int rv;
1412
1413 scm_dynwind_begin (0);
1414
1415 c_tmpl = scm_to_locale_string (tmpl);
1416 scm_dynwind_free (c_tmpl);
1417
1418 SCM_SYSCALL (rv = mkstemp (c_tmpl));
1419 if (rv == -1)
1420 SCM_SYSERROR;
1421
1422 scm_substring_move_x (scm_from_locale_string (c_tmpl),
1423 SCM_INUM0, scm_string_length (tmpl),
1424 tmpl, SCM_INUM0);
1425
1426 scm_dynwind_end ();
1427 return scm_fdes_to_port (rv, "w+", tmpl);
1428 }
1429 #undef FUNC_NAME
1430
1431 \f
1432 /* Filename manipulation */
1433
1434 SCM scm_dot_string;
1435
1436 SCM_DEFINE (scm_dirname, "dirname", 1, 0, 0,
1437 (SCM filename),
1438 "Return the directory name component of the file name\n"
1439 "@var{filename}. If @var{filename} does not contain a directory\n"
1440 "component, @code{.} is returned.")
1441 #define FUNC_NAME s_scm_dirname
1442 {
1443 long int i;
1444 unsigned long int len;
1445
1446 SCM_VALIDATE_STRING (1, filename);
1447
1448 len = scm_i_string_length (filename);
1449
1450 i = len - 1;
1451 #ifdef __MINGW32__
1452 while (i >= 0 && (scm_i_string_ref (filename, i) == '/'
1453 || scm_i_string_ref (filename, i) == '\\'))
1454 --i;
1455 while (i >= 0 && (scm_i_string_ref (filename, i) != '/'
1456 && scm_i_string_ref (filename, i) != '\\'))
1457 --i;
1458 while (i >= 0 && (scm_i_string_ref (filename, i) == '/'
1459 || scm_i_string_ref (filename, i) == '\\'))
1460 --i;
1461 #else
1462 while (i >= 0 && scm_i_string_ref (filename, i) == '/')
1463 --i;
1464 while (i >= 0 && scm_i_string_ref (filename, i) != '/')
1465 --i;
1466 while (i >= 0 && scm_i_string_ref (filename, i) == '/')
1467 --i;
1468 #endif /* ndef __MINGW32__ */
1469 if (i < 0)
1470 {
1471 #ifdef __MINGW32__
1472 if (len > 0 && (scm_i_string_ref (filename, 0) == '/'
1473 || scm_i_string_ref (filename, 0) == '\\'))
1474 #else
1475 if (len > 0 && scm_i_string_ref (filename, 0) == '/')
1476 #endif /* ndef __MINGW32__ */
1477 return scm_c_substring (filename, 0, 1);
1478 else
1479 return scm_dot_string;
1480 }
1481 else
1482 return scm_c_substring (filename, 0, i + 1);
1483 }
1484 #undef FUNC_NAME
1485
1486 SCM_DEFINE (scm_basename, "basename", 1, 1, 0,
1487 (SCM filename, SCM suffix),
1488 "Return the base name of the file name @var{filename}. The\n"
1489 "base name is the file name without any directory components.\n"
1490 "If @var{suffix} is provided, and is equal to the end of\n"
1491 "@var{filename}, it is removed also.")
1492 #define FUNC_NAME s_scm_basename
1493 {
1494 int i, j, len, end;
1495
1496 SCM_VALIDATE_STRING (1, filename);
1497 len = scm_i_string_length (filename);
1498
1499 if (SCM_UNBNDP (suffix))
1500 j = -1;
1501 else
1502 {
1503 SCM_VALIDATE_STRING (2, suffix);
1504 j = scm_i_string_length (suffix) - 1;
1505 }
1506 i = len - 1;
1507 #ifdef __MINGW32__
1508 while (i >= 0 && (scm_i_string_ref (filename, i) == '/'
1509 || scm_i_string_ref (filename, i) == '\\'))
1510 --i;
1511 #else
1512 while (i >= 0 && scm_i_string_ref (filename, i) == '/')
1513 --i;
1514 #endif /* ndef __MINGW32__ */
1515 end = i;
1516 while (i >= 0 && j >= 0
1517 && (scm_i_string_ref (filename, i)
1518 == scm_i_string_ref (suffix, j)))
1519 {
1520 --i;
1521 --j;
1522 }
1523 if (j == -1)
1524 end = i;
1525 #ifdef __MINGW32__
1526 while (i >= 0 && (scm_i_string_ref (filename, i) != '/'
1527 && scm_i_string_ref (filename, i) != '\\'))
1528 --i;
1529 #else
1530 while (i >= 0 && scm_i_string_ref (filename, i) != '/')
1531 --i;
1532 #endif /* ndef __MINGW32__ */
1533 if (i == end)
1534 {
1535 #ifdef __MINGW32__
1536 if (len > 0 && (scm_i_string_ref (filename, 0) == '/'
1537 || scm_i_string_ref (filename, 0) == '\\'))
1538 #else
1539 if (len > 0 && scm_i_string_ref (filename, 0) == '/')
1540 #endif /* ndef __MINGW32__ */
1541 return scm_c_substring (filename, 0, 1);
1542 else
1543 return scm_dot_string;
1544 }
1545 else
1546 return scm_c_substring (filename, i+1, end+1);
1547 }
1548 #undef FUNC_NAME
1549
1550 SCM_DEFINE (scm_canonicalize_path, "canonicalize-path", 1, 0, 0,
1551 (SCM path),
1552 "Return the canonical path of @var{path}. A canonical path has\n"
1553 "no @code{.} or @code{..} components, nor any repeated path\n"
1554 "separators (@code{/}) nor symlinks.\n\n"
1555 "Raises an error if any component of @var{path} does not exist.")
1556 #define FUNC_NAME s_scm_canonicalize_path
1557 {
1558 char *str, *canon;
1559
1560 SCM_VALIDATE_STRING (1, path);
1561
1562 str = scm_to_locale_string (path);
1563 canon = canonicalize_file_name (str);
1564 free (str);
1565
1566 if (canon)
1567 return scm_take_locale_string (canon);
1568 else
1569 SCM_SYSERROR;
1570 }
1571 #undef FUNC_NAME
1572
1573 SCM
1574 scm_i_relativize_path (SCM path, SCM in_path)
1575 {
1576 char *str, *canon;
1577 SCM scanon;
1578
1579 str = scm_to_locale_string (path);
1580 canon = canonicalize_file_name (str);
1581 free (str);
1582
1583 if (!canon)
1584 return SCM_BOOL_F;
1585
1586 scanon = scm_take_locale_string (canon);
1587
1588 for (; scm_is_pair (in_path); in_path = scm_cdr (in_path))
1589 {
1590 SCM dir = scm_car (in_path);
1591 size_t len = scm_c_string_length (dir);
1592
1593 /* When DIR is empty, it means "current working directory". We
1594 could set DIR to (getcwd) in that case, but then the
1595 canonicalization would depend on the current directory, which
1596 is not what we want in the context of `compile-file', for
1597 instance. */
1598 if (len > 0
1599 && scm_is_true (scm_string_prefix_p (dir, scanon,
1600 SCM_UNDEFINED, SCM_UNDEFINED,
1601 SCM_UNDEFINED, SCM_UNDEFINED)))
1602 {
1603 /* DIR either has a trailing delimiter or doesn't. SCANON
1604 will be delimited by single delimiters. When DIR does not
1605 have a trailing delimiter, add one to the length to strip
1606 off the delimiter within SCANON. */
1607 if (
1608 #ifdef __MINGW32__
1609 (scm_i_string_ref (dir, len - 1) != '/'
1610 && scm_i_string_ref (dir, len - 1) != '\\')
1611 #else
1612 scm_i_string_ref (dir, len - 1) != '/'
1613 #endif
1614 )
1615 len++;
1616
1617 if (scm_c_string_length (scanon) > len)
1618 return scm_substring (scanon, scm_from_size_t (len), SCM_UNDEFINED);
1619 else
1620 return SCM_BOOL_F;
1621 }
1622 }
1623
1624 return SCM_BOOL_F;
1625 }
1626
1627 \f
1628 /* Examining directories. These procedures are used by `check-guile'
1629 and thus compiled unconditionally. */
1630
1631 scm_t_bits scm_tc16_dir;
1632
1633
1634 SCM_DEFINE (scm_directory_stream_p, "directory-stream?", 1, 0, 0,
1635 (SCM obj),
1636 "Return a boolean indicating whether @var{obj} is a directory\n"
1637 "stream as returned by @code{opendir}.")
1638 #define FUNC_NAME s_scm_directory_stream_p
1639 {
1640 return scm_from_bool (SCM_DIRP (obj));
1641 }
1642 #undef FUNC_NAME
1643
1644
1645 SCM_DEFINE (scm_opendir, "opendir", 1, 0, 0,
1646 (SCM dirname),
1647 "Open the directory specified by @var{dirname} and return a directory\n"
1648 "stream.")
1649 #define FUNC_NAME s_scm_opendir
1650 {
1651 DIR *ds;
1652 STRING_SYSCALL (dirname, c_dirname, ds = opendir (c_dirname));
1653 if (ds == NULL)
1654 SCM_SYSERROR;
1655 SCM_RETURN_NEWSMOB (scm_tc16_dir | (SCM_DIR_FLAG_OPEN<<16), ds);
1656 }
1657 #undef FUNC_NAME
1658
1659
1660 /* FIXME: The glibc manual has a portability note that readdir_r may not
1661 null-terminate its return string. The circumstances outlined for this
1662 are not clear, nor is it clear what should be done about it. Lets use
1663 NAMLEN and worry about what else should be done if/when someone can
1664 figure it out. */
1665
1666 SCM_DEFINE (scm_readdir, "readdir", 1, 0, 0,
1667 (SCM port),
1668 "Return (as a string) the next directory entry from the directory stream\n"
1669 "@var{port}. If there is no remaining entry to be read then the\n"
1670 "end of file object is returned.")
1671 #define FUNC_NAME s_scm_readdir
1672 {
1673 struct dirent_or_dirent64 *rdent;
1674
1675 SCM_VALIDATE_DIR (1, port);
1676 if (!SCM_DIR_OPEN_P (port))
1677 SCM_MISC_ERROR ("Directory ~S is not open.", scm_list_1 (port));
1678
1679 #if HAVE_READDIR_R
1680 /* As noted in the glibc manual, on various systems (such as Solaris) the
1681 d_name[] field is only 1 char and you're expected to size the dirent
1682 buffer for readdir_r based on NAME_MAX. The SCM_MAX expressions below
1683 effectively give either sizeof(d_name) or NAME_MAX+1, whichever is
1684 bigger.
1685
1686 On solaris 10 there's no NAME_MAX constant, it's necessary to use
1687 pathconf(). We prefer NAME_MAX though, since it should be a constant
1688 and will therefore save a system call. We also prefer it since dirfd()
1689 is not available everywhere.
1690
1691 An alternative to dirfd() would be to open() the directory and then use
1692 fdopendir(), if the latter is available. That'd let us hold the fd
1693 somewhere in the smob, or just the dirent size calculated once. */
1694 {
1695 struct dirent_or_dirent64 de; /* just for sizeof */
1696 DIR *ds = (DIR *) SCM_SMOB_DATA_1 (port);
1697 #ifdef NAME_MAX
1698 char buf [SCM_MAX (sizeof (de),
1699 sizeof (de) - sizeof (de.d_name) + NAME_MAX + 1)];
1700 #else
1701 char *buf;
1702 long name_max = fpathconf (dirfd (ds), _PC_NAME_MAX);
1703 if (name_max == -1)
1704 SCM_SYSERROR;
1705 buf = alloca (SCM_MAX (sizeof (de),
1706 sizeof (de) - sizeof (de.d_name) + name_max + 1));
1707 #endif
1708
1709 errno = 0;
1710 SCM_SYSCALL (readdir_r_or_readdir64_r (ds, (struct dirent_or_dirent64 *) buf, &rdent));
1711 if (errno != 0)
1712 SCM_SYSERROR;
1713 if (! rdent)
1714 return SCM_EOF_VAL;
1715
1716 return (rdent ? scm_from_locale_stringn (rdent->d_name, NAMLEN (rdent))
1717 : SCM_EOF_VAL);
1718 }
1719 #else
1720 {
1721 SCM ret;
1722 scm_dynwind_begin (0);
1723 scm_i_dynwind_pthread_mutex_lock (&scm_i_misc_mutex);
1724
1725 errno = 0;
1726 SCM_SYSCALL (rdent = readdir_or_readdir64 ((DIR *) SCM_SMOB_DATA_1 (port)));
1727 if (errno != 0)
1728 SCM_SYSERROR;
1729
1730 ret = (rdent ? scm_from_locale_stringn (rdent->d_name, NAMLEN (rdent))
1731 : SCM_EOF_VAL);
1732
1733 scm_dynwind_end ();
1734 return ret;
1735 }
1736 #endif
1737 }
1738 #undef FUNC_NAME
1739
1740
1741 SCM_DEFINE (scm_rewinddir, "rewinddir", 1, 0, 0,
1742 (SCM port),
1743 "Reset the directory port @var{port} so that the next call to\n"
1744 "@code{readdir} will return the first directory entry.")
1745 #define FUNC_NAME s_scm_rewinddir
1746 {
1747 SCM_VALIDATE_DIR (1, port);
1748 if (!SCM_DIR_OPEN_P (port))
1749 SCM_MISC_ERROR ("Directory ~S is not open.", scm_list_1 (port));
1750
1751 rewinddir ((DIR *) SCM_SMOB_DATA_1 (port));
1752
1753 return SCM_UNSPECIFIED;
1754 }
1755 #undef FUNC_NAME
1756
1757
1758 SCM_DEFINE (scm_closedir, "closedir", 1, 0, 0,
1759 (SCM port),
1760 "Close the directory stream @var{port}.\n"
1761 "The return value is unspecified.")
1762 #define FUNC_NAME s_scm_closedir
1763 {
1764 SCM_VALIDATE_DIR (1, port);
1765
1766 if (SCM_DIR_OPEN_P (port))
1767 {
1768 int sts;
1769
1770 SCM_SYSCALL (sts = closedir ((DIR *) SCM_SMOB_DATA_1 (port)));
1771 if (sts != 0)
1772 SCM_SYSERROR;
1773
1774 SCM_SET_SMOB_DATA_0 (port, scm_tc16_dir);
1775 }
1776
1777 return SCM_UNSPECIFIED;
1778 }
1779 #undef FUNC_NAME
1780
1781
1782 #ifdef HAVE_POSIX
1783 static int
1784 scm_dir_print (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
1785 {
1786 scm_puts ("#<", port);
1787 if (!SCM_DIR_OPEN_P (exp))
1788 scm_puts ("closed: ", port);
1789 scm_puts ("directory stream ", port);
1790 scm_uintprint (SCM_SMOB_DATA_1 (exp), 16, port);
1791 scm_putc ('>', port);
1792 return 1;
1793 }
1794
1795
1796 static size_t
1797 scm_dir_free (SCM p)
1798 {
1799 if (SCM_DIR_OPEN_P (p))
1800 closedir ((DIR *) SCM_SMOB_DATA_1 (p));
1801 return 0;
1802 }
1803 #endif
1804
1805 \f
1806
1807 void
1808 scm_init_filesys ()
1809 {
1810 #ifdef HAVE_POSIX
1811 scm_tc16_dir = scm_make_smob_type ("directory", 0);
1812 scm_set_smob_free (scm_tc16_dir, scm_dir_free);
1813 scm_set_smob_print (scm_tc16_dir, scm_dir_print);
1814
1815 #ifdef O_RDONLY
1816 scm_c_define ("O_RDONLY", scm_from_int (O_RDONLY));
1817 #endif
1818 #ifdef O_WRONLY
1819 scm_c_define ("O_WRONLY", scm_from_int (O_WRONLY));
1820 #endif
1821 #ifdef O_RDWR
1822 scm_c_define ("O_RDWR", scm_from_int (O_RDWR));
1823 #endif
1824 #ifdef O_CREAT
1825 scm_c_define ("O_CREAT", scm_from_int (O_CREAT));
1826 #endif
1827 #ifdef O_EXCL
1828 scm_c_define ("O_EXCL", scm_from_int (O_EXCL));
1829 #endif
1830 #ifdef O_NOCTTY
1831 scm_c_define ("O_NOCTTY", scm_from_int (O_NOCTTY));
1832 #endif
1833 #ifdef O_TRUNC
1834 scm_c_define ("O_TRUNC", scm_from_int (O_TRUNC));
1835 #endif
1836 #ifdef O_APPEND
1837 scm_c_define ("O_APPEND", scm_from_int (O_APPEND));
1838 #endif
1839 #ifdef O_NONBLOCK
1840 scm_c_define ("O_NONBLOCK", scm_from_int (O_NONBLOCK));
1841 #endif
1842 #ifdef O_NDELAY
1843 scm_c_define ("O_NDELAY", scm_from_int (O_NDELAY));
1844 #endif
1845 #ifdef O_SYNC
1846 scm_c_define ("O_SYNC", scm_from_int (O_SYNC));
1847 #endif
1848 #ifdef O_LARGEFILE
1849 scm_c_define ("O_LARGEFILE", scm_from_int (O_LARGEFILE));
1850 #endif
1851 #ifdef O_NOTRANS
1852 scm_c_define ("O_NOTRANS", scm_from_int (O_NOTRANS));
1853 #endif
1854
1855 #ifdef F_DUPFD
1856 scm_c_define ("F_DUPFD", scm_from_int (F_DUPFD));
1857 #endif
1858 #ifdef F_GETFD
1859 scm_c_define ("F_GETFD", scm_from_int (F_GETFD));
1860 #endif
1861 #ifdef F_SETFD
1862 scm_c_define ("F_SETFD", scm_from_int (F_SETFD));
1863 #endif
1864 #ifdef F_GETFL
1865 scm_c_define ("F_GETFL", scm_from_int (F_GETFL));
1866 #endif
1867 #ifdef F_SETFL
1868 scm_c_define ("F_SETFL", scm_from_int (F_SETFL));
1869 #endif
1870 #ifdef F_GETOWN
1871 scm_c_define ("F_GETOWN", scm_from_int (F_GETOWN));
1872 #endif
1873 #ifdef F_SETOWN
1874 scm_c_define ("F_SETOWN", scm_from_int (F_SETOWN));
1875 #endif
1876 #ifdef FD_CLOEXEC
1877 scm_c_define ("FD_CLOEXEC", scm_from_int (FD_CLOEXEC));
1878 #endif
1879 #endif /* HAVE_POSIX */
1880
1881 /* `access' symbols. */
1882 scm_c_define ("R_OK", scm_from_int (R_OK));
1883 scm_c_define ("W_OK", scm_from_int (W_OK));
1884 scm_c_define ("X_OK", scm_from_int (X_OK));
1885 scm_c_define ("F_OK", scm_from_int (F_OK));
1886
1887 scm_dot_string = scm_from_locale_string (".");
1888
1889 #include "libguile/filesys.x"
1890 }
1891
1892 /*
1893 Local Variables:
1894 c-file-style: "gnu"
1895 End:
1896 */