1 /* $NetBSD: util.c,v 1.25 2021/08/27 01:38:49 lukem Exp $ */
2 /* from NetBSD: util.c,v 1.162 2021/04/25 08:26:35 lukem Exp */
5 * Copyright (c) 1997-2020 The NetBSD Foundation, Inc.
8 * This code is derived from software contributed to The NetBSD Foundation
11 * This code is derived from software contributed to The NetBSD Foundation
12 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
13 * NASA Ames Research Center.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
24 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
25 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
26 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
28 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 * POSSIBILITY OF SUCH DAMAGE.
38 * Copyright (c) 1985, 1989, 1993, 1994
39 * The Regents of the University of California. All rights reserved.
41 * Redistribution and use in source and binary forms, with or without
42 * modification, are permitted provided that the following conditions
44 * 1. Redistributions of source code must retain the above copyright
45 * notice, this list of conditions and the following disclaimer.
46 * 2. Redistributions in binary form must reproduce the above copyright
47 * notice, this list of conditions and the following disclaimer in the
48 * documentation and/or other materials provided with the distribution.
49 * 3. Neither the name of the University nor the names of its contributors
50 * may be used to endorse or promote products derived from this software
51 * without specific prior written permission.
53 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
70 #include <sys/cdefs.h>
72 __RCSID(" NetBSD: util.c,v 1.162 2021/04/25 08:26:35 lukem Exp ");
76 * FTP User Program -- Misc support routines
78 #include <sys/param.h>
79 #include <sys/socket.h>
80 #include <sys/ioctl.h>
82 #include <netinet/in.h>
108 * Connect to peer server and auto-login, if possible.
111 setpeer(int argc
, char *argv
[])
119 fprintf(ttyout
, "Already connected to %s, use close first.\n",
125 (void)another(&argc
, &argv
, "to");
126 if (argc
< 2 || argc
> 3) {
128 UPRINTF("usage: %s host-name [port]\n", argv
[0]);
140 if (gateserver
== NULL
|| *gateserver
== '\0')
141 errx(1, "main: gateserver not defined");
142 host
= hookup(gateserver
, port
);
144 host
= hookup(argv
[1], port
);
147 if (gatemode
&& verbose
) {
149 "Connecting via pass-through server %s\n",
155 * Set up defaults for FTP.
157 (void)strlcpy(typename
, "ascii", sizeof(typename
));
160 (void)strlcpy(formname
, "non-print", sizeof(formname
));
162 (void)strlcpy(modename
, "stream", sizeof(modename
));
164 (void)strlcpy(structname
, "file", sizeof(structname
));
166 (void)strlcpy(bytename
, "8", sizeof(bytename
));
169 (void)ftp_login(argv
[1], NULL
, NULL
);
174 parse_feat(const char *fline
)
178 * work-around broken ProFTPd servers that can't
179 * even obey RFC 2389.
181 while (*fline
&& isspace((int)*fline
))
184 if (strcasecmp(fline
, "MDTM") == 0)
185 features
[FEAT_MDTM
] = 1;
186 else if (strncasecmp(fline
, "MLST", sizeof("MLST") - 1) == 0) {
187 features
[FEAT_MLST
] = 1;
188 } else if (strcasecmp(fline
, "REST STREAM") == 0)
189 features
[FEAT_REST_STREAM
] = 1;
190 else if (strcasecmp(fline
, "SIZE") == 0)
191 features
[FEAT_SIZE
] = 1;
192 else if (strcasecmp(fline
, "TVFS") == 0)
193 features
[FEAT_TVFS
] = 1;
197 * Determine the remote system type (SYST) and features (FEAT).
198 * Call after a successful login (i.e, connected = -1)
209 /* determine remote system type */
210 if (command("SYST") == COMPLETE
) {
212 int os_len
= strcspn(reply_string
+ 4, " \r\n\t");
213 if (os_len
> 1 && reply_string
[4 + os_len
- 1] == '.')
215 fprintf(ttyout
, "Remote system type is %.*s.\n",
216 os_len
, reply_string
+ 4);
219 * Decide whether we should default to bninary.
220 * Traditionally checked for "215 UNIX Type: L8", but
221 * some printers report "Linux" ! so be more forgiving.
222 * In reality we probably almost never want text any more.
224 if (!strncasecmp(reply_string
+ 4, "unix", 4) ||
225 !strncasecmp(reply_string
+ 4, "linux", 5)) {
231 * Set type to 0 (not specified by user),
232 * meaning binary by default, but don't bother
233 * telling server. We can use binary
234 * for text files unless changed by the user.
237 (void)strlcpy(typename
, "binary", sizeof(typename
));
240 "Using %s mode to transfer files.\n",
248 !strncmp(reply_string
, "215 TOPS20", 10))
250 "Remember to set tenex mode when transferring binary files from this machine.\n",
255 /* determine features (if any) */
256 for (i
= 0; i
< FEAT_max
; i
++)
258 reply_callback
= parse_feat
;
259 if (command("FEAT") == COMPLETE
) {
260 for (i
= 0; i
< FEAT_max
; i
++) {
261 if (features
[i
] == -1)
264 features
[FEAT_FEAT
] = 1;
266 features
[FEAT_FEAT
] = 0;
269 #define DEBUG_FEAT(x) fprintf(ttyout, "features[" #x "] = %d\n", features[(x)])
270 DEBUG_FEAT(FEAT_FEAT
);
271 DEBUG_FEAT(FEAT_MDTM
);
272 DEBUG_FEAT(FEAT_MLST
);
273 DEBUG_FEAT(FEAT_REST_STREAM
);
274 DEBUG_FEAT(FEAT_SIZE
);
275 DEBUG_FEAT(FEAT_TVFS
);
279 reply_callback
= NULL
;
285 * Reset the various variables that indicate connection state back to
286 * disconnected settings.
287 * The caller is responsible for issuing any commands to the remote server
288 * to perform a clean shutdown before this is invoked.
301 * determine if anonftp was specifically set with -a
302 * (1), or implicitly set by auto_fetch() (2). in the
303 * latter case, disable after the current xfer
318 * Top-level signal handler for interrupted commands.
327 write(fileno(ttyout
), "\n", 1);
328 siglongjmp(toplevel
, 1);
332 * Signal handler for lost connections; cleanup various elements of
333 * the connection state, and call cleanuppeer() to finish it off.
334 * This function is not signal safe, so exit if called by a signal.
344 (void)shutdown(fileno(cout
), 1+1);
349 (void)shutdown(data
, 1+1);
358 (void)shutdown(fileno(cout
), 1+1);
368 errx(1, "lostpeer due to signal %d", signo
);
375 * Login to remote host, using given username & password if supplied.
376 * Return non-zero if successful.
379 ftp_login(const char *host
, const char *luser
, const char *lpass
)
382 char *fuser
, *pass
, *facct
, *p
;
383 char emptypass
[] = "";
384 const char *errormsg
;
385 int n
, aflag
, rval
, nlen
;
388 fuser
= pass
= facct
= NULL
;
390 fuser
= ftp_strdup(luser
);
392 pass
= ftp_strdup(lpass
);
394 DPRINTF("ftp_login: user `%s' pass `%s' host `%s'\n",
395 STRorNULL(fuser
), STRorNULL(pass
), STRorNULL(host
));
398 * Set up arguments for an anonymous FTP session, if necessary.
402 fuser
= ftp_strdup("anonymous"); /* as per RFC 1635 */
404 pass
= ftp_strdup(getoptionvalue("anonpass"));
407 if (ruserpass(host
, &fuser
, &pass
, &facct
) < 0) {
409 goto cleanup_ftp_login
;
412 while (fuser
== NULL
) {
414 fprintf(ttyout
, "Name (%s:%s): ", host
, localname
);
416 fprintf(ttyout
, "Name (%s): ", host
);
418 nlen
= get_line(stdin
, tmp
, sizeof(tmp
), &errormsg
);
420 fprintf(ttyout
, "%s; %s aborted.\n", errormsg
, "login");
422 goto cleanup_ftp_login
;
423 } else if (nlen
== 0) {
424 fuser
= ftp_strdup(localname
);
426 fuser
= ftp_strdup(tmp
);
434 len
= strlen(fuser
) + 1 + strlen(host
) + 1;
435 nuser
= ftp_malloc(len
);
436 (void)strlcpy(nuser
, fuser
, len
);
437 (void)strlcat(nuser
, "@", len
);
438 (void)strlcat(nuser
, host
, len
);
443 n
= command("USER %s", fuser
);
446 p
= getpass("Password: ");
449 pass
= ftp_strdup(p
);
450 memset(p
, 0, strlen(p
));
452 n
= command("PASS %s", pass
);
453 memset(pass
, 0, strlen(pass
));
458 p
= getpass("Account: ");
461 facct
= ftp_strdup(p
);
462 memset(p
, 0, strlen(p
));
464 if (facct
[0] == '\0') {
465 warnx("Login failed");
466 goto cleanup_ftp_login
;
468 n
= command("ACCT %s", facct
);
469 memset(facct
, 0, strlen(facct
));
471 if ((n
!= COMPLETE
) ||
472 (!aflag
&& facct
!= NULL
&& command("ACCT %s", facct
) != COMPLETE
)) {
473 warnx("Login failed");
474 goto cleanup_ftp_login
;
477 username
= ftp_strdup(fuser
);
479 goto cleanup_ftp_login
;
483 for (n
= 0; n
< macnum
; ++n
) {
484 if (!strcmp("init", macros
[n
].mac_name
)) {
485 (void)strlcpy(line
, "$init", sizeof(line
));
487 domacro(margc
, margv
);
498 memset(pass
, 0, strlen(pass
));
501 memset(facct
, 0, strlen(facct
));
507 * `another' gets another argument, and stores the new argc and argv.
508 * It reverts to the top level (via intr()) on EOF/error.
510 * Returns false if no new arguments have been added.
513 another(int *pargc
, char ***pargv
, const char *aprompt
)
515 const char *errormsg
;
520 if (len
>= sizeof(line
) - 3) {
521 fputs("Sorry, arguments too long.\n", ttyout
);
524 fprintf(ttyout
, "(%s) ", aprompt
);
527 nlen
= get_line(stdin
, line
+ len
, sizeof(line
)-len
, &errormsg
);
529 fprintf(ttyout
, "%s; %s aborted.\n", errormsg
, "operation");
534 ret
= margc
> *pargc
;
541 * glob files given in argv[] from the remote server.
542 * if errbuf isn't NULL, store error messages there instead
543 * of writing to the screen.
546 remglob(char *argv
[], int doswitch
, const char **errbuf
)
548 static char buf
[MAXPATHLEN
];
549 static FILE *ftemp
= NULL
;
551 char temp
[MAXPATHLEN
];
552 int oldverbose
, oldhash
, oldprogress
, fd
;
557 if (!mflag
|| !connected
) {
571 if ((cp
= *++args
) == NULL
)
576 len
= strlcpy(temp
, tmpdir
, sizeof(temp
));
577 if (temp
[len
- 1] != '/')
578 (void)strlcat(temp
, "/", sizeof(temp
));
579 (void)strlcat(temp
, TMPFILE
, sizeof(temp
));
580 if ((fd
= mkstemp(temp
)) < 0) {
581 warn("Unable to create temporary file `%s'", temp
);
585 oldverbose
= verbose
;
586 verbose
= (errbuf
!= NULL
) ? -1 : 0;
588 oldprogress
= progress
;
593 for (rmode
= "w"; *++argv
!= NULL
; rmode
= "a")
594 recvrequest("NLST", temp
, *argv
, rmode
, 0, 0);
595 if ((code
/ 100) != COMPLETE
) {
597 *errbuf
= reply_string
;
601 verbose
= oldverbose
;
603 progress
= oldprogress
;
604 ftemp
= fopen(temp
, "r");
608 warnx("Can't find list of remote files");
611 "Can't find list of remote files";
615 if (fgets(buf
, sizeof(buf
), ftemp
) == NULL
) {
620 if ((cp
= strchr(buf
, '\n')) != NULL
)
626 * Glob a local file name specification with the expectation of a single
627 * return value. Can't control multiple values being expanded from the
628 * expression, we return only the first.
629 * Returns NULL on error, or a pointer to a buffer containing the filename
630 * that's the caller's responsiblity to free(3) when finished with.
633 globulize(const char *pattern
)
640 return (ftp_strdup(pattern
));
642 flags
= GLOB_BRACE
|GLOB_NOCHECK
|GLOB_TILDE
;
643 memset(&gl
, 0, sizeof(gl
));
644 if (glob(pattern
, flags
, NULL
, &gl
) || gl
.gl_pathc
== 0) {
645 warnx("Glob pattern `%s' not found", pattern
);
649 p
= ftp_strdup(gl
.gl_pathv
[0]);
655 * determine size of remote file
658 remotesize(const char *file
, int noisy
)
667 if (! features
[FEAT_SIZE
]) {
670 "SIZE is not supported by remote server.\n");
671 goto cleanup_remotesize
;
673 r
= command("SIZE %s", file
);
677 cp
= strchr(reply_string
, ' ');
680 size
= STRTOLL(cp
, &ep
, 10);
681 if (*ep
!= '\0' && !isspace((unsigned char)*ep
))
685 if (r
== ERROR
&& code
== 500 && features
[FEAT_SIZE
] == -1)
686 features
[FEAT_SIZE
] = 0;
687 if (noisy
&& ftp_debug
== 0) {
688 fputs(reply_string
, ttyout
);
698 * determine last modification time (in GMT) of remote file
701 remotemodtime(const char *file
, int noisy
)
703 int overbose
, ocode
, r
;
711 if (! features
[FEAT_MDTM
]) {
714 "MDTM is not supported by remote server.\n");
715 goto cleanup_parse_time
;
717 r
= command("MDTM %s", file
);
720 char *timestr
, *frac
;
723 * time-val = 14DIGIT [ "." 1*DIGIT ]
724 * YYYYMMDDHHMMSS[.sss]
725 * mdtm-response = "213" SP time-val CRLF / error-response
727 timestr
= reply_string
+ 4;
731 * XXX: ignored for now
733 frac
= strchr(timestr
, '\r');
736 frac
= strchr(timestr
, '.');
739 if (strlen(timestr
) == 15 && strncmp(timestr
, "191", 3) == 0) {
741 * XXX: Workaround for buggy ftp servers that return
742 * `19100' instead of `2000'
745 "Y2K warning! Incorrect time-val `%s' received from server.\n",
750 fprintf(ttyout
, "Converted to `%s'\n", timestr
);
752 memset(&timebuf
, 0, sizeof(timebuf
));
753 if (strlen(timestr
) != 14 ||
754 (strptime(timestr
, "%Y%m%d%H%M%S", &timebuf
) == NULL
)) {
756 fprintf(ttyout
, "Can't parse time `%s'.\n", timestr
);
757 goto cleanup_parse_time
;
759 timebuf
.tm_isdst
= -1;
760 rtime
= timegm(&timebuf
);
762 if (noisy
|| ftp_debug
!= 0)
765 goto cleanup_parse_time
;
767 DPRINTF("remotemodtime: parsed time `%s' as " LLF
770 rfc2822time(localtime(&rtime
)));
773 if (r
== ERROR
&& code
== 500 && features
[FEAT_MDTM
] == -1)
774 features
[FEAT_MDTM
] = 0;
775 if (noisy
&& ftp_debug
== 0) {
776 fputs(reply_string
, ttyout
);
788 * Format tm in an RFC 2822 compatible manner, with a trailing \n.
789 * Returns a pointer to a static string containing the result.
792 rfc2822time(const struct tm
*tm
)
794 static char result
[50];
796 if (strftime(result
, sizeof(result
),
797 "%a, %d %b %Y %H:%M:%S %z\n", tm
) == 0)
798 errx(1, "Can't convert RFC 2822 time: buffer too small");
803 * Parse HTTP-date as per RFC 2616.
804 * Return a pointer to the next character of the consumed date string,
808 parse_rfc2616time(struct tm
*parsed
, const char *httpdate
)
811 #if defined(HAVE_SETLOCALE)
812 const char *curlocale
;
814 /* The representation of %a depends on the current locale. */
815 curlocale
= setlocale(LC_TIME
, NULL
);
816 (void)setlocale(LC_TIME
, "C");
819 if ((t
= strptime(httpdate
, "%a, %d %b %Y %H:%M:%S GMT", parsed
)) ||
821 (t
= strptime(httpdate
, "%a, %d-%b-%y %H:%M:%S GMT", parsed
)) ||
823 (t
= strptime(httpdate
, "%a, %b %d %H:%M:%S %Y", parsed
))) {
826 #if defined(HAVE_SETLOCALE)
827 (void)setlocale(LC_TIME
, curlocale
);
833 * Update global `localcwd', which contains the state of the local cwd
839 if (getcwd(localcwd
, sizeof(localcwd
)) == NULL
)
841 DPRINTF("updatelocalcwd: got `%s'\n", localcwd
);
845 * Update global `remotecwd', which contains the state of the remote cwd
848 updateremotecwd(void)
854 remcwdvalid
= 1; /* whether it works or not, we are done */
859 if (command("PWD") != COMPLETE
)
861 cp
= strchr(reply_string
, ' ');
862 if (cp
== NULL
|| cp
[0] == '\0' || cp
[1] != '"')
865 for (i
= 0; *cp
&& i
< sizeof(remotecwd
) - 1; i
++, cp
++) {
875 DPRINTF("updateremotecwd: got `%s'\n", remotecwd
);
876 goto cleanupremotecwd
;
885 * Ensure file is in or under dir.
886 * Returns 1 if so, 0 if not (or an error occurred).
889 fileindir(const char *file
, const char *dir
)
891 char parentdirbuf
[PATH_MAX
+1], *parentdir
;
892 char realdir
[PATH_MAX
+1];
895 /* determine parent directory of file */
896 (void)strlcpy(parentdirbuf
, file
, sizeof(parentdirbuf
));
897 parentdir
= dirname(parentdirbuf
);
898 if (strcmp(parentdir
, ".") == 0)
899 return 1; /* current directory is ok */
901 /* find the directory */
902 if (realpath(parentdir
, realdir
) == NULL
) {
903 warn("Unable to determine real path of `%s'", parentdir
);
906 if (realdir
[0] != '/') /* relative result is ok */
908 dirlen
= strlen(dir
);
909 if (strncmp(realdir
, dir
, dirlen
) == 0 &&
910 (realdir
[dirlen
] == '/' || realdir
[dirlen
] == '\0'))
916 * List words in stringlist, vertically arranged
919 list_vertical(StringList
*sl
)
922 size_t columns
, lines
;
928 for (i
= 0 ; i
< sl
->sl_cur
; i
++) {
929 w
= strlen(sl
->sl_str
[i
]);
933 width
= (width
+ 8) &~ 7;
935 columns
= ttywidth
/ width
;
938 lines
= (sl
->sl_cur
+ columns
- 1) / columns
;
939 for (i
= 0; i
< lines
; i
++) {
940 for (j
= 0; j
< columns
; j
++) {
941 p
= sl
->sl_str
[j
* lines
+ i
];
944 if (j
* lines
+ i
+ lines
>= sl
->sl_cur
) {
952 (void)putc('\t', ttyout
);
960 * Update the global ttywidth value, using TIOCGWINSZ.
965 struct winsize winsize
;
968 if (ioctl(fileno(ttyout
), TIOCGWINSZ
, &winsize
) != -1 &&
970 ttywidth
= winsize
.ws_col
;
977 * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
986 rate_get
+= rate_get_incr
;
988 rate_put
+= rate_put_incr
;
991 if (rate_get
&& rate_get
> rate_get_incr
)
992 rate_get
-= rate_get_incr
;
993 if (rate_put
&& rate_put
> rate_put_incr
)
994 rate_put
-= rate_put_incr
;
997 err(1, "crankrate invoked with unknown signal: %d", sig
);
1003 * Setup or cleanup EditLine structures
1005 #ifndef NO_EDITCOMPLETE
1007 controlediting(void)
1009 if (editing
&& el
== NULL
&& hist
== NULL
) {
1013 el
= el_init(getprogname(), stdin
, ttyout
, stderr
);
1015 hist
= history_init(); /* init the builtin history */
1016 history(hist
, &ev
, H_SETSIZE
, 100);/* remember 100 events */
1017 el_set(el
, EL_HIST
, history
, hist
); /* use history */
1019 el_set(el
, EL_EDITOR
, "emacs"); /* default editor is emacs */
1020 el_set(el
, EL_PROMPT
, prompt
); /* set the prompt functions */
1021 el_set(el
, EL_RPROMPT
, rprompt
);
1023 /* add local file completion, bind to TAB */
1024 el_set(el
, EL_ADDFN
, "ftp-complete",
1025 "Context sensitive argument completion",
1027 el_set(el
, EL_BIND
, "^I", "ftp-complete", NULL
);
1028 el_source(el
, NULL
); /* read ~/.editrc */
1029 if ((el_get(el
, EL_EDITMODE
, &editmode
) != -1) && editmode
== 0)
1030 editing
= 0; /* the user doesn't want editing,
1031 * so disable, and let statement
1034 el_set(el
, EL_SIGNAL
, 1);
1047 #endif /* !NO_EDITCOMPLETE */
1050 * Convert the string `arg' to an int, which may have an optional SI suffix
1051 * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
1054 strsuftoi(const char *arg
)
1059 if (!isdigit((unsigned char)arg
[0]))
1062 val
= strtol(arg
, &cp
, 10);
1064 if (cp
[0] != '\0' && cp
[1] != '\0')
1066 switch (tolower((unsigned char)cp
[0])) {
1083 if (val
< 0 || val
> INT_MAX
)
1090 * Set up socket buffer sizes before a connection is made.
1093 setupsockbufsize(int sock
)
1097 if (0 == rcvbuf_size
) {
1098 slen
= sizeof(rcvbuf_size
);
1099 if (getsockopt(sock
, SOL_SOCKET
, SO_RCVBUF
,
1100 (void *)&rcvbuf_size
, &slen
) == -1)
1101 err(1, "Unable to determine rcvbuf size");
1102 if (rcvbuf_size
<= 0)
1103 rcvbuf_size
= 8 * 1024;
1104 if (rcvbuf_size
> 8 * 1024 * 1024)
1105 rcvbuf_size
= 8 * 1024 * 1024;
1106 DPRINTF("setupsockbufsize: rcvbuf_size determined as %d\n",
1109 if (0 == sndbuf_size
) {
1110 slen
= sizeof(sndbuf_size
);
1111 if (getsockopt(sock
, SOL_SOCKET
, SO_SNDBUF
,
1112 (void *)&sndbuf_size
, &slen
) == -1)
1113 err(1, "Unable to determine sndbuf size");
1114 if (sndbuf_size
<= 0)
1115 sndbuf_size
= 8 * 1024;
1116 if (sndbuf_size
> 8 * 1024 * 1024)
1117 sndbuf_size
= 8 * 1024 * 1024;
1118 DPRINTF("setupsockbufsize: sndbuf_size determined as %d\n",
1122 if (setsockopt(sock
, SOL_SOCKET
, SO_SNDBUF
,
1123 (void *)&sndbuf_size
, sizeof(sndbuf_size
)) == -1)
1124 warn("Unable to set sndbuf size %d", sndbuf_size
);
1126 if (setsockopt(sock
, SOL_SOCKET
, SO_RCVBUF
,
1127 (void *)&rcvbuf_size
, sizeof(rcvbuf_size
)) == -1)
1128 warn("Unable to set rcvbuf size %d", rcvbuf_size
);
1132 * Copy characters from src into dst, \ quoting characters that require it
1135 ftpvis(char *dst
, size_t dstlen
, const char *src
, size_t srclen
)
1140 while (src
[si
] != '\0' && di
< dstlen
&& si
< srclen
) {
1149 * Need room for two characters and NUL, avoiding
1150 * incomplete escape sequences at end of dst.
1152 if (di
>= dstlen
- 3)
1157 dst
[di
] = src
[si
++];
1166 * Copy src into buf (which is len bytes long), expanding % sequences.
1169 formatbuf(char *buf
, size_t len
, const char *src
)
1171 const char *p
, *p2
, *q
;
1173 int op
, updirs
, pdirs
;
1175 #define ADDBUF(x) do { \
1182 for (i
= 0; *p
; p
++) {
1194 if (connected
&& !remcwdvalid
)
1196 p2
= connected
? remotecwd
: "";
1199 /* option to determine fixed # of dirs from path */
1200 if (op
== '.' || op
== 'c') {
1204 while (*p2
) /* calc # of /'s */
1207 if (p
[1] == '0') { /* print <x> or ... */
1211 if (p
[1] >= '1' && p
[1] <= '9') {
1212 /* calc # to skip */
1219 while (skip
-- > 0) {
1220 while ((p2
> q
) && (*p2
!= '/'))
1225 if (*p2
== '/' && p2
!= q
)
1229 if (updirs
> 0 && pdirs
) {
1243 ADDBUF('0' + updirs
);
1253 for (p2
= connected
&& hostname
? hostname
: "-";
1255 if (op
== 'm' && *p2
== '.')
1262 for (p2
= connected
? username
: "-"; *p2
; p2
++)
1270 default: /* display unknown codes literally */
1282 * Determine if given string is an IPv6 address or not.
1283 * Return 1 for yes, 0 for no
1286 isipv6addr(const char *addr
)
1290 struct addrinfo hints
, *res
;
1292 memset(&hints
, 0, sizeof(hints
));
1293 hints
.ai_family
= AF_INET6
;
1294 hints
.ai_socktype
= SOCK_DGRAM
; /*dummy*/
1295 hints
.ai_flags
= AI_NUMERICHOST
;
1296 if (getaddrinfo(addr
, "0", &hints
, &res
) != 0)
1302 DPRINTF("isipv6addr: got %d for %s\n", rv
, addr
);
1304 return (rv
== 1) ? 1 : 0;
1308 * Read a line from the FILE stream into buf/buflen using fgets(), so up
1309 * to buflen-1 chars will be read and the result will be NUL terminated.
1310 * If the line has a trailing newline it will be removed.
1311 * If the line is too long, excess characters will be read until
1312 * newline/EOF/error.
1313 * If EOF/error occurs or a too-long line is encountered and errormsg
1314 * isn't NULL, it will be changed to a description of the problem.
1315 * (The EOF message has a leading \n for cosmetic purposes).
1317 * >=0 length of line (excluding trailing newline) if all ok
1319 * -2 EOF encountered
1320 * -3 line was too long
1323 get_line(FILE *stream
, char *buf
, size_t buflen
, const char **errormsg
)
1328 if (fgets(buf
, buflen
, stream
) == NULL
) {
1329 if (feof(stream
)) { /* EOF */
1332 *errormsg
= "\nEOF received";
1333 } else { /* error */
1336 *errormsg
= "Error encountered";
1342 if (buf
[len
-1] == '\n') { /* clear any trailing newline */
1344 } else if (len
== buflen
-1) { /* line too long */
1345 while ((ch
= getchar()) != '\n' && ch
!= EOF
)
1348 *errormsg
= "Input line is too long";
1358 * Internal version of connect(2); sets socket buffer sizes,
1359 * binds to a specific local address (if set), and
1360 * supports a connection timeout using a non-blocking connect(2) with
1362 * Socket fcntl flags are temporarily updated to include O_NONBLOCK;
1363 * these will not be reverted on connection failure.
1364 * Returns 0 on success, or -1 upon failure (with an appropriate
1365 * error message displayed.)
1368 ftp_connect(int sock
, const struct sockaddr
*name
, socklen_t namelen
, int pe
)
1370 int flags
, rv
, timeout
, error
;
1372 struct timeval endtime
, now
, td
;
1373 struct pollfd pfd
[1];
1374 char hname
[NI_MAXHOST
];
1375 char sname
[NI_MAXSERV
];
1377 setupsockbufsize(sock
);
1378 if (getnameinfo(name
, namelen
,
1379 hname
, sizeof(hname
), sname
, sizeof(sname
),
1380 NI_NUMERICHOST
| NI_NUMERICSERV
) != 0) {
1381 strlcpy(hname
, "?", sizeof(hname
));
1382 strlcpy(sname
, "?", sizeof(sname
));
1385 if (bindai
!= NULL
) { /* bind to specific addr */
1386 struct addrinfo
*ai
;
1388 for (ai
= bindai
; ai
!= NULL
; ai
= ai
->ai_next
) {
1389 if (ai
->ai_family
== name
->sa_family
)
1394 if (bind(sock
, ai
->ai_addr
, ai
->ai_addrlen
) == -1) {
1395 char bname
[NI_MAXHOST
];
1399 if (getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
,
1400 bname
, sizeof(bname
), NULL
, 0, NI_NUMERICHOST
) != 0)
1401 strlcpy(bname
, "?", sizeof(bname
));
1403 warn("Can't bind to `%s'", bname
);
1408 /* save current socket flags */
1409 if ((flags
= fcntl(sock
, F_GETFL
, 0)) == -1) {
1410 warn("Can't %s socket flags for connect to `%s:%s'",
1411 "save", hname
, sname
);
1414 /* set non-blocking connect */
1415 if (fcntl(sock
, F_SETFL
, flags
| O_NONBLOCK
) == -1) {
1416 warn("Can't set socket non-blocking for connect to `%s:%s'",
1421 /* NOTE: we now must restore socket flags on successful exit */
1424 pfd
[0].events
= POLLIN
|POLLOUT
;
1426 if (quit_time
> 0) { /* want a non default timeout */
1427 (void)gettimeofday(&endtime
, NULL
);
1428 endtime
.tv_sec
+= quit_time
; /* determine end time */
1431 rv
= connect(sock
, name
, namelen
); /* inititate the connection */
1432 if (rv
== -1) { /* connection error */
1433 if (errno
!= EINPROGRESS
) { /* error isn't "please wait" */
1434 if (pe
|| (errno
!= EHOSTUNREACH
))
1436 warn("Can't connect to `%s:%s'", hname
, sname
);
1440 /* connect EINPROGRESS; wait */
1442 if (quit_time
> 0) { /* determine timeout */
1443 (void)gettimeofday(&now
, NULL
);
1444 timersub(&endtime
, &now
, &td
);
1445 timeout
= td
.tv_sec
* 1000 + td
.tv_usec
/1000;
1452 rv
= ftp_poll(pfd
, 1, timeout
);
1453 /* loop until poll ! EINTR */
1454 } while (rv
== -1 && errno
== EINTR
);
1456 if (rv
== 0) { /* poll (connect) timed out */
1461 if (rv
== -1) { /* poll error */
1463 } else if (pfd
[0].revents
& (POLLIN
|POLLOUT
)) {
1464 slen
= sizeof(error
); /* OK, or pending error */
1465 if (getsockopt(sock
, SOL_SOCKET
, SO_ERROR
,
1466 &error
, &slen
) == -1) {
1467 /* Solaris pending error */
1469 } else if (error
!= 0) {
1470 errno
= error
; /* BSD pending error */
1474 errno
= EBADF
; /* this shouldn't happen ... */
1479 if (fcntl(sock
, F_SETFL
, flags
) == -1) {
1480 /* restore socket flags */
1481 warn("Can't %s socket flags for connect to `%s:%s'",
1482 "restore", hname
, sname
);
1489 * Internal version of listen(2); sets socket buffer sizes first.
1492 ftp_listen(int sock
, int backlog
)
1495 setupsockbufsize(sock
);
1496 return (listen(sock
, backlog
));
1500 * Internal version of poll(2), to allow reimplementation by select(2)
1501 * on platforms without the former.
1504 ftp_poll(struct pollfd
*fds
, int nfds
, int timeout
)
1506 #if defined(HAVE_POLL)
1507 return poll(fds
, nfds
, timeout
);
1509 #elif defined(HAVE_SELECT)
1510 /* implement poll(2) using select(2) */
1511 fd_set rset
, wset
, xset
;
1512 const int rsetflags
= POLLIN
| POLLRDNORM
;
1513 const int wsetflags
= POLLOUT
| POLLWRNORM
;
1514 const int xsetflags
= POLLRDBAND
;
1515 struct timeval tv
, *ptv
;
1518 FD_ZERO(&rset
); /* build list of read & write events */
1522 for (i
= 0; i
< nfds
; i
++) {
1523 if (fds
[i
].fd
> FD_SETSIZE
) {
1524 warnx("can't select fd %d", fds
[i
].fd
);
1527 } else if (fds
[i
].fd
> max
)
1529 if (fds
[i
].events
& rsetflags
)
1530 FD_SET(fds
[i
].fd
, &rset
);
1531 if (fds
[i
].events
& wsetflags
)
1532 FD_SET(fds
[i
].fd
, &wset
);
1533 if (fds
[i
].events
& xsetflags
)
1534 FD_SET(fds
[i
].fd
, &xset
);
1537 ptv
= &tv
; /* determine timeout */
1538 if (timeout
== -1) { /* wait forever */
1540 } else if (timeout
== 0) { /* poll once */
1544 else if (timeout
!= 0) { /* wait timeout milliseconds */
1545 ptv
->tv_sec
= timeout
/ 1000;
1546 ptv
->tv_usec
= (timeout
% 1000) * 1000;
1548 rv
= select(max
+ 1, &rset
, &wset
, &xset
, ptv
);
1549 if (rv
<= 0) /* -1 == error, 0 == timeout */
1552 for (i
= 0; i
< nfds
; i
++) { /* determine results */
1553 if (FD_ISSET(fds
[i
].fd
, &rset
))
1554 fds
[i
].revents
|= (fds
[i
].events
& rsetflags
);
1555 if (FD_ISSET(fds
[i
].fd
, &wset
))
1556 fds
[i
].revents
|= (fds
[i
].events
& wsetflags
);
1557 if (FD_ISSET(fds
[i
].fd
, &xset
))
1558 fds
[i
].revents
|= (fds
[i
].events
& xsetflags
);
1563 # error no way to implement xpoll
1569 * malloc() with inbuilt error checking
1572 ftp_malloc(size_t size
)
1578 err(1, "Unable to allocate %ld bytes of memory", (long)size
);
1583 * sl_init() with inbuilt error checking
1592 err(1, "Unable to allocate memory for stringlist");
1597 * sl_add() with inbuilt error checking
1600 ftp_sl_add(StringList
*sl
, char *i
)
1607 * strdup() with inbuilt error checking
1610 ftp_strdup(const char *str
)
1615 errx(1, "ftp_strdup: called with NULL argument");
1618 err(1, "Unable to allocate memory for string copy");