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