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