]> git.sur5r.net Git - openldap/blob - clients/mail500/main.c
Add <ac/param.h> to wrap <sys/param.h>
[openldap] / clients / mail500 / main.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  * Copyright 1998,1999 The OpenLDAP Foundation
14  * COPYING RESTRICTIONS APPLY.  See COPYRIGHT File in top level directory
15  * of this package for details.
16  */
17
18 #include "portable.h"
19
20 #include <stdio.h>
21
22 #include <ac/stdlib.h>
23
24 #include <ac/ctype.h>
25 #include <ac/param.h>
26 #include <ac/signal.h>
27 #include <ac/string.h>
28 #include <ac/sysexits.h>
29 #include <ac/syslog.h>
30 #include <ac/time.h>
31 #include <ac/unistd.h>
32 #include <ac/wait.h>
33
34 #include <sys/stat.h>
35
36 #ifdef HAVE_SYS_RESOURCE_H
37 #include <sys/resource.h>
38 #endif
39
40 #include <ldap.h>
41
42 #include "ldap_defaults.h"
43
44 #ifndef MAIL500_BOUNCEFROM
45 #define MAIL500_BOUNCEFROM "<>"
46 #endif
47
48 #define USER            0x01
49 #define GROUP_ERRORS    0x02
50 #define GROUP_REQUEST   0x04
51 #define GROUP_MEMBERS   0x08
52 #define GROUP_OWNER     0x10
53
54 #define ERROR           "error"
55 #define ERRORS          "errors"
56 #define REQUEST         "request"
57 #define REQUESTS        "requests"
58 #define MEMBERS         "members"
59 #define OWNER           "owner"
60 #define OWNERS          "owners"
61
62 LDAP    *ld;
63 char    *vacationhost = NULL;
64 char    *errorsfrom = MAIL500_BOUNCEFROM;
65 char    *mailfrom = NULL;
66 char    *host = NULL;
67 char    *ldaphost = NULL;
68 int     hostlen = 0;
69 int     debug;
70
71 typedef struct errs {
72         int             e_code;
73 #define E_USERUNKNOWN           1
74 #define E_AMBIGUOUS             2
75 #define E_NOEMAIL               3
76 #define E_NOREQUEST             4
77 #define E_NOERRORS              5
78 #define E_BADMEMBER             6
79 #define E_JOINMEMBERNOEMAIL     7
80 #define E_MEMBERNOEMAIL         8
81 #define E_LOOP                  9
82 #define E_NOMEMBERS             10
83 #define E_NOOWNER               11
84 #define E_GROUPUNKNOWN          12
85         char            *e_addr;
86         union e_union_u {
87                 char            *e_u_loop;
88                 LDAPMessage     *e_u_msg;
89         } e_union;
90 #define e_msg   e_union.e_u_msg
91 #define e_loop  e_union.e_u_loop
92 } Error;
93
94 typedef struct groupto {
95         char    *g_dn;
96         char    *g_errorsto;
97         char    **g_members;
98         int     g_nmembers;
99 } Group;
100
101 typedef struct baseinfo {
102         char    *b_url;
103         int     b_m_entries;
104         char    b_rdnpref;      /* give rdn's preference when searching? */
105         int     b_search;       /* ORed with the type of thing the address */
106                                 /*  looks like (USER, GROUP_ERRORS, etc.)  */
107                                 /*  to see if this should be searched      */
108 } Base;
109
110 /*
111  * We should limit the search to objectclass=mailRecipient or
112  * objectclass=mailGroup.
113  */
114
115 /*
116 Base    base[] = {
117         {"dc=StlInter, dc=Net",
118                 0, 0xff,
119                 {"mail=%s", "mailAlternateAddress=%s", NULL}},
120         {NULL}
121 };
122 */
123
124 Base    **base = NULL;
125
126 char    *sendmailargs[] = { MAIL500_SENDMAIL, "-oMrLDAP", "-odi", "-oi", "-f", NULL, NULL };
127
128 typedef struct attr_semantics {
129         char    *as_name;
130         int     as_m_valued;    /* Is multivalued? */
131         int     as_final;       /* If true, no further expansion is tried. */
132         int     as_syntax;      /* How to interpret values */
133         int     as_m_entries;   /* Can resolve to several entries? */
134         int     as_kind;        /* Recipient, sender, etc. */
135         char    *as_param;      /* Extra info for filters and things alike */
136 } AttrSemantics;
137
138 #define AS_SYNTAX_UNKNOWN       0       /* Unqualified mailbox name */
139 #define AS_SYNTAX_NATIVE_MB     1       /* Unqualified mailbox name */
140 #define AS_SYNTAX_RFC822        2       /* RFC822 mail address */
141 #define AS_SYNTAX_HOST          3
142 #define AS_SYNTAX_DN            4       /* A directory entry */
143 #define AS_SYNTAX_RFC822_EXT    5
144 #define AS_SYNTAX_URL           6       /* mailto: or ldap: URL */
145 #define AS_SYNTAX_BOOL_FILTER   7       /* For joinable, filter in as_param */
146
147 #define AS_KIND_UNKNOWN         0
148 #define AS_KIND_RECIPIENT       1
149 #define AS_KIND_ERRORS          2       /* For ErrorsTo and similar */
150 #define AS_KIND_REQUEST         3
151 #define AS_KIND_OWNER           4
152 #define AS_KIND_FORWARD_TO_HOST 5       /* Expand at some other host */
153 #define AS_KIND_ALLOWED_SENDER  6       /* Can send to group */
154 #define AS_KIND_MODERATOR       7
155
156 AttrSemantics **attr_semantics = NULL;
157
158 typedef struct subst {
159         char    sub_char;
160         char    *sub_value;
161 } Subst;
162
163 char    **groupclasses = NULL;
164 char    **def_attr = NULL;
165
166 static void load_config( char *filespec );
167 static void split_address( char *address, char **localpart, char **domainpart);
168 static int entry_engine( LDAPMessage *e, char *dn, char *address, char ***to, int *nto, Group **togroups, int *ngroups, Error **err, int *nerr, int type );
169 static void do_address( char *name, char ***to, int *nto, Group **togroups, int *ngroups, Error **err, int *nerr, int type );
170 static void send_message( char **to );
171 static void send_errors( Error *err, int nerr );
172 static void do_noemail( FILE *fp, Error *err, int namelen );
173 static void do_ambiguous( FILE *fp, Error *err, int namelen );
174 static int count_values( char **list );
175 static void add_to( char ***list, int *nlist, char **new );
176 static void add_single_to( char ***list, char *new );
177 static int  isgroup( LDAPMessage *e );
178 static void add_error( Error **err, int *nerr, int code, char *addr, LDAPMessage *msg );
179 static void unbind_and_exit( int rc ) LDAP_GCCATTR((noreturn));
180 static void send_group( Group *group, int ngroup );
181
182 static int  connect_to_x500( void );
183
184
185 int
186 main ( int argc, char **argv )
187 {
188         char            *myname;
189         char            **tolist;
190         Error           *errlist;
191         Group           *togroups;
192         int             numto, ngroups, numerr, nargs;
193         int             i, j;
194         char            *conffile = NULL;
195
196         if ( (myname = strrchr( argv[0], '/' )) == NULL )
197                 myname = strdup( argv[0] );
198         else
199                 myname = strdup( myname + 1 );
200
201 #ifdef SIGPIPE
202         (void) SIGNAL( SIGPIPE, SIG_IGN );
203 #endif
204
205 #ifdef LOG_MAIL
206         openlog( myname, OPENLOG_OPTIONS, LOG_MAIL );
207 #else
208         openlog( myname, OPENLOG_OPTIONS );
209 #endif
210
211         while ( (i = getopt( argc, argv, "d:C:f:h:l:m:v:" )) != EOF ) {
212                 switch( i ) {
213                 case 'd':       /* turn on debugging */
214                         debug = atoi( optarg );
215                         break;
216
217                 case 'C':       /* path to configuration file */
218                         conffile = strdup( optarg );
219                         break;
220
221                 case 'f':       /* who it's from & where errors should go */
222                         mailfrom = strdup( optarg );
223                         for ( j = 0; sendmailargs[j] != NULL; j++ ) {
224                                 if ( strcmp( sendmailargs[j], "-f" ) == 0 ) {
225                                         sendmailargs[j+1] = mailfrom;
226                                         break;
227                                 }
228                         }
229                         break;
230
231                 case 'h':       /* hostname */
232                         host = strdup( optarg );
233                         hostlen = strlen(host);
234                         break;
235
236                 case 'l':       /* ldap host */
237                         ldaphost = strdup( optarg );
238                         break;
239
240                                 /* mailer-daemon address - who we should */
241                 case 'm':       /* say errors come from */
242                         errorsfrom = strdup( optarg );
243                         break;
244
245                 case 'v':       /* vacation host */
246                         vacationhost = strdup( optarg );
247                         break;
248
249                 default:
250                         syslog( LOG_ALERT, "unknown option" );
251                         break;
252                 }
253         }
254
255         if ( mailfrom == NULL ) {
256                 syslog( LOG_ALERT, "required argument -f not present" );
257                 exit( EX_TEMPFAIL );
258         }
259         if ( errorsfrom == NULL ) {
260                 syslog( LOG_ALERT, "required argument -m not present" );
261                 exit( EX_TEMPFAIL );
262         }
263 /*      if ( host == NULL ) { */
264 /*              syslog( LOG_ALERT, "required argument -h not present" ); */
265 /*              exit( EX_TEMPFAIL ); */
266 /*      } */
267         if ( conffile == NULL ) {
268                 syslog( LOG_ALERT, "required argument -C not present" );
269                 exit( EX_TEMPFAIL );
270         }
271
272         load_config( conffile );
273
274         if ( connect_to_x500() != 0 )
275                 exit( EX_TEMPFAIL );
276
277         setuid( geteuid() );
278
279         if ( debug ) {
280                 char    buf[1024];
281                 int     i;
282
283                 syslog( LOG_ALERT, "running as %d", geteuid() );
284                 strcpy( buf, argv[0] );
285                 for ( i = 1; i < argc; i++ ) {
286                         strcat( buf, " " );
287                         strcat( buf, argv[i] );
288                 }
289
290                 syslog( LOG_ALERT, "args: (%s)", buf );
291         }
292
293         tolist = NULL;
294         numto = 0;
295         add_to( &tolist, &numto, sendmailargs );
296         nargs = numto;
297         ngroups = numerr = 0;
298         togroups = NULL;
299         errlist = NULL;
300         for ( i = optind; i < argc; i++ ) {
301                 char    *s;
302                 int     type;
303                 char    *localpart, *domainpart;
304                 char    address[1024];
305
306 /*  TBC: Make this processing optional */
307 /*              for ( j = 0; argv[i][j] != '\0'; j++ ) { */
308 /*                      if ( argv[i][j] == '.' || argv[i][j] == '_' ) */
309 /*                              argv[i][j] = ' '; */
310 /*              } */
311
312                 type = USER;
313                 split_address( argv[i], &localpart, &domainpart );
314                 if ( (s = strrchr( localpart, '-' )) != NULL ) {
315                         s++;
316
317                         if ((strcasecmp(s, ERROR) == 0) ||
318                                 (strcasecmp(s, ERRORS) == 0)) {
319                                 type = GROUP_ERRORS;
320                                 *(--s) = '\0';
321                         } else if ((strcasecmp(s, REQUEST) == 0) ||
322                                 (strcasecmp(s, REQUESTS) == 0)) {
323                                 type = GROUP_REQUEST;
324                                 *(--s) = '\0';
325                         } else if ( strcasecmp( s, MEMBERS ) == 0 ) {
326                                 type = GROUP_MEMBERS;
327                                 *(--s) = '\0';
328                         } else if ((strcasecmp(s, OWNER) == 0) ||
329                                 (strcasecmp(s, OWNERS) == 0)) {
330                                 type = GROUP_OWNER;
331                                 *(--s) = '\0';
332                         }
333                 }
334
335                 if ( domainpart ) {
336                         sprintf( address, "%s@%s", localpart, domainpart );
337                         free( localpart );
338                         free( domainpart );
339                 } else {
340                         sprintf( address, "%s@%s", localpart, domainpart );
341                         free( localpart );
342                 }
343                 do_address( address, &tolist, &numto, &togroups, &ngroups,
344                     &errlist, &numerr, type );
345         }
346
347         /*
348          * If we have both errors and successful deliveries to make or if
349          * if there are any groups to deliver to, we basically need to read
350          * the message twice.  So, we have to put it in a tmp file.
351          */
352
353         if ( numerr > 0 && numto > nargs || ngroups > 0 ) {
354                 FILE    *fp;
355                 char    buf[BUFSIZ];
356
357                 umask( 077 );
358                 if ( (fp = tmpfile()) == NULL ) {
359                         syslog( LOG_ALERT, "could not open tmp file" );
360                         unbind_and_exit( EX_TEMPFAIL );
361                 }
362
363                 /* copy the message to a temp file */
364                 while ( fgets( buf, sizeof(buf), stdin ) != NULL ) {
365                         if ( fputs( buf, fp ) == EOF ) {
366                                 syslog( LOG_ALERT, "error writing tmpfile" );
367                                 unbind_and_exit( EX_TEMPFAIL );
368                         }
369                 }
370
371                 if ( dup2( fileno( fp ), 0 ) == -1 ) {
372                         syslog( LOG_ALERT, "could not dup2 tmpfile" );
373                         unbind_and_exit( EX_TEMPFAIL );
374                 }
375
376                 fclose( fp );
377         }
378
379         /* deal with errors */
380         if ( numerr > 0 ) {
381                 if ( debug ) {
382                         syslog( LOG_ALERT, "sending errors" );
383                 }
384                 (void) rewind( stdin );
385                 send_errors( errlist, numerr );
386         }
387
388         (void) ldap_unbind( ld );
389
390         /* send to groups with errorsTo */
391         if ( ngroups > 0 ) {
392                 if ( debug ) {
393                         syslog( LOG_ALERT, "sending to groups with errorsto" );
394                 }
395                 (void) rewind( stdin );
396                 send_group( togroups, ngroups );
397         }
398
399         /* send to expanded aliases and groups w/o errorsTo */
400         if ( numto > nargs ) {
401                 if ( debug ) {
402                         syslog( LOG_ALERT, "sending to aliases and groups" );
403                 }
404                 (void) rewind( stdin );
405                 send_message( tolist );
406         }
407
408         return( EX_OK );
409 }
410
411 static char *
412 get_config_line( FILE *cf, int *lineno)
413 {
414         static char     buf[2048];
415         int             len;
416         int             pos;
417         int             room;
418
419         pos = 0;
420         room = sizeof( buf );
421         while ( fgets( &buf[pos], room, cf ) ) {
422                 (*lineno)++;
423                 if ( pos > 0 ) {
424                         /* Delete whitespace at the beginning of new data */
425                         if ( isspace( buf[pos] ) ) {
426                                 char *s, *d;
427                                 for ( s = buf+pos; isspace(*s); s++ )
428                                         ;
429                                 for ( d = buf+pos; *s; s++, d++ ) {
430                                         *d = *s;
431                                 }
432                                 *d = *s;
433                         }
434                 }
435                 len = strlen( buf );
436                 if ( buf[len-1] != '\n' ) {
437                         syslog( LOG_ALERT, "Definition too long at line %d",
438                                 *lineno );
439                         exit( EX_TEMPFAIL );
440                 }
441                 if ( buf[0] == '#' )
442                         continue;
443                 if ( strspn( buf, " \t\n" ) == len )
444                         continue;
445                 if ( buf[len-2] == '\\' ) {
446                         pos = len - 2;
447                         room = sizeof(buf) - pos;
448                         continue;
449                 }
450                 /* We have a real line, we will exit the loop */
451                 buf[len-1] = '\0';
452                 return( buf );
453         }
454         return( NULL );
455 }
456
457 static void
458 add_url ( char *url, int rdnpref, int typemask )
459 {
460         Base            **list_temp;
461         int             size;
462         Base            *b;
463
464         b = calloc(1, sizeof(Base));
465         if ( !b ) {
466                 syslog( LOG_ALERT, "Out of memory" );
467                 exit( EX_TEMPFAIL );
468         }
469         b->b_url = strdup( url );
470         b->b_rdnpref = rdnpref;
471         b->b_search   = typemask;
472
473         if ( base == NULL ) {
474                 base = calloc(2, sizeof(LDAPURLDesc *));
475                 if ( !base ) {
476                         syslog( LOG_ALERT, "Out of memory" );
477                         exit( EX_TEMPFAIL );
478                 }
479                 base[0] = b;
480         } else {
481                 for ( size = 0; base[size]; size++ )
482                         ;
483                 size += 2;
484                 list_temp = realloc( base, size*sizeof(LDAPURLDesc *) );
485                 if ( !list_temp ) {
486                         syslog( LOG_ALERT, "Out of memory" );
487                         exit( EX_TEMPFAIL );
488                 }
489                 base = list_temp;
490                 base[size-2] = b;
491                 base[size-1] = NULL;
492         }
493 }
494
495 static void
496 add_def_attr( char *s )
497 {
498         char *p, *q;
499
500         p = s;
501         while ( *p ) {
502                 p += strspn( p, "\t," );
503                 q = strpbrk( p, " \t," );
504                 if ( q ) {
505                         *q = '\0';
506                         add_single_to( &def_attr, p );
507                 } else {
508                         add_single_to( &def_attr, p );
509                         break;
510                 }
511                 p = q + 1;
512         }
513 }
514
515 static void
516 add_attr_semantics( char *s )
517 {
518         char *p, *q;
519         AttrSemantics *as;
520
521         as = calloc( 1, sizeof( AttrSemantics ) );
522         p = s;
523         while ( isspace ( *p ) )
524                 p++;
525         q = p;
526         while ( !isspace ( *q ) && *q != '\0' )
527                 q++;
528         *q = '\0';
529         as->as_name = strdup( p );
530         p = q + 1;
531
532         while ( *p ) {
533                 while ( isspace ( *p ) )
534                         p++;
535                 q = p;
536                 while ( !isspace ( *q ) && *q != '\0' )
537                         q++;
538                 *q = '\0';
539                 if ( !strcasecmp( p, "multivalued" ) ) {
540                         as->as_m_valued = 1;
541                 } else if ( !strcasecmp( p, "multiple-entries" ) ) {
542                         as->as_m_entries = 1;
543                 } else if ( !strcasecmp( p, "final" ) ) {
544                         as->as_final = 1;
545                 } else if ( !strcasecmp( p, "local-native-mailbox" ) ) {
546                         as->as_syntax = AS_SYNTAX_NATIVE_MB;
547                 } else if ( !strcasecmp( p, "rfc822" ) ) {
548                         as->as_syntax = AS_SYNTAX_RFC822;
549                 } else if ( !strcasecmp( p, "rfc822-extended" ) ) {
550                         as->as_syntax = AS_SYNTAX_RFC822_EXT;
551                 } else if ( !strcasecmp( p, "dn" ) ) {
552                         as->as_syntax = AS_SYNTAX_DN;
553                 } else if ( !strcasecmp( p, "url" ) ) {
554                         as->as_syntax = AS_SYNTAX_URL;
555                 } else if ( !strncasecmp( p, "search-with-filter=", 19 ) ) {
556                         as->as_syntax = AS_SYNTAX_BOOL_FILTER;
557                         q = strchr( p, '=' );
558                         if ( q ) {
559                                 p = q + 1;
560                                 while ( *q && !isspace( *q ) ) {
561                                         q++;
562                                 }
563                                 if ( *q ) {
564                                         *q = '\0';
565                                         as->as_param = strdup( p );
566                                         p = q + 1;
567                                 } else {
568                                         as->as_param = strdup( p );
569                                         p = q;
570                                 }
571                         } else {
572                                 syslog( LOG_ALERT,
573                                         "Missing filter in %s", s );
574                                 exit( EX_TEMPFAIL );
575                         }
576                 } else if ( !strcasecmp( p, "host" ) ) {
577                         as->as_kind = AS_SYNTAX_HOST;
578                 } else if ( !strcasecmp( p, "forward-to-host" ) ) {
579                         as->as_kind = AS_KIND_FORWARD_TO_HOST;
580                 } else if ( !strcasecmp( p, "recipient" ) ) {
581                         as->as_kind = AS_KIND_RECIPIENT;
582                 } else if ( !strcasecmp( p, "errors" ) ) {
583                         as->as_kind = AS_KIND_ERRORS;
584                 } else if ( !strcasecmp( p, "request" ) ) {
585                         as->as_kind = AS_KIND_REQUEST;
586                 } else if ( !strcasecmp( p, "owner" ) ) {
587                         as->as_kind = AS_KIND_OWNER;
588                 } else {
589                         syslog( LOG_ALERT,
590                                 "Unknown semantics word %s", p );
591                         exit( EX_TEMPFAIL );
592                 }
593                 p = q + 1;
594         }
595         if ( attr_semantics == NULL ) {
596                 attr_semantics = calloc(2, sizeof(AttrSemantics *));
597                 if ( !attr_semantics ) {
598                         syslog( LOG_ALERT, "Out of memory" );
599                         exit( EX_TEMPFAIL );
600                 }
601                 attr_semantics[0] = as;
602         } else {
603                 int size;
604                 AttrSemantics **list_temp;
605                 for ( size = 0; attr_semantics[size]; size++ )
606                         ;
607                 size += 2;
608                 list_temp = realloc( attr_semantics,
609                                      size*sizeof(AttrSemantics *) );
610                 if ( !list_temp ) {
611                         syslog( LOG_ALERT, "Out of memory" );
612                         exit( EX_TEMPFAIL );
613                 }
614                 attr_semantics = list_temp;
615                 attr_semantics[size-2] = as;
616                 attr_semantics[size-1] = NULL;
617         }
618 }
619
620 static void
621 load_config( char *filespec )
622 {
623         FILE            *cf;
624         char            *line;
625         int             lineno = 0;
626         char            *p;
627         int             rdnpref;
628         int             typemask;
629
630         cf = fopen( filespec, "r" );
631         if ( !cf ) {
632                 perror( "Opening config file" );
633                 exit( EX_TEMPFAIL );
634         }
635
636         while ( ( line = get_config_line( cf,&lineno ) ) ) {
637                 p = strpbrk( line, " \t" );
638                 if ( !p ) {
639                         syslog( LOG_ALERT,
640                                 "Missing space at line %d", lineno );
641                         exit( EX_TEMPFAIL );
642                 }
643                 if ( !strncmp( line, "search", p-line ) ) {
644                         p += strspn( p, " \t" );
645                         /* TBC, get these */
646                         rdnpref = 0;
647                         typemask = 0xFF;
648                         add_url( p, rdnpref, typemask );
649                 } else if ( !strncmp(line, "attribute", p-line) ) {
650                         p += strspn(p, " \t");
651                         add_attr_semantics( p );
652                 } else if ( !strncmp(line, "default-attributes", p-line) ) {
653                         p += strspn(p, " \t");
654                         add_def_attr( p );
655                 } else if ( !strncmp(line, "group-classes", p-line) ) {
656                         p += strspn(p, " \t");
657                         add_single_to( &groupclasses, p );
658                 } else {
659                         syslog( LOG_ALERT,
660                                 "Unparseable config definition at line %d",
661                                 lineno );
662                         exit( EX_TEMPFAIL );
663                 }
664         }
665         fclose( cf );
666 }
667
668 static int
669 connect_to_x500( void )
670 {
671         int opt;
672
673         if ( (ld = ldap_init( ldaphost, 0 )) == NULL ) {
674                 syslog( LOG_ALERT, "ldap_init failed" );
675                 return( -1 );
676         }
677
678         /*  TBC: Set this only when it makes sense
679         opt = MAIL500_MAXAMBIGUOUS;
680         ldap_set_option(ld, LDAP_OPT_SIZELIMIT, &opt);
681         */
682         opt = LDAP_DEREF_ALWAYS;
683         ldap_set_option(ld, LDAP_OPT_DEREF, &opt);
684
685         if ( ldap_simple_bind_s( ld, NULL, NULL ) != LDAP_SUCCESS ) {
686                 syslog( LOG_ALERT, "ldap_simple_bind_s failed" );
687                 return( -1 );
688         }
689
690         return( 0 );
691 }
692
693 static Group *
694 new_group( char *dn, Group **list, int *nlist )
695 {
696         int     i;
697         Group   *this_group;
698
699         for ( i = 0; i < *nlist; i++ ) {
700                 if ( strcmp( dn, (*list)[i].g_dn ) == 0 ) {
701                         syslog( LOG_ALERT, "group loop 2 detected (%s)", dn );
702                         return NULL;
703                 }
704         }
705
706         if ( *nlist == 0 ) {
707                 *list = (Group *) malloc( sizeof(Group) );
708         } else {
709                 *list = (Group *) realloc( *list, (*nlist + 1) *
710                     sizeof(Group) );
711         }
712
713         this_group = *list;
714
715         (*list)[*nlist].g_errorsto = NULL;
716         (*list)[*nlist].g_members = NULL;
717         (*list)[*nlist].g_nmembers = 0;
718         /* save the group's dn so we can check for loops above */
719         (*list)[*nlist].g_dn = strdup( dn );
720
721         (*nlist)++;
722
723         return( this_group );
724 }
725
726 static void
727 split_address(
728         char    *address,
729         char    **localpart,
730         char    **domainpart
731 )
732 {
733         char            *p;
734
735         if ( ( p = strrchr( address, '@' ) ) == NULL ) {
736                 *localpart = strdup( address );
737                 *domainpart = NULL;
738         } else {
739                 *localpart = malloc( p - address + 1 );
740                 strncpy( *localpart, address, p - address );
741                 (*localpart)[p - address] = '\0';
742                 p++;
743                 *domainpart = strdup( p );
744         }
745 }
746
747 static int
748 dn_search(
749         char    **dnlist, 
750         char    *address,
751         char    ***to,
752         int     *nto,
753         Group   **togroups,
754         int     *ngroups,
755         Error   **err,
756         int     *nerr
757 )
758 {
759         int             rc;
760         int             i;
761         int             resolved = 0;
762         LDAPMessage     *res, *e;
763         struct timeval  timeout;
764
765         timeout.tv_sec = MAIL500_TIMEOUT;
766         timeout.tv_usec = 0;
767         for ( i = 0; dnlist[i]; i++ ) {
768                 if ( (rc = ldap_search_st( ld, dnlist[i], LDAP_SCOPE_BASE,
769                         "(objectclass=*)", def_attr, 0,
770                          &timeout, &res )) != LDAP_SUCCESS ) {
771                         if ( rc == LDAP_NO_SUCH_OBJECT ) {
772                                 add_error( err, nerr, E_BADMEMBER, dnlist[i], NULL );
773                                 continue;
774                         } else {
775                                 syslog( LOG_ALERT, "member search return 0x%x", rc );
776
777                                 unbind_and_exit( EX_TEMPFAIL );
778                         }
779                 } else {
780                         if ( (e = ldap_first_entry( ld, res )) == NULL ) {
781                                 syslog( LOG_ALERT, "member search error parsing entry" );
782                                 unbind_and_exit( EX_TEMPFAIL );
783                         }
784                         if ( entry_engine( e, dnlist[i], address, to, nto,
785                                            togroups, ngroups, err, nerr,
786                                            USER | GROUP_MEMBERS ) ) {
787                                 resolved = 1;
788                         }
789                 }
790         }
791         return( resolved );
792 }
793
794 static int
795 search_ldap_url(
796         char    *url,
797         Subst   *substs,
798         char    *address,
799         int     rdnpref,
800         int     multi_entry,
801         char    ***to,
802         int     *nto,
803         Group   **togroups,
804         int     *ngroups,
805         Error   **err,
806         int     *nerr,
807         int     type
808 )
809 {
810         LDAPURLDesc     *ludp;
811         char            *p, *s, *d;
812         int             i;
813         char            filter[1024];
814         char            realfilter[1024];
815         LDAPMessage     *e, *res;
816         int             rc;
817         char            **attrlist;
818         struct timeval  timeout;
819         int             match;
820         int             resolved = 0;
821         char            *dn;
822
823         timeout.tv_sec = MAIL500_TIMEOUT;
824         timeout.tv_usec = 0;
825
826         rc = ldap_url_parse( url, &ludp );
827         if ( rc ) {
828                 switch ( rc ) {
829                 case LDAP_URL_ERR_NOTLDAP:
830                         syslog( LOG_ALERT,
831                                 "Not an LDAP URL: %s", url );
832                         break;
833                 case LDAP_URL_ERR_BADENCLOSURE:
834                         syslog( LOG_ALERT,
835                                 "Bad Enclosure in URL: %s", url );
836                         break;
837                 case LDAP_URL_ERR_BADURL:
838                         syslog( LOG_ALERT,
839                                 "Bad URL: %s", url );
840                         break;
841                 case LDAP_URL_ERR_BADHOST:
842                         syslog( LOG_ALERT,
843                                 "Host is invalid in URL: %s", url );
844                         break;
845                 case LDAP_URL_ERR_BADATTRS:
846                         syslog( LOG_ALERT,
847                                 "Attributes are invalid in URL: %s", url );
848                         break;
849                 case LDAP_URL_ERR_BADSCOPE:
850                         syslog( LOG_ALERT,
851                                 "Scope is invalid in URL: %s", url );
852                         break;
853                 case LDAP_URL_ERR_BADFILTER:
854                         syslog( LOG_ALERT,
855                                 "Filter is invalid in URL: %s", url );
856                         break;
857                 case LDAP_URL_ERR_BADEXTS:
858                         syslog( LOG_ALERT,
859                                 "Extensions are invalid in URL: %s", url );
860                         break;
861                 case LDAP_URL_ERR_MEM:
862                         syslog( LOG_ALERT,
863                                 "Out of memory parsing URL: %s", url );
864                         break;
865                 case LDAP_URL_ERR_PARAM:
866                         syslog( LOG_ALERT,
867                                 "bad parameter parsing URL: %s", url );
868                         break;
869                 default:
870                         syslog( LOG_ALERT,
871                                 "Unknown error %d parsing URL: %s",
872                                 rc, url );
873                         break;
874                 }
875                 add_error( err, nerr, E_BADMEMBER,
876                            url, NULL );
877                 return 0;
878         }
879
880         if ( substs ) {
881                 for ( s = ludp->lud_filter, d = filter; *s; s++,d++ ) {
882                         if ( *s == '%' ) {
883                                 s++;
884                                 if ( *s == '%' ) {
885                                         *d = '%';
886                                         continue;
887                                 }
888                                 for ( i = 0; substs[i].sub_char != '\0';
889                                       i++ ) {
890                                         if ( *s == substs[i].sub_char ) {
891                                                 for ( p = substs[i].sub_value;
892                                                       *p; p++,d++ ) {
893                                                         *d = *p;
894                                                 }
895                                                 d--;
896                                                 break;
897                                         }
898                                 }
899                                 if ( substs[i].sub_char == '\0' ) {
900                                         syslog( LOG_ALERT,
901                                                 "unknown format %c", *s );
902                                 }
903                         } else {
904                                 *d = *s;
905                         }
906                 }
907                 *d = *s;
908         } else {
909                 strncpy( filter, ludp->lud_filter, sizeof( filter ) - 1 );
910                 filter[ sizeof( filter ) - 1 ] = '\0';
911         }
912
913         for ( s = filter, d = realfilter; *s; s++, d++ ) {
914                 if ( *s == '*' ) {
915                         *d++ = '\\';
916                 }
917                 *d = *s;
918         }
919         *d = '\0';
920
921         if ( ludp->lud_attrs ) {
922                 attrlist = ludp->lud_attrs;
923         } else {
924                 attrlist = def_attr;
925         }
926         res = NULL;
927         /* TBC: we don't read the host, dammit */
928         rc = ldap_search_st( ld, ludp->lud_dn, ludp->lud_scope,
929                              realfilter, attrlist, 0,
930                              &timeout, &res );
931
932         /* some other trouble - try again later */
933         if ( rc != LDAP_SUCCESS &&
934              rc != LDAP_SIZELIMIT_EXCEEDED ) {
935                 syslog( LOG_ALERT, "return 0x%x from X.500",
936                         rc );
937                 unbind_and_exit( EX_TEMPFAIL );
938         }
939
940         match = ldap_count_entries( ld, res );
941
942         /* trouble - try again later */
943         if ( match == -1 ) {
944                 syslog( LOG_ALERT, "error parsing result from X.500" );
945                 unbind_and_exit( EX_TEMPFAIL );
946         }
947
948         if ( match == 1 || multi_entry ) {
949                 for ( e = ldap_first_entry( ld, res ); e != NULL;
950                       e = ldap_next_entry( ld, e ) ) {
951                         dn = ldap_get_dn( ld, e );
952                         resolved = entry_engine( e, dn, address, to, nto,
953                                                  togroups, ngroups,
954                                                  err, nerr, type );
955                         if ( !resolved ) {
956                                 add_error( err, nerr, E_NOEMAIL, address, res );
957                         }
958                 }
959                 return ( resolved );
960         }
961
962         /* more than one match - bounce with ambiguous user? */
963         if ( match > 1 ) {
964                 LDAPMessage     *next, *tmpres = NULL;
965                 char            *dn;
966                 char            **xdn;
967
968                 /* not giving rdn preference - bounce with ambiguous user */
969                 if ( rdnpref == 0 ) {
970                         add_error( err, nerr, E_AMBIGUOUS, address, res );
971                         return 0;
972                 }
973
974                 /*
975                  * giving rdn preference - see if any entries were matched
976                  * because of their rdn.  If so, collect them to deal with
977                  * later (== 1 we deliver, > 1 we bounce).
978                  */
979
980                 for ( e = ldap_first_entry( ld, res ); e != NULL; e = next ) {
981                         next = ldap_next_entry( ld, e );
982                         dn = ldap_get_dn( ld, e );
983                         xdn = ldap_explode_dn( dn, 1 );
984
985                         /* XXX bad, but how else can we do it? XXX */
986                         if ( strcasecmp( xdn[0], address ) == 0 ) {
987                                 ldap_delete_result_entry( &res, e );
988                                 ldap_add_result_entry( &tmpres, e );
989                         }
990
991                         ldap_value_free( xdn );
992                         free( dn );
993                 }
994
995                 /* nothing matched by rdn - go ahead and bounce */
996                 if ( tmpres == NULL ) {
997                         add_error( err, nerr, E_AMBIGUOUS, address, res );
998                         return 0;
999
1000                 /* more than one matched by rdn - bounce with rdn matches */
1001                 } else if ( (match = ldap_count_entries( ld, tmpres )) > 1 ) {
1002                         add_error( err, nerr, E_AMBIGUOUS, address, tmpres );
1003                         return 0;
1004
1005                 /* trouble... */
1006                 } else if ( match < 0 ) {
1007                         syslog( LOG_ALERT, "error parsing result from X.500" );
1008                         unbind_and_exit( EX_TEMPFAIL );
1009                 }
1010
1011                 /* otherwise one matched by rdn - send to it */
1012                 ldap_msgfree( res );
1013                 res = tmpres;
1014
1015                 /* trouble */
1016                 if ( (e = ldap_first_entry( ld, res )) == NULL ) {
1017                         syslog( LOG_ALERT, "error parsing entry from X.500" );
1018                         unbind_and_exit( EX_TEMPFAIL );
1019                 }
1020
1021                 dn = ldap_get_dn( ld, e );
1022
1023                 resolved = entry_engine( e, dn, address, to, nto,
1024                                          togroups, ngroups,
1025                                          err, nerr, type );
1026                 if ( !resolved ) {
1027                         add_error( err, nerr, E_NOEMAIL, address, res );
1028                         /* Don't free res if we passed it to add_error */
1029                 } else {
1030                         ldap_msgfree( res );
1031                 }
1032         }
1033         return( resolved );
1034 }
1035
1036 static int
1037 url_list_search(
1038         char    **urllist, 
1039         char    *address,
1040         int     multi_entry,
1041         char    ***to,
1042         int     *nto,
1043         Group   **togroups,
1044         int     *ngroups,
1045         Error   **err,
1046         int     *nerr,
1047         int     type
1048 )
1049 {
1050         int             i;
1051         int             resolved = 0;
1052
1053         for ( i = 0; urllist[i]; i++ ) {
1054
1055                 if ( !strncasecmp( urllist[i], "mail:", 5 ) ) {
1056                         char    *vals[2];
1057
1058                         vals[0] = urllist[i] + 5;
1059                         vals[1] = NULL;
1060                         add_to( to, nto, vals );
1061                         resolved = 1;
1062
1063                 } else if ( ldap_is_ldap_url( urllist[i] ) ) {
1064
1065                         resolved = search_ldap_url( urllist[i], NULL,
1066                                                     address, 0, multi_entry,
1067                                                     to, nto, togroups, ngroups,
1068                                                     err, nerr, type );
1069                 } else {
1070                         /* Produce some sensible error here */
1071                         resolved = 0;
1072                 }
1073         }
1074         return( resolved );
1075 }
1076
1077 /*
1078  * The entry engine processes an entry.  Normally, each entry will resolve
1079  * to one or more values that will be added to the 'to' argument.  This
1080  * argument needs not be the global 'to' list, it may be the g_to field
1081  * in a group.  Groups have no special treatment, unless they require
1082  * a special sender.
1083  */
1084
1085 static int
1086 entry_engine(
1087         LDAPMessage *e,
1088         char    *dn,
1089         char    *address,
1090         char    ***to,
1091         int     *nto,
1092         Group   **togroups,
1093         int     *ngroups,
1094         Error   **err,
1095         int     *nerr,
1096         int     type
1097 )
1098 {
1099         char    **vals;
1100         int     i;
1101         int     resolved = 0;
1102         char    ***current_to = to;
1103         int     *current_nto = nto;
1104         Group   *current_group = NULL;
1105         char    buf[1024];
1106         char    *localpart, *domainpart;
1107         Subst   substs[2];
1108
1109         for ( i=0; attr_semantics[i] != NULL; i++ ) {
1110                 AttrSemantics   *as = attr_semantics[i];
1111                 int             nent;
1112
1113                 vals = ldap_get_values( ld, e, as->as_name );
1114                 if ( !vals || vals[0] == NULL ) {
1115                         continue;
1116                 }
1117                 nent = count_values( vals );
1118                 if ( nent > 1 && !as->as_m_valued ) {
1119                         add_error( err, nerr, E_AMBIGUOUS, address, e );
1120                         return( 0 );
1121                 }
1122                 switch ( as->as_kind ) {
1123                 case AS_KIND_RECIPIENT:
1124                         if ( ! ( type & ( USER | GROUP_MEMBERS ) ) )
1125                                 break;
1126                         switch ( as->as_syntax ) {
1127                         case AS_SYNTAX_RFC822:
1128                                 add_to( current_to, current_nto, vals );
1129                                 resolved = 1;
1130                                 break;
1131                         case AS_SYNTAX_RFC822_EXT:
1132                                 add_to( current_to, current_nto, vals );
1133                                 resolved = 1;
1134                                 break;
1135                         case AS_SYNTAX_NATIVE_MB:
1136                                 /* We used to concatenate mailHost if set here */
1137                                 /*
1138                                  * We used to send a copy to the vacation host
1139                                  * if onVacation to uid@vacationhost
1140                                  */
1141                                 add_to( current_to, current_nto, vals );
1142                                 resolved = 1;
1143                                 break;
1144
1145                         case AS_SYNTAX_DN:
1146                                 if ( dn_search( vals, address,
1147                                                 current_to, current_nto,
1148                                                 togroups, ngroups,
1149                                                 err, nerr ) ) {
1150                                         resolved = 1;
1151                                 }
1152                                 break;
1153
1154                         case AS_SYNTAX_URL:
1155                                 if ( url_list_search( vals, address,
1156                                                  as->as_m_entries,
1157                                                  current_to, current_nto,
1158                                                  togroups, ngroups,
1159                                                  err, nerr, type ) ) {
1160                                         resolved = 1;
1161                                 }
1162                                 break;
1163
1164                         case AS_SYNTAX_BOOL_FILTER:
1165                                 if ( strcasecmp( vals[0], "true" ) ) {
1166                                         break;
1167                                 }
1168                                 substs[0].sub_char = 'D';
1169                                 substs[0].sub_value = dn;
1170                                 substs[1].sub_char = '\0';
1171                                 substs[1].sub_value = NULL;
1172                                 if ( url_list_search( vals, address,
1173                                                  as->as_m_entries,
1174                                                  current_to, current_nto,
1175                                                  togroups, ngroups,
1176                                                  err, nerr, type ) ) {
1177                                         resolved = 1;
1178                                 }
1179                                 break;
1180
1181                         default:
1182                                 syslog( LOG_ALERT,
1183                                         "Invalid syntax %d for kind %d",
1184                                         as->as_syntax, as->as_kind );
1185                                 break;
1186                         }
1187                         break;
1188
1189                 case AS_KIND_ERRORS:
1190                         /* This is a group with special processing */
1191                         if ( type & GROUP_ERRORS ) {
1192                                 switch (as->as_kind) {
1193                                 case AS_SYNTAX_RFC822:
1194                                         add_to( current_to, current_nto, vals );
1195                                         resolved = 1;
1196                                         break;
1197                                 case AS_SYNTAX_URL:
1198                                 default:
1199                                         syslog( LOG_ALERT,
1200                                                 "Invalid syntax %d for kind %d",
1201                                                 as->as_syntax, as->as_kind );
1202                                 }
1203                         } else {
1204                                 current_group = new_group( dn, togroups,
1205                                                            ngroups );
1206                                 current_to = &current_group->g_members;
1207                                 current_nto = &current_group->g_nmembers;
1208                                 split_address( address,
1209                                                &localpart, &domainpart );
1210                                 if ( domainpart ) {
1211                                         sprintf( buf, "%s-%s@%s",
1212                                                  localpart, ERRORS,
1213                                                  domainpart );
1214                                         free( localpart );
1215                                         free( domainpart );
1216                                 } else {
1217                                         sprintf( buf, "%s-%s@%s",
1218                                                  localpart, ERRORS,
1219                                                  host );
1220                                         free( localpart );
1221                                 }
1222                                 current_group->g_errorsto = strdup( buf );
1223                         }
1224                         break;
1225
1226                 case AS_KIND_REQUEST:
1227                         /* This is a group with special processing */
1228                         if ( type & GROUP_REQUEST ) {
1229                                 add_to( current_to, current_nto, vals );
1230                                 resolved = 1;
1231                         }
1232                         break;
1233
1234                 case AS_KIND_OWNER:
1235                         /* This is a group with special processing */
1236                         if ( type & GROUP_REQUEST ) {
1237                                 add_to( current_to, current_nto, vals );
1238                                 resolved = 1;
1239                         }
1240                         break;
1241
1242                 default:
1243                         syslog( LOG_ALERT,
1244                                 "Invalid kind %d", as->as_kind );
1245                         /* Error, TBC */
1246                 }
1247                 ldap_value_free( vals );
1248                 if ( as->as_final ) {
1249                         return( resolved );
1250                 }
1251         }
1252         return( resolved );
1253 }
1254
1255 static int
1256 search_bases(
1257         char    *filter,
1258         Subst   *substs,
1259         char    *name,
1260         char    ***to,
1261         int     *nto,
1262         Group   **togroups,
1263         int     *ngroups,
1264         Error   **err,
1265         int     *nerr,
1266         int     type
1267 )
1268 {
1269         int             b, resolved = 0;
1270
1271         for ( b = 0; base[b] != NULL; b++ ) {
1272
1273                 if ( ! (base[b]->b_search & type) ) {
1274                         continue;
1275                 }
1276
1277                 resolved = search_ldap_url( base[b]->b_url, substs, name,
1278                                             base[b]->b_rdnpref,
1279                                             base[b]->b_m_entries,
1280                                             to, nto, togroups, ngroups,
1281                                             err, nerr, type );
1282                 if ( resolved )
1283                         break;
1284         }
1285         return( resolved );
1286 }
1287
1288 static void
1289 do_address(
1290         char    *name,
1291         char    ***to,
1292         int     *nto,
1293         Group   **togroups,
1294         int     *ngroups,
1295         Error   **err,
1296         int     *nerr,
1297         int     type
1298 )
1299 {
1300         struct timeval  timeout;
1301         char            *localpart, *domainpart;
1302         int             resolved;
1303         Subst   substs[5];
1304
1305         /*
1306          * Look up the name in X.500, add the appropriate addresses found
1307          * to the to list, or to the err list in case of error.  Groups are
1308          * handled by the do_group routine, individuals are handled here.
1309          * When looking up name, we follow the bases hierarchy, looking
1310          * in base[0] first, then base[1], etc.  For each base, there is
1311          * a set of search filters to try, in order.  If something goes
1312          * wrong here trying to contact X.500, we exit with EX_TEMPFAIL.
1313          * If the b_rdnpref flag is set, then we give preference to entries
1314          * that matched name because it's their rdn, otherwise not.
1315          */
1316
1317         split_address( name, &localpart, &domainpart );
1318         timeout.tv_sec = MAIL500_TIMEOUT;
1319         timeout.tv_usec = 0;
1320         substs[0].sub_char = 'm';
1321         substs[0].sub_value = name;
1322         substs[1].sub_char = 'h';
1323         substs[1].sub_value = host;
1324         substs[2].sub_char = 'l';
1325         substs[2].sub_value = localpart;
1326         substs[3].sub_char = 'd';
1327         substs[3].sub_value = domainpart;
1328         substs[4].sub_char = '\0';
1329         substs[4].sub_value = NULL;
1330
1331         resolved = search_bases( NULL, substs, name,
1332                                  to, nto, togroups, ngroups,
1333                                  err, nerr, type );
1334
1335         if ( !resolved ) {
1336                 /* not resolved - bounce with user unknown */
1337                 if ( type == USER ) {
1338                         add_error( err, nerr, E_USERUNKNOWN, name, NULL );
1339                 } else {
1340                         add_error( err, nerr, E_GROUPUNKNOWN, name, NULL );
1341                 }
1342         }
1343 }
1344
1345 static void
1346 send_message( char **to )
1347 {
1348         int     pid;
1349 #ifndef HAVE_WAITPID
1350         WAITSTATUSTYPE  status;
1351 #endif
1352
1353         if ( debug ) {
1354                 char    buf[1024];
1355                 int     i;
1356
1357                 strcpy( buf, to[0] );
1358                 for ( i = 1; to[i] != NULL; i++ ) {
1359                         strcat( buf, " " );
1360                         strcat( buf, to[i] );
1361                 }
1362
1363                 syslog( LOG_ALERT, "send_message execing sendmail: (%s)", buf );
1364         }
1365
1366         /* parent */
1367         if ( (pid = fork()) != 0 ) {
1368 #ifdef HAVE_WAITPID
1369                 waitpid( pid, (int *) NULL, 0 );
1370 #else
1371                 wait4( pid, &status, WAIT_FLAGS, 0 );
1372 #endif
1373         /* child */
1374         } else {
1375                 /* to includes sendmailargs */
1376                 execv( MAIL500_SENDMAIL, to );
1377
1378                 syslog( LOG_ALERT, "execv failed" );
1379
1380                 exit( EX_TEMPFAIL );
1381         }
1382 }
1383
1384 static void
1385 send_group( Group *group, int ngroup )
1386 {
1387         int     i, pid;
1388         char    **argv;
1389         int     argc;
1390         char    *iargv[7];
1391 #ifndef HAVE_WAITPID
1392         WAITSTATUSTYPE  status;
1393 #endif
1394
1395         for ( i = 0; i < ngroup; i++ ) {
1396                 (void) rewind( stdin );
1397
1398                 iargv[0] = MAIL500_SENDMAIL;
1399                 iargv[1] = "-f";
1400                 iargv[2] = group[i].g_errorsto;
1401                 iargv[3] = "-oMrX.500";
1402                 iargv[4] = "-odi";
1403                 iargv[5] = "-oi";
1404                 iargv[6] = NULL;
1405
1406                 argv = NULL;
1407                 argc = 0;
1408                 add_to( &argv, &argc, iargv );
1409                 add_to( &argv, &argc, group[i].g_members );
1410
1411                 if ( debug ) {
1412                         char    buf[1024];
1413                         int     i;
1414
1415                         strcpy( buf, argv[0] );
1416                         for ( i = 1; i < argc; i++ ) {
1417                                 strcat( buf, " " );
1418                                 strcat( buf, argv[i] );
1419                         }
1420
1421                         syslog( LOG_ALERT, "execing sendmail: (%s)", buf );
1422                 }
1423
1424                 /* parent */
1425                 if ( (pid = fork()) != 0 ) {
1426 #ifdef HAVE_WAITPID
1427                         waitpid( pid, (int *) NULL, 0 );
1428 #else
1429                         wait4( pid, &status, WAIT_FLAGS, 0 );
1430 #endif
1431                 /* child */
1432                 } else {
1433                         execv( MAIL500_SENDMAIL, argv );
1434
1435                         syslog( LOG_ALERT, "execv failed" );
1436
1437                         exit( EX_TEMPFAIL );
1438                 }
1439         }
1440 }
1441
1442 static void
1443 send_errors( Error *err, int nerr )
1444 {
1445         int     pid, i, namelen;
1446         FILE    *fp;
1447         int     fd[2];
1448         char    *argv[8];
1449         char    buf[1024];
1450 #ifndef HAVE_WAITPID
1451         WAITSTATUSTYPE  status;
1452 #endif
1453
1454         if ( strcmp( MAIL500_BOUNCEFROM, mailfrom ) == 0 ) {
1455             mailfrom = errorsfrom;
1456         }
1457
1458         argv[0] = MAIL500_SENDMAIL;
1459         argv[1] = "-oMrX.500";
1460         argv[2] = "-odi";
1461         argv[3] = "-oi";
1462         argv[4] = "-f";
1463         argv[5] = MAIL500_BOUNCEFROM;
1464         argv[6] = mailfrom;
1465         argv[7] = NULL;
1466
1467         if ( debug ) {
1468                 int     i;
1469
1470                 strcpy( buf, argv[0] );
1471                 for ( i = 1; argv[i] != NULL; i++ ) {
1472                         strcat( buf, " " );
1473                         strcat( buf, argv[i] );
1474                 }
1475
1476                 syslog( LOG_ALERT, "execing sendmail: (%s)", buf );
1477         }
1478
1479         if ( pipe( fd ) == -1 ) {
1480                 syslog( LOG_ALERT, "cannot create pipe" );
1481                 exit( EX_TEMPFAIL );
1482         }
1483
1484         if ( (pid = fork()) != 0 ) {
1485                 if ( (fp = fdopen( fd[1], "w" )) == NULL ) {
1486                         syslog( LOG_ALERT, "cannot fdopen pipe" );
1487                         exit( EX_TEMPFAIL );
1488                 }
1489
1490                 fprintf( fp, "To: %s\n", mailfrom );
1491                 fprintf( fp, "From: %s\n", errorsfrom );
1492                 fprintf( fp, "Subject: undeliverable mail\n" );
1493                 fprintf( fp, "\n" );
1494                 fprintf( fp, "The following errors occurred when trying to deliver the attached mail:\n" );
1495                 for ( i = 0; i < nerr; i++ ) {
1496                         namelen = strlen( err[i].e_addr );
1497                         fprintf( fp, "\n" );
1498
1499                         switch ( err[i].e_code ) {
1500                         case E_USERUNKNOWN:
1501                                 fprintf( fp, "%s: User unknown\n", err[i].e_addr );
1502                                 break;
1503
1504                         case E_GROUPUNKNOWN:
1505                                 fprintf( fp, "%s: Group unknown\n", err[i].e_addr );
1506                                 break;
1507
1508                         case E_BADMEMBER:
1509                                 fprintf( fp, "%s: Group member does not exist\n",
1510                                     err[i].e_addr );
1511                                 fprintf( fp, "This could be because the distinguished name of the person has changed\n" );
1512                                 fprintf( fp, "If this is the case, the problem can be solved by removing and\n" );
1513                                 fprintf( fp, "then re-adding the person to the group.\n" );
1514                                 break;
1515
1516                         case E_NOREQUEST:
1517                                 fprintf( fp, "%s: Group exists but has no request address\n",
1518                                     err[i].e_addr );
1519                                 break;
1520
1521                         case E_NOERRORS:
1522                                 fprintf( fp, "%s: Group exists but has no errors-to address\n",
1523                                     err[i].e_addr );
1524                                 break;
1525
1526                         case E_NOOWNER:
1527                                 fprintf( fp, "%s: Group exists but has no owner\n",
1528                                     err[i].e_addr );
1529                                 break;
1530
1531                         case E_AMBIGUOUS:
1532                                 do_ambiguous( fp, &err[i], namelen );
1533                                 break;
1534
1535                         case E_NOEMAIL:
1536                                 do_noemail( fp, &err[i], namelen );
1537                                 break;
1538
1539                         case E_MEMBERNOEMAIL:
1540                                 fprintf( fp, "%s: Group member exists but does not have an email address\n",
1541                                     err[i].e_addr );
1542                                 break;
1543
1544                         case E_JOINMEMBERNOEMAIL:
1545                                 fprintf( fp, "%s: User has joined group but does not have an email address\n",
1546                                     err[i].e_addr );
1547                                 break;
1548
1549                         case E_LOOP:
1550                                 fprintf( fp, "%s: User has created a mail loop by adding address %s to their X.500 entry\n",
1551                                     err[i].e_addr, err[i].e_loop );
1552                                 break;
1553
1554                         case E_NOMEMBERS:
1555                                 fprintf( fp, "%s: Group has no members\n",
1556                                     err[i].e_addr );
1557                                 break;
1558
1559                         default:
1560                                 syslog( LOG_ALERT, "unknown error %d", err[i].e_code );
1561                                 unbind_and_exit( EX_TEMPFAIL );
1562                                 break;
1563                         }
1564                 }
1565
1566                 fprintf( fp, "\n------- The original message sent:\n\n" );
1567
1568                 while ( fgets( buf, sizeof(buf), stdin ) != NULL ) {
1569                         fputs( buf, fp );
1570                 }
1571                 fclose( fp );
1572
1573 #ifdef HAVE_WAITPID
1574                 waitpid( pid, (int *) NULL, 0 );
1575 #else
1576                 wait4( pid, &status, WAIT_FLAGS, 0 );
1577 #endif
1578         } else {
1579                 dup2( fd[0], 0 );
1580
1581                 execv( MAIL500_SENDMAIL, argv );
1582
1583                 syslog( LOG_ALERT, "execv failed" );
1584
1585                 exit( EX_TEMPFAIL );
1586         }
1587 }
1588
1589 static void
1590 do_noemail( FILE *fp, Error *err, int namelen )
1591 {
1592         int             i, last;
1593         char            *dn, *rdn;
1594         char            **ufn, **vals;
1595
1596         fprintf(fp, "%s: User has no email address registered.\n",
1597             err->e_addr );
1598         fprintf( fp, "%*s  Name, title, postal address and phone for '%s':\n\n",
1599             namelen, " ", err->e_addr );
1600
1601         /* name */
1602         dn = ldap_get_dn( ld, err->e_msg );
1603         ufn = ldap_explode_dn( dn, 1 );
1604         rdn = strdup( ufn[0] );
1605         if ( strcasecmp( rdn, err->e_addr ) == 0 ) {
1606                 if ( (vals = ldap_get_values( ld, err->e_msg, "cn" ))
1607                     != NULL ) {
1608                         for ( i = 0; vals[i]; i++ ) {
1609                                 last = strlen( vals[i] ) - 1;
1610                                 if ( isdigit((unsigned char) vals[i][last]) ) {
1611                                         rdn = strdup( vals[i] );
1612                                         break;
1613                                 }
1614                         }
1615
1616                         ldap_value_free( vals );
1617                 }
1618         }
1619         fprintf( fp, "%*s  %s\n", namelen, " ", rdn );
1620         free( dn );
1621         free( rdn );
1622         ldap_value_free( ufn );
1623
1624         /* titles or descriptions */
1625         if ( (vals = ldap_get_values( ld, err->e_msg, "title" )) == NULL &&
1626             (vals = ldap_get_values( ld, err->e_msg, "description" ))
1627             == NULL ) {
1628                 fprintf( fp, "%*s  No title or description registered\n",
1629                     namelen, " " );
1630         } else {
1631                 for ( i = 0; vals[i] != NULL; i++ ) {
1632                         fprintf( fp, "%*s  %s\n", namelen, " ", vals[i] );
1633                 }
1634
1635                 ldap_value_free( vals );
1636         }
1637
1638         /* postal address */
1639         if ( (vals = ldap_get_values( ld, err->e_msg, "postalAddress" ))
1640             == NULL ) {
1641                 fprintf( fp, "%*s  No postal address registered\n", namelen,
1642                     " " );
1643         } else {
1644                 fprintf( fp, "%*s  ", namelen, " " );
1645                 for ( i = 0; vals[0][i] != '\0'; i++ ) {
1646                         if ( vals[0][i] == '$' ) {
1647                                 fprintf( fp, "\n%*s  ", namelen, " " );
1648                                 while ( isspace((unsigned char) vals[0][i+1]) )
1649                                         i++;
1650                         } else {
1651                                 fprintf( fp, "%c", vals[0][i] );
1652                         }
1653                 }
1654                 fprintf( fp, "\n" );
1655
1656                 ldap_value_free( vals );
1657         }
1658
1659         /* telephone number */
1660         if ( (vals = ldap_get_values( ld, err->e_msg, "telephoneNumber" ))
1661             == NULL ) {
1662                 fprintf( fp, "%*s  No phone number registered\n", namelen,
1663                     " " );
1664         } else {
1665                 for ( i = 0; vals[i] != NULL; i++ ) {
1666                         fprintf( fp, "%*s  %s\n", namelen, " ", vals[i] );
1667                 }
1668
1669                 ldap_value_free( vals );
1670         }
1671 }
1672
1673 /* ARGSUSED */
1674 static void
1675 do_ambiguous( FILE *fp, Error *err, int namelen )
1676 {
1677         int             i, last;
1678         char            *dn, *rdn;
1679         char            **ufn, **vals;
1680         LDAPMessage     *e;
1681
1682         i = ldap_result2error( ld, err->e_msg, 0 );
1683
1684         fprintf( fp, "%s: Ambiguous user.  %s%d matches found:\n\n",
1685             err->e_addr, i == LDAP_SIZELIMIT_EXCEEDED ? "First " : "",
1686             ldap_count_entries( ld, err->e_msg ) );
1687
1688         for ( e = ldap_first_entry( ld, err->e_msg ); e != NULL;
1689             e = ldap_next_entry( ld, e ) ) {
1690                 dn = ldap_get_dn( ld, e );
1691                 ufn = ldap_explode_dn( dn, 1 );
1692                 rdn = strdup( ufn[0] );
1693                 if ( strcasecmp( rdn, err->e_addr ) == 0 ) {
1694                         if ( (vals = ldap_get_values( ld, e, "cn" )) != NULL ) {
1695                                 for ( i = 0; vals[i]; i++ ) {
1696                                         last = strlen( vals[i] ) - 1;
1697                                         if (isdigit((unsigned char) vals[i][last])) {
1698                                                 rdn = strdup( vals[i] );
1699                                                 break;
1700                                         }
1701                                 }
1702
1703                                 ldap_value_free( vals );
1704                         }
1705                 }
1706
1707                 /* 
1708                 if ( isgroup( e ) ) {
1709                         vals = ldap_get_values( ld, e, "description" );
1710                 } else {
1711                         vals = ldap_get_values( ld, e, "title" );
1712                 }
1713                 */
1714                 vals = ldap_get_values( ld, e, "description" );
1715
1716                 fprintf( fp, "    %-20s %s\n", rdn, vals ? vals[0] : "" );
1717                 for ( i = 1; vals && vals[i] != NULL; i++ ) {
1718                         fprintf( fp, "                         %s\n", vals[i] );
1719                 }
1720
1721                 free( dn );
1722                 free( rdn );
1723                 ldap_value_free( ufn );
1724                 if ( vals != NULL )
1725                         ldap_value_free( vals );
1726         }
1727 }
1728
1729 static int
1730 count_values( char **list )
1731 {
1732         int     i;
1733
1734         for ( i = 0; list && list[i] != NULL; i++ )
1735                 ;       /* NULL */
1736
1737         return( i );
1738 }
1739
1740 static void
1741 add_to( char ***list, int *nlist, char **new )
1742 {
1743         int     i, nnew, oldnlist;
1744
1745         nnew = count_values( new );
1746
1747         oldnlist = *nlist;
1748         if ( *list == NULL || *nlist == 0 ) {
1749                 *list = (char **) malloc( (nnew + 1) * sizeof(char *) );
1750                 *nlist = nnew;
1751         } else {
1752                 *list = (char **) realloc( *list, *nlist * sizeof(char *) +
1753                     nnew * sizeof(char *) + sizeof(char *) );
1754                 *nlist += nnew;
1755         }
1756
1757         for ( i = 0; i < nnew; i++ )
1758                 (*list)[i + oldnlist] = strdup( new[i] );
1759         (*list)[*nlist] = NULL;
1760 }
1761
1762 static void
1763 add_single_to( char ***list, char *new )
1764 {
1765         int     nlist;
1766
1767         if ( *list == NULL ) {
1768                 nlist = 0;
1769                 *list = (char **) malloc( 2 * sizeof(char *) );
1770         } else {
1771                 nlist = count_values( *list );
1772                 *list = (char **) realloc( *list,
1773                                            ( nlist + 2 ) * sizeof(char *) );
1774         }
1775
1776         (*list)[nlist] = strdup( new );
1777         (*list)[nlist+1] = NULL;
1778 }
1779
1780 static int
1781 isgroup( LDAPMessage *e )
1782 {
1783         int     i, j;
1784         char    **oclist;
1785
1786         if ( !groupclasses ) {
1787                 return( 0 );
1788         }
1789
1790         oclist = ldap_get_values( ld, e, "objectClass" );
1791
1792         for ( i = 0; oclist[i] != NULL; i++ ) {
1793                 for ( j = 0; groupclasses[j] != NULL; j++ ) {
1794                         if ( strcasecmp( oclist[i], groupclasses[j] ) == 0 ) {
1795                                 ldap_value_free( oclist );
1796                                 return( 1 );
1797                         }
1798                 }
1799         }
1800         ldap_value_free( oclist );
1801
1802         return( 0 );
1803 }
1804
1805 static void
1806 add_error( Error **err, int *nerr, int code, char *addr, LDAPMessage *msg )
1807 {
1808         if ( *nerr == 0 ) {
1809                 *err = (Error *) malloc( sizeof(Error) );
1810         } else {
1811                 *err = (Error *) realloc( *err, (*nerr + 1) * sizeof(Error) );
1812         }
1813
1814         (*err)[*nerr].e_code = code;
1815         (*err)[*nerr].e_addr = strdup( addr );
1816         (*err)[*nerr].e_msg = msg;
1817         (*nerr)++;
1818 }
1819
1820 static void
1821 unbind_and_exit( int rc )
1822 {
1823         int     i;
1824
1825         if ( (i = ldap_unbind( ld )) != LDAP_SUCCESS )
1826                 syslog( LOG_ALERT, "ldap_unbind failed %d\n", i );
1827
1828         exit( rc );
1829 }