Merge branch 'vendor/BINUTILS_ALL'
[dragonfly.git] / contrib / tnftp / complete.c
1 /*      $NetBSD: complete.c,v 1.46 2009/04/12 10:18:52 lukem Exp $      */
2
3 /*-
4  * Copyright (c) 1997-2009 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.46 2009/04/12 10:18:52 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         size_t 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, ftp_strdup(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, 1);
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, ftp_strdup(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, 1);
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         size_t           i;
282         unsigned char    rv;
283         char             cmdbuf[MAX_C_NAME];
284         char            *dummyargv[3] = { NULL, NULL, NULL };
285
286         (void)strlcpy(cmdbuf, "complete", sizeof(cmdbuf));
287         dummyargv[0] = cmdbuf;
288         dummyargv[1] = dir;
289
290         if ((file = strrchr(word, '/')) == NULL) {
291                 dir[0] = '\0';
292                 file = word;
293         } else {
294                 cp = file;
295                 while (*cp == '/' && cp > word)
296                         cp--;
297                 (void)strlcpy(dir, word, cp - word + 2);
298                 file++;
299         }
300
301         if (dirchange || dirlist == NULL ||
302             strcmp(dir, lastdir) != 0) {                /* dir not cached */
303                 const char *emesg;
304
305                 if (dirlist != NULL)
306                         sl_free(dirlist, 1);
307                 dirlist = ftp_sl_init();
308
309                 mflag = 1;
310                 emesg = NULL;
311                 while ((cp = remglob(dummyargv, 0, &emesg)) != NULL) {
312                         char *tcp;
313
314                         if (!mflag)
315                                 continue;
316                         if (*cp == '\0') {
317                                 mflag = 0;
318                                 continue;
319                         }
320                         tcp = strrchr(cp, '/');
321                         if (tcp)
322                                 tcp++;
323                         else
324                                 tcp = cp;
325                         tcp = ftp_strdup(tcp);
326                         ftp_sl_add(dirlist, tcp);
327                 }
328                 if (emesg != NULL) {
329                         fprintf(ttyout, "\n%s\n", emesg);
330                         return (CC_REDISPLAY);
331                 }
332                 (void)strlcpy(lastdir, dir, sizeof(lastdir));
333                 dirchange = 0;
334         }
335
336         words = ftp_sl_init();
337         for (i = 0; i < dirlist->sl_cur; i++) {
338                 cp = dirlist->sl_str[i];
339                 if (strlen(file) > strlen(cp))
340                         continue;
341                 if (strncmp(file, cp, strlen(file)) == 0)
342                         ftp_sl_add(words, cp);
343         }
344         rv = complete_ambiguous(file, list, words);
345         sl_free(words, 0);
346         return (rv);
347 }
348
349 /*
350  * Generic complete routine
351  */
352 unsigned char
353 complete(EditLine *cel, int ch)
354 {
355         static char word[FTPBUFLEN];
356         static size_t lastc_argc, lastc_argo;
357
358         struct cmd *c;
359         const LineInfo *lf;
360         int dolist, cmpltype;
361         size_t celems, len;
362
363         lf = el_line(cel);
364         len = lf->lastchar - lf->buffer;
365         if (len >= sizeof(line))
366                 return (CC_ERROR);
367         (void)strlcpy(line, lf->buffer, len + 1);
368         cursor_pos = line + (lf->cursor - lf->buffer);
369         lastc_argc = cursor_argc;       /* remember last cursor pos */
370         lastc_argo = cursor_argo;
371         makeargv();                     /* build argc/argv of current line */
372
373         if (cursor_argo >= sizeof(word))
374                 return (CC_ERROR);
375
376         dolist = 0;
377                         /* if cursor and word is same, list alternatives */
378         if (lastc_argc == cursor_argc && lastc_argo == cursor_argo
379             && strncmp(word, margv[cursor_argc] ? margv[cursor_argc] : "",
380                         cursor_argo) == 0)
381                 dolist = 1;
382         else if (cursor_argc < (size_t)margc)
383                 (void)strlcpy(word, margv[cursor_argc], cursor_argo + 1);
384         word[cursor_argo] = '\0';
385
386         if (cursor_argc == 0)
387                 return (complete_command(word, dolist));
388
389         c = getcmd(margv[0]);
390         if (c == (struct cmd *)-1 || c == 0)
391                 return (CC_ERROR);
392         celems = strlen(c->c_complete);
393
394                 /* check for 'continuation' completes (which are uppercase) */
395         if ((cursor_argc > celems) && (celems > 0)
396             && isupper((unsigned char) c->c_complete[celems-1]))
397                 cursor_argc = celems;
398
399         if (cursor_argc > celems)
400                 return (CC_ERROR);
401
402         cmpltype = c->c_complete[cursor_argc - 1];
403         switch (cmpltype) {
404                 case 'c':                       /* command complete */
405                 case 'C':
406                         return (complete_command(word, dolist));
407                 case 'l':                       /* local complete */
408                 case 'L':
409                         return (complete_local(word, dolist));
410                 case 'n':                       /* no complete */
411                 case 'N':                       /* no complete */
412                         return (CC_ERROR);
413                 case 'o':                       /* local complete */
414                 case 'O':
415                         return (complete_option(word, dolist));
416                 case 'r':                       /* remote complete */
417                 case 'R':
418                         if (connected != -1) {
419                                 fputs("\nMust be logged in to complete.\n",
420                                     ttyout);
421                                 return (CC_REDISPLAY);
422                         }
423                         return (complete_remote(word, dolist));
424                 default:
425                         errx(1, "complete: unknown complete type `%c'",
426                             cmpltype);
427                         return (CC_ERROR);
428         }
429         /* NOTREACHED */
430 }
431
432 #endif /* !NO_EDITCOMPLETE */