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