Import of NetBSD's ftp client under its new name (tnftp)
[dragonfly.git] / contrib / tnftp / complete.c
1 /*      $NetBSD: complete.c,v 1.41 2006/01/31 20:01:23 christos Exp $   */
2
3 /*-
4  * Copyright (c) 1997-2000,2005 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  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the NetBSD
21  *      Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38
39 #include <sys/cdefs.h>
40 #ifndef lint
41 __RCSID("$NetBSD: complete.c,v 1.41 2006/01/31 20:01:23 christos Exp $");
42 #endif /* not lint */
43
44 /*
45  * FTP user program - command and file completion routines
46  */
47
48 #include <sys/stat.h>
49
50 #include <ctype.h>
51 #include <err.h>
52 #include <dirent.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56
57 #include "ftp_var.h"
58
59 #ifndef NO_EDITCOMPLETE
60
61 static int           comparstr          (const void *, const void *);
62 static unsigned char complete_ambiguous (char *, int, StringList *);
63 static unsigned char complete_command   (char *, int);
64 static unsigned char complete_local     (char *, int);
65 static unsigned char complete_option    (char *, int);
66 static unsigned char complete_remote    (char *, int);
67
68 static int
69 comparstr(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  */
85 static unsigned char
86 complete_ambiguous(char *word, int list, StringList *words)
87 {
88         char insertstr[MAXPATHLEN];
89         char *lastmatch, *p;
90         int 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  */
138 static unsigned char
139 complete_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, 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, 0);
162         return (rv);
163 }
164
165 /*
166  * Complete a local file
167  */
168 static unsigned char
169 complete_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  */
250 static unsigned char
251 complete_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, 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, 0);
274         return (rv);
275 }
276
277 /*
278  * Complete a remote file
279  */
280 static unsigned char
281 complete_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         int              i;
289         unsigned char    rv;
290
291         char *dummyargv[] = { "complete", NULL, NULL };
292         dummyargv[1] = dir;
293
294         if ((file = strrchr(word, '/')) == NULL) {
295                 dir[0] = '\0';
296                 file = word;
297         } else {
298                 cp = file;
299                 while (*cp == '/' && cp > word)
300                         cp--;
301                 (void)strlcpy(dir, word, cp - word + 2);
302                 file++;
303         }
304
305         if (dirchange || dirlist == NULL ||
306             strcmp(dir, lastdir) != 0) {                /* dir not cached */
307                 const char *emesg;
308
309                 if (dirlist != NULL)
310                         sl_free(dirlist, 1);
311                 dirlist = ftp_sl_init();
312
313                 mflag = 1;
314                 emesg = NULL;
315                 while ((cp = remglob(dummyargv, 0, &emesg)) != NULL) {
316                         char *tcp;
317
318                         if (!mflag)
319                                 continue;
320                         if (*cp == '\0') {
321                                 mflag = 0;
322                                 continue;
323                         }
324                         tcp = strrchr(cp, '/');
325                         if (tcp)
326                                 tcp++;
327                         else
328                                 tcp = cp;
329                         tcp = ftp_strdup(tcp);
330                         ftp_sl_add(dirlist, tcp);
331                 }
332                 if (emesg != NULL) {
333                         fprintf(ttyout, "\n%s\n", emesg);
334                         return (CC_REDISPLAY);
335                 }
336                 (void)strlcpy(lastdir, dir, sizeof(lastdir));
337                 dirchange = 0;
338         }
339
340         words = ftp_sl_init();
341         for (i = 0; i < dirlist->sl_cur; i++) {
342                 cp = dirlist->sl_str[i];
343                 if (strlen(file) > strlen(cp))
344                         continue;
345                 if (strncmp(file, cp, strlen(file)) == 0)
346                         ftp_sl_add(words, cp);
347         }
348         rv = complete_ambiguous(file, list, words);
349         sl_free(words, 0);
350         return (rv);
351 }
352
353 /*
354  * Generic complete routine
355  */
356 unsigned char
357 complete(EditLine *el, int ch)
358 {
359         static char word[FTPBUFLEN];
360         static int lastc_argc, lastc_argo;
361
362         struct cmd *c;
363         const LineInfo *lf;
364         int celems, dolist, cmpltype;
365         size_t len;
366
367         lf = el_line(el);
368         len = lf->lastchar - lf->buffer;
369         if (len >= sizeof(line))
370                 return (CC_ERROR);
371         (void)strlcpy(line, lf->buffer, len + 1);
372         cursor_pos = line + (lf->cursor - lf->buffer);
373         lastc_argc = cursor_argc;       /* remember last cursor pos */
374         lastc_argo = cursor_argo;
375         makeargv();                     /* build argc/argv of current line */
376
377         if (cursor_argo >= sizeof(word))
378                 return (CC_ERROR);
379
380         dolist = 0;
381                         /* if cursor and word is same, list alternatives */
382         if (lastc_argc == cursor_argc && lastc_argo == cursor_argo
383             && strncmp(word, margv[cursor_argc] ? margv[cursor_argc] : "",
384                         cursor_argo) == 0)
385                 dolist = 1;
386         else if (cursor_argc < margc)
387                 (void)strlcpy(word, margv[cursor_argc], cursor_argo + 1);
388         word[cursor_argo] = '\0';
389
390         if (cursor_argc == 0)
391                 return (complete_command(word, dolist));
392
393         c = getcmd(margv[0]);
394         if (c == (struct cmd *)-1 || c == 0)
395                 return (CC_ERROR);
396         celems = strlen(c->c_complete);
397
398                 /* check for 'continuation' completes (which are uppercase) */
399         if ((cursor_argc > celems) && (celems > 0)
400             && isupper((unsigned char) c->c_complete[celems-1]))
401                 cursor_argc = celems;
402
403         if (cursor_argc > celems)
404                 return (CC_ERROR);
405
406         cmpltype = c->c_complete[cursor_argc - 1];
407         switch (cmpltype) {
408                 case 'c':                       /* command complete */
409                 case 'C':
410                         return (complete_command(word, dolist));
411                 case 'l':                       /* local complete */
412                 case 'L':
413                         return (complete_local(word, dolist));
414                 case 'n':                       /* no complete */
415                 case 'N':                       /* no complete */
416                         return (CC_ERROR);
417                 case 'o':                       /* local complete */
418                 case 'O':
419                         return (complete_option(word, dolist));
420                 case 'r':                       /* remote complete */
421                 case 'R':
422                         if (connected != -1) {
423                                 fputs("\nMust be logged in to complete.\n",
424                                     ttyout);
425                                 return (CC_REDISPLAY);
426                         }
427                         return (complete_remote(word, dolist));
428                 default:
429                         errx(1, "unknown complete type `%c'", cmpltype);
430                         return (CC_ERROR);
431         }
432         /* NOTREACHED */
433 }
434
435 #endif /* !NO_EDITCOMPLETE */