1 /* $NetBSD: util.c,v 1.151 2009/04/15 04:19:39 jld Exp $ */
4 * Copyright (c) 1997-2009 The NetBSD Foundation, Inc.
7 * This code is derived from software contributed to The NetBSD Foundation
10 * This code is derived from software contributed to The NetBSD Foundation
11 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
12 * NASA Ames Research Center.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
23 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
24 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
25 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
27 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 * POSSIBILITY OF SUCH DAMAGE.
37 * Copyright (c) 1985, 1989, 1993, 1994
38 * The Regents of the University of California. All rights reserved.
40 * Redistribution and use in source and binary forms, with or without
41 * modification, are permitted provided that the following conditions
43 * 1. Redistributions of source code must retain the above copyright
44 * notice, this list of conditions and the following disclaimer.
45 * 2. Redistributions in binary form must reproduce the above copyright
46 * notice, this list of conditions and the following disclaimer in the
47 * documentation and/or other materials provided with the distribution.
48 * 3. Neither the name of the University nor the names of its contributors
49 * may be used to endorse or promote products derived from this software
50 * without specific prior written permission.
52 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
53 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
55 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
56 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
57 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
58 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
59 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
60 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
61 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65 #include <sys/cdefs.h>
67 __RCSID("$NetBSD: util.c,v 1.151 2009/04/15 04:19:39 jld Exp $");
71 * FTP User Program -- Misc support routines
73 #include <sys/param.h>
74 #include <sys/socket.h>
75 #include <sys/ioctl.h>
77 #include <netinet/in.h>
100 * Connect to peer server and auto-login, if possible.
103 setpeer(int argc
, char *argv
[])
111 fprintf(ttyout
, "Already connected to %s, use close first.\n",
117 (void)another(&argc
, &argv
, "to");
118 if (argc
< 2 || argc
> 3) {
120 UPRINTF("usage: %s host-name [port]\n", argv
[0]);
132 if (gateserver
== NULL
|| *gateserver
== '\0')
133 errx(1, "main: gateserver not defined");
134 host
= hookup(gateserver
, port
);
136 host
= hookup(argv
[1], port
);
139 if (gatemode
&& verbose
) {
141 "Connecting via pass-through server %s\n",
147 * Set up defaults for FTP.
149 (void)strlcpy(typename
, "ascii", sizeof(typename
));
152 (void)strlcpy(formname
, "non-print", sizeof(formname
));
154 (void)strlcpy(modename
, "stream", sizeof(modename
));
156 (void)strlcpy(structname
, "file", sizeof(structname
));
158 (void)strlcpy(bytename
, "8", sizeof(bytename
));
161 (void)ftp_login(argv
[1], NULL
, NULL
);
166 parse_feat(const char *fline
)
170 * work-around broken ProFTPd servers that can't
173 while (*fline
&& isspace((int)*fline
))
176 if (strcasecmp(fline
, "MDTM") == 0)
177 features
[FEAT_MDTM
] = 1;
178 else if (strncasecmp(fline
, "MLST", sizeof("MLST") - 1) == 0) {
179 features
[FEAT_MLST
] = 1;
180 } else if (strcasecmp(fline
, "REST STREAM") == 0)
181 features
[FEAT_REST_STREAM
] = 1;
182 else if (strcasecmp(fline
, "SIZE") == 0)
183 features
[FEAT_SIZE
] = 1;
184 else if (strcasecmp(fline
, "TVFS") == 0)
185 features
[FEAT_TVFS
] = 1;
189 * Determine the remote system type (SYST) and features (FEAT).
190 * Call after a successful login (i.e, connected = -1)
201 /* determine remote system type */
202 if (command("SYST") == COMPLETE
) {
207 cp
= strchr(reply_string
+ 4, ' ');
209 cp
= strchr(reply_string
+ 4, '\r');
217 fprintf(ttyout
, "Remote system type is %s.\n",
222 if (!strncmp(reply_string
, "215 UNIX Type: L8", 17)) {
228 * Set type to 0 (not specified by user),
229 * meaning binary by default, but don't bother
230 * telling server. We can use binary
231 * for text files unless changed by the user.
234 (void)strlcpy(typename
, "binary", sizeof(typename
));
237 "Using %s mode to transfer files.\n",
245 !strncmp(reply_string
, "215 TOPS20", 10))
247 "Remember to set tenex mode when transferring binary files from this machine.\n",
252 /* determine features (if any) */
253 for (i
= 0; i
< FEAT_max
; i
++)
255 reply_callback
= parse_feat
;
256 if (command("FEAT") == COMPLETE
) {
257 for (i
= 0; i
< FEAT_max
; i
++) {
258 if (features
[i
] == -1)
261 features
[FEAT_FEAT
] = 1;
263 features
[FEAT_FEAT
] = 0;
266 #define DEBUG_FEAT(x) fprintf(ttyout, "features[" #x "] = %d\n", features[(x)])
267 DEBUG_FEAT(FEAT_FEAT
);
268 DEBUG_FEAT(FEAT_MDTM
);
269 DEBUG_FEAT(FEAT_MLST
);
270 DEBUG_FEAT(FEAT_REST_STREAM
);
271 DEBUG_FEAT(FEAT_SIZE
);
272 DEBUG_FEAT(FEAT_TVFS
);
276 reply_callback
= NULL
;
282 * Reset the various variables that indicate connection state back to
283 * disconnected settings.
284 * The caller is responsible for issuing any commands to the remote server
285 * to perform a clean shutdown before this is invoked.
298 * determine if anonftp was specifically set with -a
299 * (1), or implicitly set by auto_fetch() (2). in the
300 * latter case, disable after the current xfer
315 * Top-level signal handler for interrupted commands.
324 write(fileno(ttyout
), "\n", 1);
325 siglongjmp(toplevel
, 1);
329 * Signal handler for lost connections; cleanup various elements of
330 * the connection state, and call cleanuppeer() to finish it off.
340 (void)shutdown(fileno(cout
), 1+1);
345 (void)shutdown(data
, 1+1);
354 (void)shutdown(fileno(cout
), 1+1);
368 * Login to remote host, using given username & password if supplied.
369 * Return non-zero if successful.
372 ftp_login(const char *host
, const char *luser
, const char *lpass
)
375 char *fuser
, *pass
, *facct
, *p
;
376 char emptypass
[] = "";
377 const char *errormsg
;
378 int n
, aflag
, rval
, nlen
;
381 fuser
= pass
= facct
= NULL
;
383 fuser
= ftp_strdup(luser
);
385 pass
= ftp_strdup(lpass
);
387 DPRINTF("ftp_login: user `%s' pass `%s' host `%s'\n",
388 STRorNULL(fuser
), STRorNULL(pass
), STRorNULL(host
));
391 * Set up arguments for an anonymous FTP session, if necessary.
395 fuser
= ftp_strdup("anonymous"); /* as per RFC1635 */
397 pass
= ftp_strdup(getoptionvalue("anonpass"));
400 if (ruserpass(host
, &fuser
, &pass
, &facct
) < 0) {
402 goto cleanup_ftp_login
;
405 while (fuser
== NULL
) {
407 fprintf(ttyout
, "Name (%s:%s): ", host
, localname
);
409 fprintf(ttyout
, "Name (%s): ", host
);
411 nlen
= get_line(stdin
, tmp
, sizeof(tmp
), &errormsg
);
413 fprintf(ttyout
, "%s; %s aborted.\n", errormsg
, "login");
415 goto cleanup_ftp_login
;
416 } else if (nlen
== 0) {
417 fuser
= ftp_strdup(localname
);
419 fuser
= ftp_strdup(tmp
);
427 len
= strlen(fuser
) + 1 + strlen(host
) + 1;
428 nuser
= ftp_malloc(len
);
429 (void)strlcpy(nuser
, fuser
, len
);
430 (void)strlcat(nuser
, "@", len
);
431 (void)strlcat(nuser
, host
, len
);
436 n
= command("USER %s", fuser
);
439 p
= getpass("Password: ");
442 pass
= ftp_strdup(p
);
443 memset(p
, 0, strlen(p
));
445 n
= command("PASS %s", pass
);
446 memset(pass
, 0, strlen(pass
));
451 p
= getpass("Account: ");
454 facct
= ftp_strdup(p
);
455 memset(p
, 0, strlen(p
));
457 if (facct
[0] == '\0') {
458 warnx("Login failed");
459 goto cleanup_ftp_login
;
461 n
= command("ACCT %s", facct
);
462 memset(facct
, 0, strlen(facct
));
464 if ((n
!= COMPLETE
) ||
465 (!aflag
&& facct
!= NULL
&& command("ACCT %s", facct
) != COMPLETE
)) {
466 warnx("Login failed");
467 goto cleanup_ftp_login
;
470 username
= ftp_strdup(fuser
);
472 goto cleanup_ftp_login
;
476 for (n
= 0; n
< macnum
; ++n
) {
477 if (!strcmp("init", macros
[n
].mac_name
)) {
478 (void)strlcpy(line
, "$init", sizeof(line
));
480 domacro(margc
, margv
);
490 memset(pass
, 0, strlen(pass
));
493 memset(facct
, 0, strlen(facct
));
499 * `another' gets another argument, and stores the new argc and argv.
500 * It reverts to the top level (via intr()) on EOF/error.
502 * Returns false if no new arguments have been added.
505 another(int *pargc
, char ***pargv
, const char *aprompt
)
507 const char *errormsg
;
512 if (len
>= sizeof(line
) - 3) {
513 fputs("Sorry, arguments too long.\n", ttyout
);
516 fprintf(ttyout
, "(%s) ", aprompt
);
519 nlen
= get_line(stdin
, line
+ len
, sizeof(line
)-len
, &errormsg
);
521 fprintf(ttyout
, "%s; %s aborted.\n", errormsg
, "operation");
526 ret
= margc
> *pargc
;
533 * glob files given in argv[] from the remote server.
534 * if errbuf isn't NULL, store error messages there instead
535 * of writing to the screen.
538 remglob(char *argv
[], int doswitch
, const char **errbuf
)
540 static char buf
[MAXPATHLEN
];
541 static FILE *ftemp
= NULL
;
543 char temp
[MAXPATHLEN
];
544 int oldverbose
, oldhash
, oldprogress
, fd
;
549 if (!mflag
|| !connected
) {
563 if ((cp
= *++args
) == NULL
)
568 len
= strlcpy(temp
, tmpdir
, sizeof(temp
));
569 if (temp
[len
- 1] != '/')
570 (void)strlcat(temp
, "/", sizeof(temp
));
571 (void)strlcat(temp
, TMPFILE
, sizeof(temp
));
572 if ((fd
= mkstemp(temp
)) < 0) {
573 warn("Unable to create temporary file `%s'", temp
);
577 oldverbose
= verbose
;
578 verbose
= (errbuf
!= NULL
) ? -1 : 0;
580 oldprogress
= progress
;
585 for (rmode
= "w"; *++argv
!= NULL
; rmode
= "a")
586 recvrequest("NLST", temp
, *argv
, rmode
, 0, 0);
587 if ((code
/ 100) != COMPLETE
) {
589 *errbuf
= reply_string
;
593 verbose
= oldverbose
;
595 progress
= oldprogress
;
596 ftemp
= fopen(temp
, "r");
600 warnx("Can't find list of remote files");
603 "Can't find list of remote files";
607 if (fgets(buf
, sizeof(buf
), ftemp
) == NULL
) {
612 if ((cp
= strchr(buf
, '\n')) != NULL
)
618 * Glob a local file name specification with the expectation of a single
619 * return value. Can't control multiple values being expanded from the
620 * expression, we return only the first.
621 * Returns NULL on error, or a pointer to a buffer containing the filename
622 * that's the caller's responsiblity to free(3) when finished with.
625 globulize(const char *pattern
)
632 return (ftp_strdup(pattern
));
634 flags
= GLOB_BRACE
|GLOB_NOCHECK
|GLOB_TILDE
;
635 memset(&gl
, 0, sizeof(gl
));
636 if (glob(pattern
, flags
, NULL
, &gl
) || gl
.gl_pathc
== 0) {
637 warnx("Glob pattern `%s' not found", pattern
);
641 p
= ftp_strdup(gl
.gl_pathv
[0]);
647 * determine size of remote file
650 remotesize(const char *file
, int noisy
)
659 if (! features
[FEAT_SIZE
]) {
662 "SIZE is not supported by remote server.\n");
663 goto cleanup_remotesize
;
665 r
= command("SIZE %s", file
);
669 cp
= strchr(reply_string
, ' ');
672 size
= STRTOLL(cp
, &ep
, 10);
673 if (*ep
!= '\0' && !isspace((unsigned char)*ep
))
677 if (r
== ERROR
&& code
== 500 && features
[FEAT_SIZE
] == -1)
678 features
[FEAT_SIZE
] = 0;
679 if (noisy
&& ftp_debug
== 0) {
680 fputs(reply_string
, ttyout
);
690 * determine last modification time (in GMT) of remote file
693 remotemodtime(const char *file
, int noisy
)
695 int overbose
, ocode
, r
;
703 if (! features
[FEAT_MDTM
]) {
706 "MDTM is not supported by remote server.\n");
707 goto cleanup_parse_time
;
709 r
= command("MDTM %s", file
);
712 char *timestr
, *frac
;
715 * time-val = 14DIGIT [ "." 1*DIGIT ]
716 * YYYYMMDDHHMMSS[.sss]
717 * mdtm-response = "213" SP time-val CRLF / error-response
719 timestr
= reply_string
+ 4;
723 * XXX: ignored for now
725 frac
= strchr(timestr
, '\r');
728 frac
= strchr(timestr
, '.');
731 if (strlen(timestr
) == 15 && strncmp(timestr
, "191", 3) == 0) {
733 * XXX: Workaround for lame ftpd's that return
734 * `19100' instead of `2000'
737 "Y2K warning! Incorrect time-val `%s' received from server.\n",
742 fprintf(ttyout
, "Converted to `%s'\n", timestr
);
744 memset(&timebuf
, 0, sizeof(timebuf
));
745 if (strlen(timestr
) != 14 ||
746 (strptime(timestr
, "%Y%m%d%H%M%S", &timebuf
) == NULL
)) {
748 fprintf(ttyout
, "Can't parse time `%s'.\n", timestr
);
749 goto cleanup_parse_time
;
751 timebuf
.tm_isdst
= -1;
752 rtime
= timegm(&timebuf
);
754 if (noisy
|| ftp_debug
!= 0)
757 goto cleanup_parse_time
;
759 DPRINTF("remotemodtime: parsed date `%s' as " LLF
762 rfc2822time(localtime(&rtime
)));
765 if (r
== ERROR
&& code
== 500 && features
[FEAT_MDTM
] == -1)
766 features
[FEAT_MDTM
] = 0;
767 if (noisy
&& ftp_debug
== 0) {
768 fputs(reply_string
, ttyout
);
780 * Format tm in an RFC2822 compatible manner, with a trailing \n.
781 * Returns a pointer to a static string containing the result.
784 rfc2822time(const struct tm
*tm
)
786 static char result
[50];
788 if (strftime(result
, sizeof(result
),
789 "%a, %d %b %Y %H:%M:%S %z\n", tm
) == 0)
790 errx(1, "Can't convert RFC2822 time: buffer too small");
795 * Update global `localcwd', which contains the state of the local cwd
801 if (getcwd(localcwd
, sizeof(localcwd
)) == NULL
)
803 DPRINTF("updatelocalcwd: got `%s'\n", localcwd
);
807 * Update global `remotecwd', which contains the state of the remote cwd
810 updateremotecwd(void)
820 if (command("PWD") != COMPLETE
)
822 cp
= strchr(reply_string
, ' ');
823 if (cp
== NULL
|| cp
[0] == '\0' || cp
[1] != '"')
826 for (i
= 0; *cp
&& i
< sizeof(remotecwd
) - 1; i
++, cp
++) {
836 DPRINTF("updateremotecwd: got `%s'\n", remotecwd
);
837 goto cleanupremotecwd
;
846 * Ensure file is in or under dir.
847 * Returns 1 if so, 0 if not (or an error occurred).
850 fileindir(const char *file
, const char *dir
)
852 char parentdirbuf
[PATH_MAX
+1], *parentdir
;
853 char realdir
[PATH_MAX
+1];
856 /* determine parent directory of file */
857 (void)strlcpy(parentdirbuf
, file
, sizeof(parentdirbuf
));
858 parentdir
= dirname(parentdirbuf
);
859 if (strcmp(parentdir
, ".") == 0)
860 return 1; /* current directory is ok */
862 /* find the directory */
863 if (realpath(parentdir
, realdir
) == NULL
) {
864 warn("Unable to determine real path of `%s'", parentdir
);
867 if (realdir
[0] != '/') /* relative result is ok */
869 dirlen
= strlen(dir
);
870 if (strncmp(realdir
, dir
, dirlen
) == 0 &&
871 (realdir
[dirlen
] == '/' || realdir
[dirlen
] == '\0'))
877 * List words in stringlist, vertically arranged
880 list_vertical(StringList
*sl
)
883 size_t columns
, lines
;
889 for (i
= 0 ; i
< sl
->sl_cur
; i
++) {
890 w
= strlen(sl
->sl_str
[i
]);
894 width
= (width
+ 8) &~ 7;
896 columns
= ttywidth
/ width
;
899 lines
= (sl
->sl_cur
+ columns
- 1) / columns
;
900 for (i
= 0; i
< lines
; i
++) {
901 for (j
= 0; j
< columns
; j
++) {
902 p
= sl
->sl_str
[j
* lines
+ i
];
905 if (j
* lines
+ i
+ lines
>= sl
->sl_cur
) {
913 (void)putc('\t', ttyout
);
921 * Update the global ttywidth value, using TIOCGWINSZ.
926 struct winsize winsize
;
929 if (ioctl(fileno(ttyout
), TIOCGWINSZ
, &winsize
) != -1 &&
931 ttywidth
= winsize
.ws_col
;
938 * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
947 rate_get
+= rate_get_incr
;
949 rate_put
+= rate_put_incr
;
952 if (rate_get
&& rate_get
> rate_get_incr
)
953 rate_get
-= rate_get_incr
;
954 if (rate_put
&& rate_put
> rate_put_incr
)
955 rate_put
-= rate_put_incr
;
958 err(1, "crankrate invoked with unknown signal: %d", sig
);
964 * Setup or cleanup EditLine structures
966 #ifndef NO_EDITCOMPLETE
970 if (editing
&& el
== NULL
&& hist
== NULL
) {
974 el
= el_init(getprogname(), stdin
, ttyout
, stderr
);
976 hist
= history_init(); /* init the builtin history */
977 history(hist
, &ev
, H_SETSIZE
, 100);/* remember 100 events */
978 el_set(el
, EL_HIST
, history
, hist
); /* use history */
980 el_set(el
, EL_EDITOR
, "emacs"); /* default editor is emacs */
981 el_set(el
, EL_PROMPT
, prompt
); /* set the prompt functions */
982 el_set(el
, EL_RPROMPT
, rprompt
);
984 /* add local file completion, bind to TAB */
985 el_set(el
, EL_ADDFN
, "ftp-complete",
986 "Context sensitive argument completion",
988 el_set(el
, EL_BIND
, "^I", "ftp-complete", NULL
);
989 el_source(el
, NULL
); /* read ~/.editrc */
990 if ((el_get(el
, EL_EDITMODE
, &editmode
) != -1) && editmode
== 0)
991 editing
= 0; /* the user doesn't want editing,
992 * so disable, and let statement
995 el_set(el
, EL_SIGNAL
, 1);
1008 #endif /* !NO_EDITCOMPLETE */
1011 * Convert the string `arg' to an int, which may have an optional SI suffix
1012 * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
1015 strsuftoi(const char *arg
)
1020 if (!isdigit((unsigned char)arg
[0]))
1023 val
= strtol(arg
, &cp
, 10);
1025 if (cp
[0] != '\0' && cp
[1] != '\0')
1027 switch (tolower((unsigned char)cp
[0])) {
1044 if (val
< 0 || val
> INT_MAX
)
1051 * Set up socket buffer sizes before a connection is made.
1054 setupsockbufsize(int sock
)
1057 if (setsockopt(sock
, SOL_SOCKET
, SO_SNDBUF
,
1058 (void *)&sndbuf_size
, sizeof(sndbuf_size
)) == -1)
1059 warn("Unable to set sndbuf size %d", sndbuf_size
);
1061 if (setsockopt(sock
, SOL_SOCKET
, SO_RCVBUF
,
1062 (void *)&rcvbuf_size
, sizeof(rcvbuf_size
)) == -1)
1063 warn("Unable to set rcvbuf size %d", rcvbuf_size
);
1067 * Copy characters from src into dst, \ quoting characters that require it
1070 ftpvis(char *dst
, size_t dstlen
, const char *src
, size_t srclen
)
1075 src
[si
] != '\0' && di
< dstlen
&& si
< srclen
;
1096 * Copy src into buf (which is len bytes long), expanding % sequences.
1099 formatbuf(char *buf
, size_t len
, const char *src
)
1101 const char *p
, *p2
, *q
;
1103 int op
, updirs
, pdirs
;
1105 #define ADDBUF(x) do { \
1112 for (i
= 0; *p
; p
++) {
1124 p2
= connected
? remotecwd
: "";
1127 /* option to determine fixed # of dirs from path */
1128 if (op
== '.' || op
== 'c') {
1132 while (*p2
) /* calc # of /'s */
1135 if (p
[1] == '0') { /* print <x> or ... */
1139 if (p
[1] >= '1' && p
[1] <= '9') {
1140 /* calc # to skip */
1147 while (skip
-- > 0) {
1148 while ((p2
> q
) && (*p2
!= '/'))
1153 if (*p2
== '/' && p2
!= q
)
1157 if (updirs
> 0 && pdirs
) {
1171 ADDBUF('0' + updirs
);
1181 for (p2
= connected
&& hostname
? hostname
: "-";
1183 if (op
== 'm' && *p2
== '.')
1190 for (p2
= connected
? username
: "-"; *p2
; p2
++)
1198 default: /* display unknown codes literally */
1210 * Determine if given string is an IPv6 address or not.
1211 * Return 1 for yes, 0 for no
1214 isipv6addr(const char *addr
)
1218 struct addrinfo hints
, *res
;
1220 memset(&hints
, 0, sizeof(hints
));
1221 hints
.ai_family
= AF_INET6
;
1222 hints
.ai_socktype
= SOCK_DGRAM
; /*dummy*/
1223 hints
.ai_flags
= AI_NUMERICHOST
;
1224 if (getaddrinfo(addr
, "0", &hints
, &res
) != 0)
1230 DPRINTF("isipv6addr: got %d for %s\n", rv
, addr
);
1232 return (rv
== 1) ? 1 : 0;
1236 * Read a line from the FILE stream into buf/buflen using fgets(), so up
1237 * to buflen-1 chars will be read and the result will be NUL terminated.
1238 * If the line has a trailing newline it will be removed.
1239 * If the line is too long, excess characters will be read until
1240 * newline/EOF/error.
1241 * If EOF/error occurs or a too-long line is encountered and errormsg
1242 * isn't NULL, it will be changed to a description of the problem.
1243 * (The EOF message has a leading \n for cosmetic purposes).
1245 * >=0 length of line (excluding trailing newline) if all ok
1247 * -2 EOF encountered
1248 * -3 line was too long
1251 get_line(FILE *stream
, char *buf
, size_t buflen
, const char **errormsg
)
1256 if (fgets(buf
, buflen
, stream
) == NULL
) {
1257 if (feof(stream
)) { /* EOF */
1260 *errormsg
= "\nEOF received";
1261 } else { /* error */
1264 *errormsg
= "Error encountered";
1270 if (buf
[len
-1] == '\n') { /* clear any trailing newline */
1272 } else if (len
== buflen
-1) { /* line too long */
1273 while ((ch
= getchar()) != '\n' && ch
!= EOF
)
1276 *errormsg
= "Input line is too long";
1286 * Internal version of connect(2); sets socket buffer sizes,
1287 * binds to a specific local address (if set), and
1288 * supports a connection timeout using a non-blocking connect(2) with
1290 * Socket fcntl flags are temporarily updated to include O_NONBLOCK;
1291 * these will not be reverted on connection failure.
1292 * Returns 0 on success, or -1 upon failure (with an appropriate
1293 * error message displayed.)
1296 ftp_connect(int sock
, const struct sockaddr
*name
, socklen_t namelen
)
1298 int flags
, rv
, timeout
, error
;
1300 struct timeval endtime
, now
, td
;
1301 struct pollfd pfd
[1];
1302 char hname
[NI_MAXHOST
];
1303 char sname
[NI_MAXSERV
];
1305 setupsockbufsize(sock
);
1306 if (getnameinfo(name
, namelen
,
1307 hname
, sizeof(hname
), sname
, sizeof(sname
),
1308 NI_NUMERICHOST
| NI_NUMERICSERV
) != 0) {
1309 strlcpy(hname
, "?", sizeof(hname
));
1310 strlcpy(sname
, "?", sizeof(sname
));
1313 if (bindai
!= NULL
) { /* bind to specific addr */
1314 struct addrinfo
*ai
;
1316 for (ai
= bindai
; ai
!= NULL
; ai
= ai
->ai_next
) {
1317 if (ai
->ai_family
== name
->sa_family
)
1322 if (bind(sock
, ai
->ai_addr
, ai
->ai_addrlen
) == -1) {
1323 char bname
[NI_MAXHOST
];
1327 if (getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
,
1328 bname
, sizeof(bname
), NULL
, 0, NI_NUMERICHOST
) != 0)
1329 strlcpy(bname
, "?", sizeof(bname
));
1331 warn("Can't bind to `%s'", bname
);
1336 /* save current socket flags */
1337 if ((flags
= fcntl(sock
, F_GETFL
, 0)) == -1) {
1338 warn("Can't %s socket flags for connect to `%s:%s'",
1339 "save", hname
, sname
);
1342 /* set non-blocking connect */
1343 if (fcntl(sock
, F_SETFL
, flags
| O_NONBLOCK
) == -1) {
1344 warn("Can't set socket non-blocking for connect to `%s:%s'",
1349 /* NOTE: we now must restore socket flags on successful exit */
1352 pfd
[0].events
= POLLIN
|POLLOUT
;
1354 if (quit_time
> 0) { /* want a non default timeout */
1355 (void)gettimeofday(&endtime
, NULL
);
1356 endtime
.tv_sec
+= quit_time
; /* determine end time */
1359 rv
= connect(sock
, name
, namelen
); /* inititate the connection */
1360 if (rv
== -1) { /* connection error */
1361 if (errno
!= EINPROGRESS
) { /* error isn't "please wait" */
1363 warn("Can't connect to `%s:%s'", hname
, sname
);
1367 /* connect EINPROGRESS; wait */
1369 if (quit_time
> 0) { /* determine timeout */
1370 (void)gettimeofday(&now
, NULL
);
1371 timersub(&endtime
, &now
, &td
);
1372 timeout
= td
.tv_sec
* 1000 + td
.tv_usec
/1000;
1379 rv
= ftp_poll(pfd
, 1, timeout
);
1380 /* loop until poll ! EINTR */
1381 } while (rv
== -1 && errno
== EINTR
);
1383 if (rv
== 0) { /* poll (connect) timed out */
1388 if (rv
== -1) { /* poll error */
1390 } else if (pfd
[0].revents
& (POLLIN
|POLLOUT
)) {
1391 slen
= sizeof(error
); /* OK, or pending error */
1392 if (getsockopt(sock
, SOL_SOCKET
, SO_ERROR
,
1393 &error
, &slen
) == -1) {
1394 /* Solaris pending error */
1396 } else if (error
!= 0) {
1397 errno
= error
; /* BSD pending error */
1401 errno
= EBADF
; /* this shouldn't happen ... */
1406 if (fcntl(sock
, F_SETFL
, flags
) == -1) {
1407 /* restore socket flags */
1408 warn("Can't %s socket flags for connect to `%s:%s'",
1409 "restore", hname
, sname
);
1416 * Internal version of listen(2); sets socket buffer sizes first.
1419 ftp_listen(int sock
, int backlog
)
1422 setupsockbufsize(sock
);
1423 return (listen(sock
, backlog
));
1427 * Internal version of poll(2), to allow reimplementation by select(2)
1428 * on platforms without the former.
1431 ftp_poll(struct pollfd
*fds
, int nfds
, int timeout
)
1433 return poll(fds
, nfds
, timeout
);
1437 * malloc() with inbuilt error checking
1440 ftp_malloc(size_t size
)
1446 err(1, "Unable to allocate %ld bytes of memory", (long)size
);
1451 * sl_init() with inbuilt error checking
1460 err(1, "Unable to allocate memory for stringlist");
1465 * sl_add() with inbuilt error checking
1468 ftp_sl_add(StringList
*sl
, char *i
)
1471 if (sl_add(sl
, i
) == -1)
1472 err(1, "Unable to add `%s' to stringlist", i
);
1476 * strdup() with inbuilt error checking
1479 ftp_strdup(const char *str
)
1484 errx(1, "ftp_strdup: called with NULL argument");
1487 err(1, "Unable to allocate memory for string copy");