util.c revision 1.102 1 /* $NetBSD: util.c,v 1.102 2000/09/08 11:54:53 lukem Exp $ */
2
3 /*-
4 * Copyright (c) 1997-2000 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 * 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.
13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
16 * are met:
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.
29 *
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.
41 */
42
43 /*
44 * Copyright (c) 1985, 1989, 1993, 1994
45 * The Regents of the University of California. All rights reserved.
46 *
47 * Redistribution and use in source and binary forms, with or without
48 * modification, are permitted provided that the following conditions
49 * are met:
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. All advertising materials mentioning features or use of this software
56 * must display the following acknowledgement:
57 * This product includes software developed by the University of
58 * California, Berkeley and its contributors.
59 * 4. Neither the name of the University nor the names of its contributors
60 * may be used to endorse or promote products derived from this software
61 * without specific prior written permission.
62 *
63 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
64 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
65 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
66 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
67 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
68 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
69 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
70 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
71 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
72 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
73 * SUCH DAMAGE.
74 */
75
76 #include <sys/cdefs.h>
77 #ifndef lint
78 __RCSID("$NetBSD: util.c,v 1.102 2000/09/08 11:54:53 lukem Exp $");
79 #endif /* not lint */
80
81 /*
82 * FTP User Program -- Misc support routines
83 */
84 #include <sys/types.h>
85 #include <sys/socket.h>
86 #include <sys/ioctl.h>
87 #include <sys/time.h>
88 #include <netinet/in.h>
89 #include <arpa/ftp.h>
90
91 #include <ctype.h>
92 #include <err.h>
93 #include <errno.h>
94 #include <fcntl.h>
95 #include <glob.h>
96 #include <signal.h>
97 #include <limits.h>
98 #include <netdb.h>
99 #include <pwd.h>
100 #include <stdio.h>
101 #include <stdlib.h>
102 #include <string.h>
103 #include <termios.h>
104 #include <time.h>
105 #include <tzfile.h>
106 #include <unistd.h>
107
108 #include "ftp_var.h"
109
110 /*
111 * Connect to peer server and auto-login, if possible.
112 */
113 void
114 setpeer(int argc, char *argv[])
115 {
116 char *host;
117 char *port;
118
119 if (argc == 0)
120 goto usage;
121 if (connected) {
122 fprintf(ttyout, "Already connected to %s, use close first.\n",
123 hostname);
124 code = -1;
125 return;
126 }
127 if (argc < 2)
128 (void)another(&argc, &argv, "to");
129 if (argc < 2 || argc > 3) {
130 usage:
131 fprintf(ttyout, "usage: %s host-name [port]\n", argv[0]);
132 code = -1;
133 return;
134 }
135 if (gatemode)
136 port = gateport;
137 else
138 port = ftpport;
139 if (argc > 2)
140 port = argv[2];
141
142 if (gatemode) {
143 if (gateserver == NULL || *gateserver == '\0')
144 errx(1, "gateserver not defined (shouldn't happen)");
145 host = hookup(gateserver, port);
146 } else
147 host = hookup(argv[1], port);
148
149 if (host) {
150 if (gatemode && verbose) {
151 fprintf(ttyout,
152 "Connecting via pass-through server %s\n",
153 gateserver);
154 }
155
156 connected = 1;
157 /*
158 * Set up defaults for FTP.
159 */
160 (void)strlcpy(typename, "ascii", sizeof(typename));
161 type = TYPE_A;
162 curtype = TYPE_A;
163 (void)strlcpy(formname, "non-print", sizeof(formname));
164 form = FORM_N;
165 (void)strlcpy(modename, "stream", sizeof(modename));
166 mode = MODE_S;
167 (void)strlcpy(structname, "file", sizeof(structname));
168 stru = STRU_F;
169 (void)strlcpy(bytename, "8", sizeof(bytename));
170 bytesize = 8;
171 if (autologin)
172 (void)ftp_login(argv[1], NULL, NULL);
173 }
174 }
175
176 static void
177 parse_feat(const char *line)
178 {
179
180 if (strcasecmp(line, " MDTM") == 0)
181 features[FEAT_MDTM] = 1;
182 else if (strncasecmp(line, " MLST", sizeof(" MLST") - 1) == 0) {
183 features[FEAT_MLST] = 1;
184 } else if (strcasecmp(line, " REST STREAM") == 0)
185 features[FEAT_REST_STREAM] = 1;
186 else if (strcasecmp(line, " SIZE") == 0)
187 features[FEAT_SIZE] = 1;
188 else if (strcasecmp(line, " TVFS") == 0)
189 features[FEAT_TVFS] = 1;
190 }
191
192 /*
193 * Determine the remote system type (SYST) and features (FEAT).
194 * Call after a successful login (i.e, connected = -1)
195 */
196 void
197 getremoteinfo(void)
198 {
199 int overbose, i;
200
201 overbose = verbose;
202 if (debug == 0)
203 verbose = -1;
204
205 /* determine remote system type */
206 if (command("SYST") == COMPLETE) {
207 if (overbose) {
208 char *cp, c;
209
210 c = 0;
211 cp = strchr(reply_string + 4, ' ');
212 if (cp == NULL)
213 cp = strchr(reply_string + 4, '\r');
214 if (cp) {
215 if (cp[-1] == '.')
216 cp--;
217 c = *cp;
218 *cp = '\0';
219 }
220
221 fprintf(ttyout, "Remote system type is %s.\n",
222 reply_string + 4);
223 if (cp)
224 *cp = c;
225 }
226 if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
227 if (proxy)
228 unix_proxy = 1;
229 else
230 unix_server = 1;
231 /*
232 * Set type to 0 (not specified by user),
233 * meaning binary by default, but don't bother
234 * telling server. We can use binary
235 * for text files unless changed by the user.
236 */
237 type = 0;
238 (void)strlcpy(typename, "binary", sizeof(typename));
239 if (overbose)
240 fprintf(ttyout,
241 "Using %s mode to transfer files.\n",
242 typename);
243 } else {
244 if (proxy)
245 unix_proxy = 0;
246 else
247 unix_server = 0;
248 if (overbose &&
249 !strncmp(reply_string, "215 TOPS20", 10))
250 fputs(
251 "Remember to set tenex mode when transferring binary files from this machine.\n",
252 ttyout);
253 }
254 }
255
256 /* determine features (if any) */
257 for (i = 0; i < FEAT_max; i++)
258 features[i] = -1;
259 reply_callback = parse_feat;
260 if (command("FEAT") == COMPLETE) {
261 for (i = 0; i < FEAT_max; i++) {
262 if (features[i] == -1)
263 features[i] = 0;
264 }
265 features[FEAT_FEAT] = 1;
266 } else
267 features[FEAT_FEAT] = 0;
268 if (debug)
269 for (i = 0; i < FEAT_max; i++)
270 printf("features[%d] = %d\n", i, features[i]);
271 reply_callback = NULL;
272
273 verbose = overbose;
274 }
275
276 /*
277 * Reset the various variables that indicate connection state back to
278 * disconnected settings.
279 * The caller is responsible for issuing any commands to the remote server
280 * to perform a clean shutdown before this is invoked.
281 */
282 void
283 cleanuppeer(void)
284 {
285
286 if (cout)
287 (void)fclose(cout);
288 cout = NULL;
289 connected = 0;
290 unix_server = 0;
291 unix_proxy = 0;
292 /*
293 * determine if anonftp was specifically set with -a
294 * (1), or implicitly set by auto_fetch() (2). in the
295 * latter case, disable after the current xfer
296 */
297 if (anonftp == 2)
298 anonftp = 0;
299 data = -1;
300 epsv4bad = 0;
301 if (username)
302 free(username);
303 username = NULL;
304 if (!proxy)
305 macnum = 0;
306 }
307
308 /*
309 * Top-level signal handler for interrupted commands.
310 */
311 void
312 intr(int dummy)
313 {
314
315 alarmtimer(0);
316 if (fromatty)
317 write(fileno(ttyout), "\n", 1);
318 siglongjmp(toplevel, 1);
319 }
320
321 /*
322 * Signal handler for lost connections; cleanup various elements of
323 * the connection state, and call cleanuppeer() to finish it off.
324 */
325 void
326 lostpeer(int dummy)
327 {
328 int oerrno = errno;
329
330 alarmtimer(0);
331 if (connected) {
332 if (cout != NULL) {
333 (void)shutdown(fileno(cout), 1+1);
334 (void)fclose(cout);
335 cout = NULL;
336 }
337 if (data >= 0) {
338 (void)shutdown(data, 1+1);
339 (void)close(data);
340 data = -1;
341 }
342 connected = 0;
343 }
344 pswitch(1);
345 if (connected) {
346 if (cout != NULL) {
347 (void)shutdown(fileno(cout), 1+1);
348 (void)fclose(cout);
349 cout = NULL;
350 }
351 connected = 0;
352 }
353 proxflag = 0;
354 pswitch(0);
355 cleanuppeer();
356 errno = oerrno;
357 }
358
359
360 /*
361 * Login to remote host, using given username & password if supplied.
362 * Return non-zero if successful.
363 */
364 int
365 ftp_login(const char *host, const char *user, const char *pass)
366 {
367 char tmp[80];
368 const char *acct;
369 struct passwd *pw;
370 int n, aflag, rval, freeuser, freepass, freeacct;
371
372 acct = NULL;
373 aflag = rval = freeuser = freepass = freeacct = 0;
374
375 if (debug)
376 fprintf(ttyout, "ftp_login: user `%s' pass `%s' host `%s'\n",
377 user ? user : "<null>", pass ? pass : "<null>",
378 host ? host : "<null>");
379
380
381 /*
382 * Set up arguments for an anonymous FTP session, if necessary.
383 */
384 if (anonftp) {
385 user = "anonymous"; /* as per RFC 1635 */
386 pass = getoptionvalue("anonpass");
387 }
388
389 if (user == NULL)
390 freeuser = 1;
391 if (pass == NULL)
392 freepass = 1;
393 freeacct = 1;
394 if (ruserpass(host, &user, &pass, &acct) < 0) {
395 code = -1;
396 goto cleanup_ftp_login;
397 }
398
399 while (user == NULL) {
400 const char *myname = getlogin();
401
402 if (myname == NULL && (pw = getpwuid(getuid())) != NULL)
403 myname = pw->pw_name;
404 if (myname)
405 fprintf(ttyout, "Name (%s:%s): ", host, myname);
406 else
407 fprintf(ttyout, "Name (%s): ", host);
408 *tmp = '\0';
409 if (fgets(tmp, sizeof(tmp) - 1, stdin) == NULL) {
410 fprintf(ttyout, "\nEOF received; login aborted.\n");
411 clearerr(stdin);
412 code = -1;
413 goto cleanup_ftp_login;
414 }
415 tmp[strlen(tmp) - 1] = '\0';
416 freeuser = 0;
417 if (*tmp == '\0')
418 user = myname;
419 else
420 user = tmp;
421 }
422
423 if (gatemode) {
424 char *nuser;
425 int len;
426
427 len = strlen(user) + 1 + strlen(host) + 1;
428 nuser = xmalloc(len);
429 (void)strlcpy(nuser, user, len);
430 (void)strlcat(nuser, "@", len);
431 (void)strlcat(nuser, host, len);
432 freeuser = 1;
433 user = nuser;
434 }
435
436 n = command("USER %s", user);
437 if (n == CONTINUE) {
438 if (pass == NULL) {
439 freepass = 0;
440 pass = getpass("Password:");
441 }
442 n = command("PASS %s", pass);
443 }
444 if (n == CONTINUE) {
445 aflag++;
446 if (acct == NULL) {
447 freeacct = 0;
448 acct = getpass("Account:");
449 }
450 if (acct[0] == '\0') {
451 warnx("Login failed.");
452 goto cleanup_ftp_login;
453 }
454 n = command("ACCT %s", acct);
455 }
456 if ((n != COMPLETE) ||
457 (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
458 warnx("Login failed.");
459 goto cleanup_ftp_login;
460 }
461 rval = 1;
462 username = xstrdup(user);
463 if (proxy)
464 goto cleanup_ftp_login;
465
466 connected = -1;
467 getremoteinfo();
468 for (n = 0; n < macnum; ++n) {
469 if (!strcmp("init", macros[n].mac_name)) {
470 (void)strlcpy(line, "$init", sizeof(line));
471 makeargv();
472 domacro(margc, margv);
473 break;
474 }
475 }
476 updateremotepwd();
477
478 cleanup_ftp_login:
479 if (user != NULL && freeuser)
480 free((char *)user);
481 if (pass != NULL && freepass)
482 free((char *)pass);
483 if (acct != NULL && freeacct)
484 free((char *)acct);
485 return (rval);
486 }
487
488 /*
489 * `another' gets another argument, and stores the new argc and argv.
490 * It reverts to the top level (via intr()) on EOF/error.
491 *
492 * Returns false if no new arguments have been added.
493 */
494 int
495 another(int *pargc, char ***pargv, const char *prompt)
496 {
497 int len = strlen(line), ret;
498
499 if (len >= sizeof(line) - 3) {
500 fputs("sorry, arguments too long.\n", ttyout);
501 intr(0);
502 }
503 fprintf(ttyout, "(%s) ", prompt);
504 line[len++] = ' ';
505 if (fgets(&line[len], sizeof(line) - len, stdin) == NULL) {
506 clearerr(stdin);
507 intr(0);
508 }
509 len += strlen(&line[len]);
510 if (len > 0 && line[len - 1] == '\n')
511 line[len - 1] = '\0';
512 makeargv();
513 ret = margc > *pargc;
514 *pargc = margc;
515 *pargv = margv;
516 return (ret);
517 }
518
519 /*
520 * glob files given in argv[] from the remote server.
521 * if errbuf isn't NULL, store error messages there instead
522 * of writing to the screen.
523 */
524 char *
525 remglob(char *argv[], int doswitch, char **errbuf)
526 {
527 char temp[MAXPATHLEN];
528 static char buf[MAXPATHLEN];
529 static FILE *ftemp = NULL;
530 static char **args;
531 int oldverbose, oldhash, fd, len;
532 char *cp, *mode;
533
534 if (!mflag || !connected) {
535 if (!doglob)
536 args = NULL;
537 else {
538 if (ftemp) {
539 (void)fclose(ftemp);
540 ftemp = NULL;
541 }
542 }
543 return (NULL);
544 }
545 if (!doglob) {
546 if (args == NULL)
547 args = argv;
548 if ((cp = *++args) == NULL)
549 args = NULL;
550 return (cp);
551 }
552 if (ftemp == NULL) {
553 len = strlcpy(temp, tmpdir, sizeof(temp));
554 if (temp[len - 1] != '/')
555 (void)strlcat(temp, "/", sizeof(temp));
556 (void)strlcat(temp, TMPFILE, sizeof(temp));
557 if ((fd = mkstemp(temp)) < 0) {
558 warn("unable to create temporary file %s", temp);
559 return (NULL);
560 }
561 close(fd);
562 oldverbose = verbose;
563 verbose = (errbuf != NULL) ? -1 : 0;
564 oldhash = hash;
565 hash = 0;
566 if (doswitch)
567 pswitch(!proxy);
568 for (mode = "w"; *++argv != NULL; mode = "a")
569 recvrequest("NLST", temp, *argv, mode, 0, 0);
570 if ((code / 100) != COMPLETE) {
571 if (errbuf != NULL)
572 *errbuf = reply_string;
573 }
574 if (doswitch)
575 pswitch(!proxy);
576 verbose = oldverbose;
577 hash = oldhash;
578 ftemp = fopen(temp, "r");
579 (void)unlink(temp);
580 if (ftemp == NULL) {
581 if (errbuf == NULL)
582 fputs(
583 "can't find list of remote files, oops.\n",
584 ttyout);
585 else
586 *errbuf =
587 "can't find list of remote files, oops.";
588 return (NULL);
589 }
590 }
591 if (fgets(buf, sizeof(buf), ftemp) == NULL) {
592 (void)fclose(ftemp);
593 ftemp = NULL;
594 return (NULL);
595 }
596 if ((cp = strchr(buf, '\n')) != NULL)
597 *cp = '\0';
598 return (buf);
599 }
600
601 /*
602 * Glob a local file name specification with the expectation of a single
603 * return value. Can't control multiple values being expanded from the
604 * expression, we return only the first.
605 * Returns NULL on error, or a pointer to a buffer containing the filename
606 * that's the caller's responsiblity to free(3) when finished with.
607 */
608 char *
609 globulize(const char *pattern)
610 {
611 glob_t gl;
612 int flags;
613 char *p;
614
615 if (!doglob)
616 return (xstrdup(pattern));
617
618 flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
619 memset(&gl, 0, sizeof(gl));
620 if (glob(pattern, flags, NULL, &gl) || gl.gl_pathc == 0) {
621 warnx("%s: not found", pattern);
622 globfree(&gl);
623 return (NULL);
624 }
625 p = xstrdup(gl.gl_pathv[0]);
626 globfree(&gl);
627 return (p);
628 }
629
630 /*
631 * determine size of remote file
632 */
633 off_t
634 remotesize(const char *file, int noisy)
635 {
636 int overbose, r;
637 off_t size;
638
639 overbose = verbose;
640 size = -1;
641 if (debug == 0)
642 verbose = -1;
643 if (! features[FEAT_SIZE]) {
644 if (noisy)
645 fprintf(ttyout,
646 "SIZE is not supported by remote server.\n");
647 goto cleanup_remotesize;
648 }
649 r = command("SIZE %s", file);
650 if (r == COMPLETE) {
651 char *cp, *ep;
652
653 cp = strchr(reply_string, ' ');
654 if (cp != NULL) {
655 cp++;
656 size = STRTOLL(cp, &ep, 10);
657 if (*ep != '\0' && !isspace((unsigned char)*ep))
658 size = -1;
659 }
660 } else {
661 if (r == ERROR && code == 500 && features[FEAT_SIZE] == -1)
662 features[FEAT_SIZE] = 0;
663 if (noisy && debug == 0) {
664 fputs(reply_string, ttyout);
665 putc('\n', ttyout);
666 }
667 }
668 cleanup_remotesize:
669 verbose = overbose;
670 return (size);
671 }
672
673 /*
674 * determine last modification time (in GMT) of remote file
675 */
676 time_t
677 remotemodtime(const char *file, int noisy)
678 {
679 int overbose, ocode, r;
680 time_t rtime;
681
682 overbose = verbose;
683 ocode = code;
684 rtime = -1;
685 if (debug == 0)
686 verbose = -1;
687 if (! features[FEAT_MDTM]) {
688 if (noisy)
689 fprintf(ttyout,
690 "MDTM is not supported by remote server.\n");
691 goto cleanup_parse_time;
692 }
693 r = command("MDTM %s", file);
694 if (r == COMPLETE) {
695 struct tm timebuf;
696 char *timestr, *frac;
697 int yy, mo, day, hour, min, sec;
698
699 /*
700 * time-val = 14DIGIT [ "." 1*DIGIT ]
701 * YYYYMMDDHHMMSS[.sss]
702 * mdtm-response = "213" SP time-val CRLF / error-response
703 */
704 timestr = reply_string + 4;
705
706 /*
707 * parse fraction.
708 * XXX: ignored for now
709 */
710 frac = strchr(timestr, '\r');
711 if (frac != NULL)
712 *frac = '\0';
713 frac = strchr(timestr, '.');
714 if (frac != NULL)
715 *frac++ = '\0';
716 if (strlen(timestr) == 15 && strncmp(timestr, "191", 3) == 0) {
717 /*
718 * XXX: Workaround for lame ftpd's that return
719 * `19100' instead of `2000'
720 */
721 fprintf(ttyout,
722 "Y2K warning! Incorrect time-val `%s' received from server.\n",
723 timestr);
724 timestr++;
725 timestr[0] = '2';
726 timestr[1] = '0';
727 fprintf(ttyout, "Converted to `%s'\n", timestr);
728 }
729 if (strlen(timestr) != 14 ||
730 sscanf(timestr, "%04d%02d%02d%02d%02d%02d",
731 &yy, &mo, &day, &hour, &min, &sec) != 6) {
732 bad_parse_time:
733 fprintf(ttyout, "Can't parse time `%s'.\n", timestr);
734 goto cleanup_parse_time;
735 }
736 memset(&timebuf, 0, sizeof(timebuf));
737 timebuf.tm_sec = sec;
738 timebuf.tm_min = min;
739 timebuf.tm_hour = hour;
740 timebuf.tm_mday = day;
741 timebuf.tm_mon = mo - 1;
742 timebuf.tm_year = yy - TM_YEAR_BASE;
743 timebuf.tm_isdst = -1;
744 rtime = timegm(&timebuf);
745 if (rtime == -1) {
746 if (noisy || debug != 0)
747 goto bad_parse_time;
748 else
749 goto cleanup_parse_time;
750 } else if (debug)
751 fprintf(ttyout, "parsed date as: %s", ctime(&rtime));
752 } else {
753 if (r == ERROR && code == 500 && features[FEAT_MDTM] == -1)
754 features[FEAT_MDTM] = 0;
755 if (noisy && debug == 0) {
756 fputs(reply_string, ttyout);
757 putc('\n', ttyout);
758 }
759 }
760 cleanup_parse_time:
761 verbose = overbose;
762 if (rtime == -1)
763 code = ocode;
764 return (rtime);
765 }
766
767 /*
768 * update global `remotepwd', which contains the state of the remote cwd
769 */
770 void
771 updateremotepwd(void)
772 {
773 int overbose, ocode, i;
774 char *cp;
775
776 overbose = verbose;
777 ocode = code;
778 if (debug == 0)
779 verbose = -1;
780 if (command("PWD") != COMPLETE)
781 goto badremotepwd;
782 cp = strchr(reply_string, ' ');
783 if (cp == NULL || cp[0] == '\0' || cp[1] != '"')
784 goto badremotepwd;
785 cp += 2;
786 for (i = 0; *cp && i < sizeof(remotepwd) - 1; i++, cp++) {
787 if (cp[0] == '"') {
788 if (cp[1] == '"')
789 cp++;
790 else
791 break;
792 }
793 remotepwd[i] = *cp;
794 }
795 remotepwd[i] = '\0';
796 if (debug)
797 fprintf(ttyout, "got remotepwd as `%s'\n", remotepwd);
798 goto cleanupremotepwd;
799 badremotepwd:
800 remotepwd[0]='\0';
801 cleanupremotepwd:
802 verbose = overbose;
803 code = ocode;
804 }
805
806 #ifndef NO_PROGRESS
807
808 /*
809 * return non-zero if we're the current foreground process
810 */
811 int
812 foregroundproc(void)
813 {
814 static pid_t pgrp = -1;
815
816 if (pgrp == -1)
817 pgrp = getpgrp();
818
819 return (tcgetpgrp(fileno(ttyout)) == pgrp);
820 }
821
822
823 static void updateprogressmeter(int);
824
825 /*
826 * SIGALRM handler to update the progress meter
827 */
828 static void
829 updateprogressmeter(int dummy)
830 {
831 int oerrno = errno;
832
833 progressmeter(0);
834 errno = oerrno;
835 }
836 #endif /* NO_PROGRESS */
837
838
839 /*
840 * List of order of magnitude prefixes.
841 * The last is `P', as 2^64 = 16384 Petabytes
842 */
843 static const char prefixes[] = " KMGTP";
844
845 /*
846 * Display a transfer progress bar if progress is non-zero.
847 * SIGALRM is hijacked for use by this function.
848 * - Before the transfer, set filesize to size of file (or -1 if unknown),
849 * and call with flag = -1. This starts the once per second timer,
850 * and a call to updateprogressmeter() upon SIGALRM.
851 * - During the transfer, updateprogressmeter will call progressmeter
852 * with flag = 0
853 * - After the transfer, call with flag = 1
854 */
855 static struct timeval start;
856 static struct timeval lastupdate;
857
858 #define BUFLEFT (sizeof(buf) - len)
859
860 void
861 progressmeter(int flag)
862 {
863 static off_t lastsize;
864 #ifndef NO_PROGRESS
865 struct timeval now, td, wait;
866 off_t cursize, abbrevsize, bytespersec;
867 double elapsed;
868 int ratio, barlength, i, len, remaining;
869
870 /*
871 * Work variables for progress bar.
872 *
873 * XXX: if the format of the progress bar changes
874 * (especially the number of characters in the
875 * `static' portion of it), be sure to update
876 * these appropriately.
877 */
878 char buf[256]; /* workspace for progress bar */
879 #define BAROVERHEAD 43 /* non `*' portion of progress bar */
880 /*
881 * stars should contain at least
882 * sizeof(buf) - BAROVERHEAD entries
883 */
884 const char stars[] =
885 "*****************************************************************************"
886 "*****************************************************************************"
887 "*****************************************************************************";
888
889 #endif
890
891 if (flag == -1) {
892 (void)gettimeofday(&start, NULL);
893 lastupdate = start;
894 lastsize = restart_point;
895 }
896 #ifndef NO_PROGRESS
897 len = 0;
898 if (!progress || filesize <= 0)
899 return;
900
901 /*
902 * print progress bar only if we are foreground process.
903 */
904 if (! foregroundproc())
905 return;
906
907 (void)gettimeofday(&now, NULL);
908 cursize = bytes + restart_point;
909 timersub(&now, &lastupdate, &wait);
910 if (cursize > lastsize) {
911 lastupdate = now;
912 lastsize = cursize;
913 wait.tv_sec = 0;
914 }
915
916 ratio = (int)((double)cursize * 100.0 / (double)filesize);
917 ratio = MAX(ratio, 0);
918 ratio = MIN(ratio, 100);
919 len += snprintf(buf + len, BUFLEFT, "\r%3d%% ", ratio);
920
921 /*
922 * calculate the length of the `*' bar, ensuring that
923 * the number of stars won't exceed the buffer size
924 */
925 barlength = MIN(sizeof(buf) - 1, ttywidth) - BAROVERHEAD;
926 if (barlength > 0) {
927 i = barlength * ratio / 100;
928 len += snprintf(buf + len, BUFLEFT,
929 "|%.*s%*s|", i, stars, barlength - i, "");
930 }
931
932 abbrevsize = cursize;
933 for (i = 0; abbrevsize >= 100000 && i < sizeof(prefixes); i++)
934 abbrevsize >>= 10;
935 len += snprintf(buf + len, BUFLEFT, " " LLFP("5") " %c%c ",
936 (LLT)abbrevsize,
937 prefixes[i],
938 i == 0 ? ' ' : 'B');
939
940 timersub(&now, &start, &td);
941 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
942
943 bytespersec = 0;
944 if (bytes > 0) {
945 bytespersec = bytes;
946 if (elapsed > 0.0)
947 bytespersec /= elapsed;
948 }
949 for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
950 bytespersec >>= 10;
951 len += snprintf(buf + len, BUFLEFT,
952 " " LLFP("3") ".%02d %cB/s ",
953 (LLT)(bytespersec / 1024),
954 (int)((bytespersec % 1024) * 100 / 1024),
955 prefixes[i]);
956
957 if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
958 len += snprintf(buf + len, BUFLEFT, " --:-- ETA");
959 } else if (wait.tv_sec >= STALLTIME) {
960 len += snprintf(buf + len, BUFLEFT, " - stalled -");
961 } else {
962 remaining = (int)
963 ((filesize - restart_point) / (bytes / elapsed) - elapsed);
964 if (remaining >= 100 * SECSPERHOUR)
965 len += snprintf(buf + len, BUFLEFT, " --:-- ETA");
966 else {
967 i = remaining / SECSPERHOUR;
968 if (i)
969 len += snprintf(buf + len, BUFLEFT, "%2d:", i);
970 else
971 len += snprintf(buf + len, BUFLEFT, " ");
972 i = remaining % SECSPERHOUR;
973 len += snprintf(buf + len, BUFLEFT,
974 "%02d:%02d ETA", i / 60, i % 60);
975 }
976 }
977 if (flag == 1)
978 len += snprintf(buf + len, BUFLEFT, "\n");
979 (void)write(fileno(ttyout), buf, len);
980
981 if (flag == -1) {
982 (void)xsignal_restart(SIGALRM, updateprogressmeter, 1);
983 alarmtimer(1); /* set alarm timer for 1 Hz */
984 } else if (flag == 1) {
985 (void)xsignal(SIGALRM, SIG_DFL);
986 alarmtimer(0);
987 }
988 #endif /* !NO_PROGRESS */
989 }
990
991 /*
992 * Display transfer statistics.
993 * Requires start to be initialised by progressmeter(-1),
994 * direction to be defined by xfer routines, and filesize and bytes
995 * to be updated by xfer routines
996 * If siginfo is nonzero, an ETA is displayed, and the output goes to stderr
997 * instead of ttyout.
998 */
999 void
1000 ptransfer(int siginfo)
1001 {
1002 struct timeval now, td, wait;
1003 double elapsed;
1004 off_t bytespersec;
1005 int remaining, hh, i, len;
1006
1007 char buf[256]; /* Work variable for transfer status. */
1008
1009 if (!verbose && !progress && !siginfo)
1010 return;
1011
1012 (void)gettimeofday(&now, NULL);
1013 timersub(&now, &start, &td);
1014 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
1015 bytespersec = 0;
1016 if (bytes > 0) {
1017 bytespersec = bytes;
1018 if (elapsed > 0.0)
1019 bytespersec /= elapsed;
1020 }
1021 len = 0;
1022 len += snprintf(buf + len, BUFLEFT, LLF " byte%s %s in ",
1023 (LLT)bytes, bytes == 1 ? "" : "s", direction);
1024 remaining = (int)elapsed;
1025 if (remaining > SECSPERDAY) {
1026 int days;
1027
1028 days = remaining / SECSPERDAY;
1029 remaining %= SECSPERDAY;
1030 len += snprintf(buf + len, BUFLEFT,
1031 "%d day%s ", days, days == 1 ? "" : "s");
1032 }
1033 hh = remaining / SECSPERHOUR;
1034 remaining %= SECSPERHOUR;
1035 if (hh)
1036 len += snprintf(buf + len, BUFLEFT, "%2d:", hh);
1037 len += snprintf(buf + len, BUFLEFT,
1038 "%02d:%02d ", remaining / 60, remaining % 60);
1039
1040 for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
1041 bytespersec >>= 10;
1042 len += snprintf(buf + len, BUFLEFT, "(" LLF ".%02d %cB/s)",
1043 (LLT)(bytespersec / 1024),
1044 (int)((bytespersec % 1024) * 100 / 1024),
1045 prefixes[i]);
1046
1047 if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
1048 && bytes + restart_point <= filesize) {
1049 remaining = (int)((filesize - restart_point) /
1050 (bytes / elapsed) - elapsed);
1051 hh = remaining / SECSPERHOUR;
1052 remaining %= SECSPERHOUR;
1053 len += snprintf(buf + len, BUFLEFT, " ETA: ");
1054 if (hh)
1055 len += snprintf(buf + len, BUFLEFT, "%2d:", hh);
1056 len += snprintf(buf + len, BUFLEFT, "%02d:%02d",
1057 remaining / 60, remaining % 60);
1058 timersub(&now, &lastupdate, &wait);
1059 if (wait.tv_sec >= STALLTIME)
1060 len += snprintf(buf + len, BUFLEFT, " (stalled)");
1061 }
1062 len += snprintf(buf + len, BUFLEFT, "\n");
1063 (void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, len);
1064 }
1065
1066 /*
1067 * SIG{INFO,QUIT} handler to print transfer stats if a transfer is in progress
1068 */
1069 void
1070 psummary(int notused)
1071 {
1072 int oerrno = errno;
1073
1074 if (bytes > 0) {
1075 if (fromatty)
1076 write(fileno(ttyout), "\n", 1);
1077 ptransfer(1);
1078 }
1079 errno = oerrno;
1080 }
1081
1082 /*
1083 * List words in stringlist, vertically arranged
1084 */
1085 void
1086 list_vertical(StringList *sl)
1087 {
1088 int i, j, w;
1089 int columns, width, lines;
1090 char *p;
1091
1092 width = 0;
1093
1094 for (i = 0 ; i < sl->sl_cur ; i++) {
1095 w = strlen(sl->sl_str[i]);
1096 if (w > width)
1097 width = w;
1098 }
1099 width = (width + 8) &~ 7;
1100
1101 columns = ttywidth / width;
1102 if (columns == 0)
1103 columns = 1;
1104 lines = (sl->sl_cur + columns - 1) / columns;
1105 for (i = 0; i < lines; i++) {
1106 for (j = 0; j < columns; j++) {
1107 p = sl->sl_str[j * lines + i];
1108 if (p)
1109 fputs(p, ttyout);
1110 if (j * lines + i + lines >= sl->sl_cur) {
1111 putc('\n', ttyout);
1112 break;
1113 }
1114 w = strlen(p);
1115 while (w < width) {
1116 w = (w + 8) &~ 7;
1117 (void)putc('\t', ttyout);
1118 }
1119 }
1120 }
1121 }
1122
1123 /*
1124 * Update the global ttywidth value, using TIOCGWINSZ.
1125 */
1126 void
1127 setttywidth(int a)
1128 {
1129 struct winsize winsize;
1130 int oerrno = errno;
1131
1132 if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
1133 winsize.ws_col != 0)
1134 ttywidth = winsize.ws_col;
1135 else
1136 ttywidth = 80;
1137 errno = oerrno;
1138 }
1139
1140 /*
1141 * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
1142 */
1143 void
1144 crankrate(int sig)
1145 {
1146
1147 switch (sig) {
1148 case SIGUSR1:
1149 if (rate_get)
1150 rate_get += rate_get_incr;
1151 if (rate_put)
1152 rate_put += rate_put_incr;
1153 break;
1154 case SIGUSR2:
1155 if (rate_get && rate_get > rate_get_incr)
1156 rate_get -= rate_get_incr;
1157 if (rate_put && rate_put > rate_put_incr)
1158 rate_put -= rate_put_incr;
1159 break;
1160 default:
1161 err(1, "crankrate invoked with unknown signal: %d", sig);
1162 }
1163 }
1164
1165
1166 /*
1167 * Set the SIGALRM interval timer for wait seconds, 0 to disable.
1168 */
1169 void
1170 alarmtimer(int wait)
1171 {
1172 struct itimerval itv;
1173
1174 itv.it_value.tv_sec = wait;
1175 itv.it_value.tv_usec = 0;
1176 itv.it_interval = itv.it_value;
1177 setitimer(ITIMER_REAL, &itv, NULL);
1178 }
1179
1180 /*
1181 * Setup or cleanup EditLine structures
1182 */
1183 #ifndef NO_EDITCOMPLETE
1184 void
1185 controlediting(void)
1186 {
1187 if (editing && el == NULL && hist == NULL) {
1188 HistEvent ev;
1189 int editmode;
1190
1191 el = el_init(__progname, stdin, ttyout, stderr);
1192 /* init editline */
1193 hist = history_init(); /* init the builtin history */
1194 history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
1195 el_set(el, EL_HIST, history, hist); /* use history */
1196
1197 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
1198 el_set(el, EL_PROMPT, prompt); /* set the prompt functions */
1199 el_set(el, EL_RPROMPT, rprompt);
1200
1201 /* add local file completion, bind to TAB */
1202 el_set(el, EL_ADDFN, "ftp-complete",
1203 "Context sensitive argument completion",
1204 complete);
1205 el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
1206 el_source(el, NULL); /* read ~/.editrc */
1207 if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
1208 editing = 0; /* the user doesn't want editing,
1209 * so disable, and let statement
1210 * below cleanup */
1211 else
1212 el_set(el, EL_SIGNAL, 1);
1213 }
1214 if (!editing) {
1215 if (hist) {
1216 history_end(hist);
1217 hist = NULL;
1218 }
1219 if (el) {
1220 el_end(el);
1221 el = NULL;
1222 }
1223 }
1224 }
1225 #endif /* !NO_EDITCOMPLETE */
1226
1227 /*
1228 * Convert the string `arg' to an int, which may have an optional SI suffix
1229 * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
1230 */
1231 int
1232 strsuftoi(const char *arg)
1233 {
1234 char *cp;
1235 long val;
1236
1237 if (!isdigit((unsigned char)arg[0]))
1238 return (-1);
1239
1240 val = strtol(arg, &cp, 10);
1241 if (cp != NULL) {
1242 if (cp[0] != '\0' && cp[1] != '\0')
1243 return (-1);
1244 switch (tolower((unsigned char)cp[0])) {
1245 case '\0':
1246 case 'b':
1247 break;
1248 case 'k':
1249 val <<= 10;
1250 break;
1251 case 'm':
1252 val <<= 20;
1253 break;
1254 case 'g':
1255 val <<= 30;
1256 break;
1257 default:
1258 return (-1);
1259 }
1260 }
1261 if (val < 0 || val > INT_MAX)
1262 return (-1);
1263
1264 return (val);
1265 }
1266
1267 /*
1268 * Set up socket buffer sizes before a connection is made.
1269 */
1270 void
1271 setupsockbufsize(int sock)
1272 {
1273
1274 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (void *) &sndbuf_size,
1275 sizeof(rcvbuf_size)) < 0)
1276 warn("unable to set sndbuf size %d", sndbuf_size);
1277
1278 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *) &rcvbuf_size,
1279 sizeof(rcvbuf_size)) < 0)
1280 warn("unable to set rcvbuf size %d", rcvbuf_size);
1281 }
1282
1283 /*
1284 * Copy characters from src into dst, \ quoting characters that require it
1285 */
1286 void
1287 ftpvis(char *dst, size_t dstlen, const char *src, size_t srclen)
1288 {
1289 int di, si;
1290
1291 for (di = si = 0;
1292 src[si] != '\0' && di < dstlen && si < srclen;
1293 di++, si++) {
1294 switch (src[si]) {
1295 case '\\':
1296 case ' ':
1297 case '\t':
1298 case '\r':
1299 case '\n':
1300 case '"':
1301 dst[di++] = '\\';
1302 if (di >= dstlen)
1303 break;
1304 /* FALLTHROUGH */
1305 default:
1306 dst[di] = src[si];
1307 }
1308 }
1309 dst[di] = '\0';
1310 }
1311
1312 /*
1313 * Copy src into buf (which is len bytes long), expanding % sequences.
1314 */
1315 void
1316 formatbuf(char *buf, size_t len, const char *src)
1317 {
1318 const char *p;
1319 char *p2, *q;
1320 int i, op, updirs, pdirs;
1321
1322 #define ADDBUF(x) do { \
1323 if (i >= len - 1) \
1324 goto endbuf; \
1325 buf[i++] = (x); \
1326 } while (0)
1327
1328 p = src;
1329 for (i = 0; *p; p++) {
1330 if (*p != '%') {
1331 ADDBUF(*p);
1332 continue;
1333 }
1334 p++;
1335
1336 switch (op = *p) {
1337
1338 case '/':
1339 case '.':
1340 case 'c':
1341 p2 = connected ? remotepwd : "";
1342 updirs = pdirs = 0;
1343
1344 /* option to determine fixed # of dirs from path */
1345 if (op == '.' || op == 'c') {
1346 int skip;
1347
1348 q = p2;
1349 while (*p2) /* calc # of /'s */
1350 if (*p2++ == '/')
1351 updirs++;
1352 if (p[1] == '0') { /* print <x> or ... */
1353 pdirs = 1;
1354 p++;
1355 }
1356 if (p[1] >= '1' && p[1] <= '9') {
1357 /* calc # to skip */
1358 skip = p[1] - '0';
1359 p++;
1360 } else
1361 skip = 1;
1362
1363 updirs -= skip;
1364 while (skip-- > 0) {
1365 while ((p2 > q) && (*p2 != '/'))
1366 p2--; /* back up */
1367 if (skip && p2 > q)
1368 p2--;
1369 }
1370 if (*p2 == '/' && p2 != q)
1371 p2++;
1372 }
1373
1374 if (updirs > 0 && pdirs) {
1375 if (i >= len - 5)
1376 break;
1377 if (op == '.') {
1378 ADDBUF('.');
1379 ADDBUF('.');
1380 ADDBUF('.');
1381 } else {
1382 ADDBUF('/');
1383 ADDBUF('<');
1384 if (updirs > 9) {
1385 ADDBUF('9');
1386 ADDBUF('+');
1387 } else
1388 ADDBUF('0' + updirs);
1389 ADDBUF('>');
1390 }
1391 }
1392 for (; *p2; p2++)
1393 ADDBUF(*p2);
1394 break;
1395
1396 case 'M':
1397 case 'm':
1398 for (p2 = connected ? hostname : "-"; *p2; p2++) {
1399 if (op == 'm' && *p2 == '.')
1400 break;
1401 ADDBUF(*p2);
1402 }
1403 break;
1404
1405 case 'n':
1406 for (p2 = connected ? username : "-"; *p2 ; p2++)
1407 ADDBUF(*p2);
1408 break;
1409
1410 case '%':
1411 ADDBUF('%');
1412 break;
1413
1414 default: /* display unknown codes literally */
1415 ADDBUF('%');
1416 ADDBUF(op);
1417 break;
1418
1419 }
1420 }
1421 endbuf:
1422 buf[i] = '\0';
1423 }
1424
1425 /*
1426 * Parse `port' into a TCP port number, defaulting to `defport' if `port' is
1427 * an unknown service name. If defport != -1, print a warning upon bad parse.
1428 */
1429 int
1430 parseport(const char *port, int defport)
1431 {
1432 int rv;
1433 long nport;
1434 char *p, *ep;
1435
1436 p = xstrdup(port);
1437 nport = strtol(p, &ep, 10);
1438 if (*ep != '\0' && ep == p) {
1439 struct servent *svp;
1440
1441 svp = getservbyname(port, "tcp");
1442 if (svp == NULL) {
1443 badparseport:
1444 if (defport != -1)
1445 warnx("Unknown port `%s', using port %d",
1446 port, defport);
1447 rv = defport;
1448 } else
1449 rv = ntohs(svp->s_port);
1450 } else if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0')
1451 goto badparseport;
1452 else
1453 rv = nport;
1454 free(p);
1455 return (rv);
1456 }
1457
1458 /*
1459 * Determine if given string is an IPv6 address or not.
1460 * Return 1 for yes, 0 for no
1461 */
1462 int
1463 isipv6addr(const char *addr)
1464 {
1465 int rv = 0;
1466 #ifdef INET6
1467 struct addrinfo hints, *res;
1468
1469 memset(&hints, 0, sizeof(hints));
1470 hints.ai_family = PF_INET6;
1471 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
1472 hints.ai_flags = AI_NUMERICHOST;
1473 if (getaddrinfo(addr, "0", &hints, &res) != 0)
1474 rv = 0;
1475 else {
1476 rv = 1;
1477 freeaddrinfo(res);
1478 }
1479 if (debug)
1480 fprintf(ttyout, "isipv6addr: got %d for %s\n", rv, addr);
1481 #endif
1482 return (rv == 1) ? 1 : 0;
1483 }
1484
1485
1486 /*
1487 * Internal version of connect(2); sets socket buffer sizes first.
1488 */
1489 int
1490 xconnect(int sock, const struct sockaddr *name, int namelen)
1491 {
1492
1493 setupsockbufsize(sock);
1494 return (connect(sock, name, namelen));
1495 }
1496
1497 /*
1498 * Internal version of listen(2); sets socket buffer sizes first.
1499 */
1500 int
1501 xlisten(int sock, int backlog)
1502 {
1503
1504 setupsockbufsize(sock);
1505 return (listen(sock, backlog));
1506 }
1507
1508 /*
1509 * malloc() with inbuilt error checking
1510 */
1511 void *
1512 xmalloc(size_t size)
1513 {
1514 void *p;
1515
1516 p = malloc(size);
1517 if (p == NULL)
1518 err(1, "Unable to allocate %ld bytes of memory", (long)size);
1519 return (p);
1520 }
1521
1522 /*
1523 * sl_init() with inbuilt error checking
1524 */
1525 StringList *
1526 xsl_init(void)
1527 {
1528 StringList *p;
1529
1530 p = sl_init();
1531 if (p == NULL)
1532 err(1, "Unable to allocate memory for stringlist");
1533 return (p);
1534 }
1535
1536 /*
1537 * sl_add() with inbuilt error checking
1538 */
1539 void
1540 xsl_add(StringList *sl, char *i)
1541 {
1542
1543 if (sl_add(sl, i) == -1)
1544 err(1, "Unable to add `%s' to stringlist", i);
1545 }
1546
1547 /*
1548 * strdup() with inbuilt error checking
1549 */
1550 char *
1551 xstrdup(const char *str)
1552 {
1553 char *s;
1554
1555 if (str == NULL)
1556 errx(1, "xstrdup() called with NULL argument");
1557 s = strdup(str);
1558 if (s == NULL)
1559 err(1, "Unable to allocate memory for string copy");
1560 return (s);
1561 }
1562
1563 /*
1564 * Install a POSIX signal handler, allowing the invoker to set whether
1565 * the signal should be restartable or not
1566 */
1567 sigfunc
1568 xsignal_restart(int sig, sigfunc func, int restartable)
1569 {
1570 struct sigaction act, oact;
1571 act.sa_handler = func;
1572
1573 sigemptyset(&act.sa_mask);
1574 #if defined(SA_RESTART) /* 4.4BSD, Posix(?), SVR4 */
1575 act.sa_flags = restartable ? SA_RESTART : 0;
1576 #elif defined(SA_INTERRUPT) /* SunOS 4.x */
1577 act.sa_flags = restartable ? 0 : SA_INTERRUPT;
1578 #else
1579 #error "system must have SA_RESTART or SA_INTERRUPT"
1580 #endif
1581 if (sigaction(sig, &act, &oact) < 0)
1582 return (SIG_ERR);
1583 return (oact.sa_handler);
1584 }
1585
1586 /*
1587 * Install a signal handler with the `restartable' flag set dependent upon
1588 * which signal is being set. (This is a wrapper to xsignal_restart())
1589 */
1590 sigfunc
1591 xsignal(int sig, sigfunc func)
1592 {
1593 int restartable;
1594
1595 /*
1596 * Some signals print output or change the state of the process.
1597 * There should be restartable, so that reads and writes are
1598 * not affected. Some signals should cause program flow to change;
1599 * these signals should not be restartable, so that the system call
1600 * will return with EINTR, and the program will go do something
1601 * different. If the signal handler calls longjmp() or siglongjmp(),
1602 * it doesn't matter if it's restartable.
1603 */
1604
1605 switch(sig) {
1606 #ifdef SIGINFO
1607 case SIGINFO:
1608 #endif
1609 case SIGQUIT:
1610 case SIGUSR1:
1611 case SIGUSR2:
1612 case SIGWINCH:
1613 restartable = 1;
1614 break;
1615
1616 case SIGALRM:
1617 case SIGINT:
1618 case SIGPIPE:
1619 restartable = 0;
1620 break;
1621
1622 default:
1623 /*
1624 * This is unpleasant, but I don't know what would be better.
1625 * Right now, this "can't happen"
1626 */
1627 errx(1, "xsignal_restart called with signal %d", sig);
1628 }
1629
1630 return(xsignal_restart(sig, func, restartable));
1631 }
1632