* New version 2.21.999
[alpine.git] / pith / osdep / fnexpand.c
blob52ce7fd6404e3d967886dd928c7eefe7d2402bb4
1 #if !defined(lint) && !defined(DOS)
2 static char rcsid[] = "$Id: fnexpand.c 761 2007-10-23 22:35:18Z hubert@u.washington.edu $";
3 #endif
5 /*
6 * ========================================================================
7 * Copyright 2013-2018 Eduardo Chappa
8 * Copyright 2006 University of Washington
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
14 * http://www.apache.org/licenses/LICENSE-2.0
16 * ========================================================================
19 #include <system.h>
21 #include "../charconv/filesys.h"
23 #include "fnexpand.h"
28 /*----------------------------------------------------------------------
29 Expand the ~ in a file ala the csh (as home directory)
31 Args: buf -- The filename to expand (nothing happens unless begins with ~)
32 len -- The length of the buffer passed in (expansion is in place)
34 Result: Expanded string is returned using same storage as passed in.
35 If expansion fails, NULL is returned
36 ----*/
37 char *
38 fnexpand(char *buf, int len)
40 #ifdef _WINDOWS
41 /* We used to use ps_global->home_dir, now we have to build it */
42 if(*buf == '~' && *(buf+1) == '\\'){
43 char temp_path[_MAX_PATH], home_buf[_MAX_PATH], *temp_home_str;
45 if(getenv("HOME") != NULL)
46 temp_home_str = getenv("HOME");
47 else{
48 /* should eventually strip this out of get_user_info */
49 char *p, *q;
51 if((p = (char *) getenv("HOMEDRIVE"))
52 && (q = (char *) getenv("HOMEPATH")))
53 snprintf(home_buf, sizeof(home_buf), "%s%s", p, q);
54 else
55 snprintf(home_buf, sizeof(home_buf), "%c:\\", '@' + _getdrive());
57 temp_home_str = home_buf;
59 snprintf(temp_path, sizeof(temp_path), "%s", buf+1);
60 snprintf(buf, sizeof(buf), "%s%s", temp_path, fname_to_utf8(temp_home_str));
62 return(buf);
63 #else /* UNIX */
64 struct passwd *pw;
65 register char *x,*y;
66 char name[20], *tbuf;
68 if(*buf == '~') {
69 for(x = buf+1, y = name;
70 *x != '/' && *x != '\0' && y < name + sizeof(name)-1;
71 *y++ = *x++)
74 *y = '\0';
75 if(x == buf + 1)
76 pw = getpwuid(getuid());
77 else
78 pw = getpwnam(name);
80 if(pw == NULL)
81 return((char *)NULL);
82 if(strlen(pw->pw_dir) + strlen(buf) > len) {
83 return((char *)NULL);
86 if((tbuf = (char *) malloc((len+1)*sizeof(char))) != NULL){
87 snprintf(tbuf, len, "%s%s", pw->pw_dir, x);
88 snprintf(buf, len, "%s", tbuf);
89 free((void *)tbuf);
93 return(len ? buf : (char *)NULL);
94 #endif /* UNIX */