xref: /netbsd-src/usr.bin/ftp/complete.c (revision 404fbe5fb94ca1e054339640cabb2801ce52dd30)
1 /*	$NetBSD: complete.c,v 1.44 2008/09/30 03:41:53 lukem Exp $	*/
2 
3 /*-
4  * Copyright (c) 1997-2008 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Luke Mewburn.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __RCSID("$NetBSD: complete.c,v 1.44 2008/09/30 03:41:53 lukem Exp $");
35 #endif /* not lint */
36 
37 /*
38  * FTP user program - command and file completion routines
39  */
40 
41 #include <sys/stat.h>
42 
43 #include <ctype.h>
44 #include <err.h>
45 #include <dirent.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 
50 #include "ftp_var.h"
51 
52 #ifndef NO_EDITCOMPLETE
53 
54 static int	     comparstr		(const void *, const void *);
55 static unsigned char complete_ambiguous	(char *, int, StringList *);
56 static unsigned char complete_command	(char *, int);
57 static unsigned char complete_local	(char *, int);
58 static unsigned char complete_option	(char *, int);
59 static unsigned char complete_remote	(char *, int);
60 
61 static int
62 comparstr(const void *a, const void *b)
63 {
64 	return (strcmp(*(const char * const *)a, *(const char * const *)b));
65 }
66 
67 /*
68  * Determine if complete is ambiguous. If unique, insert.
69  * If no choices, error. If unambiguous prefix, insert that.
70  * Otherwise, list choices. words is assumed to be filtered
71  * to only contain possible choices.
72  * Args:
73  *	word	word which started the match
74  *	list	list by default
75  *	words	stringlist containing possible matches
76  * Returns a result as per el_set(EL_ADDFN, ...)
77  */
78 static unsigned char
79 complete_ambiguous(char *word, int list, StringList *words)
80 {
81 	char insertstr[MAXPATHLEN];
82 	char *lastmatch, *p;
83 	int i, j;
84 	size_t matchlen, wordlen;
85 
86 	wordlen = strlen(word);
87 	if (words->sl_cur == 0)
88 		return (CC_ERROR);	/* no choices available */
89 
90 	if (words->sl_cur == 1) {	/* only once choice available */
91 		p = words->sl_str[0] + wordlen;
92 		if (*p == '\0')		/* at end of word? */
93 			return (CC_REFRESH);
94 		ftpvis(insertstr, sizeof(insertstr), p, strlen(p));
95 		if (el_insertstr(el, insertstr) == -1)
96 			return (CC_ERROR);
97 		else
98 			return (CC_REFRESH);
99 	}
100 
101 	if (!list) {
102 		matchlen = 0;
103 		lastmatch = words->sl_str[0];
104 		matchlen = strlen(lastmatch);
105 		for (i = 1 ; i < words->sl_cur ; i++) {
106 			for (j = wordlen ; j < strlen(words->sl_str[i]); j++)
107 				if (lastmatch[j] != words->sl_str[i][j])
108 					break;
109 			if (j < matchlen)
110 				matchlen = j;
111 		}
112 		if (matchlen > wordlen) {
113 			ftpvis(insertstr, sizeof(insertstr),
114 			    lastmatch + wordlen, matchlen - wordlen);
115 			if (el_insertstr(el, insertstr) == -1)
116 				return (CC_ERROR);
117 			else
118 				return (CC_REFRESH_BEEP);
119 		}
120 	}
121 
122 	putc('\n', ttyout);
123 	qsort(words->sl_str, words->sl_cur, sizeof(char *), comparstr);
124 	list_vertical(words);
125 	return (CC_REDISPLAY);
126 }
127 
128 /*
129  * Complete a command
130  */
131 static unsigned char
132 complete_command(char *word, int list)
133 {
134 	struct cmd *c;
135 	StringList *words;
136 	size_t wordlen;
137 	unsigned char rv;
138 
139 	words = ftp_sl_init();
140 	wordlen = strlen(word);
141 
142 	for (c = cmdtab; c->c_name != NULL; c++) {
143 		if (wordlen > strlen(c->c_name))
144 			continue;
145 		if (strncmp(word, c->c_name, wordlen) == 0)
146 			ftp_sl_add(words, c->c_name);
147 	}
148 
149 	rv = complete_ambiguous(word, list, words);
150 	if (rv == CC_REFRESH) {
151 		if (el_insertstr(el, " ") == -1)
152 			rv = CC_ERROR;
153 	}
154 	sl_free(words, 0);
155 	return (rv);
156 }
157 
158 /*
159  * Complete a local file
160  */
161 static unsigned char
162 complete_local(char *word, int list)
163 {
164 	StringList *words;
165 	char dir[MAXPATHLEN];
166 	char *file;
167 	DIR *dd;
168 	struct dirent *dp;
169 	unsigned char rv;
170 	size_t len;
171 
172 	if ((file = strrchr(word, '/')) == NULL) {
173 		dir[0] = '.';
174 		dir[1] = '\0';
175 		file = word;
176 	} else {
177 		if (file == word) {
178 			dir[0] = '/';
179 			dir[1] = '\0';
180 		} else
181 			(void)strlcpy(dir, word, file - word + 1);
182 		file++;
183 	}
184 	if (dir[0] == '~') {
185 		char *p;
186 
187 		if ((p = globulize(dir)) == NULL)
188 			return (CC_ERROR);
189 		(void)strlcpy(dir, p, sizeof(dir));
190 		free(p);
191 	}
192 
193 	if ((dd = opendir(dir)) == NULL)
194 		return (CC_ERROR);
195 
196 	words = ftp_sl_init();
197 	len = strlen(file);
198 
199 	for (dp = readdir(dd); dp != NULL; dp = readdir(dd)) {
200 		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
201 			continue;
202 
203 #if defined(DIRENT_MISSING_D_NAMLEN)
204 		if (len > strlen(dp->d_name))
205 			continue;
206 #else
207 		if (len > dp->d_namlen)
208 			continue;
209 #endif
210 		if (strncmp(file, dp->d_name, len) == 0) {
211 			char *tcp;
212 
213 			tcp = ftp_strdup(dp->d_name);
214 			ftp_sl_add(words, tcp);
215 		}
216 	}
217 	closedir(dd);
218 
219 	rv = complete_ambiguous(file, list, words);
220 	if (rv == CC_REFRESH) {
221 		struct stat sb;
222 		char path[MAXPATHLEN];
223 
224 		(void)strlcpy(path, dir,		sizeof(path));
225 		(void)strlcat(path, "/",		sizeof(path));
226 		(void)strlcat(path, words->sl_str[0],	sizeof(path));
227 
228 		if (stat(path, &sb) >= 0) {
229 			char suffix[2] = " ";
230 
231 			if (S_ISDIR(sb.st_mode))
232 				suffix[0] = '/';
233 			if (el_insertstr(el, suffix) == -1)
234 				rv = CC_ERROR;
235 		}
236 	}
237 	sl_free(words, 1);
238 	return (rv);
239 }
240 /*
241  * Complete an option
242  */
243 static unsigned char
244 complete_option(char *word, int list)
245 {
246 	struct option *o;
247 	StringList *words;
248 	size_t wordlen;
249 	unsigned char rv;
250 
251 	words = ftp_sl_init();
252 	wordlen = strlen(word);
253 
254 	for (o = optiontab; o->name != NULL; o++) {
255 		if (wordlen > strlen(o->name))
256 			continue;
257 		if (strncmp(word, o->name, wordlen) == 0)
258 			ftp_sl_add(words, o->name);
259 	}
260 
261 	rv = complete_ambiguous(word, list, words);
262 	if (rv == CC_REFRESH) {
263 		if (el_insertstr(el, " ") == -1)
264 			rv = CC_ERROR;
265 	}
266 	sl_free(words, 0);
267 	return (rv);
268 }
269 
270 /*
271  * Complete a remote file
272  */
273 static unsigned char
274 complete_remote(char *word, int list)
275 {
276 	static StringList *dirlist;
277 	static char	 lastdir[MAXPATHLEN];
278 	StringList	*words;
279 	char		 dir[MAXPATHLEN];
280 	char		*file, *cp;
281 	int		 i;
282 	unsigned char	 rv;
283 
284 	char *dummyargv[] = { "complete", NULL, NULL };
285 	dummyargv[1] = dir;
286 
287 	if ((file = strrchr(word, '/')) == NULL) {
288 		dir[0] = '\0';
289 		file = word;
290 	} else {
291 		cp = file;
292 		while (*cp == '/' && cp > word)
293 			cp--;
294 		(void)strlcpy(dir, word, cp - word + 2);
295 		file++;
296 	}
297 
298 	if (dirchange || dirlist == NULL ||
299 	    strcmp(dir, lastdir) != 0) {		/* dir not cached */
300 		const char *emesg;
301 
302 		if (dirlist != NULL)
303 			sl_free(dirlist, 1);
304 		dirlist = ftp_sl_init();
305 
306 		mflag = 1;
307 		emesg = NULL;
308 		while ((cp = remglob(dummyargv, 0, &emesg)) != NULL) {
309 			char *tcp;
310 
311 			if (!mflag)
312 				continue;
313 			if (*cp == '\0') {
314 				mflag = 0;
315 				continue;
316 			}
317 			tcp = strrchr(cp, '/');
318 			if (tcp)
319 				tcp++;
320 			else
321 				tcp = cp;
322 			tcp = ftp_strdup(tcp);
323 			ftp_sl_add(dirlist, tcp);
324 		}
325 		if (emesg != NULL) {
326 			fprintf(ttyout, "\n%s\n", emesg);
327 			return (CC_REDISPLAY);
328 		}
329 		(void)strlcpy(lastdir, dir, sizeof(lastdir));
330 		dirchange = 0;
331 	}
332 
333 	words = ftp_sl_init();
334 	for (i = 0; i < dirlist->sl_cur; i++) {
335 		cp = dirlist->sl_str[i];
336 		if (strlen(file) > strlen(cp))
337 			continue;
338 		if (strncmp(file, cp, strlen(file)) == 0)
339 			ftp_sl_add(words, cp);
340 	}
341 	rv = complete_ambiguous(file, list, words);
342 	sl_free(words, 0);
343 	return (rv);
344 }
345 
346 /*
347  * Generic complete routine
348  */
349 unsigned char
350 complete(EditLine *el, int ch)
351 {
352 	static char word[FTPBUFLEN];
353 	static int lastc_argc, lastc_argo;
354 
355 	struct cmd *c;
356 	const LineInfo *lf;
357 	int celems, dolist, cmpltype;
358 	size_t len;
359 
360 	lf = el_line(el);
361 	len = lf->lastchar - lf->buffer;
362 	if (len >= sizeof(line))
363 		return (CC_ERROR);
364 	(void)strlcpy(line, lf->buffer, len + 1);
365 	cursor_pos = line + (lf->cursor - lf->buffer);
366 	lastc_argc = cursor_argc;	/* remember last cursor pos */
367 	lastc_argo = cursor_argo;
368 	makeargv();			/* build argc/argv of current line */
369 
370 	if (cursor_argo >= sizeof(word))
371 		return (CC_ERROR);
372 
373 	dolist = 0;
374 			/* if cursor and word is same, list alternatives */
375 	if (lastc_argc == cursor_argc && lastc_argo == cursor_argo
376 	    && strncmp(word, margv[cursor_argc] ? margv[cursor_argc] : "",
377 			cursor_argo) == 0)
378 		dolist = 1;
379 	else if (cursor_argc < margc)
380 		(void)strlcpy(word, margv[cursor_argc], cursor_argo + 1);
381 	word[cursor_argo] = '\0';
382 
383 	if (cursor_argc == 0)
384 		return (complete_command(word, dolist));
385 
386 	c = getcmd(margv[0]);
387 	if (c == (struct cmd *)-1 || c == 0)
388 		return (CC_ERROR);
389 	celems = strlen(c->c_complete);
390 
391 		/* check for 'continuation' completes (which are uppercase) */
392 	if ((cursor_argc > celems) && (celems > 0)
393 	    && isupper((unsigned char) c->c_complete[celems-1]))
394 		cursor_argc = celems;
395 
396 	if (cursor_argc > celems)
397 		return (CC_ERROR);
398 
399 	cmpltype = c->c_complete[cursor_argc - 1];
400 	switch (cmpltype) {
401 		case 'c':			/* command complete */
402 		case 'C':
403 			return (complete_command(word, dolist));
404 		case 'l':			/* local complete */
405 		case 'L':
406 			return (complete_local(word, dolist));
407 		case 'n':			/* no complete */
408 		case 'N':			/* no complete */
409 			return (CC_ERROR);
410 		case 'o':			/* local complete */
411 		case 'O':
412 			return (complete_option(word, dolist));
413 		case 'r':			/* remote complete */
414 		case 'R':
415 			if (connected != -1) {
416 				fputs("\nMust be logged in to complete.\n",
417 				    ttyout);
418 				return (CC_REDISPLAY);
419 			}
420 			return (complete_remote(word, dolist));
421 		default:
422 			errx(1, "complete: unknown complete type `%c'",
423 			    cmpltype);
424 			return (CC_ERROR);
425 	}
426 	/* NOTREACHED */
427 }
428 
429 #endif /* !NO_EDITCOMPLETE */
430