Debian Codegraph @

pTk/mTk/tclUnix/tclUnixFCmd.c

raw symbols SCIP
1 /*
2 * tclUnixFCmd.c
3 *
4 * This file implements the unix specific portion of file manipulation
5 * subcommands of the "file" command. All filename arguments should
6 * already be translated to native format.
7 *
8 * Copyright (c) 1996-1998 Sun Microsystems, Inc.
9 *
10 * See the file "license.terms" for information on usage and redistribution
11 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
12 *
13 * RCS: @(#) $Id: tclUnixFCmd.c,v 1.28.2.2 2003/10/03 17:45:37 vincentdarley Exp $
14 *
15 * Portions of this code were derived from NetBSD source code which has
16 * the following copyright notice:
17 *
18 * Copyright (c) 1988, 1993, 1994
19 * The Regents of the University of California. All rights reserved.
20 *
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
23 * are met:
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
29 * 3. All advertising materials mentioning features or use of this software
30 * must display the following acknowledgement:
31 * This product includes software developed by the University of
32 * California, Berkeley and its contributors.
33 * 4. Neither the name of the University nor the names of its contributors
34 * may be used to endorse or promote products derived from this software
35 * without specific prior written permission.
36 *
37 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
38 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
39 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
40 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
41 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
42 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
43 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
45 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
46 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * SUCH DAMAGE.
48 */
49
50 #include "tclInt.h"
51 #include "tclPort.h"
52 #include <utime.h>
53 #include <grp.h>
54 #ifndef HAVE_ST_BLKSIZE
55 #ifndef NO_FSTATFS
56 #include <sys/statfs.h>
57 #endif
58 #endif
59
60 /*
61 * The following constants specify the type of callback when
62 * TraverseUnixTree() calls the traverseProc()
63 */
64
65 #define DOTREE_PRED 1 /* pre-order directory */
66 #define DOTREE_POSTD 2 /* post-order directory */
67 #define DOTREE_F 3 /* regular file */
68
69 /*
70 * Callbacks for file attributes code.
71 */
72
73 static int GetGroupAttribute _ANSI_ARGS_((Tcl_Interp *interp,
74 int objIndex, Tcl_Obj *fileName,
75 Tcl_Obj **attributePtrPtr));
76 static int GetOwnerAttribute _ANSI_ARGS_((Tcl_Interp *interp,
77 int objIndex, Tcl_Obj *fileName,
78 Tcl_Obj **attributePtrPtr));
79 static int GetPermissionsAttribute _ANSI_ARGS_((
80 Tcl_Interp *interp, int objIndex,
81 Tcl_Obj *fileName, Tcl_Obj **attributePtrPtr));
82 static int SetGroupAttribute _ANSI_ARGS_((Tcl_Interp *interp,
83 int objIndex, Tcl_Obj *fileName,
84 Tcl_Obj *attributePtr));
85 static int SetOwnerAttribute _ANSI_ARGS_((Tcl_Interp *interp,
86 int objIndex, Tcl_Obj *fileName,
87 Tcl_Obj *attributePtr));
88 static int SetPermissionsAttribute _ANSI_ARGS_((
89 Tcl_Interp *interp, int objIndex,
90 Tcl_Obj *fileName, Tcl_Obj *attributePtr));
91 static int GetModeFromPermString _ANSI_ARGS_((
92 Tcl_Interp *interp, char *modeStringPtr,
93 mode_t *modePtr));
94
95 /*
96 * Prototype for the TraverseUnixTree callback function.
97 */
98
99 typedef int (TraversalProc) _ANSI_ARGS_((Tcl_DString *srcPtr,
100 Tcl_DString *dstPtr, CONST Tcl_StatBuf *statBufPtr, int type,
101 Tcl_DString *errorPtr));
102
103 /*
104 * Constants and variables necessary for file attributes subcommand.
105 */
106
107 enum {
108 UNIX_GROUP_ATTRIBUTE,
109 UNIX_OWNER_ATTRIBUTE,
110 UNIX_PERMISSIONS_ATTRIBUTE
111 };
112
113 CONST char *tclpFileAttrStrings[] = {
114 "-group",
115 "-owner",
116 "-permissions",
117 (char *) NULL
118 };
119
120 CONST TclFileAttrProcs tclpFileAttrProcs[] = {
121 {GetGroupAttribute, SetGroupAttribute},
122 {GetOwnerAttribute, SetOwnerAttribute},
123 {GetPermissionsAttribute, SetPermissionsAttribute}
124 };
125
126 /*
127 * Declarations for local procedures defined in this file:
128 */
129
130 static int CopyFile _ANSI_ARGS_((CONST char *src,
131 CONST char *dst, CONST Tcl_StatBuf *statBufPtr));
132 static int CopyFileAtts _ANSI_ARGS_((CONST char *src,
133 CONST char *dst, CONST Tcl_StatBuf *statBufPtr));
134 static int DoCopyFile _ANSI_ARGS_((CONST char *srcPtr,
135 CONST char *dstPtr));
136 static int DoCreateDirectory _ANSI_ARGS_((CONST char *pathPtr));
137 static int DoRemoveDirectory _ANSI_ARGS_((Tcl_DString *pathPtr,
138 int recursive, Tcl_DString *errorPtr));
139 static int DoRenameFile _ANSI_ARGS_((CONST char *src,
140 CONST char *dst));
141 static int TraversalCopy _ANSI_ARGS_((Tcl_DString *srcPtr,
142 Tcl_DString *dstPtr, CONST Tcl_StatBuf *statBufPtr,
143 int type, Tcl_DString *errorPtr));
144 static int TraversalDelete _ANSI_ARGS_((Tcl_DString *srcPtr,
145 Tcl_DString *dstPtr, CONST Tcl_StatBuf *statBufPtr,
146 int type, Tcl_DString *errorPtr));
147 static int TraverseUnixTree _ANSI_ARGS_((
148 TraversalProc *traversalProc,
149 Tcl_DString *sourcePtr, Tcl_DString *destPtr,
150 Tcl_DString *errorPtr));
151
152 #ifdef PURIFY
153 /*
154 * realpath and purify don't mix happily. It has been noted that realpath
155 * should not be used with purify because of bogus warnings, but just
156 * memset'ing the resolved path will squelch those. This assumes we are
157 * passing the standard MAXPATHLEN size resolved arg.
158 */
159 static char * Realpath _ANSI_ARGS_((CONST char *path,
160 char *resolved));
161
162 char *
163 Realpath(path, resolved)
164 CONST char *path;
165 char *resolved;
166 {
167 memset(resolved, 0, MAXPATHLEN);
168 return realpath(path, resolved);
169 }
170 #else
171 #define Realpath realpath
172 #endif
173
174
175 /*
176 *---------------------------------------------------------------------------
177 *
178 * TclpObjRenameFile, DoRenameFile --
179 *
180 * Changes the name of an existing file or directory, from src to dst.
181 * If src and dst refer to the same file or directory, does nothing
182 * and returns success. Otherwise if dst already exists, it will be
183 * deleted and replaced by src subject to the following conditions:
184 * If src is a directory, dst may be an empty directory.
185 * If src is a file, dst may be a file.
186 * In any other situation where dst already exists, the rename will
187 * fail.
188 *
189 * Results:
190 * If the directory was successfully created, returns TCL_OK.
191 * Otherwise the return value is TCL_ERROR and errno is set to
192 * indicate the error. Some possible values for errno are:
193 *
194 * EACCES: src or dst parent directory can't be read and/or written.
195 * EEXIST: dst is a non-empty directory.
196 * EINVAL: src is a root directory or dst is a subdirectory of src.
197 * EISDIR: dst is a directory, but src is not.
198 * ENOENT: src doesn't exist, or src or dst is "".
199 * ENOTDIR: src is a directory, but dst is not.
200 * EXDEV: src and dst are on different filesystems.
201 *
202 * Side effects:
203 * The implementation of rename may allow cross-filesystem renames,
204 * but the caller should be prepared to emulate it with copy and
205 * delete if errno is EXDEV.
206 *
207 *---------------------------------------------------------------------------
208 */
209
210 int
211 TclpObjRenameFile(srcPathPtr, destPathPtr)
212 Tcl_Obj *srcPathPtr;
213 Tcl_Obj *destPathPtr;
214 {
215 return DoRenameFile(Tcl_FSGetNativePath(srcPathPtr),
216 Tcl_FSGetNativePath(destPathPtr));
217 }
218
219 static int
220 DoRenameFile(src, dst)
221 CONST char *src; /* Pathname of file or dir to be renamed
222 * (native). */
223 CONST char *dst; /* New pathname of file or directory
224 * (native). */
225 {
226 if (rename(src, dst) == 0) { /* INTL: Native. */
227 return TCL_OK;
228 }
229 if (errno == ENOTEMPTY) {
230 errno = EEXIST;
231 }
232
233 /*
234 * IRIX returns EIO when you attept to move a directory into
235 * itself. We just map EIO to EINVAL get the right message on SGI.
236 * Most platforms don't return EIO except in really strange cases.
237 */
238
239 if (errno == EIO) {
240 errno = EINVAL;
241 }
242
243 #ifndef NO_REALPATH
244 /*
245 * SunOS 4.1.4 reports overwriting a non-empty directory with a
246 * directory as EINVAL instead of EEXIST (first rule out the correct
247 * EINVAL result code for moving a directory into itself). Must be
248 * conditionally compiled because realpath() not defined on all systems.
249 */
250
251 if (errno == EINVAL) {
252 char srcPath[MAXPATHLEN], dstPath[MAXPATHLEN];
253 DIR *dirPtr;
254 Tcl_DirEntry *dirEntPtr;
255
256 if ((Realpath((char *) src, srcPath) != NULL) /* INTL: Native. */
257 && (Realpath((char *) dst, dstPath) != NULL) /* INTL: Native. */
258 && (strncmp(srcPath, dstPath, strlen(srcPath)) != 0)) {
259 dirPtr = opendir(dst); /* INTL: Native. */
260 if (dirPtr != NULL) {
261 while (1) {
262 dirEntPtr = TclOSreaddir(dirPtr); /* INTL: Native. */
263 if (dirEntPtr == NULL) {
264 break;
265 }
266 if ((strcmp(dirEntPtr->d_name, ".") != 0) &&
267 (strcmp(dirEntPtr->d_name, "..") != 0)) {
268 errno = EEXIST;
269 closedir(dirPtr);
270 return TCL_ERROR;
271 }
272 }
273 closedir(dirPtr);
274 }
275 }
276 errno = EINVAL;
277 }
278 #endif /* !NO_REALPATH */
279
280 if (strcmp(src, "/") == 0) {
281 /*
282 * Alpha reports renaming / as EBUSY and Linux reports it as EACCES,
283 * instead of EINVAL.
284 */
285
286 errno = EINVAL;
287 }
288
289 /*
290 * DEC Alpha OSF1 V3.0 returns EACCES when attempting to move a
291 * file across filesystems and the parent directory of that file is
292 * not writable. Most other systems return EXDEV. Does nothing to
293 * correct this behavior.
294 */
295
296 return TCL_ERROR;
297 }
298
299 /*
300 *---------------------------------------------------------------------------
301 *
302 * TclpObjCopyFile, DoCopyFile --
303 *
304 * Copy a single file (not a directory). If dst already exists and
305 * is not a directory, it is removed.
306 *
307 * Results:
308 * If the file was successfully copied, returns TCL_OK. Otherwise
309 * the return value is TCL_ERROR and errno is set to indicate the
310 * error. Some possible values for errno are:
311 *
312 * EACCES: src or dst parent directory can't be read and/or written.
313 * EISDIR: src or dst is a directory.
314 * ENOENT: src doesn't exist. src or dst is "".
315 *
316 * Side effects:
317 * This procedure will also copy symbolic links, block, and
318 * character devices, and fifos. For symbolic links, the links
319 * themselves will be copied and not what they point to. For the
320 * other special file types, the directory entry will be copied and
321 * not the contents of the device that it refers to.
322 *
323 *---------------------------------------------------------------------------
324 */
325
326 int
327 TclpObjCopyFile(srcPathPtr, destPathPtr)
328 Tcl_Obj *srcPathPtr;
329 Tcl_Obj *destPathPtr;
330 {
331 return DoCopyFile(Tcl_FSGetNativePath(srcPathPtr),
332 Tcl_FSGetNativePath(destPathPtr));
333 }
334
335 static int
336 DoCopyFile(src, dst)
337 CONST char *src; /* Pathname of file to be copied (native). */
338 CONST char *dst; /* Pathname of file to copy to (native). */
339 {
340 Tcl_StatBuf srcStatBuf, dstStatBuf;
341
342 /*
343 * Have to do a stat() to determine the filetype.
344 */
345
346 if (TclOSlstat(src, &srcStatBuf) != 0) { /* INTL: Native. */
347 return TCL_ERROR;
348 }
349 if (S_ISDIR(srcStatBuf.st_mode)) {
350 errno = EISDIR;
351 return TCL_ERROR;
352 }
353
354 /*
355 * symlink, and some of the other calls will fail if the target
356 * exists, so we remove it first
357 */
358
359 if (TclOSlstat(dst, &dstStatBuf) == 0) { /* INTL: Native. */
360 if (S_ISDIR(dstStatBuf.st_mode)) {
361 errno = EISDIR;
362 return TCL_ERROR;
363 }
364 }
365 if (unlink(dst) != 0) { /* INTL: Native. */
366 if (errno != ENOENT) {
367 return TCL_ERROR;
368 }
369 }
370
371 switch ((int) (srcStatBuf.st_mode & S_IFMT)) {
372 #ifndef DJGPP
373 case S_IFLNK: {
374 char link[MAXPATHLEN];
375 int length;
376
377 length = readlink(src, link, sizeof(link)); /* INTL: Native. */
378 if (length == -1) {
379 return TCL_ERROR;
380 }
381 link[length] = '\0';
382 if (symlink(link, dst) < 0) { /* INTL: Native. */
383 return TCL_ERROR;
384 }
385 break;
386 }
387 #endif
388 case S_IFBLK:
389 case S_IFCHR: {
390 if (mknod(dst, srcStatBuf.st_mode, /* INTL: Native. */
391 srcStatBuf.st_rdev) < 0) {
392 return TCL_ERROR;
393 }
394 return CopyFileAtts(src, dst, &srcStatBuf);
395 }
396 case S_IFIFO: {
397 if (mkfifo(dst, srcStatBuf.st_mode) < 0) { /* INTL: Native. */
398 return TCL_ERROR;
399 }
400 return CopyFileAtts(src, dst, &srcStatBuf);
401 }
402 default: {
403 return CopyFile(src, dst, &srcStatBuf);
404 }
405 }
406 return TCL_OK;
407 }
408
409 /*
410 *----------------------------------------------------------------------
411 *
412 * CopyFile -
413 *
414 * Helper function for TclpCopyFile. Copies one regular file,
415 * using read() and write().
416 *
417 * Results:
418 * A standard Tcl result.
419 *
420 * Side effects:
421 * A file is copied. Dst will be overwritten if it exists.
422 *
423 *----------------------------------------------------------------------
424 */
425
426 static int
427 CopyFile(src, dst, statBufPtr)
428 CONST char *src; /* Pathname of file to copy (native). */
429 CONST char *dst; /* Pathname of file to create/overwrite
430 * (native). */
431 CONST Tcl_StatBuf *statBufPtr;
432 /* Used to determine mode and blocksize. */
433 {
434 int srcFd;
435 int dstFd;
436 u_int blockSize; /* Optimal I/O blocksize for filesystem */
437 char *buffer; /* Data buffer for copy */
438 size_t nread;
439
440 if ((srcFd = TclOSopen(src, O_RDONLY, 0)) < 0) { /* INTL: Native. */
441 return TCL_ERROR;
442 }
443
444 dstFd = TclOSopen(dst, O_CREAT|O_TRUNC|O_WRONLY, /* INTL: Native. */
445 statBufPtr->st_mode);
446 if (dstFd < 0) {
447 close(srcFd);
448 return TCL_ERROR;
449 }
450
451 #ifdef HAVE_ST_BLKSIZE
452 blockSize = statBufPtr->st_blksize;
453 #else
454 #ifndef NO_FSTATFS
455 {
456 struct statfs fs;
457 if (fstatfs(srcFd, &fs, sizeof(fs), 0) == 0) {
458 blockSize = fs.f_bsize;
459 } else {
460 blockSize = 4096;
461 }
462 }
463 #else
464 blockSize = 4096;
465 #endif
466 #endif
467
468 buffer = ckalloc(blockSize);
469 while (1) {
470 nread = read(srcFd, buffer, blockSize);
471 if ((nread == -1) || (nread == 0)) {
472 break;
473 }
474 if (write(dstFd, buffer, nread) != nread) {
475 nread = (size_t) -1;
476 break;
477 }
478 }
479
480 ckfree(buffer);
481 close(srcFd);
482 if ((close(dstFd) != 0) || (nread == -1)) {
483 unlink(dst); /* INTL: Native. */
484 return TCL_ERROR;
485 }
486 if (CopyFileAtts(src, dst, statBufPtr) == TCL_ERROR) {
487 /*
488 * The copy succeeded, but setting the permissions failed, so be in
489 * a consistent state, we remove the file that was created by the
490 * copy.
491 */
492
493 unlink(dst); /* INTL: Native. */
494 return TCL_ERROR;
495 }
496 return TCL_OK;
497 }
498
499 /*
500 *---------------------------------------------------------------------------
501 *
502 * TclpObjDeleteFile, TclpDeleteFile --
503 *
504 * Removes a single file (not a directory).
505 *
506 * Results:
507 * If the file was successfully deleted, returns TCL_OK. Otherwise
508 * the return value is TCL_ERROR and errno is set to indicate the
509 * error. Some possible values for errno are:
510 *
511 * EACCES: a parent directory can't be read and/or written.
512 * EISDIR: path is a directory.
513 * ENOENT: path doesn't exist or is "".
514 *
515 * Side effects:
516 * The file is deleted, even if it is read-only.
517 *
518 *---------------------------------------------------------------------------
519 */
520
521 int
522 TclpObjDeleteFile(pathPtr)
523 Tcl_Obj *pathPtr;
524 {
525 return TclpDeleteFile(Tcl_FSGetNativePath(pathPtr));
526 }
527
528 int
529 TclpDeleteFile(path)
530 CONST char *path; /* Pathname of file to be removed (native). */
531 {
532 if (unlink(path) != 0) { /* INTL: Native. */
533 return TCL_ERROR;
534 }
535 return TCL_OK;
536 }
537
538 /*
539 *---------------------------------------------------------------------------
540 *
541 * TclpCreateDirectory, DoCreateDirectory --
542 *
543 * Creates the specified directory. All parent directories of the
544 * specified directory must already exist. The directory is
545 * automatically created with permissions so that user can access
546 * the new directory and create new files or subdirectories in it.
547 *
548 * Results:
549 * If the directory was successfully created, returns TCL_OK.
550 * Otherwise the return value is TCL_ERROR and errno is set to
551 * indicate the error. Some possible values for errno are:
552 *
553 * EACCES: a parent directory can't be read and/or written.
554 * EEXIST: path already exists.
555 * ENOENT: a parent directory doesn't exist.
556 *
557 * Side effects:
558 * A directory is created with the current umask, except that
559 * permission for u+rwx will always be added.
560 *
561 *---------------------------------------------------------------------------
562 */
563
564 int
565 TclpObjCreateDirectory(pathPtr)
566 Tcl_Obj *pathPtr;
567 {
568 return DoCreateDirectory(Tcl_FSGetNativePath(pathPtr));
569 }
570
571 static int
572 DoCreateDirectory(path)
573 CONST char *path; /* Pathname of directory to create (native). */
574 {
575 mode_t mode;
576
577 mode = umask(0);
578 umask(mode);
579
580 /*
581 * umask return value is actually the inverse of the permissions.
582 */
583
584 mode = (0777 & ~mode) | S_IRUSR | S_IWUSR | S_IXUSR;
585
586 if (mkdir(path, mode) != 0) { /* INTL: Native. */
587 return TCL_ERROR;
588 }
589 return TCL_OK;
590 }
591
592 /*
593 *---------------------------------------------------------------------------
594 *
595 * TclpObjCopyDirectory --
596 *
597 * Recursively copies a directory. The target directory dst must
598 * not already exist. Note that this function does not merge two
599 * directory hierarchies, even if the target directory is an an
600 * empty directory.
601 *
602 * Results:
603 * If the directory was successfully copied, returns TCL_OK.
604 * Otherwise the return value is TCL_ERROR, errno is set to indicate
605 * the error, and the pathname of the file that caused the error
606 * is stored in errorPtr. See TclpObjCreateDirectory and
607 * TclpObjCopyFile for a description of possible values for errno.
608 *
609 * Side effects:
610 * An exact copy of the directory hierarchy src will be created
611 * with the name dst. If an error occurs, the error will
612 * be returned immediately, and remaining files will not be
613 * processed.
614 *
615 *---------------------------------------------------------------------------
616 */
617
618 int
619 TclpObjCopyDirectory(srcPathPtr, destPathPtr, errorPtr)
620 Tcl_Obj *srcPathPtr;
621 Tcl_Obj *destPathPtr;
622 Tcl_Obj **errorPtr;
623 {
624 Tcl_DString ds;
625 Tcl_DString srcString, dstString;
626 int ret;
627 Tcl_Obj *transPtr;
628
629 transPtr = Tcl_FSGetTranslatedPath(NULL,srcPathPtr);
630 Tcl_UtfToExternalDString(NULL,
631 (transPtr != NULL ? Tcl_GetString(transPtr) : NULL),
632 -1, &srcString);
633 if (transPtr != NULL) {
634 Tcl_DecrRefCount(transPtr);
635 }
636 transPtr = Tcl_FSGetTranslatedPath(NULL,destPathPtr);
637 Tcl_UtfToExternalDString(NULL,
638 (transPtr != NULL ? Tcl_GetString(transPtr) : NULL),
639 -1, &dstString);
640 if (transPtr != NULL) {
641 Tcl_DecrRefCount(transPtr);
642 }
643
644 ret = TraverseUnixTree(TraversalCopy, &srcString, &dstString, &ds);
645
646 Tcl_DStringFree(&srcString);
647 Tcl_DStringFree(&dstString);
648
649 if (ret != TCL_OK) {
650 *errorPtr = Tcl_NewStringObj(Tcl_DStringValue(&ds), -1);
651 Tcl_DStringFree(&ds);
652 Tcl_IncrRefCount(*errorPtr);
653 }
654 return ret;
655 }
656
657
658 /*
659 *---------------------------------------------------------------------------
660 *
661 * TclpRemoveDirectory, DoRemoveDirectory --
662 *
663 * Removes directory (and its contents, if the recursive flag is set).
664 *
665 * Results:
666 * If the directory was successfully removed, returns TCL_OK.
667 * Otherwise the return value is TCL_ERROR, errno is set to indicate
668 * the error, and the pathname of the file that caused the error
669 * is stored in errorPtr. Some possible values for errno are:
670 *
671 * EACCES: path directory can't be read and/or written.
672 * EEXIST: path is a non-empty directory.
673 * EINVAL: path is a root directory.
674 * ENOENT: path doesn't exist or is "".
675 * ENOTDIR: path is not a directory.
676 *
677 * Side effects:
678 * Directory removed. If an error occurs, the error will be returned
679 * immediately, and remaining files will not be deleted.
680 *
681 *---------------------------------------------------------------------------
682 */
683
684 int
685 TclpObjRemoveDirectory(pathPtr, recursive, errorPtr)
686 Tcl_Obj *pathPtr;
687 int recursive;
688 Tcl_Obj **errorPtr;
689 {
690 Tcl_DString ds;
691 Tcl_DString pathString;
692 int ret;
693 Tcl_Obj *transPtr = Tcl_FSGetTranslatedPath(NULL, pathPtr);
694
695 Tcl_UtfToExternalDString(NULL,
696 (transPtr != NULL ? Tcl_GetString(transPtr) : NULL),
697 -1, &pathString);
698 if (transPtr != NULL) {
699 Tcl_DecrRefCount(transPtr);
700 }
701 ret = DoRemoveDirectory(&pathString, recursive, &ds);
702 Tcl_DStringFree(&pathString);
703
704 if (ret != TCL_OK) {
705 *errorPtr = Tcl_NewStringObj(Tcl_DStringValue(&ds), -1);
706 Tcl_DStringFree(&ds);
707 Tcl_IncrRefCount(*errorPtr);
708 }
709 return ret;
710 }
711
712 static int
713 DoRemoveDirectory(pathPtr, recursive, errorPtr)
714 Tcl_DString *pathPtr; /* Pathname of directory to be removed
715 * (native). */
716 int recursive; /* If non-zero, removes directories that
717 * are nonempty. Otherwise, will only remove
718 * empty directories. */
719 Tcl_DString *errorPtr; /* If non-NULL, uninitialized or free
720 * DString filled with UTF-8 name of file
721 * causing error. */
722 {
723 CONST char *path;
724 mode_t oldPerm = 0;
725 int result;
726
727 path = Tcl_DStringValue(pathPtr);
728
729 if (recursive != 0) {
730 /* We should try to change permissions so this can be deleted */
731 Tcl_StatBuf statBuf;
732 int newPerm;
733
734 if (TclOSstat(path, &statBuf) == 0) {
735 oldPerm = (mode_t) (statBuf.st_mode & 0x00007FFF);
736 }
737
738 newPerm = oldPerm | (64+128+256);
739 chmod(path, (mode_t) newPerm);
740 }
741
742 if (rmdir(path) == 0) { /* INTL: Native. */
743 return TCL_OK;
744 }
745 if (errno == ENOTEMPTY) {
746 errno = EEXIST;
747 }
748
749 result = TCL_OK;
750 if ((errno != EEXIST) || (recursive == 0)) {
751 if (errorPtr != NULL) {
752 Tcl_ExternalToUtfDString(NULL, path, -1, errorPtr);
753 }
754 result = TCL_ERROR;
755 }
756
757 /*
758 * The directory is nonempty, but the recursive flag has been
759 * specified, so we recursively remove all the files in the directory.
760 */
761
762 if (result == TCL_OK) {
763 result = TraverseUnixTree(TraversalDelete, pathPtr, NULL, errorPtr);
764 }
765
766 if ((result != TCL_OK) && (recursive != 0)) {
767 /* Try to restore permissions */
768 chmod(path, oldPerm);
769 }
770 return result;
771 }
772
773 /*
774 *---------------------------------------------------------------------------
775 *
776 * TraverseUnixTree --
777 *
778 * Traverse directory tree specified by sourcePtr, calling the function
779 * traverseProc for each file and directory encountered. If destPtr
780 * is non-null, each of name in the sourcePtr directory is appended to
781 * the directory specified by destPtr and passed as the second argument
782 * to traverseProc() .
783 *
784 * Results:
785 * Standard Tcl result.
786 *
787 * Side effects:
788 * None caused by TraverseUnixTree, however the user specified
789 * traverseProc() may change state. If an error occurs, the error will
790 * be returned immediately, and remaining files will not be processed.
791 *
792 *---------------------------------------------------------------------------
793 */
794
795 static int
796 TraverseUnixTree(traverseProc, sourcePtr, targetPtr, errorPtr)
797 TraversalProc *traverseProc;/* Function to call for every file and
798 * directory in source hierarchy. */
799 Tcl_DString *sourcePtr; /* Pathname of source directory to be
800 * traversed (native). */
801 Tcl_DString *targetPtr; /* Pathname of directory to traverse in
802 * parallel with source directory (native). */
803 Tcl_DString *errorPtr; /* If non-NULL, uninitialized or free
804 * DString filled with UTF-8 name of file
805 * causing error. */
806 {
807 Tcl_StatBuf statBuf;
808 CONST char *source, *errfile;
809 int result, sourceLen;
810 int targetLen;
811 Tcl_DirEntry *dirEntPtr;
812 DIR *dirPtr;
813
814 errfile = NULL;
815 result = TCL_OK;
816 targetLen = 0; /* lint. */
817
818 source = Tcl_DStringValue(sourcePtr);
819 if (TclOSlstat(source, &statBuf) != 0) { /* INTL: Native. */
820 errfile = source;
821 goto end;
822 }
823 if (!S_ISDIR(statBuf.st_mode)) {
824 /*
825 * Process the regular file
826 */
827
828 return (*traverseProc)(sourcePtr, targetPtr, &statBuf, DOTREE_F,
829 errorPtr);
830 }
831 dirPtr = opendir(source); /* INTL: Native. */
832 if (dirPtr == NULL) {
833 /*
834 * Can't read directory
835 */
836
837 errfile = source;
838 goto end;
839 }
840 result = (*traverseProc)(sourcePtr, targetPtr, &statBuf, DOTREE_PRED,
841 errorPtr);
842 if (result != TCL_OK) {
843 closedir(dirPtr);
844 return result;
845 }
846
847 Tcl_DStringAppend(sourcePtr, "/", 1);
848 sourceLen = Tcl_DStringLength(sourcePtr);
849
850 if (targetPtr != NULL) {
851 Tcl_DStringAppend(targetPtr, "/", 1);
852 targetLen = Tcl_DStringLength(targetPtr);
853 }
854
855 while ((dirEntPtr = TclOSreaddir(dirPtr)) != NULL) { /* INTL: Native. */
856 if ((dirEntPtr->d_name[0] == '.')
857 && ((dirEntPtr->d_name[1] == '\0')
858 || (strcmp(dirEntPtr->d_name, "..") == 0))) {
859 continue;
860 }
861
862 /*
863 * Append name after slash, and recurse on the file.
864 */
865
866 Tcl_DStringAppend(sourcePtr, dirEntPtr->d_name, -1);
867 if (targetPtr != NULL) {
868 Tcl_DStringAppend(targetPtr, dirEntPtr->d_name, -1);
869 }
870 result = TraverseUnixTree(traverseProc, sourcePtr, targetPtr,
871 errorPtr);
872 if (result != TCL_OK) {
873 break;
874 }
875
876 /*
877 * Remove name after slash.
878 */
879
880 Tcl_DStringSetLength(sourcePtr, sourceLen);
881 if (targetPtr != NULL) {
882 Tcl_DStringSetLength(targetPtr, targetLen);
883 }
884 }
885 closedir(dirPtr);
886
887 /*
888 * Strip off the trailing slash we added
889 */
890
891 Tcl_DStringSetLength(sourcePtr, sourceLen - 1);
892 if (targetPtr != NULL) {
893 Tcl_DStringSetLength(targetPtr, targetLen - 1);
894 }
895
896 if (result == TCL_OK) {
897 /*
898 * Call traverseProc() on a directory after visiting all the
899 * files in that directory.
900 */
901
902 result = (*traverseProc)(sourcePtr, targetPtr, &statBuf, DOTREE_POSTD,
903 errorPtr);
904 }
905 end:
906 if (errfile != NULL) {
907 if (errorPtr != NULL) {
908 Tcl_ExternalToUtfDString(NULL, errfile, -1, errorPtr);
909 }
910 result = TCL_ERROR;
911 }
912
913 return result;
914 }
915
916 /*
917 *----------------------------------------------------------------------
918 *
919 * TraversalCopy
920 *
921 * Called from TraverseUnixTree in order to execute a recursive copy
922 * of a directory.
923 *
924 * Results:
925 * Standard Tcl result.
926 *
927 * Side effects:
928 * The file or directory src may be copied to dst, depending on
929 * the value of type.
930 *
931 *----------------------------------------------------------------------
932 */
933
934 static int
935 TraversalCopy(srcPtr, dstPtr, statBufPtr, type, errorPtr)
936 Tcl_DString *srcPtr; /* Source pathname to copy (native). */
937 Tcl_DString *dstPtr; /* Destination pathname of copy (native). */
938 CONST Tcl_StatBuf *statBufPtr;
939 /* Stat info for file specified by srcPtr. */
940 int type; /* Reason for call - see TraverseUnixTree(). */
941 Tcl_DString *errorPtr; /* If non-NULL, uninitialized or free
942 * DString filled with UTF-8 name of file
943 * causing error. */
944 {
945 switch (type) {
946 case DOTREE_F:
947 if (DoCopyFile(Tcl_DStringValue(srcPtr),
948 Tcl_DStringValue(dstPtr)) == TCL_OK) {
949 return TCL_OK;
950 }
951 break;
952
953 case DOTREE_PRED:
954 if (DoCreateDirectory(Tcl_DStringValue(dstPtr)) == TCL_OK) {
955 return TCL_OK;
956 }
957 break;
958
959 case DOTREE_POSTD:
960 if (CopyFileAtts(Tcl_DStringValue(srcPtr),
961 Tcl_DStringValue(dstPtr), statBufPtr) == TCL_OK) {
962 return TCL_OK;
963 }
964 break;
965
966 }
967
968 /*
969 * There shouldn't be a problem with src, because we already checked it
970 * to get here.
971 */
972
973 if (errorPtr != NULL) {
974 Tcl_ExternalToUtfDString(NULL, Tcl_DStringValue(dstPtr),
975 Tcl_DStringLength(dstPtr), errorPtr);
976 }
977 return TCL_ERROR;
978 }
979
980 /*
981 *---------------------------------------------------------------------------
982 *
983 * TraversalDelete --
984 *
985 * Called by procedure TraverseUnixTree for every file and directory
986 * that it encounters in a directory hierarchy. This procedure unlinks
987 * files, and removes directories after all the containing files
988 * have been processed.
989 *
990 * Results:
991 * Standard Tcl result.
992 *
993 * Side effects:
994 * Files or directory specified by src will be deleted.
995 *
996 *----------------------------------------------------------------------
997 */
998
999 static int
1000 TraversalDelete(srcPtr, ignore, statBufPtr, type, errorPtr)
1001 Tcl_DString *srcPtr; /* Source pathname (native). */
1002 Tcl_DString *ignore; /* Destination pathname (not used). */
1003 CONST Tcl_StatBuf *statBufPtr;
1004 /* Stat info for file specified by srcPtr. */
1005 int type; /* Reason for call - see TraverseUnixTree(). */
1006 Tcl_DString *errorPtr; /* If non-NULL, uninitialized or free
1007 * DString filled with UTF-8 name of file
1008 * causing error. */
1009 {
1010 switch (type) {
1011 case DOTREE_F: {
1012 if (TclpDeleteFile(Tcl_DStringValue(srcPtr)) == 0) {
1013 return TCL_OK;
1014 }
1015 break;
1016 }
1017 case DOTREE_PRED: {
1018 return TCL_OK;
1019 }
1020 case DOTREE_POSTD: {
1021 if (DoRemoveDirectory(srcPtr, 0, NULL) == 0) {
1022 return TCL_OK;
1023 }
1024 break;
1025 }
1026 }
1027 if (errorPtr != NULL) {
1028 Tcl_ExternalToUtfDString(NULL, Tcl_DStringValue(srcPtr),
1029 Tcl_DStringLength(srcPtr), errorPtr);
1030 }
1031 return TCL_ERROR;
1032 }
1033
1034 /*
1035 *---------------------------------------------------------------------------
1036 *
1037 * CopyFileAtts --
1038 *
1039 * Copy the file attributes such as owner, group, permissions,
1040 * and modification date from one file to another.
1041 *
1042 * Results:
1043 * Standard Tcl result.
1044 *
1045 * Side effects:
1046 * user id, group id, permission bits, last modification time, and
1047 * last access time are updated in the new file to reflect the
1048 * old file.
1049 *
1050 *---------------------------------------------------------------------------
1051 */
1052
1053 static int
1054 CopyFileAtts(src, dst, statBufPtr)
1055 CONST char *src; /* Path name of source file (native). */
1056 CONST char *dst; /* Path name of target file (native). */
1057 CONST Tcl_StatBuf *statBufPtr;
1058 /* Stat info for source file */
1059 {
1060 struct utimbuf tval;
1061 mode_t newMode;
1062
1063 newMode = statBufPtr->st_mode
1064 & (S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO);
1065
1066 /*
1067 * Note that if you copy a setuid file that is owned by someone
1068 * else, and you are not root, then the copy will be setuid to you.
1069 * The most correct implementation would probably be to have the
1070 * copy not setuid to anyone if the original file was owned by
1071 * someone else, but this corner case isn't currently handled.
1072 * It would require another lstat(), or getuid().
1073 */
1074
1075 if (chmod(dst, newMode)) { /* INTL: Native. */
1076 newMode &= ~(S_ISUID | S_ISGID);
1077 if (chmod(dst, newMode)) { /* INTL: Native. */
1078 return TCL_ERROR;
1079 }
1080 }
1081
1082 tval.actime = statBufPtr->st_atime;
1083 tval.modtime = statBufPtr->st_mtime;
1084
1085 if (utime(dst, &tval)) { /* INTL: Native. */
1086 return TCL_ERROR;
1087 }
1088 return TCL_OK;
1089 }
1090
1091
1092 /*
1093 *----------------------------------------------------------------------
1094 *
1095 * GetGroupAttribute
1096 *
1097 * Gets the group attribute of a file.
1098 *
1099 * Results:
1100 * Standard TCL result. Returns a new Tcl_Obj in attributePtrPtr
1101 * if there is no error.
1102 *
1103 * Side effects:
1104 * A new object is allocated.
1105 *
1106 *----------------------------------------------------------------------
1107 */
1108
1109 static int
1110 GetGroupAttribute(interp, objIndex, fileName, attributePtrPtr)
1111 Tcl_Interp *interp; /* The interp we are using for errors. */
1112 int objIndex; /* The index of the attribute. */
1113 Tcl_Obj *fileName; /* The name of the file (UTF-8). */
1114 Tcl_Obj **attributePtrPtr; /* A pointer to return the object with. */
1115 {
1116 Tcl_StatBuf statBuf;
1117 struct group *groupPtr;
1118 int result;
1119
1120 result = TclpObjStat(fileName, &statBuf);
1121
1122 if (result != 0) {
1123 Tcl_AppendResult(interp, "could not read \"",
1124 Tcl_GetString(fileName), "\": ",
1125 Tcl_PosixError(interp), (char *) NULL);
1126 return TCL_ERROR;
1127 }
1128
1129 groupPtr = getgrgid(statBuf.st_gid); /* INTL: Native. */
1130 if (groupPtr == NULL) {
1131 *attributePtrPtr = Tcl_NewIntObj((int) statBuf.st_gid);
1132 } else {
1133 Tcl_DString ds;
1134 CONST char *utf;
1135
1136 utf = Tcl_ExternalToUtfDString(NULL, groupPtr->gr_name, -1, &ds);
1137 *attributePtrPtr = Tcl_NewStringObj(utf, -1);
1138 Tcl_DStringFree(&ds);
1139 }
1140 endgrent();
1141 return TCL_OK;
1142 }
1143
1144 /*
1145 *----------------------------------------------------------------------
1146 *
1147 * GetOwnerAttribute
1148 *
1149 * Gets the owner attribute of a file.
1150 *
1151 * Results:
1152 * Standard TCL result. Returns a new Tcl_Obj in attributePtrPtr
1153 * if there is no error.
1154 *
1155 * Side effects:
1156 * A new object is allocated.
1157 *
1158 *----------------------------------------------------------------------
1159 */
1160
1161 static int
1162 GetOwnerAttribute(interp, objIndex, fileName, attributePtrPtr)
1163 Tcl_Interp *interp; /* The interp we are using for errors. */
1164 int objIndex; /* The index of the attribute. */
1165 Tcl_Obj *fileName; /* The name of the file (UTF-8). */
1166 Tcl_Obj **attributePtrPtr; /* A pointer to return the object with. */
1167 {
1168 Tcl_StatBuf statBuf;
1169 struct passwd *pwPtr;
1170 int result;
1171
1172 result = TclpObjStat(fileName, &statBuf);
1173
1174 if (result != 0) {
1175 Tcl_AppendResult(interp, "could not read \"",
1176 Tcl_GetString(fileName), "\": ",
1177 Tcl_PosixError(interp), (char *) NULL);
1178 return TCL_ERROR;
1179 }
1180
1181 pwPtr = getpwuid(statBuf.st_uid); /* INTL: Native. */
1182 if (pwPtr == NULL) {
1183 *attributePtrPtr = Tcl_NewIntObj((int) statBuf.st_uid);
1184 } else {
1185 Tcl_DString ds;
1186 CONST char *utf;
1187
1188 utf = Tcl_ExternalToUtfDString(NULL, pwPtr->pw_name, -1, &ds);
1189 *attributePtrPtr = Tcl_NewStringObj(utf, Tcl_DStringLength(&ds));
1190 Tcl_DStringFree(&ds);
1191 }
1192 endpwent();
1193 return TCL_OK;
1194 }
1195
1196 /*
1197 *----------------------------------------------------------------------
1198 *
1199 * GetPermissionsAttribute
1200 *
1201 * Gets the group attribute of a file.
1202 *
1203 * Results:
1204 * Standard TCL result. Returns a new Tcl_Obj in attributePtrPtr
1205 * if there is no error. The object will have ref count 0.
1206 *
1207 * Side effects:
1208 * A new object is allocated.
1209 *
1210 *----------------------------------------------------------------------
1211 */
1212
1213 static int
1214 GetPermissionsAttribute(interp, objIndex, fileName, attributePtrPtr)
1215 Tcl_Interp *interp; /* The interp we are using for errors. */
1216 int objIndex; /* The index of the attribute. */
1217 Tcl_Obj *fileName; /* The name of the file (UTF-8). */
1218 Tcl_Obj **attributePtrPtr; /* A pointer to return the object with. */
1219 {
1220 Tcl_StatBuf statBuf;
1221 char returnString[7];
1222 int result;
1223
1224 result = TclpObjStat(fileName, &statBuf);
1225
1226 if (result != 0) {
1227 Tcl_AppendResult(interp, "could not read \"",
1228 Tcl_GetString(fileName), "\": ",
1229 Tcl_PosixError(interp), (char *) NULL);
1230 return TCL_ERROR;
1231 }
1232
1233 sprintf(returnString, "%0#5lo", (long) (statBuf.st_mode & 0x00007FFF));
1234
1235 *attributePtrPtr = Tcl_NewStringObj(returnString, -1);
1236
1237 return TCL_OK;
1238 }
1239
1240 /*
1241 *---------------------------------------------------------------------------
1242 *
1243 * SetGroupAttribute --
1244 *
1245 * Sets the group of the file to the specified group.
1246 *
1247 * Results:
1248 * Standard TCL result.
1249 *
1250 * Side effects:
1251 * As above.
1252 *
1253 *---------------------------------------------------------------------------
1254 */
1255
1256 static int
1257 SetGroupAttribute(interp, objIndex, fileName, attributePtr)
1258 Tcl_Interp *interp; /* The interp for error reporting. */
1259 int objIndex; /* The index of the attribute. */
1260 Tcl_Obj *fileName; /* The name of the file (UTF-8). */
1261 Tcl_Obj *attributePtr; /* New group for file. */
1262 {
1263 long gid;
1264 int result;
1265 CONST char *native;
1266
1267 if (Tcl_GetLongFromObj(NULL, attributePtr, &gid) != TCL_OK) {
1268 Tcl_DString ds;
1269 struct group *groupPtr;
1270 CONST char *string;
1271 int length;
1272
1273 string = Tcl_GetStringFromObj(attributePtr, &length);
1274
1275 native = Tcl_UtfToExternalDString(NULL, string, length, &ds);
1276 groupPtr = getgrnam(native); /* INTL: Native. */
1277 Tcl_DStringFree(&ds);
1278
1279 if (groupPtr == NULL) {
1280 endgrent();
1281 Tcl_AppendResult(interp, "could not set group for file \"",
1282 Tcl_GetString(fileName), "\": group \"",
1283 string, "\" does not exist",
1284 (char *) NULL);
1285 return TCL_ERROR;
1286 }
1287 gid = groupPtr->gr_gid;
1288 }
1289
1290 native = Tcl_FSGetNativePath(fileName);
1291 result = chown(native, (uid_t) -1, (gid_t) gid); /* INTL: Native. */
1292
1293 endgrent();
1294 if (result != 0) {
1295 Tcl_AppendResult(interp, "could not set group for file \"",
1296 Tcl_GetString(fileName), "\": ", Tcl_PosixError(interp),
1297 (char *) NULL);
1298 return TCL_ERROR;
1299 }
1300 return TCL_OK;
1301 }
1302
1303 /*
1304 *---------------------------------------------------------------------------
1305 *
1306 * SetOwnerAttribute --
1307 *
1308 * Sets the owner of the file to the specified owner.
1309 *
1310 * Results:
1311 * Standard TCL result.
1312 *
1313 * Side effects:
1314 * As above.
1315 *
1316 *---------------------------------------------------------------------------
1317 */
1318
1319 static int
1320 SetOwnerAttribute(interp, objIndex, fileName, attributePtr)
1321 Tcl_Interp *interp; /* The interp for error reporting. */
1322 int objIndex; /* The index of the attribute. */
1323 Tcl_Obj *fileName; /* The name of the file (UTF-8). */
1324 Tcl_Obj *attributePtr; /* New owner for file. */
1325 {
1326 long uid;
1327 int result;
1328 CONST char *native;
1329
1330 if (Tcl_GetLongFromObj(NULL, attributePtr, &uid) != TCL_OK) {
1331 Tcl_DString ds;
1332 struct passwd *pwPtr;
1333 CONST char *string;
1334 int length;
1335
1336 string = Tcl_GetStringFromObj(attributePtr, &length);
1337
1338 native = Tcl_UtfToExternalDString(NULL, string, length, &ds);
1339 pwPtr = getpwnam(native); /* INTL: Native. */
1340 Tcl_DStringFree(&ds);
1341
1342 if (pwPtr == NULL) {
1343 Tcl_AppendResult(interp, "could not set owner for file \"",
1344 Tcl_GetString(fileName), "\": user \"",
1345 string, "\" does not exist",
1346 (char *) NULL);
1347 return TCL_ERROR;
1348 }
1349 uid = pwPtr->pw_uid;
1350 }
1351
1352 native = Tcl_FSGetNativePath(fileName);
1353 result = chown(native, (uid_t) uid, (gid_t) -1); /* INTL: Native. */
1354
1355 if (result != 0) {
1356 Tcl_AppendResult(interp, "could not set owner for file \"",
1357 Tcl_GetString(fileName), "\": ",
1358 Tcl_PosixError(interp), (char *) NULL);
1359 return TCL_ERROR;
1360 }
1361 return TCL_OK;
1362 }
1363
1364 /*
1365 *---------------------------------------------------------------------------
1366 *
1367 * SetPermissionsAttribute
1368 *
1369 * Sets the file to the given permission.
1370 *
1371 * Results:
1372 * Standard TCL result.
1373 *
1374 * Side effects:
1375 * The permission of the file is changed.
1376 *
1377 *---------------------------------------------------------------------------
1378 */
1379
1380 static int
1381 SetPermissionsAttribute(interp, objIndex, fileName, attributePtr)
1382 Tcl_Interp *interp; /* The interp we are using for errors. */
1383 int objIndex; /* The index of the attribute. */
1384 Tcl_Obj *fileName; /* The name of the file (UTF-8). */
1385 Tcl_Obj *attributePtr; /* The attribute to set. */
1386 {
1387 long mode;
1388 mode_t newMode;
1389 int result;
1390 CONST char *native;
1391
1392 /*
1393 * First try if the string is a number
1394 */
1395 if (Tcl_GetLongFromObj(NULL, attributePtr, &mode) == TCL_OK) {
1396 newMode = (mode_t) (mode & 0x00007FFF);
1397 } else {
1398 Tcl_StatBuf buf;
1399 char *modeStringPtr = Tcl_GetString(attributePtr);
1400
1401 /*
1402 * Try the forms "rwxrwxrwx" and "ugo=rwx"
1403 *
1404 * We get the current mode of the file, in order to allow for
1405 * ug+-=rwx style chmod strings.
1406 */
1407 result = TclpObjStat(fileName, &buf);
1408 if (result != 0) {
1409 Tcl_AppendResult(interp, "could not read \"",
1410 Tcl_GetString(fileName), "\": ",
1411 Tcl_PosixError(interp), (char *) NULL);
1412 return TCL_ERROR;
1413 }
1414 newMode = (mode_t) (buf.st_mode & 0x00007FFF);
1415
1416 if (GetModeFromPermString(NULL, modeStringPtr, &newMode) != TCL_OK) {
1417 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
1418 "unknown permission string format \"",
1419 modeStringPtr, "\"", (char *) NULL);
1420 return TCL_ERROR;
1421 }
1422 }
1423
1424 native = Tcl_FSGetNativePath(fileName);
1425 result = chmod(native, newMode); /* INTL: Native. */
1426 if (result != 0) {
1427 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
1428 "could not set permissions for file \"",
1429 Tcl_GetString(fileName), "\": ",
1430 Tcl_PosixError(interp), (char *) NULL);
1431 return TCL_ERROR;
1432 }
1433 return TCL_OK;
1434 }
1435
1436 /*
1437 *---------------------------------------------------------------------------
1438 *
1439 * TclpObjListVolumes --
1440 *
1441 * Lists the currently mounted volumes, which on UNIX is just /.
1442 *
1443 * Results:
1444 * The list of volumes.
1445 *
1446 * Side effects:
1447 * None.
1448 *
1449 *---------------------------------------------------------------------------
1450 */
1451
1452 Tcl_Obj*
1453 TclpObjListVolumes(void)
1454 {
1455 Tcl_Obj *resultPtr = Tcl_NewStringObj("/",1);
1456
1457 Tcl_IncrRefCount(resultPtr);
1458 return resultPtr;
1459 }
1460
1461 /*
1462 *----------------------------------------------------------------------
1463 *
1464 * GetModeFromPermString --
1465 *
1466 * This procedure is invoked to process the "file permissions"
1467 * Tcl command, to check for a "rwxrwxrwx" or "ugoa+-=rwxst" string.
1468 * See the user documentation for details on what it does.
1469 *
1470 * Results:
1471 * A standard Tcl result.
1472 *
1473 * Side effects:
1474 * See the user documentation.
1475 *
1476 *----------------------------------------------------------------------
1477 */
1478
1479 static int
1480 GetModeFromPermString(interp, modeStringPtr, modePtr)
1481 Tcl_Interp *interp; /* The interp we are using for errors. */
1482 char *modeStringPtr; /* Permissions string */
1483 mode_t *modePtr; /* pointer to the mode value */
1484 {
1485 mode_t newMode;
1486 mode_t oldMode; /* Storage for the value of the old mode
1487 * (that is passed in), to allow for the
1488 * chmod style manipulation */
1489 int i,n, who, op, what, op_found, who_found;
1490
1491 /*
1492 * We start off checking for an "rwxrwxrwx" style permissions string
1493 */
1494 if (strlen(modeStringPtr) != 9) {
1495 goto chmodStyleCheck;
1496 }
1497
1498 newMode = 0;
1499 for (i = 0; i < 9; i++) {
1500 switch (*(modeStringPtr+i)) {
1501 case 'r':
1502 if ((i%3) != 0) {
1503 goto chmodStyleCheck;
1504 }
1505 newMode |= (1<<(8-i));
1506 break;
1507 case 'w':
1508 if ((i%3) != 1) {
1509 goto chmodStyleCheck;
1510 }
1511 newMode |= (1<<(8-i));
1512 break;
1513 case 'x':
1514 if ((i%3) != 2) {
1515 goto chmodStyleCheck;
1516 }
1517 newMode |= (1<<(8-i));
1518 break;
1519 case 's':
1520 if (((i%3) != 2) || (i > 5)) {
1521 goto chmodStyleCheck;
1522 }
1523 newMode |= (1<<(8-i));
1524 newMode |= (1<<(11-(i/3)));
1525 break;
1526 case 'S':
1527 if (((i%3) != 2) || (i > 5)) {
1528 goto chmodStyleCheck;
1529 }
1530 newMode |= (1<<(11-(i/3)));
1531 break;
1532 case 't':
1533 if (i != 8) {
1534 goto chmodStyleCheck;
1535 }
1536 newMode |= (1<<(8-i));
1537 newMode |= (1<<9);
1538 break;
1539 case 'T':
1540 if (i != 8) {
1541 goto chmodStyleCheck;
1542 }
1543 newMode |= (1<<9);
1544 break;
1545 case '-':
1546 break;
1547 default:
1548 /*
1549 * Oops, not what we thought it was, so go on
1550 */
1551 goto chmodStyleCheck;
1552 }
1553 }
1554 *modePtr = newMode;
1555 return TCL_OK;
1556
1557 chmodStyleCheck:
1558 /*
1559 * We now check for an "ugoa+-=rwxst" style permissions string
1560 */
1561
1562 for (n = 0 ; *(modeStringPtr+n) != '\0' ; n = n + i) {
1563 oldMode = *modePtr;
1564 who = op = what = op_found = who_found = 0;
1565 for (i = 0 ; *(modeStringPtr+n+i) != '\0' ; i++ ) {
1566 if (!who_found) {
1567 /* who */
1568 switch (*(modeStringPtr+n+i)) {
1569 case 'u' :
1570 who |= 0x9c0;
1571 continue;
1572 case 'g' :
1573 who |= 0x438;
1574 continue;
1575 case 'o' :
1576 who |= 0x207;
1577 continue;
1578 case 'a' :
1579 who |= 0xfff;
1580 continue;
1581 }
1582 }
1583 who_found = 1;
1584 if (who == 0) {
1585 who = 0xfff;
1586 }
1587 if (!op_found) {
1588 /* op */
1589 switch (*(modeStringPtr+n+i)) {
1590 case '+' :
1591 op = 1;
1592 op_found = 1;
1593 continue;
1594 case '-' :
1595 op = 2;
1596 op_found = 1;
1597 continue;
1598 case '=' :
1599 op = 3;
1600 op_found = 1;
1601 continue;
1602 default :
1603 return TCL_ERROR;
1604 }
1605 }
1606 /* what */
1607 switch (*(modeStringPtr+n+i)) {
1608 case 'r' :
1609 what |= 0x124;
1610 continue;
1611 case 'w' :
1612 what |= 0x92;
1613 continue;
1614 case 'x' :
1615 what |= 0x49;
1616 continue;
1617 case 's' :
1618 what |= 0xc00;
1619 continue;
1620 case 't' :
1621 what |= 0x200;
1622 continue;
1623 case ',' :
1624 break;
1625 default :
1626 return TCL_ERROR;
1627 }
1628 if (*(modeStringPtr+n+i) == ',') {
1629 i++;
1630 break;
1631 }
1632 }
1633 switch (op) {
1634 case 1 :
1635 *modePtr = oldMode | (who & what);
1636 continue;
1637 case 2 :
1638 *modePtr = oldMode & ~(who & what);
1639 continue;
1640 case 3 :
1641 *modePtr = (oldMode & ~who) | (who & what);
1642 continue;
1643 }
1644 }
1645 return TCL_OK;
1646 }
1647
1648 /*
1649 *---------------------------------------------------------------------------
1650 *
1651 * TclpObjNormalizePath --
1652 *
1653 * This function scans through a path specification and replaces
1654 * it, in place, with a normalized version. A normalized version
1655 * is one in which all symlinks in the path are replaced with
1656 * their expanded form (except a symlink at the very end of the
1657 * path).
1658 *
1659 * Results:
1660 * The new 'nextCheckpoint' value, giving as far as we could
1661 * understand in the path.
1662 *
1663 * Side effects:
1664 * The pathPtr string, is modified.
1665 *
1666 *---------------------------------------------------------------------------
1667 */
1668 int
1669 TclpObjNormalizePath(interp, pathPtr, nextCheckpoint)
1670 Tcl_Interp *interp;
1671 Tcl_Obj *pathPtr;
1672 int nextCheckpoint;
1673 {
1674 char *currentPathEndPosition;
1675 int pathLen;
1676 char cur;
1677 char *path = Tcl_GetStringFromObj(pathPtr, &pathLen);
1678 #ifndef NO_REALPATH
1679 char normPath[MAXPATHLEN];
1680 Tcl_DString ds;
1681 CONST char *nativePath;
1682 #endif
1683 /*
1684 * We add '1' here because if nextCheckpoint is zero we know
1685 * that '/' exists, and if it isn't zero, it must point at
1686 * a directory separator which we also know exists.
1687 */
1688 currentPathEndPosition = path + nextCheckpoint;
1689 if (*currentPathEndPosition == '/') {
1690 currentPathEndPosition++;
1691 }
1692
1693 #ifndef NO_REALPATH
1694 /* For speed, try to get the entire path in one go */
1695 if (nextCheckpoint == 0) {
1696 char *lastDir = strrchr(currentPathEndPosition, '/');
1697 if (lastDir != NULL) {
1698 nativePath = Tcl_UtfToExternalDString(NULL, path,
1699 lastDir - path, &ds);
1700 if (Realpath(nativePath, normPath) != NULL) {
1701 nextCheckpoint = lastDir - path;
1702 goto wholeStringOk;
1703 }
1704 }
1705 }
1706 /* Else do it the slow way */
1707 #endif
1708
1709 while (1) {
1710 cur = *currentPathEndPosition;
1711 if ((cur == '/') && (path != currentPathEndPosition)) {
1712 /* Reached directory separator */
1713 Tcl_DString ds;
1714 CONST char *nativePath;
1715 int accessOk;
1716
1717 nativePath = Tcl_UtfToExternalDString(NULL, path,
1718 currentPathEndPosition - path, &ds);
1719 accessOk = access(nativePath, F_OK);
1720 Tcl_DStringFree(&ds);
1721 if (accessOk != 0) {
1722 /* File doesn't exist */
1723 break;
1724 }
1725 /* Update the acceptable point */
1726 nextCheckpoint = currentPathEndPosition - path;
1727 } else if (cur == 0) {
1728 /* Reached end of string */
1729 break;
1730 }
1731 currentPathEndPosition++;
1732 }
1733 /*
1734 * We should really now convert this to a canonical path. We do
1735 * that with 'realpath' if we have it available. Otherwise we could
1736 * step through every single path component, checking whether it is a
1737 * symlink, but that would be a lot of work, and most modern OSes
1738 * have 'realpath'.
1739 */
1740 #ifndef NO_REALPATH
1741 /*
1742 * If we only had '/foo' or '/' then we never increment nextCheckpoint
1743 * and we don't need or want to go through 'Realpath'. Also, on some
1744 * platforms, passing an empty string to 'Realpath' will give us the
1745 * normalized pwd, which is not what we want at all!
1746 */
1747 if (nextCheckpoint == 0) return 0;
1748
1749 nativePath = Tcl_UtfToExternalDString(NULL, path, nextCheckpoint, &ds);
1750 if (Realpath(nativePath, normPath) != NULL) {
1751 int newNormLen;
1752 wholeStringOk:
1753 newNormLen = strlen(normPath);
1754 if ((newNormLen == Tcl_DStringLength(&ds))
1755 && (strcmp(normPath, nativePath) == 0)) {
1756 /* String is unchanged */
1757 Tcl_DStringFree(&ds);
1758 if (path[nextCheckpoint] != '\0') {
1759 nextCheckpoint++;
1760 }
1761 return nextCheckpoint;
1762 }
1763
1764 /*
1765 * Free up the native path and put in its place the
1766 * converted, normalized path.
1767 */
1768 Tcl_DStringFree(&ds);
1769 Tcl_ExternalToUtfDString(NULL, normPath, (int) newNormLen, &ds);
1770
1771 if (path[nextCheckpoint] != '\0') {
1772 /* not at end, append remaining path */
1773 int normLen = Tcl_DStringLength(&ds);
1774 Tcl_DStringAppend(&ds, path + nextCheckpoint,
1775 pathLen - nextCheckpoint);
1776 /*
1777 * We recognise up to and including the directory
1778 * separator.
1779 */
1780 nextCheckpoint = normLen + 1;
1781 } else {
1782 /* We recognise the whole string */
1783 nextCheckpoint = Tcl_DStringLength(&ds);
1784 }
1785 /*
1786 * Overwrite with the normalized path.
1787 */
1788 Tcl_SetStringObj(pathPtr, Tcl_DStringValue(&ds),
1789 Tcl_DStringLength(&ds));
1790 }
1791 Tcl_DStringFree(&ds);
1792 #endif /* !NO_REALPATH */
1793
1794 return nextCheckpoint;
1795 }
1796
1797
1798