]> git.sur5r.net Git - openldap/blob - clients/ud/main.c
More header work toward draft-ietf-ldapext-ldap-c-api-01.
[openldap] / clients / ud / main.c
1 /*
2  * Copyright (c) 1991, 1992, 1993 
3  * Regents of the University of Michigan.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that this notice is preserved and that due credit is given
7  * to the University of Michigan at Ann Arbor. The name of the University
8  * may not be used to endorse or promote products derived from this
9  * software without specific prior written permission. This software
10  * is provided ``as is'' without express or implied warranty.
11  *
12  * The University of Michigan would like to thank the following people for
13  * their contributions to this piece of software:
14  *
15  *      Robert Urquhart    <robert@sfu.ca>
16  *      Simon Fraser University, Academic Computing Services
17  */
18
19 #include "portable.h"
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <setjmp.h>
24 #include <pwd.h>
25
26 #include <ac/signal.h>
27 #include <ac/string.h>
28 #include <ac/termios.h>
29 #include <ac/time.h>
30 #include <ac/unistd.h>
31
32 #ifdef HAVE_SYS_FILE_H
33 #include <sys/file.h>
34 #endif
35
36 #include <lber.h>
37 #include <ldap.h>
38
39 #include <ldapconfig.h>
40 #include "ud.h"
41
42 #ifndef lint
43 char copyright[] =
44 "@(#) Copyright (c) 1991, 1992, 1993 Regents of the University of Michigan.\nAll rights reserved.\n";
45 #endif
46
47 /*
48  *  Used with change_base() to indicate which base we are changing.
49  */
50 #define BASE_SEARCH     0
51 #define BASE_GROUPS     1
52
53 #define iscom(x)        (!strncasecmp(x, cmd, strlen(cmd)))
54
55 static char *server = NULL;
56 static char *config_file = UD_CONFIG_FILE;
57 static char *filter_file = FILTERFILE;
58 static int ldap_port = LDAP_PORT;
59 static int dereference = TRUE;
60
61 char *default_bind_object = UD_BINDDN;
62
63 char *bound_dn;                 /* bound user's Distinguished Name */
64 char *group_base;               /* place in LDAP tree where groups are */
65 char *search_base;              /* place in LDAP tree where searches start */
66
67 static jmp_buf env;             /* spot to jump to on an interrupt */
68
69 int lpp;                        /* lines per page */
70 int verbose;                    /* 1 if verbose mode on */
71 int col_size;                   /* characters across on the screen */
72 int bind_status;                /* user's bind status */
73
74 LDAP *ld;                       /* LDAP descriptor */
75 LDAPFiltDesc *lfdp;             /* LDAP filter descriptor */
76
77 #ifdef DEBUG
78 int debug;                      /* debug flag */
79 #endif
80
81 main(argc, argv)
82 int argc;
83 char *argv[];
84 {
85         extern char Version[];                  /* version number */
86         extern char *optarg;                    /* for parsing argv */
87         register int c;                         /* for parsing argv */
88         register char *cp;                      /* for parsing Version */
89         extern void initialize_attribute_strings();
90
91         verbose = 1;
92
93         /*  handle argument list */
94         while ((c = getopt(argc, argv, "c:d:Df:l:p:s:u:vV")) != -1) {
95                 switch (c) {
96                 case 'l' :
97 #ifdef LDAP_DEBUG
98                         ldap_debug = (int) strtol(optarg, (char **) NULL, 0);
99                         lber_debug = ldap_debug;
100 #endif
101                         break;
102                 case 'd' :
103 #ifdef DEBUG
104                         debug = (int) strtol(optarg, (char **) NULL, 0);
105 #endif
106                         break;
107                 case 's' :
108                         server = strdup(optarg);
109                         break;
110                 case 'c' :
111                         filter_file = strdup(optarg);
112                         break;
113                 case 'f' :
114                         config_file = optarg;
115                         break;
116                 case 'p' :
117                         ldap_port = atoi(optarg);
118                         break;
119                 case 'u' :
120                         default_bind_object = strdup(optarg);
121                         break;
122                 case 'v' :
123                         verbose = 1;    /* this is the default anyways... */
124                         break;
125                 case 'V' :
126                         verbose = 0;
127                         break;
128                 case 'D' :
129                         printf("\n\n  Debug flag values\n\n");
130                         printf("    1  function trace\n");
131                         printf("    2  find() information\n");
132                         printf("    4  group information\n");
133                         printf("    8  mod() information\n");
134                         printf("   16  parsing information\n");
135                         printf("   32  output information\n");
136                         printf("   64  authentication information\n");
137                         printf("  128  initialization information\n\n");
138                         format("These are masks, and may be added to form multiple debug levels.  For example, '-d 35' would perform a function trace, print out information about the find() function, and would print out information about the output routines too.", 75, 2);
139                         exit(0);
140                 default:
141                         fprintf(stderr, "Usage: %s [-c filter-config-file] [-d debug-level] [-l ldap-debug-level] [-s server] [-p port] [-V]\n", argv[0]);
142                         exit(-1);
143                         /* NOTREACHED */
144                 }
145         }
146
147         /* just print the first line of Version[] */
148         cp = strchr(Version, '\t');
149         if (cp != NULL)
150                 *cp = '\0';
151         printf(Version);
152         fflush( stdout );
153
154         initialize_client();
155         initialize_attribute_strings();
156
157         /* now tackle the user's commands */
158         do_commands();
159         /* NOTREACHED */
160 }
161
162 do_commands()
163 {
164         LDAPMessage *mp;                        /* returned by find() */
165         register char *cp;                      /* misc char pointer */
166         register char *ap;                      /* misc char pointer */
167         static char buf[MED_BUF_SIZE];          /* for prompting */
168         static char cmd[MED_BUF_SIZE];          /* holds the command */
169         static char input[MED_BUF_SIZE];        /* buffer for input */
170         extern LDAPMessage *find();
171         extern void purge_group(), add_group(), remove_group(), x_group(),
172                 tidy_up(), list_groups(), list_memberships(), edit();
173         extern char *nextstr();
174
175 #ifdef DEBUG
176         if (debug & D_TRACE)
177                 printf("->do_commands()\n");
178 #endif
179         if (verbose) 
180                 printf("\n  Enter a command.  If you need help, type 'h' or '?' and hit RETURN.\n\n");
181         /* jump here on an interrupt */
182         (void) setjmp(env);
183         for (;;) {
184                 printf("* ");
185                 fflush(stdout);
186                 cp = input;
187 /* Temporary kludge - if cp is null, dumps core under Solaris */
188                 if (cp == NULL)
189                         break;
190                 fetch_buffer(input, sizeof(input), stdin);
191                 if (*input == '\0') {
192                         putchar('\n');
193                         continue;
194                 }
195                 while (isspace(*cp))
196                         cp++;   
197                 ap = cmd;
198                 if (memset(cmd, '\0', sizeof(cmd)) == NULL)
199                         fatal("memset");
200                 while (!isspace(*cp) && (*cp != '\0'))
201                         *ap++ = *cp++;
202                 if (iscom("status"))
203                         status();
204                 else if (iscom("stop") || iscom("quit"))
205                         break;
206                 else if (iscom("cb") || iscom("cd") || iscom("moveto")) {
207                         while (isspace(*cp) && (*cp != '\0')) 
208                                 cp++;
209                         if (!strncasecmp(cp, "base", 4))
210                                 cp += 4;
211                         change_base(BASE_SEARCH, &search_base, nextstr(cp));
212                 }
213                 else if (iscom("memberships"))
214                         (void) list_memberships(nextstr(cp));
215                 else if (iscom("list"))
216                         (void) list_groups(nextstr(cp));
217                 else if (iscom("groupbase"))
218                         change_base(BASE_GROUPS, &group_base, nextstr(cp));
219                 else if (iscom("find") || iscom("display") || iscom("show")) {
220                         cp = nextstr(cp);
221                         if ((mp = find(cp, FALSE)) != NULL) {
222                                 parse_answer(mp);
223                                 print_an_entry();
224                                 ldap_msgfree(mp);
225                         }
226                         else
227                                 printf(" Could not find \"%s\".\n", cp);
228                 }
229 #ifdef UOFM
230                 else if (iscom("vedit") && isatty( 1 )) {
231 #else
232                 else if (iscom("vedit")) {
233 #endif
234                         (void) edit(nextstr(cp));
235                 }
236                 else if (iscom("modify") || iscom("change") || iscom("alter"))
237                         (void) modify(nextstr(cp));
238                 else if (iscom("bind") || iscom("iam"))
239                         (void) auth(nextstr(cp), 0);
240                 else if ((cmd[0] == '?') || iscom("help"))
241                         print_help(nextstr(cp));
242                 else if (iscom("join") || iscom("subscribe")) 
243                         (void) x_group(G_JOIN, nextstr(cp));
244                 else if (iscom("resign") || iscom("unsubscribe"))
245                         (void) x_group(G_RESIGN, nextstr(cp));
246                 else if (!strncasecmp("create", cmd, strlen(cmd)))
247                         add_group(nextstr(cp));
248                 else if (!strncasecmp("remove", cmd, strlen(cmd)))
249                         remove_group(nextstr(cp));
250                 else if (!strncasecmp("purge", cmd, strlen(cmd)))
251                         purge_group(nextstr(cp));
252                 else if (!strncasecmp("verbose", cmd, strlen(cmd))) {
253                         verbose = 1 - verbose;
254                         if (verbose)
255                                 printf("  Verbose mode has been turned on.\n");
256                 }
257                 else if (!strncasecmp("dereference", cmd, strlen(cmd))) {
258                         dereference = 1 - dereference;
259                         if (dereference == 1)
260                                 ld->ld_deref = LDAP_DEREF_ALWAYS;
261                         else
262                                 ld->ld_deref = LDAP_DEREF_NEVER;
263                 }
264                 else if (!strncasecmp("tidy", cmd, strlen(cmd)))
265                         tidy_up();
266                 else if (cmd[0] == '\0')
267                         putchar('\n');
268                 else
269                         printf("  Invalid command.  Type \"help commands.\"\n");
270         }
271         printf(" Thank you!\n");
272         
273         ldap_unbind(ld);
274 #ifdef HAVE_KERBEROS
275         destroy_tickets();
276 #endif
277         exit(0);
278         /* NOTREACHED */
279 }
280
281 status()
282 {
283         void printbase();
284         register char **rdns;
285
286 #ifdef DEBUG
287         if (debug & D_TRACE)
288                 printf("->status()\n");
289 #endif
290         printf("  Current server is %s", server);
291         if ( ld != NULL && ld->ld_host != NULL && strcasecmp( ld->ld_host,
292             server ) != 0 )
293                 printf( " (%s)", ld->ld_host );
294         putchar( '\n' );
295         printbase("  Search base is ", search_base);
296         printbase("  Group  base is ", group_base);
297         if ( bound_dn != NULL ) {
298                 rdns = ldap_explode_dn(bound_dn, TRUE);
299                 printf("  Bound as \"%s\"\n", *rdns);
300                 ldap_value_free(rdns);
301         } else {
302                 printf("  Bound as Nobody\n" );
303         }
304         printf( "  Verbose mode is %sabled\n", ( verbose ? "en" : "dis" ));
305         if ( ld != NULL ) {
306                 printf( "  Aliases are %sbeing dereferenced\n", ( ld->ld_deref == LDAP_DEREF_ALWAYS ) ? "" : "not" );
307         }
308 }
309
310 change_base(type, base, s)
311 int type;
312 char **base, *s;
313 {
314         register char *cp;                      /* utility pointers */
315         char **rdns;                            /* for parsing */
316         char *output_string;                    /* for nice output */
317         int num_picked;                         /* # of selected base */
318         int j;                                  /* used with num_picked */
319         int i = 1;                              /* index into choices array */
320         int matches;                            /* # of matches found */
321         int rest = 1;                           /* # left to display */
322         char tmp[MED_BUF_SIZE];                 /* temporary buffer */
323         static char *choices[MED_BUF_SIZE];     /* bases from which to choose */
324         static char resp[SMALL_BUF_SIZE];       /* for prompting user */
325         static char buf[MED_BUF_SIZE];
326         void printbase();
327         static char *attrs[] = { "objectClass", NULL };
328         LDAPMessage *mp;                        /* results from a search */
329         LDAPMessage *ep;                        /* for going thru bases */
330         extern char * friendly_name();
331         extern void StrFreeDup();
332         extern void Free();
333
334 #ifdef DEBUG
335         if (debug & D_TRACE)
336                 printf("->change_base(%s, %s)\n", s, s);
337 #endif
338         /*
339          *  If s is NULL we need to prompt the user for an argument.
340          */
341         while (s == NULL) {
342                 if (verbose) {
343                         printf("  You need to specify how the base is to be changed.  Valid choices are:\n");
344                         printf("     ?       - list the choices immediately below this level\n");
345                         printf("     ..      - move up one level in the Directory tree\n");
346                         printf("     root    - move to the root of the Directory tree\n");
347                         printf("     default - move to the default level built into this program\n");
348                         printf("     <entry> - move to the entry specified\n");
349                 }
350                 printf("  Change base to? ");
351                 fflush(stdout);
352                 fetch_buffer(buf, sizeof(buf), stdin);
353                 if ((buf != NULL) && (buf[0] != '\0'))
354                         s = buf;
355         }
356
357         /* set the output string */
358         if (type == BASE_SEARCH)
359                 output_string = "  Search base is now ";
360         else if (type == BASE_GROUPS)
361                 output_string = "  Group base is now ";
362
363         if (!strcasecmp(s, "root")) {
364                 StrFreeDup(base, NULL);
365                 printbase("  Search base is ", *base);
366                 return;
367         }
368
369         /*
370          *  User wants to ascend one level in the LDAP tree.
371          *  Easy:  Just strip off the first element of the
372          *  current search base, unless it's the root, in
373          *  which case we just do nothing.
374          */
375         if (!strcasecmp(s, "..")) {
376                 if (*base == NULL) {
377                         printf("  You are already at the root\n");
378                         return;
379                 }
380                 cp = strchr(*base, '=');
381                 cp++;
382                 /*
383                  *  If there isn't a second "=" in the base, then this was
384                  *  a one element base, and so now it should be NULL.
385                  */
386                 if ((cp = strchr(cp, '=')) == NULL)
387                         StrFreeDup(base, NULL);
388                 else {
389                         /*
390                          *  Back up to the start of this
391                          *
392                          *      attr=value
393                          *
394                          *  sequence now that 'cp' is pointing to the '='.
395                          */
396                         while(!isspace(*cp))
397                                 cp--;
398                         cp++;
399                         /*
400                          *  Goofy, but need to do it this way since both *base
401                          *  and cp point into the same chunk of memory, and
402                          *  we want to free *base, but keep part of it around.
403                          */
404                         cp = strdup(cp);
405                         StrFreeDup(base, cp);
406                         Free(cp);
407                 }
408                 printbase(output_string, *base);
409                 return;
410         }
411
412         /* user wants to see what is directly below this level */
413         if (*s == '?') {
414                 /*
415                  *  Fetch the list of entries directly below this level.
416                  *  Once we have the list, we will print it for the user, one
417                  *  screenful at a time.  At the end of each screen, we ask
418                  *  the user if they want to see more.  They can also just
419                  *  type a number at that point too.
420                  */
421                 if (ldap_search_s(ld, *base, LDAP_SCOPE_ONELEVEL, "(|(objectClass=quipuNonLeafObject)(objectClass=externalNonLeafObject))", attrs, FALSE, &mp) != LDAP_SUCCESS) {
422                         if ((ld->ld_errno == LDAP_TIMELIMIT_EXCEEDED) ||
423                             (ld->ld_errno == LDAP_SIZELIMIT_EXCEEDED)) {
424                                 if (verbose) {
425                                         printf("  Your query was too general and a limit was exceeded.  The results listed\n");
426                                         printf("  are not complete.  You may want to try again with a more refined query.\n\n");
427                                 }
428                                 else
429                                         printf("  Time or size limit exceeded.  Partial results follow.\n\n");
430                         } else {
431                                 ldap_perror(ld, "ldap_search_s");
432                                 return;
433                         }
434                 }
435                 if ((matches = ldap_count_entries(ld, mp)) < 1) {
436                         printf("  There is nothing below this level.\n");
437                         (void) ldap_msgfree(mp);
438                         return;
439                 }
440                 num_picked = 0;
441                 printf(" There are %d choices:\n", matches);
442                 for (ep = ldap_first_entry(ld, mp); ep != NULL; ep = ldap_next_entry(ld, ep)) {
443                         /*
444                          *  Put the last component of the DN into 'lastDN'.
445                          *  If we are at the root level, convert any country
446                          *  codes to recognizable names for printing.
447                          */
448                         choices[i] = ldap_get_dn(ld, ep);
449                         rdns = ldap_explode_dn(choices[i], TRUE);
450                         printf(" %2d. %s\n", i, friendly_name(*rdns));
451                         (void) ldap_value_free(rdns);
452                         i++;
453                         if ((rest++ > (lpp - 3)) && (i < matches)) {
454                                 printf("More? ");
455                                 fflush(stdout);
456                                 fetch_buffer(resp, sizeof(resp), stdin);
457                                 if ((resp[0] == 'n') || (resp[0] == 'N'))
458                                         break;
459                                 else if (((num_picked = atoi(resp)) != 0) && (num_picked < i))
460                                         break;
461                                 rest = 1;
462                         }
463                 }
464                 for (;;) {
465                         if (num_picked != 0) {
466                                 j = num_picked;
467                                 num_picked = 0;
468                         }
469                         else {
470                                 printf(" Which number? ");
471                                 fflush(stdout);
472                                 fetch_buffer(resp, sizeof(resp), stdin);
473                                 j = atoi(resp);
474                         }
475                         if (j == 0) {
476                                 (void) ldap_msgfree(mp);
477                                 for (i = 0; i < matches; i++)
478                                         Free(choices[i]);
479                                 return;
480                         }
481                         if ((j < 1) || (j >= i))
482                                 printf(" Invalid number\n");
483                         else {
484                                 StrFreeDup(base, choices[j]);
485                                 printbase(output_string, *base);
486                                 (void) ldap_msgfree(mp);
487                                 for (i = 0; choices[i] != NULL; i++)
488                                         Free(choices[i]);
489                                 return;
490                         }
491                 }
492         }
493         /* set the search base back to the original default value */
494         else if (!strcasecmp(s, "default")) {
495                 if (type == BASE_SEARCH)
496                         StrFreeDup(base, UD_BASE);
497                 else if (type == BASE_GROUPS)
498                         StrFreeDup(base, UD_WHERE_GROUPS_ARE_CREATED);
499                 printbase(output_string, *base);
500         }
501         /* they typed in something -- see if it is legit */
502         else {
503                 /* user cannot do something like 'cb 33' */
504                 if (atoi(s) != 0) {
505                         printf("  \"%s\" is not a valid search base\n", s);
506                         printf("  Base unchanged.\n");
507                         printf("  Try using 'cb ?'\n");
508                         return;
509                 }
510                 /* was it a fully-specified DN? */
511                 if (vrfy(s)) {
512                         StrFreeDup(base, s);
513                         printbase(output_string, *base);
514                         return;
515                 }
516                 /* was it a RDN relative to the current base? */
517                 sprintf(tmp, "ou=%s, %s", s, *base);
518                 if (vrfy(tmp)) {
519                         StrFreeDup(base, tmp);
520                         printbase(output_string, *base);
521                         return;
522                 }
523                 printf("  \"%s\" is not a valid base\n  Base unchanged.\n", s);
524         }
525 }
526
527 initialize_client()
528 {
529         FILE *fp;                               /* for config file */
530         static char buffer[MED_BUF_SIZE];       /* for input */
531         struct passwd *pw;                      /* for getting the home dir */
532         register char *cp;                      /* for fiddling with buffer */
533         char *term;                             /* for tty set-up */
534         char *config;                           /* config file to use */
535         static char bp[1024];                   /* for tty set-up */
536         extern RETSIGTYPE attn();                       /* ^C signal handler */
537         extern char *getenv();
538         extern void Free();
539
540 #ifdef DEBUG
541         if (debug & D_TRACE)
542                 printf("->initialize_client()\n");
543 #endif
544         /*
545          *  A per-user config file has precedence over any system-wide
546          *  config file, if one exists.
547          */
548         if ((pw = getpwuid((uid_t) geteuid())) == (struct passwd *) NULL)
549                 config = config_file;
550         else {
551                 if (pw->pw_dir == NULL)
552                         config = config_file;
553                 else {
554                         sprintf(buffer, "%s/%s", pw->pw_dir,
555                             UD_USER_CONFIG_FILE);
556                         if (access(buffer, R_OK) == 0)
557                                 config = buffer;
558                         else
559                                 config = config_file;
560                 }
561         }
562 #ifdef DEBUG
563         if (debug & D_INITIALIZE)
564                 printf("Using config file %s\n", config);
565 #endif
566
567         /*
568          *  If there is a config file, read it.
569          *
570          *  Could have lines that look like this:
571          *
572          *      server <ip-address or domain-name>
573          *      base   <default search base>
574          *      groupbase <default place where groups are created>
575          *
576          */
577         if ((fp = fopen(config, "r")) != NULL) {
578                 while (fgets(buffer, sizeof(buffer), fp) != NULL) {
579                         buffer[strlen(buffer) - 1] = '\0';
580                         if (!strncasecmp(buffer, "server", 6)) {
581                                 if (server != NULL)
582                                         continue;
583                                 cp = buffer + 6;
584                                 while (isspace(*cp))
585                                         cp++;
586                                 if ((*cp == '\0') || (*cp == '\n'))
587                                         continue;
588                                 server = strdup(cp);
589                         }
590                         else if (!strncasecmp(buffer, "base", 4)) {
591                                 cp = buffer + 4;
592                                 while (isspace(*cp))
593                                         cp++;
594                                 if ((*cp == '\0') || (*cp == '\n'))
595                                         continue;
596                                 search_base = strdup(cp);
597                         }
598                         else if (!strncasecmp(buffer, "groupbase", 9)) {
599                                 cp = buffer + 9;
600                                 while (isspace(*cp))
601                                         cp++;
602                                 if ((*cp == '\0') || (*cp == '\n'))
603                                         continue;
604                                 group_base = strdup(cp);
605                         }
606                         else
607                                 fprintf(stderr, "?? -> %s\n", buffer);
608                 }
609         }
610         if (group_base == NULL)
611                 group_base = strdup(UD_WHERE_GROUPS_ARE_CREATED);
612         if (search_base == NULL)
613                 search_base = strdup(UD_BASE);
614         if (server == NULL)
615                 server = strdup(LDAPHOST);
616
617         /*
618          *  Set up our LDAP connection.  The values of retry and timeout
619          *  are meaningless since we will immediately be doing a null bind
620          *  because we want to be sure to use TCP, not UDP.
621          */
622         if ((ld = ldap_open(server, ldap_port)) == NULL) {
623                 fprintf(stderr, "  The LDAP Directory is temporarily unavailable.  Please try again later.\n");
624                 exit(0);
625                 /* NOTREACHED */
626         }
627         if (ldap_bind_s(ld, (char *) default_bind_object, (char *) UD_BIND_CRED,
628             LDAP_AUTH_SIMPLE) != LDAP_SUCCESS) {
629                 fprintf(stderr, "  The LDAP Directory is temporarily unavailable.  Please try again later.\n");
630                 if (ld->ld_errno != LDAP_UNAVAILABLE)
631                         ldap_perror(ld, "  ldap_bind_s");
632                 exit(0);
633                 /* NOTREACHED */
634         }
635         ld->ld_deref = LDAP_DEREF_ALWAYS;
636         bind_status = UD_NOT_BOUND;
637         if ( default_bind_object != NULL ) {
638                 bound_dn = strdup(default_bind_object);
639         } else {
640                 bound_dn = NULL;
641         }
642
643         /* enabled local caching of ldap results, 15 minute lifetime */
644 #ifdef DOS
645         ldap_enable_cache( ld, 60 * 15, 100 * 1024 );   /* 100k max memory */
646 #else /* DOS */
647         ldap_enable_cache( ld, 60 * 15, 0 );            /* no memory limit */
648 #endif /* DOS */
649
650         /* initialize the search filters */
651         if ((lfdp = ldap_init_getfilter(filter_file)) == NULL) {
652                 fprintf(stderr, "  Problem with ldap_init_getfilter\n");
653                 fatal(filter_file);
654                 /*NOTREACHED*/
655         }
656
657         /* terminal initialization stuff goes here */
658         lpp = DEFAULT_TTY_HEIGHT;
659         col_size = DEFAULT_TTY_WIDTH;
660
661         (void) SIGNAL (SIGINT, attn);
662
663 #ifndef NO_TERMCAP
664         {
665         struct winsize win;                     /* for tty set-up */
666         extern RETSIGTYPE chwinsz();            /* WINSZ signal handler */
667
668         if (((term = getenv("TERM")) == NULL) || (tgetent(bp, term) <= 0))
669                 return;
670         else {
671                 if (ioctl(fileno(stdout), TIOCGWINSZ, &win) < 0) {
672                         lpp = tgetnum("li");
673                         col_size = tgetnum("co");
674                 }
675                 else {
676                         if ((lpp = win.ws_row) == 0)
677                                 lpp = tgetnum("li");
678                         if ((col_size = win.ws_col) == 0)
679                                 col_size = tgetnum("co");
680                         if ((lpp <= 0) || tgetflag("hc"))
681                                 lpp = DEFAULT_TTY_HEIGHT;
682                         if ((col_size <= 0) || tgetflag("hc"))
683                                 col_size = DEFAULT_TTY_WIDTH;
684                 }
685         }
686         (void) SIGNAL (SIGWINCH, chwinsz);
687
688         }
689 #endif
690 }
691
692 RETSIGTYPE attn()
693 {
694         fflush(stderr);
695         fflush(stdout);
696         printf("\n\n  INTERRUPTED!\n");
697
698         (void) SIGNAL (SIGINT, attn);
699
700         longjmp(env, 1);
701 }
702
703 #ifndef NO_TERMCAP
704 RETSIGTYPE chwinsz() 
705 {
706         struct winsize win;
707
708         (void) SIGNAL (SIGWINCH, SIG_IGN);
709         if (ioctl(fileno(stdout), TIOCGWINSZ, &win) != -1) {
710                 if (win.ws_row != 0)
711                         lpp = win.ws_row;
712                 if (win.ws_col != 0)
713                         col_size = win.ws_col;
714         }
715
716         (void) SIGNAL (SIGWINCH, chwinsz);
717 }
718 #endif