]> git.sur5r.net Git - openldap/blob - clients/mail500/main.c
Initial version of new mail500.
[openldap] / clients / mail500 / main.c
1 /*
2  * Copyright (c) 1990 Regents of the University of Michigan.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that this notice is preserved and that due credit is given
7  * to the University of Michigan at Ann Arbor. The name of the University
8  * may not be used to endorse or promote products derived from this
9  * software without specific prior written permission. This software
10  * is provided ``as is'' without express or implied warranty.
11  *
12  * Copyright 1998,1999 The OpenLDAP Foundation
13  * COPYING RESTRICTIONS APPLY.  See COPYRIGHT File in top level directory
14  * of this package for details.
15  */
16
17 #include "portable.h"
18
19 #include <stdio.h>
20
21 #include <ac/stdlib.h>
22
23 #include <ac/ctype.h>
24 #include <ac/signal.h>
25 #include <ac/string.h>
26 #include <ac/sysexits.h>
27 #include <ac/syslog.h>
28 #include <ac/time.h>
29 #include <ac/unistd.h>
30 #include <ac/wait.h>
31
32 #include <sys/stat.h>
33
34 #ifdef HAVE_SYS_PARAM_H
35 #include <sys/param.h>
36 #endif
37
38 #ifdef HAVE_SYS_RESOURCE_H
39 #include <sys/resource.h>
40 #endif
41
42 #include "lber.h"
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 );
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                 fprintf( stderr, "Read line %d:%s\n", lineno, line );
641                 p = strpbrk( line, " \t" );
642                 if ( !p ) {
643                         syslog( LOG_ALERT,
644                                 "Missing space at line %d", lineno );
645                         exit( EX_TEMPFAIL );
646                 }
647                 if ( !strncmp( line, "search", p-line ) ) {
648                         p += strspn( p, " \t" );
649                         /* TBC, get these */
650                         rdnpref = 0;
651                         typemask = 0xFF;
652                         add_url( p, rdnpref, typemask );
653                 } else if ( !strncmp(line, "attribute", p-line) ) {
654                         p += strspn(p, " \t");
655                         add_attr_semantics( p );
656                 } else if ( !strncmp(line, "default-attributes", p-line) ) {
657                         p += strspn(p, " \t");
658                         add_def_attr( p );
659                 } else if ( !strncmp(line, "group-classes", p-line) ) {
660                         p += strspn(p, " \t");
661                         add_single_to( &groupclasses, p );
662                 } else {
663                         syslog( LOG_ALERT,
664                                 "Unparseable config definition at line %d",
665                                 lineno );
666                         exit( EX_TEMPFAIL );
667                 }
668         }
669         fclose( cf );
670 }
671
672 static int
673 connect_to_x500( void )
674 {
675         int opt;
676
677         if ( (ld = ldap_init( ldaphost, 0 )) == NULL ) {
678                 syslog( LOG_ALERT, "ldap_init failed" );
679                 return( -1 );
680         }
681
682         /*  TBC: Set this only when it makes sense
683         opt = MAIL500_MAXAMBIGUOUS;
684         ldap_set_option(ld, LDAP_OPT_SIZELIMIT, &opt);
685         */
686         opt = LDAP_DEREF_ALWAYS;
687         ldap_set_option(ld, LDAP_OPT_DEREF, &opt);
688
689         if ( ldap_simple_bind_s( ld, NULL, NULL ) != LDAP_SUCCESS ) {
690                 syslog( LOG_ALERT, "ldap_simple_bind_s failed" );
691                 return( -1 );
692         }
693
694         return( 0 );
695 }
696
697 static Group *
698 new_group( char *dn, Group **list, int *nlist )
699 {
700         int     i;
701         Group   *this_group;
702
703         for ( i = 0; i < *nlist; i++ ) {
704                 if ( strcmp( dn, (*list)[i].g_dn ) == 0 ) {
705                         syslog( LOG_ALERT, "group loop 2 detected (%s)", dn );
706                         return NULL;
707                 }
708         }
709
710         if ( *nlist == 0 ) {
711                 *list = (Group *) malloc( sizeof(Group) );
712         } else {
713                 *list = (Group *) realloc( *list, (*nlist + 1) *
714                     sizeof(Group) );
715         }
716
717         this_group = *list;
718
719         (*list)[*nlist].g_errorsto = NULL;
720         (*list)[*nlist].g_members = NULL;
721         (*list)[*nlist].g_nmembers = 0;
722         /* save the group's dn so we can check for loops above */
723         (*list)[*nlist].g_dn = strdup( dn );
724
725         (*nlist)++;
726
727         return( this_group );
728 }
729
730 static void
731 split_address(
732         char    *address,
733         char    **localpart,
734         char    **domainpart
735 )
736 {
737         char            *p;
738
739         if ( ( p = strrchr( address, '@' ) ) == NULL ) {
740                 *localpart = strdup( address );
741                 *domainpart = NULL;
742         } else {
743                 *localpart = malloc( p - address + 1 );
744                 strncpy( *localpart, address, p - address );
745                 (*localpart)[p - address] = '\0';
746                 p++;
747                 *domainpart = strdup( p );
748         }
749 }
750
751 static int
752 dn_search(
753         char    **dnlist, 
754         char    *address,
755         char    ***to,
756         int     *nto,
757         Group   **togroups,
758         int     *ngroups,
759         Error   **err,
760         int     *nerr
761 )
762 {
763         int             rc;
764         int             i;
765         int             resolved = 0;
766         LDAPMessage     *res, *e;
767         struct timeval  timeout;
768
769         timeout.tv_sec = MAIL500_TIMEOUT;
770         timeout.tv_usec = 0;
771         for ( i = 0; dnlist[i]; i++ ) {
772                 if ( (rc = ldap_search_st( ld, dnlist[i], LDAP_SCOPE_BASE,
773                         "(objectclass=*)", def_attr, 0,
774                          &timeout, &res )) != LDAP_SUCCESS ) {
775                         if ( rc == LDAP_NO_SUCH_OBJECT ) {
776                                 add_error( err, nerr, E_BADMEMBER, dnlist[i], NULL );
777                                 continue;
778                         } else {
779                                 syslog( LOG_ALERT, "member search return 0x%x", rc );
780
781                                 unbind_and_exit( EX_TEMPFAIL );
782                         }
783                 } else {
784                         if ( (e = ldap_first_entry( ld, res )) == NULL ) {
785                                 syslog( LOG_ALERT, "member search error parsing entry" );
786                                 unbind_and_exit( EX_TEMPFAIL );
787                         }
788                         if ( entry_engine( e, dnlist[i], address, to, nto,
789                                            togroups, ngroups, err, nerr,
790                                            USER | GROUP_MEMBERS ) ) {
791                                 resolved = 1;
792                         }
793                 }
794         }
795         return( resolved );
796 }
797
798 static int
799 search_ldap_url(
800         char    *url,
801         Subst   *substs,
802         char    *address,
803         int     rdnpref,
804         int     multi_entry,
805         char    ***to,
806         int     *nto,
807         Group   **togroups,
808         int     *ngroups,
809         Error   **err,
810         int     *nerr,
811         int     type
812 )
813 {
814         LDAPURLDesc     *ludp;
815         char            *p, *s, *d;
816         int             i;
817         char            filter[1024];
818         char            realfilter[1024];
819         LDAPMessage     *e, *res;
820         int             rc;
821         char            **attrlist;
822         struct timeval  timeout;
823         int             match;
824         int             resolved = 0;
825         char            *dn;
826
827         timeout.tv_sec = MAIL500_TIMEOUT;
828         timeout.tv_usec = 0;
829
830         rc = ldap_url_parse( url, &ludp );
831         if ( rc ) {
832                 switch ( rc ) {
833                 case LDAP_URL_ERR_NOTLDAP:
834                         syslog( LOG_ALERT,
835                                 "Not an LDAP URL: %s", url );
836                         break;
837                 case LDAP_URL_ERR_NODN:
838                         syslog( LOG_ALERT,
839                                 "Missing DN in URL: %s", url );
840                         break;
841                 case LDAP_URL_ERR_BADSCOPE:
842                         syslog( LOG_ALERT,
843                                 "Scope string is invalid in URL: %s", url );
844                         break;
845                 case LDAP_URL_ERR_MEM:
846                         syslog( LOG_ALERT,
847                                 "Out of memory parsing URL: %s", url );
848                         break;
849                 default:
850                         syslog( LOG_ALERT,
851                                 "Unknown error %d parsing URL: %s",
852                                 rc, url );
853                         break;
854                 }
855                 add_error( err, nerr, E_BADMEMBER,
856                            url, NULL );
857                 return 0;
858         }
859
860         if ( substs ) {
861                 for ( s = ludp->lud_filter, d = filter; *s; s++,d++ ) {
862                         if ( *s == '%' ) {
863                                 s++;
864                                 if ( *s == '%' ) {
865                                         *d = '%';
866                                         continue;
867                                 }
868                                 for ( i = 0; substs[i].sub_char != '\0';
869                                       i++ ) {
870                                         if ( *s == substs[i].sub_char ) {
871                                                 for ( p = substs[i].sub_value;
872                                                       *p; p++,d++ ) {
873                                                         *d = *p;
874                                                 }
875                                                 d--;
876                                                 break;
877                                         }
878                                 }
879                                 if ( substs[i].sub_char == '\0' ) {
880                                         syslog( LOG_ALERT,
881                                                 "unknown format %c", *s );
882                                 }
883                         } else {
884                                 *d = *s;
885                         }
886                 }
887                 *d = *s;
888         } else {
889                 strncpy( filter, ludp->lud_filter, sizeof( filter ) - 1 );
890                 filter[ sizeof( filter ) - 1 ] = '\0';
891         }
892
893         for ( s = filter, d = realfilter; *s; s++, d++ ) {
894                 if ( *s == '*' ) {
895                         *d++ = '\\';
896                 }
897                 *d = *s;
898         }
899         *d = '\0';
900
901         if ( ludp->lud_attrs ) {
902                 attrlist = ludp->lud_attrs;
903         } else {
904                 attrlist = def_attr;
905         }
906         res = NULL;
907         /* TBC: we don't read the host, dammit */
908         rc = ldap_search_st( ld, ludp->lud_dn, ludp->lud_scope,
909                              realfilter, attrlist, 0,
910                              &timeout, &res );
911
912         /* some other trouble - try again later */
913         if ( rc != LDAP_SUCCESS &&
914              rc != LDAP_SIZELIMIT_EXCEEDED ) {
915                 syslog( LOG_ALERT, "return 0x%x from X.500",
916                         rc );
917                 unbind_and_exit( EX_TEMPFAIL );
918         }
919
920         match = ldap_count_entries( ld, res );
921
922         /* trouble - try again later */
923         if ( match == -1 ) {
924                 syslog( LOG_ALERT, "error parsing result from X.500" );
925                 unbind_and_exit( EX_TEMPFAIL );
926         }
927
928         if ( match == 1 || multi_entry ) {
929                 for ( e = ldap_first_entry( ld, res ); e != NULL;
930                       e = ldap_next_entry( ld, e ) ) {
931                         dn = ldap_get_dn( ld, e );
932                         resolved = entry_engine( e, dn, address, to, nto,
933                                                  togroups, ngroups,
934                                                  err, nerr, type );
935                         if ( !resolved ) {
936                                 add_error( err, nerr, E_NOEMAIL, address, res );
937                         }
938                 }
939                 return ( resolved );
940         }
941
942         /* more than one match - bounce with ambiguous user? */
943         if ( match > 1 ) {
944                 LDAPMessage     *next, *tmpres = NULL;
945                 char            *dn;
946                 char            **xdn;
947
948                 /* not giving rdn preference - bounce with ambiguous user */
949                 if ( rdnpref == 0 ) {
950                         add_error( err, nerr, E_AMBIGUOUS, address, res );
951                         return 0;
952                 }
953
954                 /*
955                  * giving rdn preference - see if any entries were matched
956                  * because of their rdn.  If so, collect them to deal with
957                  * later (== 1 we deliver, > 1 we bounce).
958                  */
959
960                 for ( e = ldap_first_entry( ld, res ); e != NULL; e = next ) {
961                         next = ldap_next_entry( ld, e );
962                         dn = ldap_get_dn( ld, e );
963                         xdn = ldap_explode_dn( dn, 1 );
964
965                         /* XXX bad, but how else can we do it? XXX */
966                         if ( strcasecmp( xdn[0], address ) == 0 ) {
967                                 ldap_delete_result_entry( &res, e );
968                                 ldap_add_result_entry( &tmpres, e );
969                         }
970
971                         ldap_value_free( xdn );
972                         free( dn );
973                 }
974
975                 /* nothing matched by rdn - go ahead and bounce */
976                 if ( tmpres == NULL ) {
977                         add_error( err, nerr, E_AMBIGUOUS, address, res );
978                         return 0;
979
980                 /* more than one matched by rdn - bounce with rdn matches */
981                 } else if ( (match = ldap_count_entries( ld, tmpres )) > 1 ) {
982                         add_error( err, nerr, E_AMBIGUOUS, address, tmpres );
983                         return 0;
984
985                 /* trouble... */
986                 } else if ( match < 0 ) {
987                         syslog( LOG_ALERT, "error parsing result from X.500" );
988                         unbind_and_exit( EX_TEMPFAIL );
989                 }
990
991                 /* otherwise one matched by rdn - send to it */
992                 ldap_msgfree( res );
993                 res = tmpres;
994
995                 /* trouble */
996                 if ( (e = ldap_first_entry( ld, res )) == NULL ) {
997                         syslog( LOG_ALERT, "error parsing entry from X.500" );
998                         unbind_and_exit( EX_TEMPFAIL );
999                 }
1000
1001                 dn = ldap_get_dn( ld, e );
1002
1003                 resolved = entry_engine( e, dn, address, to, nto,
1004                                          togroups, ngroups,
1005                                          err, nerr, type );
1006                 if ( !resolved ) {
1007                         add_error( err, nerr, E_NOEMAIL, address, res );
1008                         /* Don't free res if we passed it to add_error */
1009                 } else {
1010                         ldap_msgfree( res );
1011                 }
1012         }
1013         return( resolved );
1014 }
1015
1016 static int
1017 url_list_search(
1018         char    **urllist, 
1019         char    *address,
1020         int     multi_entry,
1021         char    ***to,
1022         int     *nto,
1023         Group   **togroups,
1024         int     *ngroups,
1025         Error   **err,
1026         int     *nerr,
1027         int     type
1028 )
1029 {
1030         int             i;
1031         int             resolved = 0;
1032
1033         for ( i = 0; urllist[i]; i++ ) {
1034
1035                 if ( !strncasecmp( urllist[i], "mail:", 5 ) ) {
1036                         char    *vals[2];
1037
1038                         vals[0] = urllist[i] + 5;
1039                         vals[1] = NULL;
1040                         add_to( to, nto, vals );
1041                         resolved = 1;
1042
1043                 } else if ( ldap_is_ldap_url( urllist[i] ) ) {
1044
1045                         resolved = search_ldap_url( urllist[i], NULL,
1046                                                     address, 0, multi_entry,
1047                                                     to, nto, togroups, ngroups,
1048                                                     err, nerr, type );
1049                 } else {
1050                         /* Produce some sensible error here */
1051                         resolved = 0;
1052                 }
1053         }
1054         return( resolved );
1055 }
1056
1057 /*
1058  * The entry engine processes an entry.  Normally, each entry will resolve
1059  * to one or more values that will be added to the 'to' argument.  This
1060  * argument needs not be the global 'to' list, it may be the g_to field
1061  * in a group.  Groups have no special treatment, unless they require
1062  * a special sender.
1063  */
1064
1065 static int
1066 entry_engine(
1067         LDAPMessage *e,
1068         char    *dn,
1069         char    *address,
1070         char    ***to,
1071         int     *nto,
1072         Group   **togroups,
1073         int     *ngroups,
1074         Error   **err,
1075         int     *nerr,
1076         int     type
1077 )
1078 {
1079         char    **vals;
1080         int     i;
1081         int     resolved = 0;
1082         char    ***current_to = to;
1083         int     *current_nto = nto;
1084         Group   *current_group = NULL;
1085         char    buf[1024];
1086         char    *localpart, *domainpart;
1087         Subst   substs[2];
1088
1089         for ( i=0; attr_semantics[i] != NULL; i++ ) {
1090                 AttrSemantics   *as = attr_semantics[i];
1091                 int             nent;
1092
1093                 vals = ldap_get_values( ld, e, as->as_name );
1094                 if ( !vals || vals[0] == NULL ) {
1095                         continue;
1096                 }
1097                 nent = count_values( vals );
1098                 if ( nent > 1 && !as->as_m_valued ) {
1099                         add_error( err, nerr, E_AMBIGUOUS, address, e );
1100                         return( 0 );
1101                 }
1102                 switch ( as->as_kind ) {
1103                 case AS_KIND_RECIPIENT:
1104                         if ( ! ( type & ( USER | GROUP_MEMBERS ) ) )
1105                                 break;
1106                         switch ( as->as_syntax ) {
1107                         case AS_SYNTAX_RFC822:
1108                                 add_to( current_to, current_nto, vals );
1109                                 resolved = 1;
1110                                 break;
1111                         case AS_SYNTAX_RFC822_EXT:
1112                                 add_to( current_to, current_nto, vals );
1113                                 resolved = 1;
1114                                 break;
1115                         case AS_SYNTAX_NATIVE_MB:
1116                                 /* We used to concatenate mailHost if set here */
1117                                 /*
1118                                  * We used to send a copy to the vacation host
1119                                  * if onVacation to uid@vacationhost
1120                                  */
1121                                 add_to( current_to, current_nto, vals );
1122                                 resolved = 1;
1123                                 break;
1124
1125                         case AS_SYNTAX_DN:
1126                                 if ( dn_search( vals, address,
1127                                                 current_to, current_nto,
1128                                                 togroups, ngroups,
1129                                                 err, nerr ) ) {
1130                                         resolved = 1;
1131                                 }
1132                                 break;
1133
1134                         case AS_SYNTAX_URL:
1135                                 if ( url_list_search( vals, address,
1136                                                  as->as_m_entries,
1137                                                  current_to, current_nto,
1138                                                  togroups, ngroups,
1139                                                  err, nerr, type ) ) {
1140                                         resolved = 1;
1141                                 }
1142                                 break;
1143
1144                         case AS_SYNTAX_BOOL_FILTER:
1145                                 if ( strcasecmp( vals[0], "true" ) ) {
1146                                         break;
1147                                 }
1148                                 substs[0].sub_char = 'D';
1149                                 substs[0].sub_value = dn;
1150                                 substs[1].sub_char = '\0';
1151                                 substs[1].sub_value = NULL;
1152                                 if ( url_list_search( vals, address,
1153                                                  as->as_m_entries,
1154                                                  current_to, current_nto,
1155                                                  togroups, ngroups,
1156                                                  err, nerr, type ) ) {
1157                                         resolved = 1;
1158                                 }
1159                                 break;
1160
1161                         default:
1162                                 syslog( LOG_ALERT,
1163                                         "Invalid syntax %d for kind %d",
1164                                         as->as_syntax, as->as_kind );
1165                                 break;
1166                         }
1167                         break;
1168
1169                 case AS_KIND_ERRORS:
1170                         /* This is a group with special processing */
1171                         if ( type & GROUP_ERRORS ) {
1172                                 switch (as->as_kind) {
1173                                 case AS_SYNTAX_RFC822:
1174                                         add_to( current_to, current_nto, vals );
1175                                         resolved = 1;
1176                                         break;
1177                                 case AS_SYNTAX_URL:
1178                                 default:
1179                                         syslog( LOG_ALERT,
1180                                                 "Invalid syntax %d for kind %d",
1181                                                 as->as_syntax, as->as_kind );
1182                                 }
1183                         } else {
1184                                 current_group = new_group( dn, togroups,
1185                                                            ngroups );
1186                                 current_to = &current_group->g_members;
1187                                 current_nto = &current_group->g_nmembers;
1188                                 split_address( address,
1189                                                &localpart, &domainpart );
1190                                 if ( domainpart ) {
1191                                         sprintf( buf, "%s-%s@%s",
1192                                                  localpart, ERRORS,
1193                                                  domainpart );
1194                                         free( localpart );
1195                                         free( domainpart );
1196                                 } else {
1197                                         sprintf( buf, "%s-%s@%s",
1198                                                  localpart, ERRORS,
1199                                                  host );
1200                                         free( localpart );
1201                                 }
1202                                 current_group->g_errorsto = strdup( buf );
1203                         }
1204                         break;
1205
1206                 case AS_KIND_REQUEST:
1207                         /* This is a group with special processing */
1208                         if ( type & GROUP_REQUEST ) {
1209                                 add_to( current_to, current_nto, vals );
1210                                 resolved = 1;
1211                         }
1212                         break;
1213
1214                 case AS_KIND_OWNER:
1215                         /* This is a group with special processing */
1216                         if ( type & GROUP_REQUEST ) {
1217                                 add_to( current_to, current_nto, vals );
1218                                 resolved = 1;
1219                         }
1220                         break;
1221
1222                 default:
1223                         syslog( LOG_ALERT,
1224                                 "Invalid kind %d", as->as_kind );
1225                         /* Error, TBC */
1226                 }
1227                 ldap_value_free( vals );
1228                 if ( as->as_final ) {
1229                         return( resolved );
1230                 }
1231         }
1232         return( resolved );
1233 }
1234
1235 static int
1236 search_bases(
1237         char    *filter,
1238         Subst   *substs,
1239         char    *name,
1240         char    ***to,
1241         int     *nto,
1242         Group   **togroups,
1243         int     *ngroups,
1244         Error   **err,
1245         int     *nerr,
1246         int     type
1247 )
1248 {
1249         int             b, resolved = 0;
1250
1251         for ( b = 0; base[b] != NULL; b++ ) {
1252
1253                 if ( ! (base[b]->b_search & type) ) {
1254                         continue;
1255                 }
1256
1257                 resolved = search_ldap_url( base[b]->b_url, substs, name,
1258                                             base[b]->b_rdnpref,
1259                                             base[b]->b_m_entries,
1260                                             to, nto, togroups, ngroups,
1261                                             err, nerr, type );
1262                 if ( resolved )
1263                         break;
1264         }
1265         return( resolved );
1266 }
1267
1268 static void
1269 do_address(
1270         char    *name,
1271         char    ***to,
1272         int     *nto,
1273         Group   **togroups,
1274         int     *ngroups,
1275         Error   **err,
1276         int     *nerr,
1277         int     type
1278 )
1279 {
1280         struct timeval  timeout;
1281         char            *localpart, *domainpart;
1282         int             resolved;
1283         Subst   substs[5];
1284
1285         /*
1286          * Look up the name in X.500, add the appropriate addresses found
1287          * to the to list, or to the err list in case of error.  Groups are
1288          * handled by the do_group routine, individuals are handled here.
1289          * When looking up name, we follow the bases hierarchy, looking
1290          * in base[0] first, then base[1], etc.  For each base, there is
1291          * a set of search filters to try, in order.  If something goes
1292          * wrong here trying to contact X.500, we exit with EX_TEMPFAIL.
1293          * If the b_rdnpref flag is set, then we give preference to entries
1294          * that matched name because it's their rdn, otherwise not.
1295          */
1296
1297         split_address( name, &localpart, &domainpart );
1298         timeout.tv_sec = MAIL500_TIMEOUT;
1299         timeout.tv_usec = 0;
1300         substs[0].sub_char = 'm';
1301         substs[0].sub_value = name;
1302         substs[1].sub_char = 'h';
1303         substs[1].sub_value = host;
1304         substs[2].sub_char = 'l';
1305         substs[2].sub_value = localpart;
1306         substs[3].sub_char = 'd';
1307         substs[3].sub_value = domainpart;
1308         substs[4].sub_char = '\0';
1309         substs[4].sub_value = NULL;
1310
1311         resolved = search_bases( NULL, substs, name,
1312                                  to, nto, togroups, ngroups,
1313                                  err, nerr, type );
1314
1315         if ( !resolved ) {
1316                 /* not resolved - bounce with user unknown */
1317                 if ( type == USER ) {
1318                         add_error( err, nerr, E_USERUNKNOWN, name, NULL );
1319                 } else {
1320                         add_error( err, nerr, E_GROUPUNKNOWN, name, NULL );
1321                 }
1322         }
1323 }
1324
1325 static void
1326 send_message( char **to )
1327 {
1328         int     pid;
1329 #ifndef HAVE_WAITPID
1330         WAITSTATUSTYPE  status;
1331 #endif
1332
1333         if ( debug ) {
1334                 char    buf[1024];
1335                 int     i;
1336
1337                 strcpy( buf, to[0] );
1338                 for ( i = 1; to[i] != NULL; i++ ) {
1339                         strcat( buf, " " );
1340                         strcat( buf, to[i] );
1341                 }
1342
1343                 syslog( LOG_ALERT, "send_message execing sendmail: (%s)", buf );
1344         }
1345
1346         /* parent */
1347         if ( (pid = fork()) != 0 ) {
1348 #ifdef HAVE_WAITPID
1349                 waitpid( pid, (int *) NULL, 0 );
1350 #else
1351                 wait4( pid, &status, WAIT_FLAGS, 0 );
1352 #endif
1353         /* child */
1354         } else {
1355                 /* to includes sendmailargs */
1356                 execv( MAIL500_SENDMAIL, to );
1357
1358                 syslog( LOG_ALERT, "execv failed" );
1359
1360                 exit( EX_TEMPFAIL );
1361         }
1362 }
1363
1364 static void
1365 send_group( Group *group, int ngroup )
1366 {
1367         int     i, pid;
1368         char    **argv;
1369         int     argc;
1370         char    *iargv[7];
1371 #ifndef HAVE_WAITPID
1372         WAITSTATUSTYPE  status;
1373 #endif
1374
1375         for ( i = 0; i < ngroup; i++ ) {
1376                 (void) rewind( stdin );
1377
1378                 iargv[0] = MAIL500_SENDMAIL;
1379                 iargv[1] = "-f";
1380                 iargv[2] = group[i].g_errorsto;
1381                 iargv[3] = "-oMrX.500";
1382                 iargv[4] = "-odi";
1383                 iargv[5] = "-oi";
1384                 iargv[6] = NULL;
1385
1386                 argv = NULL;
1387                 argc = 0;
1388                 add_to( &argv, &argc, iargv );
1389                 add_to( &argv, &argc, group[i].g_members );
1390
1391                 if ( debug ) {
1392                         char    buf[1024];
1393                         int     i;
1394
1395                         strcpy( buf, argv[0] );
1396                         for ( i = 1; i < argc; i++ ) {
1397                                 strcat( buf, " " );
1398                                 strcat( buf, argv[i] );
1399                         }
1400
1401                         syslog( LOG_ALERT, "execing sendmail: (%s)", buf );
1402                 }
1403
1404                 /* parent */
1405                 if ( (pid = fork()) != 0 ) {
1406 #ifdef HAVE_WAITPID
1407                         waitpid( pid, (int *) NULL, 0 );
1408 #else
1409                         wait4( pid, &status, WAIT_FLAGS, 0 );
1410 #endif
1411                 /* child */
1412                 } else {
1413                         execv( MAIL500_SENDMAIL, argv );
1414
1415                         syslog( LOG_ALERT, "execv failed" );
1416
1417                         exit( EX_TEMPFAIL );
1418                 }
1419         }
1420 }
1421
1422 static void
1423 send_errors( Error *err, int nerr )
1424 {
1425         int     pid, i, namelen;
1426         FILE    *fp;
1427         int     fd[2];
1428         char    *argv[8];
1429         char    buf[1024];
1430 #ifndef HAVE_WAITPID
1431         WAITSTATUSTYPE  status;
1432 #endif
1433
1434         if ( strcmp( MAIL500_BOUNCEFROM, mailfrom ) == 0 ) {
1435             mailfrom = errorsfrom;
1436         }
1437
1438         argv[0] = MAIL500_SENDMAIL;
1439         argv[1] = "-oMrX.500";
1440         argv[2] = "-odi";
1441         argv[3] = "-oi";
1442         argv[4] = "-f";
1443         argv[5] = MAIL500_BOUNCEFROM;
1444         argv[6] = mailfrom;
1445         argv[7] = NULL;
1446
1447         if ( debug ) {
1448                 int     i;
1449
1450                 strcpy( buf, argv[0] );
1451                 for ( i = 1; argv[i] != NULL; i++ ) {
1452                         strcat( buf, " " );
1453                         strcat( buf, argv[i] );
1454                 }
1455
1456                 syslog( LOG_ALERT, "execing sendmail: (%s)", buf );
1457         }
1458
1459         if ( pipe( fd ) == -1 ) {
1460                 syslog( LOG_ALERT, "cannot create pipe" );
1461                 exit( EX_TEMPFAIL );
1462         }
1463
1464         if ( (pid = fork()) != 0 ) {
1465                 if ( (fp = fdopen( fd[1], "w" )) == NULL ) {
1466                         syslog( LOG_ALERT, "cannot fdopen pipe" );
1467                         exit( EX_TEMPFAIL );
1468                 }
1469
1470                 fprintf( fp, "To: %s\n", mailfrom );
1471                 fprintf( fp, "From: %s\n", errorsfrom );
1472                 fprintf( fp, "Subject: undeliverable mail\n" );
1473                 fprintf( fp, "\n" );
1474                 fprintf( fp, "The following errors occurred when trying to deliver the attached mail:\n" );
1475                 for ( i = 0; i < nerr; i++ ) {
1476                         namelen = strlen( err[i].e_addr );
1477                         fprintf( fp, "\n" );
1478
1479                         switch ( err[i].e_code ) {
1480                         case E_USERUNKNOWN:
1481                                 fprintf( fp, "%s: User unknown\n", err[i].e_addr );
1482                                 break;
1483
1484                         case E_GROUPUNKNOWN:
1485                                 fprintf( fp, "%s: Group unknown\n", err[i].e_addr );
1486                                 break;
1487
1488                         case E_BADMEMBER:
1489                                 fprintf( fp, "%s: Group member does not exist\n",
1490                                     err[i].e_addr );
1491                                 fprintf( fp, "This could be because the distinguished name of the person has changed\n" );
1492                                 fprintf( fp, "If this is the case, the problem can be solved by removing and\n" );
1493                                 fprintf( fp, "then re-adding the person to the group.\n" );
1494                                 break;
1495
1496                         case E_NOREQUEST:
1497                                 fprintf( fp, "%s: Group exists but has no request address\n",
1498                                     err[i].e_addr );
1499                                 break;
1500
1501                         case E_NOERRORS:
1502                                 fprintf( fp, "%s: Group exists but has no errors-to address\n",
1503                                     err[i].e_addr );
1504                                 break;
1505
1506                         case E_NOOWNER:
1507                                 fprintf( fp, "%s: Group exists but has no owner\n",
1508                                     err[i].e_addr );
1509                                 break;
1510
1511                         case E_AMBIGUOUS:
1512                                 do_ambiguous( fp, &err[i], namelen );
1513                                 break;
1514
1515                         case E_NOEMAIL:
1516                                 do_noemail( fp, &err[i], namelen );
1517                                 break;
1518
1519                         case E_MEMBERNOEMAIL:
1520                                 fprintf( fp, "%s: Group member exists but does not have an email address\n",
1521                                     err[i].e_addr );
1522                                 break;
1523
1524                         case E_JOINMEMBERNOEMAIL:
1525                                 fprintf( fp, "%s: User has joined group but does not have an email address\n",
1526                                     err[i].e_addr );
1527                                 break;
1528
1529                         case E_LOOP:
1530                                 fprintf( fp, "%s: User has created a mail loop by adding address %s to their X.500 entry\n",
1531                                     err[i].e_addr, err[i].e_loop );
1532                                 break;
1533
1534                         case E_NOMEMBERS:
1535                                 fprintf( fp, "%s: Group has no members\n",
1536                                     err[i].e_addr );
1537                                 break;
1538
1539                         default:
1540                                 syslog( LOG_ALERT, "unknown error %d", err[i].e_code );
1541                                 unbind_and_exit( EX_TEMPFAIL );
1542                                 break;
1543                         }
1544                 }
1545
1546                 fprintf( fp, "\n------- The original message sent:\n\n" );
1547
1548                 while ( fgets( buf, sizeof(buf), stdin ) != NULL ) {
1549                         fputs( buf, fp );
1550                 }
1551                 fclose( fp );
1552
1553 #ifdef HAVE_WAITPID
1554                 waitpid( pid, (int *) NULL, 0 );
1555 #else
1556                 wait4( pid, &status, WAIT_FLAGS, 0 );
1557 #endif
1558         } else {
1559                 dup2( fd[0], 0 );
1560
1561                 execv( MAIL500_SENDMAIL, argv );
1562
1563                 syslog( LOG_ALERT, "execv failed" );
1564
1565                 exit( EX_TEMPFAIL );
1566         }
1567 }
1568
1569 static void
1570 do_noemail( FILE *fp, Error *err, int namelen )
1571 {
1572         int             i, last;
1573         char            *dn, *rdn;
1574         char            **ufn, **vals;
1575
1576         fprintf(fp, "%s: User has no email address registered.\n",
1577             err->e_addr );
1578         fprintf( fp, "%*s  Name, title, postal address and phone for '%s':\n\n",
1579             namelen, " ", err->e_addr );
1580
1581         /* name */
1582         dn = ldap_get_dn( ld, err->e_msg );
1583         ufn = ldap_explode_dn( dn, 1 );
1584         rdn = strdup( ufn[0] );
1585         if ( strcasecmp( rdn, err->e_addr ) == 0 ) {
1586                 if ( (vals = ldap_get_values( ld, err->e_msg, "cn" ))
1587                     != NULL ) {
1588                         for ( i = 0; vals[i]; i++ ) {
1589                                 last = strlen( vals[i] ) - 1;
1590                                 if ( isdigit((unsigned char) vals[i][last]) ) {
1591                                         rdn = strdup( vals[i] );
1592                                         break;
1593                                 }
1594                         }
1595
1596                         ldap_value_free( vals );
1597                 }
1598         }
1599         fprintf( fp, "%*s  %s\n", namelen, " ", rdn );
1600         free( dn );
1601         free( rdn );
1602         ldap_value_free( ufn );
1603
1604         /* titles or descriptions */
1605         if ( (vals = ldap_get_values( ld, err->e_msg, "title" )) == NULL &&
1606             (vals = ldap_get_values( ld, err->e_msg, "description" ))
1607             == NULL ) {
1608                 fprintf( fp, "%*s  No title or description registered\n",
1609                     namelen, " " );
1610         } else {
1611                 for ( i = 0; vals[i] != NULL; i++ ) {
1612                         fprintf( fp, "%*s  %s\n", namelen, " ", vals[i] );
1613                 }
1614
1615                 ldap_value_free( vals );
1616         }
1617
1618         /* postal address */
1619         if ( (vals = ldap_get_values( ld, err->e_msg, "postalAddress" ))
1620             == NULL ) {
1621                 fprintf( fp, "%*s  No postal address registered\n", namelen,
1622                     " " );
1623         } else {
1624                 fprintf( fp, "%*s  ", namelen, " " );
1625                 for ( i = 0; vals[0][i] != '\0'; i++ ) {
1626                         if ( vals[0][i] == '$' ) {
1627                                 fprintf( fp, "\n%*s  ", namelen, " " );
1628                                 while ( isspace((unsigned char) vals[0][i+1]) )
1629                                         i++;
1630                         } else {
1631                                 fprintf( fp, "%c", vals[0][i] );
1632                         }
1633                 }
1634                 fprintf( fp, "\n" );
1635
1636                 ldap_value_free( vals );
1637         }
1638
1639         /* telephone number */
1640         if ( (vals = ldap_get_values( ld, err->e_msg, "telephoneNumber" ))
1641             == NULL ) {
1642                 fprintf( fp, "%*s  No phone number registered\n", namelen,
1643                     " " );
1644         } else {
1645                 for ( i = 0; vals[i] != NULL; i++ ) {
1646                         fprintf( fp, "%*s  %s\n", namelen, " ", vals[i] );
1647                 }
1648
1649                 ldap_value_free( vals );
1650         }
1651 }
1652
1653 /* ARGSUSED */
1654 static void
1655 do_ambiguous( FILE *fp, Error *err, int namelen )
1656 {
1657         int             i, last;
1658         char            *dn, *rdn;
1659         char            **ufn, **vals;
1660         LDAPMessage     *e;
1661
1662         i = ldap_result2error( ld, err->e_msg, 0 );
1663
1664         fprintf( fp, "%s: Ambiguous user.  %s%d matches found:\n\n",
1665             err->e_addr, i == LDAP_SIZELIMIT_EXCEEDED ? "First " : "",
1666             ldap_count_entries( ld, err->e_msg ) );
1667
1668         for ( e = ldap_first_entry( ld, err->e_msg ); e != NULL;
1669             e = ldap_next_entry( ld, e ) ) {
1670                 dn = ldap_get_dn( ld, e );
1671                 ufn = ldap_explode_dn( dn, 1 );
1672                 rdn = strdup( ufn[0] );
1673                 if ( strcasecmp( rdn, err->e_addr ) == 0 ) {
1674                         if ( (vals = ldap_get_values( ld, e, "cn" )) != NULL ) {
1675                                 for ( i = 0; vals[i]; i++ ) {
1676                                         last = strlen( vals[i] ) - 1;
1677                                         if (isdigit((unsigned char) vals[i][last])) {
1678                                                 rdn = strdup( vals[i] );
1679                                                 break;
1680                                         }
1681                                 }
1682
1683                                 ldap_value_free( vals );
1684                         }
1685                 }
1686
1687                 /* 
1688                 if ( isgroup( e ) ) {
1689                         vals = ldap_get_values( ld, e, "description" );
1690                 } else {
1691                         vals = ldap_get_values( ld, e, "title" );
1692                 }
1693                 */
1694                 vals = ldap_get_values( ld, e, "description" );
1695
1696                 fprintf( fp, "    %-20s %s\n", rdn, vals ? vals[0] : "" );
1697                 for ( i = 1; vals && vals[i] != NULL; i++ ) {
1698                         fprintf( fp, "                         %s\n", vals[i] );
1699                 }
1700
1701                 free( dn );
1702                 free( rdn );
1703                 ldap_value_free( ufn );
1704                 if ( vals != NULL )
1705                         ldap_value_free( vals );
1706         }
1707 }
1708
1709 static int
1710 count_values( char **list )
1711 {
1712         int     i;
1713
1714         for ( i = 0; list && list[i] != NULL; i++ )
1715                 ;       /* NULL */
1716
1717         return( i );
1718 }
1719
1720 static void
1721 add_to( char ***list, int *nlist, char **new )
1722 {
1723         int     i, nnew, oldnlist;
1724
1725         nnew = count_values( new );
1726
1727         oldnlist = *nlist;
1728         if ( *list == NULL || *nlist == 0 ) {
1729                 *list = (char **) malloc( (nnew + 1) * sizeof(char *) );
1730                 *nlist = nnew;
1731         } else {
1732                 *list = (char **) realloc( *list, *nlist * sizeof(char *) +
1733                     nnew * sizeof(char *) + sizeof(char *) );
1734                 *nlist += nnew;
1735         }
1736
1737         for ( i = 0; i < nnew; i++ )
1738                 (*list)[i + oldnlist] = strdup( new[i] );
1739         (*list)[*nlist] = NULL;
1740 }
1741
1742 static void
1743 add_single_to( char ***list, char *new )
1744 {
1745         int     nlist;
1746
1747         if ( *list == NULL ) {
1748                 nlist = 0;
1749                 *list = (char **) malloc( 2 * sizeof(char *) );
1750         } else {
1751                 nlist = count_values( *list );
1752                 *list = (char **) realloc( *list,
1753                                            ( nlist + 2 ) * sizeof(char *) );
1754         }
1755
1756         (*list)[nlist] = strdup( new );
1757         (*list)[nlist+1] = NULL;
1758 }
1759
1760 static int
1761 isgroup( LDAPMessage *e )
1762 {
1763         int     i, j;
1764         char    **oclist;
1765
1766         if ( !groupclasses ) {
1767                 return( 0 );
1768         }
1769
1770         oclist = ldap_get_values( ld, e, "objectClass" );
1771
1772         for ( i = 0; oclist[i] != NULL; i++ ) {
1773                 for ( j = 0; groupclasses[j] != NULL; j++ ) {
1774                         if ( strcasecmp( oclist[i], groupclasses[j] ) == 0 ) {
1775                                 ldap_value_free( oclist );
1776                                 return( 1 );
1777                         }
1778                 }
1779         }
1780         ldap_value_free( oclist );
1781
1782         return( 0 );
1783 }
1784
1785 static void
1786 add_error( Error **err, int *nerr, int code, char *addr, LDAPMessage *msg )
1787 {
1788         if ( *nerr == 0 ) {
1789                 *err = (Error *) malloc( sizeof(Error) );
1790         } else {
1791                 *err = (Error *) realloc( *err, (*nerr + 1) * sizeof(Error) );
1792         }
1793
1794         (*err)[*nerr].e_code = code;
1795         (*err)[*nerr].e_addr = strdup( addr );
1796         (*err)[*nerr].e_msg = msg;
1797         (*nerr)++;
1798 }
1799
1800 static void
1801 unbind_and_exit( int rc )
1802 {
1803         int     i;
1804
1805         if ( (i = ldap_unbind( ld )) != LDAP_SUCCESS )
1806                 syslog( LOG_ALERT, "ldap_unbind failed %d\n", i );
1807
1808         exit( rc );
1809 }
1810
1811
1812
1813