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