2 * Copyright (c) 1993-1996,1998-2005, 2007-2013
3 * Todd C. Miller <Todd.Miller@courtesan.com>
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 * Sponsored in part by the Defense Advanced Research Projects
18 * Agency (DARPA) and Air Force Research Laboratory, Air Force
19 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
24 #include <sys/types.h>
33 #endif /* STDC_HEADERS */
36 #endif /* HAVE_STRING_H */
39 #endif /* HAVE_STRINGS_H */
46 * Expand %h and %u escapes in the prompt and pass back the dynamically
47 * allocated result. Returns the same string if there are no escapes.
50 expand_prompt(const char *old_prompt, const char *user, const char *host)
55 char *np, *new_prompt, *endp;
56 debug_decl(expand_prompt, SUDO_DEBUG_AUTH)
58 /* How much space do we need to malloc for the prompt? */
60 for (p = old_prompt, len = strlen(old_prompt); *p; p++) {
65 len += strlen(user_shost) - 2;
70 len += strlen(user_host) - 2;
77 else if (def_targetpw || def_runaspw)
78 len += strlen(runas_pw->pw_name) - 2;
80 len += strlen(user_name) - 2;
85 len += strlen(user_name) - 2;
90 len += strlen(runas_pw->pw_name) - 2;
105 new_prompt = emalloc(++len);
106 endp = new_prompt + len;
107 for (p = old_prompt, np = new_prompt; *p; p++) {
112 n = strlcpy(np, user_shost, np - endp);
119 n = strlcpy(np, user_host, np - endp);
127 n = strlcpy(np, "root", np - endp);
128 else if (def_targetpw || def_runaspw)
129 n = strlcpy(np, runas_pw->pw_name, np - endp);
131 n = strlcpy(np, user_name, np - endp);
138 n = strlcpy(np, user_name, np - endp);
145 n = strlcpy(np, runas_pw->pw_name, np - endp);
151 /* convert %% -> % */
165 new_prompt = estrdup(old_prompt);
167 debug_return_str(new_prompt);
170 /* We pre-allocate enough space, so this should never happen. */
171 fatalx(_("internal error, %s overflow"), "expand_prompt()");