Don't quit if getpwuid() fails. It can fail if some nameservices are not
[nedit.git] / util / fileUtils.c
blob66c6ebec72445b5e59522cc6538cfc4444ab5bd8
1 static const char CVSID[] = "$Id: fileUtils.c,v 1.29 2003/04/07 22:51:41 yooden Exp $";
2 /*******************************************************************************
3 * *
4 * fileUtils.c -- File utilities for Nirvana applications *
5 * *
6 * Copyright (C) 1999 Mark Edel *
7 * *
8 * This is free software; you can redistribute it and/or modify it under the *
9 * terms of the GNU General Public License as published by the Free Software *
10 * Foundation; either version 2 of the License, or (at your option) any later *
11 * version. *
12 * *
13 * This software is distributed in the hope that it will be useful, but WITHOUT *
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
15 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License *
16 * for more details. *
17 * *
18 * You should have received a copy of the GNU General Public License along with *
19 * software; if not, write to the Free Software Foundation, Inc., 59 Temple *
20 * Place, Suite 330, Boston, MA 02111-1307 USA *
21 * *
22 * Nirvana Text Editor *
23 * July 28, 1992 *
24 * *
25 * Written by Mark Edel *
26 * *
27 * Modified by: DMR - Ported to VMS (1st stage for Histo-Scope) *
28 * *
29 *******************************************************************************/
31 #ifdef HAVE_CONFIG_H
32 #include "../config.h"
33 #endif
35 #include "fileUtils.h"
36 #include "utils.h"
38 #include <stdlib.h>
39 #include <stdio.h>
40 #include <string.h>
41 #include <errno.h>
42 #include <X11/Intrinsic.h>
43 #ifdef VAXC
44 #define NULL (void *) 0
45 #endif /*VAXC*/
46 #ifdef VMS
47 #include "vmsparam.h"
48 #include <stat.h>
49 #else
50 #include <sys/types.h>
51 #ifndef __MVS__
52 #include <sys/param.h>
53 #endif
54 #include <sys/stat.h>
55 #include <unistd.h>
56 #include <pwd.h>
57 #endif /*VMS*/
59 #ifdef HAVE_DEBUG_H
60 #include "../debug.h"
61 #endif
63 #ifndef MAXSYMLINKS /* should be defined in <sys/param.h> */
64 #define MAXSYMLINKS 20
65 #endif
67 #define TRUE 1
68 #define FALSE 0
70 /* Parameters to algorithm used to auto-detect DOS format files. NEdit will
71 scan up to the lesser of FORMAT_SAMPLE_LINES lines and FORMAT_SAMPLE_CHARS
72 characters of the beginning of the file, checking that all newlines are
73 paired with carriage returns. If even a single counterexample exists,
74 the file is judged to be in Unix format. */
75 #define FORMAT_SAMPLE_LINES 5
76 #define FORMAT_SAMPLE_CHARS 2000
78 static char *nextSlash(char *ptr);
79 static char *prevSlash(char *ptr);
80 static int compareThruSlash(const char *string1, const char *string2);
81 static void copyThruSlash(char **toString, char **fromString);
84 ** Decompose a Unix file name into a file name and a path.
85 ** Return non-zero value if it fails, zero else.
86 ** For now we assume that filename and pathname are at
87 ** least MAXPATHLEN chars long.
88 ** To skip setting filename or pathname pass NULL for that argument.
90 int
91 ParseFilename(const char *fullname, char *filename, char *pathname)
93 int fullLen = strlen(fullname);
94 int i, pathLen, fileLen;
96 #ifdef VMS
97 /* find the last ] or : */
98 for (i=fullLen-1; i>=0; i--) {
99 if (fullname[i] == ']' || fullname[i] == ':')
100 break;
102 #else /* UNIX */
103 char *viewExtendPath;
104 int scanStart;
106 /* For clearcase version extended paths, slash characters after the "@@/"
107 should be considered part of the file name, rather than the path */
108 if ((viewExtendPath = strstr(fullname, "@@/")) != NULL)
109 scanStart = viewExtendPath - fullname - 1;
110 else
111 scanStart = fullLen - 1;
113 /* find the last slash */
114 for (i=scanStart; i>=0; i--) {
115 if (fullname[i] == '/')
116 break;
118 #endif
120 /* move chars before / (or ] or :) into pathname,& after into filename */
121 pathLen = i + 1;
122 fileLen = fullLen - pathLen;
123 if (pathname) {
124 if (pathLen > MAXPATHLEN) {
125 return 1;
127 strncpy(pathname, fullname, pathLen);
128 pathname[pathLen] = 0;
130 if (filename) {
131 if (fileLen > MAXPATHLEN) {
132 return 2;
134 strncpy(filename, &fullname[pathLen], fileLen);
135 filename[fileLen] = 0;
138 #ifdef VMS
139 return 0;
140 #else /* UNIX specific... Modify at a later date for VMS */
141 if(pathname)
142 return NormalizePathname(pathname);
143 else
144 return 0;
145 #endif
148 #ifndef VMS
152 ** Expand tilde characters which begin file names as done by the shell
153 ** If it doesn't work just out leave pathname unmodified.
154 ** This implementation is neither fast, nor elegant, nor ...
157 ExpandTilde(char *pathname)
159 struct passwd *passwdEntry;
160 char username[MAXPATHLEN], temp[MAXPATHLEN];
161 char *nameEnd;
162 unsigned len_left;
164 if (pathname[0] != '~')
165 return TRUE;
166 nameEnd = strchr(&pathname[1], '/');
167 if (nameEnd == NULL) {
168 nameEnd = pathname + strlen(pathname);
170 strncpy(username, &pathname[1], nameEnd - &pathname[1]);
171 username[nameEnd - &pathname[1]] = '\0';
172 /* We might consider to re-use the GetHomeDir() function,
173 but to keep the code more similar for both cases ... */
174 if (username[0] == '\0') {
175 passwdEntry = getpwuid(getuid());
176 if ((passwdEntry == NULL) || (*(passwdEntry->pw_dir)== '\0')) {
177 /* This is really serious, so just exit. */
178 perror("NEdit/nc: getpwuid() failed ");
179 exit(EXIT_FAILURE);
182 else {
183 passwdEntry = getpwnam(username);
184 if ((passwdEntry == NULL) || (*(passwdEntry->pw_dir)== '\0')) {
185 /* username was just an input by the user, this is no
186 indication for some (serious) problems */
187 return FALSE;
191 strcpy(temp, passwdEntry->pw_dir);
192 strcat(temp, "/");
193 len_left= sizeof(temp)-strlen(temp)-1;
194 if (len_left < strlen(nameEnd)) {
195 /* It won't work out */
196 return FALSE;
198 strcat(temp, nameEnd);
199 strcpy(pathname, temp);
200 return TRUE;
204 * Resolve symbolic links (if any) for the absolute path given in pathIn
205 * and place the resolved absolute path in pathResolved.
206 * - pathIn must contain an absolute path spec.
207 * - pathResolved must point to a buffer of minimum size MAXPATHLEN.
209 * Returns:
210 * TRUE if pathResolved contains a valid resolved path
211 * OR pathIn is not a symlink (pathResolved will have the same
212 * contents like pathIn)
214 * FALSE an error occured while trying to resolve the symlink, i.e.
215 * pathIn was no absolute path or the link is a loop.
218 ResolvePath(const char * pathIn, char * pathResolved)
220 char resolveBuf[MAXPATHLEN], pathBuf[MAXPATHLEN];
221 char *pathEnd;
222 int rlResult, loops;
224 #ifdef NO_READLINK
225 strncpy(pathResolved, pathIn, MAXPATHLEN);
226 /* If there are no links at all, it's a valid "resolved" path */
227 return TRUE;
228 #else
229 /* !! readlink does NOT recognize loops, i.e. links like file -> ./file */
230 for(loops=0; loops<MAXSYMLINKS; loops++) {
231 #ifdef UNICOS
232 rlResult=readlink((char *)pathIn, resolveBuf, MAXPATHLEN-1);
233 #else
234 rlResult=readlink(pathIn, resolveBuf, MAXPATHLEN-1);
235 #endif
236 if(rlResult<0) {
238 #ifndef __Lynx__
239 if (errno == EINVAL)
240 #else
241 if (errno == ENXIO)
242 #endif
244 /* It's not a symlink - we are done */
245 strncpy(pathResolved, pathIn, MAXPATHLEN);
246 return TRUE;
247 } else
249 return FALSE;
251 } else if (rlResult==0) {
252 return FALSE;
255 resolveBuf[rlResult]=0;
257 if(resolveBuf[0]!='/') {
258 strncpy(pathBuf, pathIn, MAXPATHLEN);
259 pathEnd=strrchr(pathBuf, '/');
260 if(!pathEnd)
261 return FALSE;
262 strcpy(pathEnd+1, resolveBuf);
263 } else {
264 strcpy(pathBuf, resolveBuf);
266 NormalizePathname(pathBuf);
267 pathIn=pathBuf;
269 return FALSE;
270 #endif /* NO_READLINK */
275 ** Return 0 if everything's fine. In fact it always return 0 ...
276 ** Capable to handle arbitrary path length (>MAXPATHLEN)!
279 NormalizePathname(char *pathname)
281 /* if this is a relative pathname, prepend current directory */
282 #ifdef __EMX__
283 /* OS/2, ...: welcome to the world of drive letters ... */
284 if (!_fnisabs(pathname)) {
285 #else
286 if (pathname[0] != '/') {
287 #endif
288 char *oldPathname;
289 size_t len;
291 /* make a copy of pathname to work from */
292 oldPathname=(char *)malloc(strlen(pathname)+1);
293 strcpy(oldPathname, pathname);
294 /* get the working directory and prepend to the path */
295 strcpy(pathname, GetCurrentDir());
296 /* check for trailing slash, or pathname being root dir "/":
297 don't add a second '/' character as this may break things
298 on non-un*x systems */
299 len=strlen(pathname); /* GetCurrentDir() returns non-NULL value */
300 if ( len==0 ? 1 : pathname[len-1] != '/' ) {
301 strcat(pathname, "/");
303 strcat(pathname, oldPathname);
304 free(oldPathname);
307 /* compress out .. and . */
308 return CompressPathname(pathname);
313 ** Return 0 if everything's fine, 1 else.
316 CompressPathname(char *pathname)
318 char *buf, *inPtr, *outPtr;
319 struct stat statbuf;
321 /* (Added by schwarzenberg)
322 ** replace multiple slashes by a single slash
324 inPtr=pathname;
325 buf=(char *)malloc(strlen(pathname)+2);
326 outPtr=buf;
327 while (*inPtr) {
328 *outPtr=*inPtr++;
329 if(*outPtr=='/') {
330 while(*inPtr=='/')
331 inPtr++;
333 outPtr++;
335 *outPtr=0;
336 strcpy(pathname, buf);
338 /* compress out . and .. */
339 inPtr = pathname;
340 outPtr = buf;
341 /* copy initial / */
342 copyThruSlash(&outPtr, &inPtr);
343 while (inPtr != NULL) {
344 /* if the next component is "../", remove previous component */
345 if (compareThruSlash(inPtr, "../")) {
346 *outPtr = 0;
347 /* If the ../ is at the beginning, or if the previous component
348 is a symbolic link, preserve the ../. It is not valid to
349 compress ../ when the previous component is a symbolic link
350 because ../ is relative to where the link points. If there's
351 no S_ISLNK macro, assume system does not do symbolic links. */
352 #ifdef S_ISLNK
353 if(outPtr-1 == buf || (lstat(buf, &statbuf) == 0 &&
354 S_ISLNK(statbuf.st_mode))) {
355 copyThruSlash(&outPtr, &inPtr);
356 } else
357 #endif
359 /* back up outPtr to remove last path name component */
360 outPtr = prevSlash(outPtr);
361 inPtr = nextSlash(inPtr);
363 } else if (compareThruSlash(inPtr, "./")) {
364 /* don't copy the component if it's the redundant "./" */
365 inPtr = nextSlash(inPtr);
366 } else {
367 /* copy the component to outPtr */
368 copyThruSlash(&outPtr, &inPtr);
371 /* updated pathname with the new value */
372 if (strlen(buf)>MAXPATHLEN) {
373 fprintf(stderr, "NEdit: CompressPathname(): file name too long %s\n",
374 pathname);
375 free(buf);
376 return 1;
378 else {
379 strcpy(pathname, buf);
380 free(buf);
381 return 0;
385 static char
386 *nextSlash(char *ptr)
388 for(; *ptr!='/'; ptr++) {
389 if (*ptr == '\0')
390 return NULL;
392 return ptr + 1;
395 static char
396 *prevSlash(char *ptr)
398 for(ptr -= 2; *ptr!='/'; ptr--);
399 return ptr + 1;
402 static int
403 compareThruSlash(const char *string1, const char *string2)
405 while (TRUE) {
406 if (*string1 != *string2)
407 return FALSE;
408 if (*string1 =='\0' || *string1=='/')
409 return TRUE;
410 string1++;
411 string2++;
415 static void
416 copyThruSlash(char **toString, char **fromString)
418 char *to = *toString;
419 char *from = *fromString;
421 while (TRUE) {
422 *to = *from;
423 if (*from =='\0') {
424 *fromString = NULL;
425 return;
427 if (*from=='/') {
428 *toString = to + 1;
429 *fromString = from + 1;
430 return;
432 from++;
433 to++;
437 #else /* VMS */
440 ** Dummy versions of the public functions for VMS.
444 ** Return 0 if everything's fine, 1 else.
446 int NormalizePathname(char *pathname)
448 return 0;
452 ** Return 0 if everything's fine, 1 else.
454 int CompressPathname(char *pathname)
456 return 0;
460 * Returns:
461 * TRUE if no error occured
463 * FALSE if an error occured.
465 int ResolvePath(const char * pathIn, char * pathResolved)
467 if (strlen(pathIn) < MAXPATHLEN) {
468 strcpy(pathResolved, pathIn);
469 return TRUE;
470 } else {
471 return FALSE;
475 #endif /* VMS */
478 ** Return the trailing 'n' no. of path components
480 const char
481 *GetTrailingPathComponents(const char* path,
482 int noOfComponents)
484 /* Start from the rear */
485 const char* ptr = path + strlen(path);
486 int count = 0;
488 while (--ptr > path) {
489 if (*ptr == '/') {
490 if (count++ == noOfComponents) {
491 break;
495 return(ptr);
499 ** Samples up to a maximum of FORMAT_SAMPLE_LINES lines and FORMAT_SAMPLE_CHARS
500 ** characters, to determine whether fileString represents a MS DOS or Macintosh
501 ** format file. If there's ANY ambiguity (a newline in the sample not paired
502 ** with a return in an otherwise DOS looking file, or a newline appearing in
503 ** the sampled portion of a Macintosh looking file), the file is judged to be
504 ** Unix format.
506 int FormatOfFile(const char *fileString)
508 const char *p;
509 int nNewlines = 0, nReturns = 0;
511 for (p=fileString; *p!='\0' && p < fileString + FORMAT_SAMPLE_CHARS; p++) {
512 if (*p == '\n') {
513 nNewlines++;
514 if (p == fileString || *(p-1) != '\r')
515 return UNIX_FILE_FORMAT;
516 if (nNewlines >= FORMAT_SAMPLE_LINES)
517 return DOS_FILE_FORMAT;
518 } else if (*p == '\r')
519 nReturns++;
521 if (nNewlines > 0)
522 return DOS_FILE_FORMAT;
523 if (nReturns > 1)
524 return MAC_FILE_FORMAT;
525 return UNIX_FILE_FORMAT;
529 ** Converts a string (which may represent the entire contents of the file)
530 ** from DOS or Macintosh format to Unix format. Conversion is done in-place.
531 ** In the DOS case, the length will be shorter, and passed length will be
532 ** modified to reflect the new length. The routine has support for blockwise
533 ** file to string conversion: if the fileString has a trailing '\r' and
534 ** 'pendingCR' is not zero, the '\r' is deposited in there and is not
535 ** converted. If there is no trailing '\r', a 0 is deposited in 'pendingCR'
536 ** It's the caller's responsability to make sure that the pending character,
537 ** if present, is inserted at the beginning of the next block to convert.
539 void ConvertFromDosFileString(char *fileString, int *length,
540 char* pendingCR)
542 char *outPtr = fileString;
543 char *inPtr = fileString;
544 if (pendingCR) *pendingCR = 0;
545 while (inPtr < fileString + *length) {
546 if (*inPtr == '\r') {
547 if (inPtr < fileString + *length - 1) {
548 if (*(inPtr + 1) == '\n')
549 inPtr++;
550 } else {
551 if (pendingCR) {
552 *pendingCR = *inPtr;
553 break; /* Don't copy this trailing '\r' */
557 *outPtr++ = *inPtr++;
559 *outPtr = '\0';
560 *length = outPtr - fileString;
562 void ConvertFromMacFileString(char *fileString, int length)
564 char *inPtr = fileString;
565 while (inPtr < fileString + length) {
566 if (*inPtr == '\r' )
567 *inPtr = '\n';
568 inPtr++;
573 ** Converts a string (which may represent the entire contents of the file) from
574 ** Unix to DOS format. String is re-allocated (with malloc), and length is
575 ** modified. If allocation fails, which it may, because this can potentially
576 ** be a huge hunk of memory, returns FALSE and no conversion is done.
578 ** This could be done more efficiently by asking doSave to allocate some
579 ** extra memory for this, and only re-allocating if it wasn't enough. If
580 ** anyone cares about the performance or the potential for running out of
581 ** memory on a save, it should probably be redone.
583 int ConvertToDosFileString(char **fileString, int *length)
585 char *outPtr, *outString;
586 char *inPtr = *fileString;
587 int inLength = *length;
588 int outLength = 0;
590 /* How long a string will we need? */
591 while (inPtr < *fileString + inLength) {
592 if (*inPtr == '\n')
593 outLength++;
594 inPtr++;
595 outLength++;
598 /* Allocate the new string */
599 outString = XtMalloc(outLength + 1);
600 if (outString == NULL)
601 return FALSE;
603 /* Do the conversion, free the old string */
604 inPtr = *fileString;
605 outPtr = outString;
606 while (inPtr < *fileString + inLength) {
607 if (*inPtr == '\n')
608 *outPtr++ = '\r';
609 *outPtr++ = *inPtr++;
611 *outPtr = '\0';
612 XtFree(*fileString);
613 *fileString = outString;
614 *length = outLength;
615 return TRUE;
619 ** Converts a string (which may represent the entire contents of the file)
620 ** from Unix to Macintosh format.
622 void ConvertToMacFileString(char *fileString, int length)
624 char *inPtr = fileString;
626 while (inPtr < fileString + length) {
627 if (*inPtr == '\n' )
628 *inPtr = '\r';
629 inPtr++;
634 ** Reads a text file into a string buffer, converting line breaks to
635 ** unix-style if appropriate.
637 char *ReadAnyTextFile(const char *fileName)
639 struct stat statbuf;
640 FILE *fp;
641 int fileLen, readLen;
642 char *fileString;
643 int format;
645 /* Read the whole file into fileString */
646 if ((fp = fopen(fileName, "r")) == NULL) {
647 return NULL;
649 if (fstat(fileno(fp), &statbuf) != 0) {
650 fclose(fp);
651 return NULL;
653 fileLen = statbuf.st_size;
654 fileString = XtMalloc(fileLen+1); /* +1 = space for null */
655 readLen = fread(fileString, sizeof(char), fileLen, fp);
656 if (ferror(fp)) {
657 XtFree(fileString);
658 fclose(fp);
659 return NULL;
661 fclose(fp);
662 fileString[readLen] = 0;
664 /* Convert linebreaks? */
665 format = FormatOfFile(fileString);
666 if (format == DOS_FILE_FORMAT){
667 char pendingCR;
668 ConvertFromDosFileString(fileString, &readLen, &pendingCR);
669 } else if (format == MAC_FILE_FORMAT){
670 ConvertFromMacFileString(fileString, readLen);
673 return fileString;