]> git.sur5r.net Git - openldap/blob - clients/gopher/go500.c
Use sigaction to set SA_RESTART (if appropriate).
[openldap] / clients / gopher / go500.c
1 /* $OpenLDAP$ */
2 /*
3  * Copyright (c) 1990 Regents of the University of Michigan.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms are permitted
7  * provided that this notice is preserved and that due credit is given
8  * to the University of Michigan at Ann Arbor. The name of the University
9  * may not be used to endorse or promote products derived from this
10  * software without specific prior written permission. This software
11  * is provided ``as is'' without express or implied warranty.
12  */
13
14 #include "portable.h"
15
16 #include <stdio.h>
17
18 #include <ac/stdlib.h>
19
20 #include <ac/ctype.h>
21 #include <ac/signal.h>
22 #include <ac/socket.h>
23 #include <ac/string.h>
24 #include <ac/syslog.h>
25 #include <ac/time.h>
26 #include <ac/unistd.h>
27 #include <ac/wait.h>
28
29 #include <ac/param.h>
30 #include <ac/setproctitle.h>
31
32 #ifdef HAVE_SYS_RESOURCE_H
33 #include <sys/resource.h>
34 #endif
35
36 #include <ldap.h>
37 #include <disptmpl.h>
38
39 #include "ldap_defaults.h"
40
41 #define ldap_debug debug
42 #include "ldap_log.h"
43
44 #include "lutil.h"
45
46
47 int     debug;
48 int     dosyslog;
49 int ldap_syslog;
50 int ldap_syslog_level;
51 int     inetd;
52 int     dtblsize;
53
54 char    *ldaphost = NULL;
55 char    *base = NULL;
56 int     rdncount = GO500_RDNCOUNT;
57 char    *filterfile = FILTERFILE;
58 char    *templatefile = TEMPLATEFILE;
59
60 char    myhost[MAXHOSTNAMELEN];
61 int     myport;
62
63 static void usage       ( char *name ) LDAP_GCCATTR((noreturn));
64 static int  set_socket  (int port);
65 static RETSIGTYPE wait4child(int sig);
66 static void do_queries  (int s)    LDAP_GCCATTR((noreturn));
67 static void do_error    (FILE *fp, char *s);
68 static void do_search   (LDAP *ld, FILE *fp, char *buf);
69 static void do_read     (LDAP *ld, FILE *fp, char *dn);
70
71 static void
72 usage( char *name )
73 {
74         fprintf( stderr, "usage: %s [-d debuglevel] [-f filterfile] [-t templatefile]\r\n\t[-a] [-l] [-p port] [-x ldaphost] [-b searchbase] [-c rdncount]\r\n", name );
75         exit( EXIT_FAILURE );
76 }
77
78 int
79 main( int argc, char **argv )
80 {
81         int                     s, ns, rc;
82         int                     port = -1;
83         int                     i, pid;
84         char                    *myname;
85         fd_set                  readfds;
86         struct hostent          *hp;
87         struct sockaddr_in      from;
88         socklen_t               fromlen;
89
90 #if defined( LDAP_PROCTITLE ) && !defined( HAVE_SETPROCTITLE )
91         /* for setproctitle */
92         Argv = argv;
93         Argc = argc;
94 #endif
95
96         while ( (i = getopt( argc, argv, "b:d:f:lp:c:t:x:I" )) != EOF ) {
97                 switch( i ) {
98                 case 'b':       /* searchbase */
99                         base = strdup( optarg );
100                         break;
101
102                 case 'd':       /* debug level */
103                         debug |= atoi( optarg );
104                         break;
105
106                 case 'f':       /* ldap filter file */
107                         filterfile = strdup( optarg );
108                         break;
109
110                 case 'l':       /* log via LOG_LOCAL3 */
111                         dosyslog = 1;
112                         break;
113
114                 case 'p':       /* port to listen to */
115                         port = atoi( optarg );
116                         break;
117
118                 case 'c':       /* number of DN components to show */
119                         rdncount = atoi( optarg );
120                         break;
121
122                 case 't':       /* ldap template file */
123                         templatefile = strdup( optarg );
124                         break;
125
126                 case 'x':       /* ldap server hostname */
127                         ldaphost = strdup( optarg );
128                         break;
129
130                 case 'I':       /* run from inetd */
131                         inetd = 1;
132                         break;
133
134                 default:
135                         usage( argv[0] );
136                 }
137         }
138
139 #ifdef GO500_HOSTNAME
140         strcpy( myhost, GO500_HOSTNAME );
141 #else
142         if ( myhost[0] == '\0' && gethostname( myhost, sizeof(myhost)-1 )
143             == -1 ) {
144                 perror( "gethostname" );
145                 exit( EXIT_FAILURE );
146         }
147         myhost[sizeof(myhost)-1] = '\0';
148 #endif
149
150 #ifdef HAVE_SYSCONF
151         dtblsize = sysconf( _SC_OPEN_MAX );
152 #elif HAVE_GETDTABLESIZE
153         dtblsize = getdtablesize();
154 #else
155         dtblsize = FD_SETSIZE;
156 #endif
157
158 #ifdef FD_SETSIZE
159         if (dtblsize > FD_SETSIZE) {
160                 dtblsize = FD_SETSIZE;
161         }
162 #endif  /* FD_SETSIZE*/
163
164         /* detach if stderr is redirected or no debugging */
165         if ( inetd == 0 )
166                 lutil_detach( debug && !isatty( 1 ), 1 );
167
168         if ( (myname = strrchr( argv[0], '/' )) == NULL )
169                 myname = strdup( argv[0] );
170         else
171                 myname = strdup( myname + 1 );
172
173         if ( debug ) {
174                 ber_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &debug);
175                 ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &debug);
176         }
177
178 #ifdef SIGPIPE
179         (void) SIGNAL( SIGPIPE, SIG_IGN );
180 #endif
181
182         if ( dosyslog ) {
183 #ifdef LOG_LOCAL3
184                 openlog( myname, OPENLOG_OPTIONS, LOG_LOCAL3 );
185 #elif LOG_DEBUG
186                 openlog( myname, OPENLOG_OPTIONS );
187 #endif
188         }
189         if ( dosyslog )
190                 syslog( LOG_INFO, "initializing" );
191
192         /* set up the socket to listen on */
193         if ( inetd == 0 ) {
194                 s = set_socket( port );
195
196                 /* arrange to reap children */
197                 (void) SIGNAL( SIGCHLD, wait4child );
198         } else {
199                 myport = GO500_PORT;
200
201                 fromlen = sizeof(from);
202                 if ( getpeername( 0, (struct sockaddr *) &from, &fromlen )
203                     == 0 ) {
204                         hp = gethostbyaddr( (char *) &(from.sin_addr),
205                             sizeof(from.sin_addr), AF_INET );
206                         Debug( LDAP_DEBUG_ARGS, "connection from %s (%s)\n",
207                             (hp == NULL) ? "unknown" : hp->h_name,
208                             inet_ntoa( from.sin_addr ), 0 );
209
210                         if ( dosyslog ) {
211                                 syslog( LOG_INFO, "connection from %s (%s)",
212                                     (hp == NULL) ? "unknown" : hp->h_name,
213                                     inet_ntoa( from.sin_addr ) );
214                         }
215
216 #ifdef LDAP_PROCTITLE
217                         setproctitle( "%s", hp == NULL ? inet_ntoa( from.sin_addr ) :
218                             hp->h_name );
219 #endif
220                 }
221
222                 do_queries( 0 );
223
224                 exit( EXIT_SUCCESS );
225         }
226
227         for ( ;; ) {
228                 FD_ZERO( &readfds );
229                 FD_SET( s, &readfds );
230
231                 if ( (rc = select( dtblsize, &readfds, 0, 0 ,0 )) == -1 ) {
232                         if ( debug ) perror( "select" );
233                         continue;
234                 } else if ( rc == 0 ) {
235                         continue;
236                 }
237
238                 if ( ! FD_ISSET( s, &readfds ) )
239                         continue;
240
241                 fromlen = sizeof(from);
242                 if ( (ns = accept( s, (struct sockaddr *) &from, &fromlen ))
243                     == -1 ) {
244                         if ( debug ) perror( "accept" );
245                         exit( EXIT_FAILURE );
246                 }
247
248                 hp = gethostbyaddr( (char *) &(from.sin_addr),
249                     sizeof(from.sin_addr), AF_INET );
250
251                 if ( dosyslog ) {
252                         syslog( LOG_INFO, "TCP connection from %s (%s)",
253                             (hp == NULL) ? "unknown" : hp->h_name,
254                             inet_ntoa( from.sin_addr ) );
255                 }
256
257                 switch( pid = fork() ) {
258                 case 0:         /* child */
259                         tcp_close( s );
260                         do_queries( ns );
261                         break;
262
263                 case -1:        /* failed */
264                         perror( "fork" );
265                         break;
266
267                 default:        /* parent */
268                         tcp_close( ns );
269                         if ( debug )
270                                 fprintf( stderr, "forked child %d\n", pid );
271                         break;
272                 }
273         }
274         /* NOT REACHED */
275 }
276
277 static int
278 set_socket( int port )
279 {
280         int                     s, one;
281         struct sockaddr_in      addr;
282
283         if ( port == -1 )
284                 port = GO500_PORT;
285         myport = port;
286
287         if ( (s = socket( AF_INET, SOCK_STREAM, 0 )) == -1 ) {
288                 perror( "socket" );
289                 exit( EXIT_FAILURE );
290         }
291
292 #ifdef SO_REUSEADDR
293         /* set option so clients can't keep us from coming back up */
294                 one = 1;
295         if ( setsockopt( s, SOL_SOCKET, SO_REUSEADDR, (char *) &one,
296             sizeof(one) ) < 0 ) {
297                 perror( "setsockopt" );
298                 exit( EXIT_FAILURE );
299         }
300 #endif
301 #ifdef SO_KEEPALIVE
302                 /* enable keep alives */
303                 one = 1;
304         if ( setsockopt( s, SOL_SOCKET, SO_KEEPALIVE, (char *) &one,
305             sizeof(one) ) < 0 ) {
306                 perror( "setsockopt" );
307                 exit( EXIT_FAILURE );
308         }
309 #endif
310
311         /* bind to a name */
312         addr.sin_family = AF_INET;
313         addr.sin_addr.s_addr = htonl(INADDR_ANY);
314         addr.sin_port = htons( port );
315         if ( bind( s, (struct sockaddr *) &addr, sizeof(addr) ) ) {
316                 perror( "bind" );
317                 exit( EXIT_FAILURE );
318         }
319
320         /* listen for connections */
321         if ( listen( s, 5 ) == -1 ) {
322                 perror( "listen" );
323                 exit( EXIT_FAILURE );
324         }
325
326         if ( debug ) printf("tcp socket allocated, bound, and listening\n");
327
328         return( s );
329 }
330
331 static RETSIGTYPE
332 wait4child( int sig )
333 {
334 #ifndef HAVE_WAITPID
335         WAITSTATUSTYPE     status;
336 #endif
337
338         if ( debug ) printf( "parent: catching child status\n" );
339
340 #ifdef HAVE_WAITPID
341         while (waitpid ((pid_t) -1, (int *) NULL, WAIT_FLAGS) > 0)
342                 ;       /* NULL */
343 #else
344         while ( wait4((pid_t) -1, &status, WAIT_FLAGS, 0 ) > 0 )
345                 ;       /* NULL */
346 #endif
347
348         (void) SIGNAL_REINSTALL ( SIGCHLD, wait4child );
349 }
350
351 static void
352 do_queries( int s )
353 {
354         char            buf[1024], *query;
355         int             len;
356         FILE            *fp;
357         int             rc;
358         struct timeval  timeout;
359         fd_set          readfds;
360         LDAP            *ld;
361
362         if ( (fp = fdopen( s, "a+")) == NULL ) {
363                 exit( EXIT_FAILURE );
364         }
365
366         timeout.tv_sec = GO500_TIMEOUT;
367         timeout.tv_usec = 0;
368         FD_ZERO( &readfds );
369         FD_SET( fileno( fp ), &readfds );
370
371         if ( (rc = select( dtblsize, &readfds, 0, 0, &timeout )) <= 0 )
372                 exit( EXIT_FAILURE );
373
374         if ( fgets( buf, sizeof(buf), fp ) == NULL )
375                 exit( EXIT_FAILURE );
376
377         len = strlen( buf );
378         if ( debug ) {
379                 fprintf( stderr, "got %d bytes\n", len );
380 #ifdef LDAP_DEBUG
381                 ber_bprint( buf, len );
382 #endif
383         }
384
385         /* strip of \r \n */
386         if ( buf[len - 1] == '\n' )
387                 buf[len - 1] = '\0';
388         len--;
389         if ( buf[len - 1] == '\r' )
390                 buf[len - 1] = '\0';
391         len--;
392
393         query = buf;
394
395         /* strip off leading white space */
396         while ( isspace( (unsigned char) *query )) {
397                 ++query;
398                 --len;
399         }
400
401         rewind(fp);
402
403         if ( *query == '~' || *query == '@' ) {
404                 ld = NULL;
405         } else if ( (ld = ldap_init( ldaphost, 0 )) == NULL ) {
406                 fprintf(fp,
407                         "0An error occurred (explanation)\t@%d\t%s\t%d\r\n",
408                         LDAP_SERVER_DOWN, myhost, myport );
409                 fprintf( fp, ".\r\n" );
410                 rewind(fp);
411                 exit( EXIT_FAILURE );
412         } else {
413                 int deref = GO500_DEREF;
414                 ldap_set_option(ld, LDAP_OPT_DEREF, &deref);
415
416                 rc = ldap_simple_bind_s( ld, NULL, NULL );
417                 if ( rc != LDAP_SUCCESS ) {
418                         fprintf(fp,
419                             "0An error occurred (explanation)\t@%d\t%s\t%d\r\n",
420                             rc, myhost, myport );
421                         fprintf( fp, ".\r\n" );
422                         rewind(fp);
423                         exit( EXIT_FAILURE );
424                 }
425         }
426
427         switch ( *query ) {
428         case '~':
429                 fprintf( fp, "The query you specified was not specific enough, causing a size limit\r\n" );
430                 fprintf( fp, "to be exceeded and the first several matches found to be returned.\r\n" );
431                 fprintf( fp, "If you did not find the match you were looking for, try issuing a more\r\n" );
432                 fprintf( fp, "specific query, for example one that contains both first and last name.\r\n" );
433                 fprintf( fp, ".\r\n" );
434                 break;
435
436         case '=':
437                 do_read( ld, fp, ++query );
438                 break;
439
440         case '@':
441                 do_error( fp, ++query );
442                 break;
443
444         default:
445                 do_search( ld, fp, query );
446                 break;
447         }
448
449         fprintf( fp, ".\r\n" );
450         rewind(fp);
451
452         if ( ld != NULL) {
453                 ldap_unbind( ld );
454         }
455
456         exit( EXIT_FAILURE );
457         /* NOT REACHED */
458 }
459
460 static void
461 do_error( FILE *fp, char *s )
462 {
463         int     code;
464
465         code = atoi( s );
466
467         fprintf( fp, "An error occurred searching X.500.  The error code was %d\r\n", code );
468         fprintf( fp, "The corresponding error is: %s\r\n", ldap_err2string( code ) );
469         fprintf( fp, "No additional information is available\r\n" );
470         fprintf( fp, ".\r\n" );
471 }
472
473 static void
474 do_search( LDAP *ld, FILE *fp, char *buf )
475 {
476         char            *dn, *rdn;
477         char            **title;
478         int             rc, matches = 0;
479         struct timeval  tv;
480         LDAPFiltInfo    *fi;
481         LDAPFiltDesc    *filtd;
482         LDAPMessage     *e, *res;
483         static char     *attrs[] = { "title", 0 };
484
485 #ifdef GO500_UFN
486         if ( strchr( buf, ',' ) != NULL ) {
487                 ldap_ufn_setprefix( ld, base );
488                 tv.tv_sec = GO500_TIMEOUT;
489                 tv.tv_usec = 0;
490                 ldap_ufn_timeout( (void *) &tv );
491
492                 if ( (rc = ldap_ufn_search_s( ld, buf, attrs, 0, &res ))
493                     != LDAP_SUCCESS && rc != LDAP_SIZELIMIT_EXCEEDED ) {
494                         fprintf(fp,
495                             "0An error occurred (explanation)\t@%d\t%s\t%d\r\n",
496                             rc, myhost, myport );
497                         return;
498                 }
499
500                 matches = ldap_count_entries( ld, res );
501         } else {
502 #endif
503                 if ( (filtd = ldap_init_getfilter( filterfile )) == NULL ) {
504                         fprintf( stderr, "Cannot open filter file (%s)\n",
505                             filterfile );
506                         exit( EXIT_FAILURE );
507                 }
508
509                 tv.tv_sec = GO500_TIMEOUT;
510                 tv.tv_usec = 0;
511                 for ( fi = ldap_getfirstfilter( filtd, "go500", buf );
512                     fi != NULL;
513                     fi = ldap_getnextfilter( filtd ) )
514                 {
515                         if ( (rc = ldap_search_st( ld, base, LDAP_SCOPE_SUBTREE,
516                             fi->lfi_filter, attrs, 0, &tv, &res ))
517                             != LDAP_SUCCESS && rc != LDAP_SIZELIMIT_EXCEEDED ) {
518                                 fprintf(fp, "0An error occurred (explanation)\t@%d\t%s\t%d\r\n",
519                                     rc, myhost, myport );
520                                 ldap_getfilter_free( filtd );
521                                 return;
522                         }
523
524                         if ( (matches = ldap_count_entries( ld, res )) != 0 )
525                                 break;
526                 }
527                 ldap_getfilter_free( filtd );
528 #ifdef GO500_UFN
529         }
530 #endif
531
532         if ( matches <= 0 ) {
533                 return;
534         }
535
536 #ifdef GO500_SORT_ATTR
537         ldap_sort_entries( ld, &res, GO500_SORT_ATTR, strcasecmp );
538 #endif
539
540         for ( e = ldap_first_entry( ld, res ); e != NULL;
541             e = ldap_next_entry( ld, e ) ) {
542                 char    *s;
543
544                 dn = ldap_get_dn( ld, e );
545                 rdn = strdup( dn );
546                 if ( (s = strchr( rdn, ',' )) != NULL )
547                         *s = '\0';
548
549                 if ( (s = strchr( rdn, '=' )) == NULL )
550                         s = rdn;
551                 else
552                         ++s;
553
554                 title = ldap_get_values( ld, e, "title" );
555
556                 if ( title != NULL ) {
557                         char    *p;
558
559                         for ( p = title[0]; *p; p++ ) {
560                                 if ( *p == '/' )
561                                         *p = '\\';
562                         }
563                 }
564
565                 fprintf( fp, "0%-20s    %s\t=%s\t%s\t%d\r\n", s,
566                     title ? title[0] : "", dn, myhost, myport );
567
568                 if ( title != NULL )
569                         ldap_value_free( title );
570
571                 free( rdn );
572                 free( dn );
573         }
574
575         if ( ldap_result2error( ld, res, 1 ) == LDAP_SIZELIMIT_EXCEEDED ) {
576                 fprintf( fp, "0A size limit was exceeded (explanation)\t~\t%s\t%d\r\n",
577                     myhost, myport );
578         }
579 }
580
581 static int
582 entry2textwrite( void *fp, char *buf, ber_len_t len )
583 {
584         return( fwrite( buf, len, 1, (FILE *)fp ) == 0 ? -1 : len );
585 }
586
587 static void
588 do_read( LDAP *ld, FILE *fp, char *dn )
589 {
590         static struct ldap_disptmpl *tmpllist;
591
592         ldap_init_templates( templatefile, &tmpllist );
593
594         if ( ldap_entry2text_search( ld, dn, base, NULL, tmpllist, NULL, NULL,
595             entry2textwrite, (void *) fp, "\r\n", rdncount,
596             LDAP_DISP_OPT_DOSEARCHACTIONS ) != LDAP_SUCCESS ) {
597                 ldap_perror( ld, "ldap_entry2text_search" );
598                 exit( EXIT_FAILURE );
599         }
600
601         if ( tmpllist != NULL ) {
602                 ldap_free_templates( tmpllist );
603         }
604 }