1 /* $NetBSD: util.c,v 1.144 2007/12/05 03:46:34 lukem Exp $ */
4 * Copyright (c) 1997-2007 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.
22 * 3. All advertising materials mentioning features or use of this software
23 * must display the following acknowledgement:
24 * This product includes software developed by the NetBSD
25 * Foundation, Inc. and its contributors.
26 * 4. Neither the name of The NetBSD Foundation nor the names of its
27 * contributors may be used to endorse or promote products derived
28 * from this software without specific prior written permission.
30 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
31 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
32 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
33 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
34 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
35 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
36 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
37 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
38 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
39 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
40 * POSSIBILITY OF SUCH DAMAGE.
44 * Copyright (c) 1985, 1989, 1993, 1994
45 * The Regents of the University of California. All rights reserved.
47 * Redistribution and use in source and binary forms, with or without
48 * modification, are permitted provided that the following conditions
50 * 1. Redistributions of source code must retain the above copyright
51 * notice, this list of conditions and the following disclaimer.
52 * 2. Redistributions in binary form must reproduce the above copyright
53 * notice, this list of conditions and the following disclaimer in the
54 * documentation and/or other materials provided with the distribution.
55 * 3. Neither the name of the University nor the names of its contributors
56 * may be used to endorse or promote products derived from this software
57 * without specific prior written permission.
59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
72 #include <sys/cdefs.h>
74 __RCSID("$NetBSD: util.c,v 1.144 2007/12/05 03:46:34 lukem Exp $");
78 * FTP User Program -- Misc support routines
80 #include <sys/param.h>
81 #include <sys/socket.h>
82 #include <sys/ioctl.h>
84 #include <netinet/in.h>
107 * Connect to peer server and auto-login, if possible.
110 setpeer(int argc
, char *argv
[])
118 fprintf(ttyout
, "Already connected to %s, use close first.\n",
124 (void)another(&argc
, &argv
, "to");
125 if (argc
< 2 || argc
> 3) {
127 UPRINTF("usage: %s host-name [port]\n", argv
[0]);
139 if (gateserver
== NULL
|| *gateserver
== '\0')
140 errx(1, "main: gateserver not defined");
141 host
= hookup(gateserver
, port
);
143 host
= hookup(argv
[1], port
);
146 if (gatemode
&& verbose
) {
148 "Connecting via pass-through server %s\n",
154 * Set up defaults for FTP.
156 (void)strlcpy(typename
, "ascii", sizeof(typename
));
159 (void)strlcpy(formname
, "non-print", sizeof(formname
));
161 (void)strlcpy(modename
, "stream", sizeof(modename
));
163 (void)strlcpy(structname
, "file", sizeof(structname
));
165 (void)strlcpy(bytename
, "8", sizeof(bytename
));
168 (void)ftp_login(argv
[1], NULL
, NULL
);
173 parse_feat(const char *line
)
177 * work-around broken ProFTPd servers that can't
180 while (*line
&& isspace((int)*line
))
183 if (strcasecmp(line
, "MDTM") == 0)
184 features
[FEAT_MDTM
] = 1;
185 else if (strncasecmp(line
, "MLST", sizeof("MLST") - 1) == 0) {
186 features
[FEAT_MLST
] = 1;
187 } else if (strcasecmp(line
, "REST STREAM") == 0)
188 features
[FEAT_REST_STREAM
] = 1;
189 else if (strcasecmp(line
, "SIZE") == 0)
190 features
[FEAT_SIZE
] = 1;
191 else if (strcasecmp(line
, "TVFS") == 0)
192 features
[FEAT_TVFS
] = 1;
196 * Determine the remote system type (SYST) and features (FEAT).
197 * Call after a successful login (i.e, connected = -1)
208 /* determine remote system type */
209 if (command("SYST") == COMPLETE
) {
214 cp
= strchr(reply_string
+ 4, ' ');
216 cp
= strchr(reply_string
+ 4, '\r');
224 fprintf(ttyout
, "Remote system type is %s.\n",
229 if (!strncmp(reply_string
, "215 UNIX Type: L8", 17)) {
235 * Set type to 0 (not specified by user),
236 * meaning binary by default, but don't bother
237 * telling server. We can use binary
238 * for text files unless changed by the user.
241 (void)strlcpy(typename
, "binary", sizeof(typename
));
244 "Using %s mode to transfer files.\n",
252 !strncmp(reply_string
, "215 TOPS20", 10))
254 "Remember to set tenex mode when transferring binary files from this machine.\n",
259 /* determine features (if any) */
260 for (i
= 0; i
< FEAT_max
; i
++)
262 reply_callback
= parse_feat
;
263 if (command("FEAT") == COMPLETE
) {
264 for (i
= 0; i
< FEAT_max
; i
++) {
265 if (features
[i
] == -1)
268 features
[FEAT_FEAT
] = 1;
270 features
[FEAT_FEAT
] = 0;
273 #define DEBUG_FEAT(x) fprintf(ttyout, "features[" #x "] = %d\n", features[(x)])
274 DEBUG_FEAT(FEAT_FEAT
);
275 DEBUG_FEAT(FEAT_MDTM
);
276 DEBUG_FEAT(FEAT_MLST
);
277 DEBUG_FEAT(FEAT_REST_STREAM
);
278 DEBUG_FEAT(FEAT_SIZE
);
279 DEBUG_FEAT(FEAT_TVFS
);
283 reply_callback
= NULL
;
289 * Reset the various variables that indicate connection state back to
290 * disconnected settings.
291 * The caller is responsible for issuing any commands to the remote server
292 * to perform a clean shutdown before this is invoked.
305 * determine if anonftp was specifically set with -a
306 * (1), or implicitly set by auto_fetch() (2). in the
307 * latter case, disable after the current xfer
321 * Top-level signal handler for interrupted commands.
330 write(fileno(ttyout
), "\n", 1);
331 siglongjmp(toplevel
, 1);
335 * Signal handler for lost connections; cleanup various elements of
336 * the connection state, and call cleanuppeer() to finish it off.
346 (void)shutdown(fileno(cout
), 1+1);
351 (void)shutdown(data
, 1+1);
360 (void)shutdown(fileno(cout
), 1+1);
374 * Login to remote host, using given username & password if supplied.
375 * Return non-zero if successful.
378 ftp_login(const char *host
, const char *luser
, const char *lpass
)
381 char *user
, *pass
, *acct
, *p
;
382 char emptypass
[] = "";
383 const char *errormsg
;
384 int n
, aflag
, rval
, nlen
;
387 user
= pass
= acct
= NULL
;
389 user
= ftp_strdup(luser
);
391 pass
= ftp_strdup(lpass
);
393 DPRINTF("ftp_login: user `%s' pass `%s' host `%s'\n",
394 STRorNULL(user
), STRorNULL(pass
), STRorNULL(host
));
397 * Set up arguments for an anonymous FTP session, if necessary.
401 user
= ftp_strdup("anonymous"); /* as per RFC1635 */
403 pass
= ftp_strdup(getoptionvalue("anonpass"));
406 if (ruserpass(host
, &user
, &pass
, &acct
) < 0) {
408 goto cleanup_ftp_login
;
411 while (user
== NULL
) {
413 fprintf(ttyout
, "Name (%s:%s): ", host
, localname
);
415 fprintf(ttyout
, "Name (%s): ", host
);
417 nlen
= getline(stdin
, tmp
, sizeof(tmp
), &errormsg
);
419 fprintf(ttyout
, "%s; %s aborted.\n", errormsg
, "login");
421 goto cleanup_ftp_login
;
422 } else if (nlen
== 0) {
423 user
= ftp_strdup(localname
);
425 user
= ftp_strdup(tmp
);
433 len
= strlen(user
) + 1 + strlen(host
) + 1;
434 nuser
= ftp_malloc(len
);
435 (void)strlcpy(nuser
, user
, len
);
436 (void)strlcat(nuser
, "@", len
);
437 (void)strlcat(nuser
, host
, len
);
442 n
= command("USER %s", user
);
445 p
= getpass("Password: ");
448 pass
= ftp_strdup(p
);
449 memset(p
, 0, strlen(p
));
451 n
= command("PASS %s", pass
);
452 memset(pass
, 0, strlen(pass
));
457 p
= getpass("Account: ");
460 acct
= ftp_strdup(p
);
461 memset(p
, 0, strlen(p
));
463 if (acct
[0] == '\0') {
464 warnx("Login failed");
465 goto cleanup_ftp_login
;
467 n
= command("ACCT %s", acct
);
468 memset(acct
, 0, strlen(acct
));
470 if ((n
!= COMPLETE
) ||
471 (!aflag
&& acct
!= NULL
&& command("ACCT %s", acct
) != COMPLETE
)) {
472 warnx("Login failed");
473 goto cleanup_ftp_login
;
476 username
= ftp_strdup(user
);
478 goto cleanup_ftp_login
;
482 for (n
= 0; n
< macnum
; ++n
) {
483 if (!strcmp("init", macros
[n
].mac_name
)) {
484 (void)strlcpy(line
, "$init", sizeof(line
));
486 domacro(margc
, margv
);
496 memset(pass
, 0, strlen(pass
));
499 memset(acct
, 0, strlen(acct
));
505 * `another' gets another argument, and stores the new argc and argv.
506 * It reverts to the top level (via intr()) on EOF/error.
508 * Returns false if no new arguments have been added.
511 another(int *pargc
, char ***pargv
, const char *prompt
)
513 const char *errormsg
;
518 if (len
>= sizeof(line
) - 3) {
519 fputs("Sorry, arguments too long.\n", ttyout
);
522 fprintf(ttyout
, "(%s) ", prompt
);
525 nlen
= getline(stdin
, line
+ len
, sizeof(line
)-len
, &errormsg
);
527 fprintf(ttyout
, "%s; %s aborted.\n", errormsg
, "operation");
532 ret
= margc
> *pargc
;
539 * glob files given in argv[] from the remote server.
540 * if errbuf isn't NULL, store error messages there instead
541 * of writing to the screen.
544 remglob(char *argv
[], int doswitch
, const char **errbuf
)
546 static char buf
[MAXPATHLEN
];
547 static FILE *ftemp
= NULL
;
549 char temp
[MAXPATHLEN
];
550 int oldverbose
, oldhash
, oldprogress
, fd
;
555 if (!mflag
|| !connected
) {
569 if ((cp
= *++args
) == NULL
)
574 len
= strlcpy(temp
, tmpdir
, sizeof(temp
));
575 if (temp
[len
- 1] != '/')
576 (void)strlcat(temp
, "/", sizeof(temp
));
577 (void)strlcat(temp
, TMPFILE
, sizeof(temp
));
578 if ((fd
= mkstemp(temp
)) < 0) {
579 warn("Unable to create temporary file `%s'", temp
);
583 oldverbose
= verbose
;
584 verbose
= (errbuf
!= NULL
) ? -1 : 0;
586 oldprogress
= progress
;
591 for (mode
= "w"; *++argv
!= NULL
; mode
= "a")
592 recvrequest("NLST", temp
, *argv
, mode
, 0, 0);
593 if ((code
/ 100) != COMPLETE
) {
595 *errbuf
= reply_string
;
599 verbose
= oldverbose
;
601 progress
= oldprogress
;
602 ftemp
= fopen(temp
, "r");
606 warnx("Can't find list of remote files");
609 "Can't find list of remote files";
613 if (fgets(buf
, sizeof(buf
), ftemp
) == NULL
) {
618 if ((cp
= strchr(buf
, '\n')) != NULL
)
624 * Glob a local file name specification with the expectation of a single
625 * return value. Can't control multiple values being expanded from the
626 * expression, we return only the first.
627 * Returns NULL on error, or a pointer to a buffer containing the filename
628 * that's the caller's responsiblity to free(3) when finished with.
631 globulize(const char *pattern
)
638 return (ftp_strdup(pattern
));
640 flags
= GLOB_BRACE
|GLOB_NOCHECK
|GLOB_TILDE
;
641 memset(&gl
, 0, sizeof(gl
));
642 if (glob(pattern
, flags
, NULL
, &gl
) || gl
.gl_pathc
== 0) {
643 warnx("Glob pattern `%s' not found", pattern
);
647 p
= ftp_strdup(gl
.gl_pathv
[0]);
653 * determine size of remote file
656 remotesize(const char *file
, int noisy
)
665 if (! features
[FEAT_SIZE
]) {
668 "SIZE is not supported by remote server.\n");
669 goto cleanup_remotesize
;
671 r
= command("SIZE %s", file
);
675 cp
= strchr(reply_string
, ' ');
678 size
= STRTOLL(cp
, &ep
, 10);
679 if (*ep
!= '\0' && !isspace((unsigned char)*ep
))
683 if (r
== ERROR
&& code
== 500 && features
[FEAT_SIZE
] == -1)
684 features
[FEAT_SIZE
] = 0;
685 if (noisy
&& ftp_debug
== 0) {
686 fputs(reply_string
, ttyout
);
696 * determine last modification time (in GMT) of remote file
699 remotemodtime(const char *file
, int noisy
)
701 int overbose
, ocode
, r
;
709 if (! features
[FEAT_MDTM
]) {
712 "MDTM is not supported by remote server.\n");
713 goto cleanup_parse_time
;
715 r
= command("MDTM %s", file
);
718 char *timestr
, *frac
;
721 * time-val = 14DIGIT [ "." 1*DIGIT ]
722 * YYYYMMDDHHMMSS[.sss]
723 * mdtm-response = "213" SP time-val CRLF / error-response
725 timestr
= reply_string
+ 4;
729 * XXX: ignored for now
731 frac
= strchr(timestr
, '\r');
734 frac
= strchr(timestr
, '.');
737 if (strlen(timestr
) == 15 && strncmp(timestr
, "191", 3) == 0) {
739 * XXX: Workaround for lame ftpd's that return
740 * `19100' instead of `2000'
743 "Y2K warning! Incorrect time-val `%s' received from server.\n",
748 fprintf(ttyout
, "Converted to `%s'\n", timestr
);
750 memset(&timebuf
, 0, sizeof(timebuf
));
751 if (strlen(timestr
) != 14 ||
752 (strptime(timestr
, "%Y%m%d%H%M%S", &timebuf
) == NULL
)) {
754 fprintf(ttyout
, "Can't parse time `%s'.\n", timestr
);
755 goto cleanup_parse_time
;
757 timebuf
.tm_isdst
= -1;
758 rtime
= timegm(&timebuf
);
760 if (noisy
|| ftp_debug
!= 0)
763 goto cleanup_parse_time
;
765 DPRINTF("remotemodtime: parsed date `%s' as " LLF
768 rfc2822time(localtime(&rtime
)));
770 if (r
== ERROR
&& code
== 500 && features
[FEAT_MDTM
] == -1)
771 features
[FEAT_MDTM
] = 0;
772 if (noisy
&& ftp_debug
== 0) {
773 fputs(reply_string
, ttyout
);
785 * Format tm in an RFC2822 compatible manner, with a trailing \n.
786 * Returns a pointer to a static string containing the result.
789 rfc2822time(const struct tm
*tm
)
791 static char result
[50];
793 if (strftime(result
, sizeof(result
),
794 "%a, %d %b %Y %H:%M:%S %z\n", tm
) == 0)
795 errx(1, "Can't convert RFC2822 time: buffer too small");
800 * Update global `localcwd', which contains the state of the local cwd
806 if (getcwd(localcwd
, sizeof(localcwd
)) == NULL
)
808 DPRINTF("updatelocalcwd: got `%s'\n", localcwd
);
812 * Update global `remotecwd', which contains the state of the remote cwd
815 updateremotecwd(void)
817 int overbose
, ocode
, i
;
824 if (command("PWD") != COMPLETE
)
826 cp
= strchr(reply_string
, ' ');
827 if (cp
== NULL
|| cp
[0] == '\0' || cp
[1] != '"')
830 for (i
= 0; *cp
&& i
< sizeof(remotecwd
) - 1; i
++, cp
++) {
840 DPRINTF("updateremotecwd: got `%s'\n", remotecwd
);
841 goto cleanupremotecwd
;
850 * Ensure file is in or under dir.
851 * Returns 1 if so, 0 if not (or an error occurred).
854 fileindir(const char *file
, const char *dir
)
856 char parentdirbuf
[PATH_MAX
+1], *parentdir
;
857 char realdir
[PATH_MAX
+1];
860 /* determine parent directory of file */
861 (void)strlcpy(parentdirbuf
, file
, sizeof(parentdirbuf
));
862 parentdir
= dirname(parentdirbuf
);
863 if (strcmp(parentdir
, ".") == 0)
864 return 1; /* current directory is ok */
866 /* find the directory */
867 if (realpath(parentdir
, realdir
) == NULL
) {
868 warn("Unable to determine real path of `%s'", parentdir
);
871 if (realdir
[0] != '/') /* relative result is ok */
873 dirlen
= strlen(dir
);
875 printf("file %s parent %s realdir %s dir %s [%d]\n",
876 file
, parentdir
, realdir
, dir
, dirlen
);
878 if (strncmp(realdir
, dir
, dirlen
) == 0 &&
879 (realdir
[dirlen
] == '/' || realdir
[dirlen
] == '\0'))
885 * List words in stringlist, vertically arranged
888 list_vertical(StringList
*sl
)
897 for (i
= 0 ; i
< sl
->sl_cur
; i
++) {
898 w
= strlen(sl
->sl_str
[i
]);
902 width
= (width
+ 8) &~ 7;
904 columns
= ttywidth
/ width
;
907 lines
= (sl
->sl_cur
+ columns
- 1) / columns
;
908 for (i
= 0; i
< lines
; i
++) {
909 for (j
= 0; j
< columns
; j
++) {
910 p
= sl
->sl_str
[j
* lines
+ i
];
913 if (j
* lines
+ i
+ lines
>= sl
->sl_cur
) {
921 (void)putc('\t', ttyout
);
929 * Update the global ttywidth value, using TIOCGWINSZ.
934 struct winsize winsize
;
937 if (ioctl(fileno(ttyout
), TIOCGWINSZ
, &winsize
) != -1 &&
939 ttywidth
= winsize
.ws_col
;
946 * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
955 rate_get
+= rate_get_incr
;
957 rate_put
+= rate_put_incr
;
960 if (rate_get
&& rate_get
> rate_get_incr
)
961 rate_get
-= rate_get_incr
;
962 if (rate_put
&& rate_put
> rate_put_incr
)
963 rate_put
-= rate_put_incr
;
966 err(1, "crankrate invoked with unknown signal: %d", sig
);
972 * Setup or cleanup EditLine structures
974 #ifndef NO_EDITCOMPLETE
978 if (editing
&& el
== NULL
&& hist
== NULL
) {
982 el
= el_init(getprogname(), stdin
, ttyout
, stderr
);
984 hist
= history_init(); /* init the builtin history */
985 history(hist
, &ev
, H_SETSIZE
, 100);/* remember 100 events */
986 el_set(el
, EL_HIST
, history
, hist
); /* use history */
988 el_set(el
, EL_EDITOR
, "emacs"); /* default editor is emacs */
989 el_set(el
, EL_PROMPT
, prompt
); /* set the prompt functions */
990 el_set(el
, EL_RPROMPT
, rprompt
);
992 /* add local file completion, bind to TAB */
993 el_set(el
, EL_ADDFN
, "ftp-complete",
994 "Context sensitive argument completion",
996 el_set(el
, EL_BIND
, "^I", "ftp-complete", NULL
);
997 el_source(el
, NULL
); /* read ~/.editrc */
998 if ((el_get(el
, EL_EDITMODE
, &editmode
) != -1) && editmode
== 0)
999 editing
= 0; /* the user doesn't want editing,
1000 * so disable, and let statement
1003 el_set(el
, EL_SIGNAL
, 1);
1016 #endif /* !NO_EDITCOMPLETE */
1019 * Convert the string `arg' to an int, which may have an optional SI suffix
1020 * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
1023 strsuftoi(const char *arg
)
1028 if (!isdigit((unsigned char)arg
[0]))
1031 val
= strtol(arg
, &cp
, 10);
1033 if (cp
[0] != '\0' && cp
[1] != '\0')
1035 switch (tolower((unsigned char)cp
[0])) {
1052 if (val
< 0 || val
> INT_MAX
)
1059 * Set up socket buffer sizes before a connection is made.
1062 setupsockbufsize(int sock
)
1065 if (setsockopt(sock
, SOL_SOCKET
, SO_SNDBUF
,
1066 (void *)&sndbuf_size
, sizeof(sndbuf_size
)) == -1)
1067 warn("Unable to set sndbuf size %d", sndbuf_size
);
1069 if (setsockopt(sock
, SOL_SOCKET
, SO_RCVBUF
,
1070 (void *)&rcvbuf_size
, sizeof(rcvbuf_size
)) == -1)
1071 warn("Unable to set rcvbuf size %d", rcvbuf_size
);
1075 * Copy characters from src into dst, \ quoting characters that require it
1078 ftpvis(char *dst
, size_t dstlen
, const char *src
, size_t srclen
)
1083 src
[si
] != '\0' && di
< dstlen
&& si
< srclen
;
1104 * Copy src into buf (which is len bytes long), expanding % sequences.
1107 formatbuf(char *buf
, size_t len
, const char *src
)
1109 const char *p
, *p2
, *q
;
1110 int i
, op
, updirs
, pdirs
;
1112 #define ADDBUF(x) do { \
1119 for (i
= 0; *p
; p
++) {
1131 p2
= connected
? remotecwd
: "";
1134 /* option to determine fixed # of dirs from path */
1135 if (op
== '.' || op
== 'c') {
1139 while (*p2
) /* calc # of /'s */
1142 if (p
[1] == '0') { /* print <x> or ... */
1146 if (p
[1] >= '1' && p
[1] <= '9') {
1147 /* calc # to skip */
1154 while (skip
-- > 0) {
1155 while ((p2
> q
) && (*p2
!= '/'))
1160 if (*p2
== '/' && p2
!= q
)
1164 if (updirs
> 0 && pdirs
) {
1178 ADDBUF('0' + updirs
);
1188 for (p2
= connected
&& hostname
? hostname
: "-";
1190 if (op
== 'm' && *p2
== '.')
1197 for (p2
= connected
? username
: "-"; *p2
; p2
++)
1205 default: /* display unknown codes literally */
1217 * Parse `port' into a TCP port number, defaulting to `defport' if `port' is
1218 * an unknown service name. If defport != -1, print a warning upon bad parse.
1221 parseport(const char *port
, int defport
)
1227 p
= ftp_strdup(port
);
1228 nport
= strtol(p
, &ep
, 10);
1229 if (*ep
!= '\0' && ep
== p
) {
1230 struct servent
*svp
;
1232 svp
= getservbyname(port
, "tcp");
1236 warnx("Unknown port `%s', using port %d",
1240 rv
= ntohs(svp
->s_port
);
1241 } else if (nport
< 1 || nport
> MAX_IN_PORT_T
|| *ep
!= '\0')
1250 * Determine if given string is an IPv6 address or not.
1251 * Return 1 for yes, 0 for no
1254 isipv6addr(const char *addr
)
1258 struct addrinfo hints
, *res
;
1260 memset(&hints
, 0, sizeof(hints
));
1261 hints
.ai_family
= PF_INET6
;
1262 hints
.ai_socktype
= SOCK_DGRAM
; /*dummy*/
1263 hints
.ai_flags
= AI_NUMERICHOST
;
1264 if (getaddrinfo(addr
, "0", &hints
, &res
) != 0)
1270 DPRINTF("isipv6addr: got %d for %s\n", rv
, addr
);
1272 return (rv
== 1) ? 1 : 0;
1276 * Read a line from the FILE stream into buf/buflen using fgets(), so up
1277 * to buflen-1 chars will be read and the result will be NUL terminated.
1278 * If the line has a trailing newline it will be removed.
1279 * If the line is too long, excess characters will be read until
1280 * newline/EOF/error.
1281 * If EOF/error occurs or a too-long line is encountered and errormsg
1282 * isn't NULL, it will be changed to a description of the problem.
1283 * (The EOF message has a leading \n for cosmetic purposes).
1285 * >=0 length of line (excluding trailing newline) if all ok
1287 * -2 EOF encountered
1288 * -3 line was too long
1291 getline(FILE *stream
, char *buf
, size_t buflen
, const char **errormsg
)
1296 if (fgets(buf
, buflen
, stream
) == NULL
) {
1297 if (feof(stream
)) { /* EOF */
1300 *errormsg
= "\nEOF received";
1301 } else { /* error */
1304 *errormsg
= "Error encountered";
1310 if (buf
[len
-1] == '\n') { /* clear any trailing newline */
1312 } else if (len
== buflen
-1) { /* line too long */
1313 while ((ch
= getchar()) != '\n' && ch
!= EOF
)
1316 *errormsg
= "Input line is too long";
1326 * Internal version of connect(2); sets socket buffer sizes,
1327 * binds to a specific local address (if set), and
1328 * supports a connection timeout using a non-blocking connect(2) with
1330 * Socket fcntl flags are temporarily updated to include O_NONBLOCK;
1331 * these will not be reverted on connection failure.
1332 * Returns 0 on success, or -1 upon failure (with an appropriate
1333 * error message displayed.)
1336 ftp_connect(int sock
, const struct sockaddr
*name
, socklen_t namelen
)
1338 int flags
, rv
, timeout
, error
;
1340 struct timeval endtime
, now
, td
;
1341 struct pollfd pfd
[1];
1342 char hname
[NI_MAXHOST
];
1344 setupsockbufsize(sock
);
1345 if (getnameinfo(name
, namelen
,
1346 hname
, sizeof(hname
), NULL
, 0, NI_NUMERICHOST
) != 0)
1347 strlcpy(hname
, "?", sizeof(hname
));
1349 if (bindai
!= NULL
) { /* bind to specific addr */
1350 struct addrinfo
*ai
;
1352 for (ai
= bindai
; ai
!= NULL
; ai
= ai
->ai_next
) {
1353 if (ai
->ai_family
== name
->sa_family
)
1358 if (bind(sock
, ai
->ai_addr
, ai
->ai_addrlen
) == -1) {
1359 char bname
[NI_MAXHOST
];
1363 if (getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
,
1364 bname
, sizeof(bname
), NULL
, 0, NI_NUMERICHOST
) != 0)
1365 strlcpy(bname
, "?", sizeof(bname
));
1367 warn("Can't bind to `%s'", bname
);
1372 /* save current socket flags */
1373 if ((flags
= fcntl(sock
, F_GETFL
, 0)) == -1) {
1374 warn("Can't %s socket flags for connect to `%s'",
1378 /* set non-blocking connect */
1379 if (fcntl(sock
, F_SETFL
, flags
| O_NONBLOCK
) == -1) {
1380 warn("Can't set socket non-blocking for connect to `%s'",
1385 /* NOTE: we now must restore socket flags on successful exit */
1388 pfd
[0].events
= POLLIN
|POLLOUT
;
1390 if (quit_time
> 0) { /* want a non default timeout */
1391 (void)gettimeofday(&endtime
, NULL
);
1392 endtime
.tv_sec
+= quit_time
; /* determine end time */
1395 rv
= connect(sock
, name
, namelen
); /* inititate the connection */
1396 if (rv
== -1) { /* connection error */
1397 if (errno
!= EINPROGRESS
) { /* error isn't "please wait" */
1399 warn("Can't connect to `%s'", hname
);
1403 /* connect EINPROGRESS; wait */
1405 if (quit_time
> 0) { /* determine timeout */
1406 (void)gettimeofday(&now
, NULL
);
1407 timersub(&endtime
, &now
, &td
);
1408 timeout
= td
.tv_sec
* 1000 + td
.tv_usec
/1000;
1415 rv
= ftp_poll(pfd
, 1, timeout
);
1416 /* loop until poll ! EINTR */
1417 } while (rv
== -1 && errno
== EINTR
);
1419 if (rv
== 0) { /* poll (connect) timed out */
1424 if (rv
== -1) { /* poll error */
1426 } else if (pfd
[0].revents
& (POLLIN
|POLLOUT
)) {
1427 slen
= sizeof(error
); /* OK, or pending error */
1428 if (getsockopt(sock
, SOL_SOCKET
, SO_ERROR
,
1429 &error
, &slen
) == -1) {
1430 /* Solaris pending error */
1432 } else if (error
!= 0) {
1433 errno
= error
; /* BSD pending error */
1437 errno
= EBADF
; /* this shouldn't happen ... */
1442 if (fcntl(sock
, F_SETFL
, flags
) == -1) {
1443 /* restore socket flags */
1444 warn("Can't %s socket flags for connect to `%s'",
1452 * Internal version of listen(2); sets socket buffer sizes first.
1455 ftp_listen(int sock
, int backlog
)
1458 setupsockbufsize(sock
);
1459 return (listen(sock
, backlog
));
1463 * Internal version of poll(2), to allow reimplementation by select(2)
1464 * on platforms without the former.
1467 ftp_poll(struct pollfd
*fds
, int nfds
, int timeout
)
1469 return poll(fds
, nfds
, timeout
);
1473 * malloc() with inbuilt error checking
1476 ftp_malloc(size_t size
)
1482 err(1, "Unable to allocate %ld bytes of memory", (long)size
);
1487 * sl_init() with inbuilt error checking
1496 err(1, "Unable to allocate memory for stringlist");
1501 * sl_add() with inbuilt error checking
1504 ftp_sl_add(StringList
*sl
, char *i
)
1507 if (sl_add(sl
, i
) == -1)
1508 err(1, "Unable to add `%s' to stringlist", i
);
1512 * strdup() with inbuilt error checking
1515 ftp_strdup(const char *str
)
1520 errx(1, "ftp_strdup: called with NULL argument");
1523 err(1, "Unable to allocate memory for string copy");