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