when delete from GAB now delete from ldap.
[citadel.git] / citadel / modules / vcard / serv_vcard.c
1 /*
2  * $Id$
3  * 
4  * A server-side module for Citadel which supports address book information
5  * using the standard vCard format.
6  * 
7  * Copyright (c) 1999-2007 / released under the GNU General Public License
8  */
9
10 /*
11  * Format of the "Exclusive ID" field of the message containing a user's
12  * vCard.  Doesn't matter what it really looks like as long as it's both
13  * unique and consistent (because we use it for replication checking to
14  * delete the old vCard network-wide when the user enters a new one).
15  */
16 #define VCARD_EXT_FORMAT        "Citadel vCard: personal card for %s at %s"
17
18 /*
19  * Citadel will accept either text/vcard or text/x-vcard as the MIME type
20  * for a vCard.  The following definition determines which one it *generates*
21  * when serializing.
22  */
23 #define VCARD_MIME_TYPE         "text/x-vcard"
24
25 #include "sysdep.h"
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <stdio.h>
29 #include <fcntl.h>
30 #include <signal.h>
31 #include <pwd.h>
32 #include <errno.h>
33 #include <ctype.h>
34 #include <sys/types.h>
35
36 #if TIME_WITH_SYS_TIME
37 # include <sys/time.h>
38 # include <time.h>
39 #else
40 # if HAVE_SYS_TIME_H
41 #  include <sys/time.h>
42 # else
43 #  include <time.h>
44 # endif
45 #endif
46
47 #include <sys/wait.h>
48 #include <string.h>
49 #include <limits.h>
50 #include "citadel.h"
51 #include "server.h"
52 #include "citserver.h"
53 #include "support.h"
54 #include "config.h"
55 #include "control.h"
56 #include "room_ops.h"
57 #include "user_ops.h"
58 #include "policy.h"
59 #include "database.h"
60 #include "msgbase.h"
61 #include "internet_addressing.h"
62 #include "tools.h"
63 #include "mime_parser.h"
64 #include "vcard.h"
65 #include "serv_vcard.h"
66
67 #include "ctdl_module.h"
68
69
70
71 /*
72  * set global flag calling for an aide to validate new users
73  */
74 void set_mm_valid(void) {
75         begin_critical_section(S_CONTROL);
76         get_control();
77         CitControl.MMflags = CitControl.MMflags | MM_VALID ;
78         put_control();
79         end_critical_section(S_CONTROL);
80 }
81
82
83
84 /*
85  * Extract Internet e-mail addresses from a message containing a vCard, and
86  * perform a callback for any found.
87  */
88 void vcard_extract_internet_addresses(struct CtdlMessage *msg,
89                                 void (*callback)(char *, char *) ) {
90         struct vCard *v;
91         char *s;
92         char *addr;
93         char citadel_address[SIZ];
94         int instance = 0;
95         int found_something = 0;
96
97         if (msg->cm_fields['A'] == NULL) return;
98         if (msg->cm_fields['N'] == NULL) return;
99         snprintf(citadel_address, sizeof citadel_address, "%s @ %s",
100                 msg->cm_fields['A'], msg->cm_fields['N']);
101
102         v = vcard_load(msg->cm_fields['M']);
103         if (v == NULL) return;
104
105         /* Go through the vCard searching for *all* instances of
106          * the "email;internet" key
107          */
108         do {
109                 s = vcard_get_prop(v, "email;internet", 0, instance++, 0);
110                 if (s != NULL) {
111                         addr = strdup(s);
112                         striplt(addr);
113                         if (!IsEmptyStr(addr)) {
114                                 if (callback != NULL) {
115                                         callback(addr, citadel_address);
116                                 }
117                         }
118                         free(addr);
119                         found_something = 1;
120                 }
121                 else {
122                         found_something = 0;
123                 }
124         } while(found_something);
125
126         vcard_free(v);
127 }
128
129
130 /* 
131  * vCard-to-LDAP conversions.
132  *
133  * If 'op' is set to V2L_WRITE, then write
134  * (add, or change if already exists) a directory entry to the
135  * LDAP server, based on the information supplied in a vCard.
136  *
137  * If 'op' is set to V2L_DELETE, then delete the entry from LDAP.
138  */
139  
140  
141 void ctdl_vcard_to_directory(struct CtdlMessage *msg, int op) {
142         struct vCard *v = NULL;
143         int i;
144         int num_emails = 0;
145         int num_phones = 0;
146         int have_addr = 0;
147         int have_cn = 0;
148         
149         void *objectlist = NULL;
150
151         char givenname[128];
152         char sn[128];
153         char uid[256];
154         char street[256];
155         char city[128];
156         char state[3];
157         char zipcode[10];
158         char calFBURL[256];
159         char *EUID=NULL;
160
161         if (msg == NULL) return;
162         if (msg->cm_fields['M'] == NULL) return;
163         if (msg->cm_fields['A'] == NULL) return;
164         if (msg->cm_fields['N'] == NULL) return;
165
166         /* Initialize variables */
167         strcpy(givenname, "");
168         strcpy(sn, "");
169         strcpy(calFBURL, "");
170
171         sprintf(uid, "%s@%s",
172                 msg->cm_fields['A'],
173                 msg->cm_fields['N']
174         );
175
176         /* Are we just deleting?  If so, it's simple... */
177         if (op == V2L_DELETE) {
178                 (void) CtdlDoDirectoryServiceFunc (msg->cm_fields['E'], msg->cm_fields['N'], NULL, "ldap", DIRECTORY_USER_DEL);
179                 return;
180         }
181
182         /*
183          * If we get to this point then it must be a V2L_WRITE operation.
184          */
185
186         /* First make sure the OU for the user's home Citadel host is created */
187         (void) CtdlDoDirectoryServiceFunc (NULL, msg->cm_fields['N'], NULL, "ldap", DIRECTORY_CREATE_HOST);
188         
189         /* Next create the directory service object */
190         (void) CtdlDoDirectoryServiceFunc(NULL, NULL, &objectlist, "ldap", DIRECTORY_CREATE_OBJECT);
191
192         /* The first LDAP attribute will be an 'objectclass' list.  Citadel
193          * doesn't do anything with this.  It's just there for compatibility
194          * with Kolab.
195          */
196         (void) CtdlDoDirectoryServiceFunc("objectclass", "citadelInetOrgPerson", &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
197
198         /* Convert the vCard fields to LDAP properties */
199         v = vcard_load(msg->cm_fields['M']);
200         if (v->numprops) for (i=0; i<(v->numprops); ++i) if (striplt(v->prop[i].value), strlen(v->prop[i].value) > 0) {
201
202                 if (!strcasecmp(v->prop[i].name, "n")) {
203                         extract_token(sn,               v->prop[i].value, 0, ';', sizeof sn);
204                         extract_token(givenname,        v->prop[i].value, 1, ';', sizeof givenname);
205                 }
206
207                 if (!strcasecmp(v->prop[i].name, "fn")) {
208                         (void) CtdlDoDirectoryServiceFunc("cn", v->prop[i].value, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
209                         have_cn = 1;
210                 }
211
212                 if (!strcasecmp(v->prop[i].name, "title")) {
213                         (void) CtdlDoDirectoryServiceFunc("title", v->prop[i].value, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
214                 }
215
216                 if (!strcasecmp(v->prop[i].name, "org")) {
217                         (void) CtdlDoDirectoryServiceFunc("o", v->prop[i].value, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
218                 }
219
220                 if ( (!strcasecmp(v->prop[i].name, "adr"))
221                    ||(!strncasecmp(v->prop[i].name, "adr;", 4)) ) {
222                         /* Unfortunately, we can only do a single address */
223                         if (!have_addr) {
224                                 have_addr = 1;
225                                 strcpy(street, "");
226                                 extract_token(&street[strlen(street)],
227                                         v->prop[i].value, 0, ';', (sizeof street - strlen(street))); /* po box */
228                                 strcat(street, " ");
229                                 extract_token(&street[strlen(street)],
230                                         v->prop[i].value, 1, ';', (sizeof street - strlen(street))); /* extend addr */
231                                 strcat(street, " ");
232                                 extract_token(&street[strlen(street)],
233                                         v->prop[i].value, 2, ';', (sizeof street - strlen(street))); /* street */
234                                 striplt(street);
235                                 extract_token(city, v->prop[i].value, 3, ';', sizeof city);
236                                 extract_token(state, v->prop[i].value, 4, ';', sizeof state);
237                                 extract_token(zipcode, v->prop[i].value, 5, ';', sizeof zipcode);
238
239                                 // ldap requires these fields to be something
240                                 if (IsEmptyStr(street)) strcpy(street, "_");
241                                 if (IsEmptyStr(zipcode)) strcpy(zipcode, "_");
242                                 if (IsEmptyStr(city)) strcpy(city, "_");
243                                 if (IsEmptyStr(state)) strcpy(state, "_");
244
245                                 (void) CtdlDoDirectoryServiceFunc("street", street, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
246                                 (void) CtdlDoDirectoryServiceFunc("l", city, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
247                                 (void) CtdlDoDirectoryServiceFunc("st", state, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
248                                 (void) CtdlDoDirectoryServiceFunc("postalcode", zipcode, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
249                         }
250                 }
251
252                 if ( (!strcasecmp(v->prop[i].name, "tel"))
253                    ||(!strncasecmp(v->prop[i].name, "tel;", 4)) ) {
254                         ++num_phones;
255                         /* The first 'tel' property creates the 'telephoneNumber' attribute */
256                         if (num_phones == 1) {
257                                 (void) CtdlDoDirectoryServiceFunc("telephoneNumber", v->prop[i].value, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
258                         }
259                         /* Subsequent 'tel' properties *add to* the 'telephoneNumber' attribute */
260                         else {
261                                 (void) CtdlDoDirectoryServiceFunc("telephoneNumber", v->prop[i].value, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
262                         }
263                 }
264
265
266                 if ( (!strcasecmp(v->prop[i].name, "email"))
267                    ||(!strcasecmp(v->prop[i].name, "email;internet")) ) {
268         
269                         ++num_emails;
270                         lprintf(CTDL_DEBUG, "email addr %d\n", num_emails);
271
272                         /* The first email address creates the 'mail' attribute */
273                         if (num_emails == 1) {
274                                 (void) CtdlDoDirectoryServiceFunc("mail", v->prop[i].value, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
275                         }
276                         /* The second and subsequent email address creates the 'alias' attribute */
277                         else if (num_emails >= 2) {
278                                 (void) CtdlDoDirectoryServiceFunc("alias", v->prop[i].value, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
279                         }
280                 }
281
282                 /* Calendar free/busy URL (take the first one we find, but if a subsequent
283                  * one contains the "pref" designation then we go with that instead.)
284                  */
285                 if ( (!strcasecmp(v->prop[i].name, "fburl"))
286                    ||(!strncasecmp(v->prop[i].name, "fburl;", 6)) ) {
287                         if ( (IsEmptyStr(calFBURL))
288                            || (!strncasecmp(v->prop[i].name, "fburl;pref", 10)) ) {
289                                 safestrncpy(calFBURL, v->prop[i].value, sizeof calFBURL);
290                         }
291                 }
292
293         }
294         vcard_free(v);  /* Don't need this anymore. */
295
296         /* "sn" (surname) based on info in vCard */
297         (void) CtdlDoDirectoryServiceFunc("sn", sn, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
298
299         /* "givenname" (first name) based on info in vCard */
300         if (IsEmptyStr(givenname)) strcpy(givenname, "_");
301         if (IsEmptyStr(sn)) strcpy(sn, "_");
302         (void) CtdlDoDirectoryServiceFunc("givenname", givenname, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
303
304         /* "uid" is a Kolab compatibility thing.  We just do cituser@citnode */
305         (void) CtdlDoDirectoryServiceFunc("uid", uid, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
306
307         /* Add a "cn" (Common Name) attribute based on the user's screen name,
308          * but only there was no 'fn' (full name) property in the vCard 
309          */
310         if (!have_cn)
311                 (void) CtdlDoDirectoryServiceFunc("cn", msg->cm_fields['A'], &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
312
313         /* Add a "calFBURL" attribute if a calendar free/busy URL exists */
314         if (!IsEmptyStr(calFBURL)) {
315                 (void) CtdlDoDirectoryServiceFunc("calFBURL", calFBURL, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
316         }
317         
318         // Add this messages EUID as the primary key for this entry.
319         EUID=msg->cm_fields['E'];
320         (void) CtdlDoDirectoryServiceFunc("euid", EUID, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
321         
322         
323         (void) CtdlDoDirectoryServiceFunc(EUID, msg->cm_fields['N'], &objectlist, "ldap", DIRECTORY_SAVE_OBJECT);
324         
325         (void) CtdlDoDirectoryServiceFunc(NULL, NULL, &objectlist, "ldap", DIRECTORY_FREE_OBJECT);
326         lprintf(CTDL_DEBUG, "LDAP write operation complete.\n");
327 }
328
329
330
331 /*
332  * Callback for vcard_add_to_directory()
333  * (Lotsa ugly nested callbacks.  Oh well.)
334  */
335 void vcard_directory_add_user(char *internet_addr, char *citadel_addr) {
336         char buf[SIZ];
337
338         /* We have to validate that we're not stepping on someone else's
339          * email address ... but only if we're logged in.  Otherwise it's
340          * probably just the networker or something.
341          */
342         if (CC->logged_in) {
343                 lprintf(CTDL_DEBUG, "Checking for <%s>...\n", internet_addr);
344                 if (CtdlDirectoryLookup(buf, internet_addr, sizeof buf) == 0) {
345                         if (strcasecmp(buf, citadel_addr)) {
346                                 /* This address belongs to someone else.
347                                  * Bail out silently without saving.
348                                  */
349                                 lprintf(CTDL_DEBUG, "DOOP!\n");
350                                 return;
351                         }
352                 }
353         }
354         lprintf(CTDL_INFO, "Adding %s (%s) to directory\n",
355                         citadel_addr, internet_addr);
356         CtdlDirectoryAddUser(internet_addr, citadel_addr);
357 }
358
359
360 /*
361  * Back end function for cmd_igab()
362  */
363 void vcard_add_to_directory(long msgnum, void *data) {
364         struct CtdlMessage *msg;
365
366         msg = CtdlFetchMessage(msgnum, 1);
367         if (msg != NULL) {
368                 vcard_extract_internet_addresses(msg, vcard_directory_add_user);
369         }
370
371         ctdl_vcard_to_directory(msg, V2L_WRITE);
372
373         CtdlFreeMessage(msg);
374 }
375
376
377 /*
378  * Initialize Global Adress Book
379  */
380 void cmd_igab(char *argbuf) {
381         char hold_rm[ROOMNAMELEN];
382
383         if (CtdlAccessCheck(ac_aide)) return;
384
385         strcpy(hold_rm, CC->room.QRname);       /* save current room */
386
387         if (getroom(&CC->room, ADDRESS_BOOK_ROOM) != 0) {
388                 getroom(&CC->room, hold_rm);
389                 cprintf("%d cannot get address book room\n", ERROR + ROOM_NOT_FOUND);
390                 return;
391         }
392
393         /* Empty the existing database first.
394          */
395         CtdlDirectoryInit();
396
397         /* We want *all* vCards in this room */
398         CtdlForEachMessage(MSGS_ALL, 0, NULL, "^[Tt][Ee][Xx][Tt]/.*[Vv][Cc][Aa][Rr][Dd]$",
399                 NULL, vcard_add_to_directory, NULL);
400
401         getroom(&CC->room, hold_rm);    /* return to saved room */
402         cprintf("%d Directory has been rebuilt.\n", CIT_OK);
403 }
404
405
406
407
408 /*
409  * See if there is a valid Internet address in a vCard to use for outbound
410  * Internet messages.  If there is, stick it in the buffer.
411  */
412 void extract_inet_email_addrs(char *emailaddrbuf, size_t emailaddrbuf_len,
413                                 char *secemailaddrbuf, size_t secemailaddrbuf_len,
414                                 struct vCard *v, int local_addrs_only) {
415         char *s, *addr;
416         int instance = 0;
417         int saved_instance = 0;
418
419         /* Go through the vCard searching for *all* instances of
420          * the "email;internet" key
421          */
422         while (s = vcard_get_prop(v, "email;internet", 0, instance++, 0),  s != NULL) {
423                 addr = strdup(s);
424                 striplt(addr);
425                 if (!IsEmptyStr(addr)) {
426                         if ( (IsDirectory(addr, 1)) || 
427                              (!local_addrs_only) ) {
428                                 ++saved_instance;
429                                 if ((saved_instance == 1) && (emailaddrbuf != NULL)) {
430                                         safestrncpy(emailaddrbuf, addr, emailaddrbuf_len);
431                                 }
432                                 else if ((saved_instance == 2) && (secemailaddrbuf != NULL)) {
433                                         safestrncpy(secemailaddrbuf, addr, secemailaddrbuf_len);
434                                 }
435                                 else if ((saved_instance > 2) && (secemailaddrbuf != NULL)) {
436                                         if ( (strlen(addr) + strlen(secemailaddrbuf) + 2) 
437                                            < secemailaddrbuf_len ) {
438                                                 strcat(secemailaddrbuf, "|");
439                                                 strcat(secemailaddrbuf, addr);
440                                         }
441                                 }
442                         }
443                 }
444                 free(addr);
445         }
446 }
447
448
449
450 /*
451  * See if there is a name / screen name / friendly name  in a vCard to use for outbound
452  * Internet messages.  If there is, stick it in the buffer.
453  */
454 void extract_friendly_name(char *namebuf, size_t namebuf_len, struct vCard *v)
455 {
456         char *s;
457
458         s = vcard_get_prop(v, "fn", 0, 0, 0);
459         if (s == NULL) {
460                 s = vcard_get_prop(v, "n", 0, 0, 0);
461         }
462
463         if (s != NULL) {
464                 safestrncpy(namebuf, s, namebuf_len);
465         }
466 }
467
468
469 /*
470  * Callback function for vcard_upload_beforesave() hunts for the real vcard in the MIME structure
471  */
472 void vcard_extract_vcard(char *name, char *filename, char *partnum, char *disp,
473                    void *content, char *cbtype, char *cbcharset, size_t length,
474                    char *encoding, void *cbuserdata)
475 {
476         struct vCard **v = (struct vCard **) cbuserdata;
477
478         if (  (!strcasecmp(cbtype, "text/x-vcard"))
479            || (!strcasecmp(cbtype, "text/vcard")) ) {
480
481                 lprintf(CTDL_DEBUG, "Part %s contains a vCard!  Loading...\n", partnum);
482                 if (*v != NULL) {
483                         vcard_free(*v);
484                 }
485                 *v = vcard_load(content);
486         }
487 }
488
489
490 /*
491  * This handler detects whether the user is attempting to save a new
492  * vCard as part of his/her personal configuration, and handles the replace
493  * function accordingly (delete the user's existing vCard in the config room
494  * and in the global address book).
495  */
496 int vcard_upload_beforesave(struct CtdlMessage *msg) {
497         char *ptr;
498         char *s;
499         char buf[SIZ];
500         struct ctdluser usbuf;
501         long what_user;
502         struct vCard *v = NULL;
503         char *ser = NULL;
504         int i = 0;
505         int yes_my_citadel_config = 0;
506         int yes_any_vcard_room = 0;
507
508         if (!CC->logged_in) return(0);  /* Only do this if logged in. */
509
510         /* Is this some user's "My Citadel Config" room? */
511         if ( (CC->room.QRflags && QR_MAILBOX)
512            && (!strcasecmp(&CC->room.QRname[11], USERCONFIGROOM)) ) {
513                 /* Yes, we want to do this */
514                 yes_my_citadel_config = 1;
515
516 #ifdef VCARD_SAVES_BY_AIDES_ONLY
517                 /* Prevent non-aides from performing registration changes */
518                 if (CC->user.axlevel < 6) {
519                         return(1);
520                 }
521 #endif
522
523         }
524
525         /* Is this a room with an address book in it? */
526         if (CC->room.QRdefaultview == VIEW_ADDRESSBOOK) {
527                 yes_any_vcard_room = 1;
528         }
529
530         /* If neither condition exists, don't run this hook. */
531         if ( (!yes_my_citadel_config) && (!yes_any_vcard_room) ) {
532                 return(0);
533         }
534
535         /* If this isn't a MIME message, don't bother. */
536         if (msg->cm_format_type != 4) return(0);
537
538         /* Ok, if we got this far, look into the situation further... */
539
540         ptr = msg->cm_fields['M'];
541         if (ptr == NULL) return(0);
542
543         mime_parser(msg->cm_fields['M'],
544                 NULL,
545                 *vcard_extract_vcard,
546                 NULL, NULL,
547                 &v,             /* user data ptr - put the vcard here */
548                 0
549         );
550
551         if (v == NULL) return(0);       /* no vCards were found in this message */
552
553         /* If users cannot create their own accounts, they cannot re-register either. */
554         if ( (yes_my_citadel_config) && (config.c_disable_newu) && (CC->user.axlevel < 6) ) {
555                 return(1);
556         }
557
558         s = vcard_get_prop(v, "FN", 0, 0, 0);
559         if (s) lprintf(CTDL_DEBUG, "vCard beforesave hook running for <%s>\n", s);
560
561         if (yes_my_citadel_config) {
562                 /* Bingo!  The user is uploading a new vCard, so
563                  * delete the old one.  First, figure out which user
564                  * is being re-registered...
565                  */
566                 what_user = atol(CC->room.QRname);
567
568                 if (what_user == CC->user.usernum) {
569                         /* It's the logged in user.  That was easy. */
570                         memcpy(&usbuf, &CC->user, sizeof(struct ctdluser));
571                 }
572                 
573                 else if (getuserbynumber(&usbuf, what_user) == 0) {
574                         /* We fetched a valid user record */
575                 }
576
577                 else {
578                         /* somebody set up us the bomb! */
579                         yes_my_citadel_config = 0;
580                 }
581         }
582         
583         if (yes_my_citadel_config) {
584                 /* Delete the user's old vCard.  This would probably
585                  * get taken care of by the replication check, but we
586                  * want to make sure there is absolutely only one
587                  * vCard in the user's config room at all times.
588                  *
589                  */
590                 CtdlDeleteMessages(CC->room.QRname, NULL, 0, "^[Tt][Ee][Xx][Tt]/.*[Vv][Cc][Aa][Rr][Dd]$");
591
592                 /* Make the author of the message the name of the user. */
593                 if (msg->cm_fields['A'] != NULL) {
594                         free(msg->cm_fields['A']);
595                 }
596                 msg->cm_fields['A'] = strdup(usbuf.fullname);
597         }
598
599         /* Insert or replace RFC2739-compliant free/busy URL */
600         if (yes_my_citadel_config) {
601                 sprintf(buf, "http://%s/%s.vfb",
602                         config.c_fqdn,
603                         usbuf.fullname);
604                 for (i=0; buf[i]; ++i) {
605                         if (buf[i] == ' ') buf[i] = '_';
606                 }
607                 vcard_set_prop(v, "FBURL;PREF", buf, 0);
608         }
609
610         /* If the vCard has no UID, then give it one. */
611         s = vcard_get_prop(v, "UID", 0, 0, 0);
612         if (s == NULL) {
613                 generate_uuid(buf);
614                 vcard_set_prop(v, "UID", buf, 0);
615         }
616
617         /* Enforce local UID policy if applicable */
618         if (yes_my_citadel_config) {
619                 snprintf(buf, sizeof buf, VCARD_EXT_FORMAT, msg->cm_fields['A'], NODENAME);
620                 vcard_set_prop(v, "UID", buf, 0);
621         }
622
623         /* 
624          * Set the EUID of the message to the UID of the vCard.
625          */
626         if (msg->cm_fields['E'] != NULL) free(msg->cm_fields['E']);
627         s = vcard_get_prop(v, "UID", 0, 0, 0);
628         if (s != NULL) {
629                 msg->cm_fields['E'] = strdup(s);
630                 if (msg->cm_fields['U'] == NULL) {
631                         msg->cm_fields['U'] = strdup(s);
632                 }
633         }
634
635         /*
636          * Set the Subject to the name in the vCard.
637          */
638         s = vcard_get_prop(v, "FN", 0, 0, 0);
639         if (s == NULL) {
640                 s = vcard_get_prop(v, "N", 0, 0, 0);
641         }
642         if (s != NULL) {
643                 if (msg->cm_fields['U'] != NULL) {
644                         free(msg->cm_fields['U']);
645                 }
646                 msg->cm_fields['U'] = strdup(s);
647         }
648
649         /* Re-serialize it back into the msg body */
650         ser = vcard_serialize(v);
651         if (ser != NULL) {
652                 msg->cm_fields['M'] = realloc(msg->cm_fields['M'], strlen(ser) + 1024);
653                 sprintf(msg->cm_fields['M'],
654                         "Content-type: " VCARD_MIME_TYPE
655                         "\r\n\r\n%s\r\n", ser);
656                 free(ser);
657         }
658
659         /* Now allow the save to complete. */
660         vcard_free(v);
661         return(0);
662 }
663
664
665
666 /*
667  * This handler detects whether the user is attempting to save a new
668  * vCard as part of his/her personal configuration, and handles the replace
669  * function accordingly (copy the vCard from the config room to the global
670  * address book).
671  */
672 int vcard_upload_aftersave(struct CtdlMessage *msg) {
673         char *ptr;
674         int linelen;
675         long I;
676         struct vCard *v;
677         int is_UserConf=0;
678         int is_GAB=0;
679
680         if (!CC->logged_in) return(0);  /* Only do this if logged in. */
681
682         /* If this isn't the configuration room, or if this isn't a MIME
683          * message, don't bother.
684          */
685         if (msg->cm_fields['O'] == NULL) return(0);
686         if (!strcasecmp(msg->cm_fields['O'], USERCONFIGROOM)) is_UserConf = 1;
687         if (!strcasecmp(msg->cm_fields['O'], ADDRESS_BOOK_ROOM)) is_GAB = 1;
688         if (!is_UserConf && !is_GAB) return(0);
689         if (msg->cm_format_type != 4) return(0);
690
691         ptr = msg->cm_fields['M'];
692         if (ptr == NULL) return(0);
693         while (ptr != NULL) {
694         
695                 linelen = strcspn(ptr, "\n");
696                 if (linelen == 0) return(0);    /* end of headers */    
697                 
698                 if (  (!strncasecmp(ptr, "Content-type: text/x-vcard", 26))
699                    || (!strncasecmp(ptr, "Content-type: text/vcard", 24)) ) {
700                         /*
701                          * Bingo!  The user is uploading a new vCard, so
702                          * copy it to the Global Address Book room.
703                          */
704
705                         I = atol(msg->cm_fields['I']);
706                         if (I < 0L) return(0);
707
708                         /* Store our Internet return address in memory */
709                         v = vcard_load(msg->cm_fields['M']);
710                         extract_inet_email_addrs(CC->cs_inet_email, sizeof CC->cs_inet_email,
711                                                 CC->cs_inet_other_emails, sizeof CC->cs_inet_other_emails,
712                                                 v, 1);
713                         extract_friendly_name(CC->cs_inet_fn, sizeof CC->cs_inet_fn, v);
714                         vcard_free(v);
715
716                         if (!is_GAB)
717                         {       // This is not the GAB
718                                 /* Put it in the Global Address Book room... */
719                                 CtdlSaveMsgPointerInRoom(ADDRESS_BOOK_ROOM, I, 1, msg);
720                         }
721
722                         /* ...and also in the directory database. */
723                         vcard_add_to_directory(I, NULL);
724
725                         /* Some sites want an Aide to be notified when a
726                          * user registers or re-registers...
727                          */
728                         set_mm_valid();
729
730                         /* ...which also means we need to flag the user */
731                         lgetuser(&CC->user, CC->curr_user);
732                         CC->user.flags |= (US_REGIS|US_NEEDVALID);
733                         lputuser(&CC->user);
734
735                         return(0);
736                 }
737
738                 ptr = strchr((char *)ptr, '\n');
739                 if (ptr != NULL) ++ptr;
740         }
741
742         return(0);
743 }
744
745
746
747 /*
748  * back end function used for callbacks
749  */
750 void vcard_gu_backend(long supplied_msgnum, void *userdata) {
751         long *msgnum;
752
753         msgnum = (long *) userdata;
754         *msgnum = supplied_msgnum;
755 }
756
757
758 /*
759  * If this user has a vcard on disk, read it into memory, otherwise allocate
760  * and return an empty vCard.
761  */
762 struct vCard *vcard_get_user(struct ctdluser *u) {
763         char hold_rm[ROOMNAMELEN];
764         char config_rm[ROOMNAMELEN];
765         struct CtdlMessage *msg = NULL;
766         struct vCard *v;
767         long VCmsgnum;
768
769         strcpy(hold_rm, CC->room.QRname);       /* save current room */
770         MailboxName(config_rm, sizeof config_rm, u, USERCONFIGROOM);
771
772         if (getroom(&CC->room, config_rm) != 0) {
773                 getroom(&CC->room, hold_rm);
774                 return vcard_new();
775         }
776
777         /* We want the last (and probably only) vcard in this room */
778         VCmsgnum = (-1);
779         CtdlForEachMessage(MSGS_LAST, 1, NULL, "^[Tt][Ee][Xx][Tt]/.*[Vv][Cc][Aa][Rr][Dd]$",
780                 NULL, vcard_gu_backend, (void *)&VCmsgnum );
781         getroom(&CC->room, hold_rm);    /* return to saved room */
782
783         if (VCmsgnum < 0L) return vcard_new();
784
785         msg = CtdlFetchMessage(VCmsgnum, 1);
786         if (msg == NULL) return vcard_new();
787
788         v = vcard_load(msg->cm_fields['M']);
789         CtdlFreeMessage(msg);
790         return v;
791 }
792
793
794 /*
795  * Store this user's vCard in the appropriate place
796  */
797 /*
798  * Write our config to disk
799  */
800 void vcard_write_user(struct ctdluser *u, struct vCard *v) {
801         char temp[PATH_MAX];
802         FILE *fp;
803         char *ser;
804
805         CtdlMakeTempFileName(temp, sizeof temp);
806         ser = vcard_serialize(v);
807
808         fp = fopen(temp, "w");
809         if (fp == NULL) return;
810         if (ser == NULL) {
811                 fprintf(fp, "begin:vcard\r\nend:vcard\r\n");
812         } else {
813                 fwrite(ser, strlen(ser), 1, fp);
814                 free(ser);
815         }
816         fclose(fp);
817
818         /* This handy API function does all the work for us.
819          * NOTE: normally we would want to set that last argument to 1, to
820          * force the system to delete the user's old vCard.  But it doesn't
821          * have to, because the vcard_upload_beforesave() hook above
822          * is going to notice what we're trying to do, and delete the old vCard.
823          */
824         CtdlWriteObject(USERCONFIGROOM, /* which room */
825                         VCARD_MIME_TYPE,/* MIME type */
826                         temp,           /* temp file */
827                         u,              /* which user */
828                         0,              /* not binary */
829                         0,              /* don't delete others of this type */
830                         0);             /* no flags */
831
832         unlink(temp);
833 }
834
835
836
837 /*
838  * Old style "enter registration info" command.  This function simply honors
839  * the REGI protocol command, translates the entered parameters into a vCard,
840  * and enters the vCard into the user's configuration.
841  */
842 void cmd_regi(char *argbuf) {
843         int a,b,c;
844         char buf[SIZ];
845         struct vCard *my_vcard;
846
847         char tmpaddr[SIZ];
848         char tmpcity[SIZ];
849         char tmpstate[SIZ];
850         char tmpzip[SIZ];
851         char tmpaddress[SIZ];
852         char tmpcountry[SIZ];
853
854         unbuffer_output();
855
856         if (!(CC->logged_in)) {
857                 cprintf("%d Not logged in.\n",ERROR + NOT_LOGGED_IN);
858                 return;
859         }
860
861         /* If users cannot create their own accounts, they cannot re-register either. */
862         if ( (config.c_disable_newu) && (CC->user.axlevel < 6) ) {
863                 cprintf("%d Self-service registration is not allowed here.\n",
864                         ERROR + HIGHER_ACCESS_REQUIRED);
865         }
866
867         my_vcard = vcard_get_user(&CC->user);
868         strcpy(tmpaddr, "");
869         strcpy(tmpcity, "");
870         strcpy(tmpstate, "");
871         strcpy(tmpzip, "");
872         strcpy(tmpcountry, "USA");
873
874         cprintf("%d Send registration...\n", SEND_LISTING);
875         a=0;
876         while (client_getln(buf, sizeof buf), strcmp(buf,"000")) {
877                 if (a==0) vcard_set_prop(my_vcard, "n", buf, 0);
878                 if (a==1) strcpy(tmpaddr, buf);
879                 if (a==2) strcpy(tmpcity, buf);
880                 if (a==3) strcpy(tmpstate, buf);
881                 if (a==4) {
882                         for (c=0; buf[c]; ++c) {
883                                 if ((buf[c]>='0') && (buf[c]<='9')) {
884                                         b = strlen(tmpzip);
885                                         tmpzip[b] = buf[c];
886                                         tmpzip[b+1] = 0;
887                                 }
888                         }
889                 }
890                 if (a==5) vcard_set_prop(my_vcard, "tel;home", buf, 0);
891                 if (a==6) vcard_set_prop(my_vcard, "email;internet", buf, 0);
892                 if (a==7) strcpy(tmpcountry, buf);
893                 ++a;
894         }
895
896         snprintf(tmpaddress, sizeof tmpaddress, ";;%s;%s;%s;%s;%s",
897                 tmpaddr, tmpcity, tmpstate, tmpzip, tmpcountry);
898         vcard_set_prop(my_vcard, "adr", tmpaddress, 0);
899         vcard_write_user(&CC->user, my_vcard);
900         vcard_free(my_vcard);
901 }
902
903
904 /*
905  * Protocol command to fetch registration info for a user
906  */
907 void cmd_greg(char *argbuf)
908 {
909         struct ctdluser usbuf;
910         struct vCard *v;
911         char *s;
912         char who[USERNAME_SIZE];
913         char adr[256];
914         char buf[256];
915
916         extract_token(who, argbuf, 0, '|', sizeof who);
917
918         if (!(CC->logged_in)) {
919                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
920                 return;
921         }
922
923         if (!strcasecmp(who,"_SELF_")) strcpy(who,CC->curr_user);
924
925         if ((CC->user.axlevel < 6) && (strcasecmp(who,CC->curr_user))) {
926                 cprintf("%d Higher access required.\n",
927                         ERROR + HIGHER_ACCESS_REQUIRED);
928                 return;
929         }
930
931         if (getuser(&usbuf, who) != 0) {
932                 cprintf("%d '%s' not found.\n", ERROR + NO_SUCH_USER, who);
933                 return;
934         }
935
936         v = vcard_get_user(&usbuf);
937
938         cprintf("%d %s\n", LISTING_FOLLOWS, usbuf.fullname);
939         cprintf("%ld\n", usbuf.usernum);
940         cprintf("%s\n", usbuf.password);
941         s = vcard_get_prop(v, "n", 0, 0, 0);
942         cprintf("%s\n", s ? s : " ");   /* name */
943
944         s = vcard_get_prop(v, "adr", 0, 0, 0);
945         snprintf(adr, sizeof adr, "%s", s ? s : " ");/* address... */
946
947         extract_token(buf, adr, 2, ';', sizeof buf);
948         cprintf("%s\n", buf);                           /* street */
949         extract_token(buf, adr, 3, ';', sizeof buf);
950         cprintf("%s\n", buf);                           /* city */
951         extract_token(buf, adr, 4, ';', sizeof buf);
952         cprintf("%s\n", buf);                           /* state */
953         extract_token(buf, adr, 5, ';', sizeof buf);
954         cprintf("%s\n", buf);                           /* zip */
955
956         s = vcard_get_prop(v, "tel;home", 0, 0, 0);
957         if (s == NULL) s = vcard_get_prop(v, "tel", 1, 0, 0);
958         if (s != NULL) {
959                 cprintf("%s\n", s);
960         }
961         else {
962                 cprintf(" \n");
963         }
964
965         cprintf("%d\n", usbuf.axlevel);
966
967         s = vcard_get_prop(v, "email;internet", 0, 0, 0);
968         cprintf("%s\n", s ? s : " ");
969         s = vcard_get_prop(v, "adr", 0, 0, 0);
970         snprintf(adr, sizeof adr, "%s", s ? s : " ");/* address... */
971
972         extract_token(buf, adr, 6, ';', sizeof buf);
973         cprintf("%s\n", buf);                           /* country */
974         cprintf("000\n");
975         vcard_free(v);
976 }
977
978
979
980 /*
981  * When a user is being created, create his/her vCard.
982  */
983 void vcard_newuser(struct ctdluser *usbuf) {
984         char vname[256];
985         char buf[256];
986         int i;
987         struct vCard *v;
988
989         vcard_fn_to_n(vname, usbuf->fullname, sizeof vname);
990         lprintf(CTDL_DEBUG, "Converted <%s> to <%s>\n", usbuf->fullname, vname);
991
992         /* Create and save the vCard */
993         v = vcard_new();
994         if (v == NULL) return;
995         sprintf(buf, "%s@%s", usbuf->fullname, config.c_fqdn);
996         for (i=0; buf[i]; ++i) {
997                 if (buf[i] == ' ') buf[i] = '_';
998         }
999         vcard_add_prop(v, "fn", usbuf->fullname);
1000         vcard_add_prop(v, "n", vname);
1001         vcard_add_prop(v, "adr", "adr:;;_;_;_;00000;__");
1002         vcard_add_prop(v, "email;internet", buf);
1003         vcard_write_user(usbuf, v);
1004         vcard_free(v);
1005 }
1006
1007
1008 /*
1009  * When a user is being deleted, we have to remove his/her vCard.
1010  * This is accomplished by issuing a message with 'CANCEL' in the S (special)
1011  * field, and the same Exclusive ID as the existing card.
1012  */
1013 void vcard_purge(struct ctdluser *usbuf) {
1014         struct CtdlMessage *msg;
1015         char buf[SIZ];
1016
1017         msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1018         if (msg == NULL) return;
1019         memset(msg, 0, sizeof(struct CtdlMessage));
1020
1021         msg->cm_magic = CTDLMESSAGE_MAGIC;
1022         msg->cm_anon_type = MES_NORMAL;
1023         msg->cm_format_type = 0;
1024         msg->cm_fields['A'] = strdup(usbuf->fullname);
1025         msg->cm_fields['O'] = strdup(ADDRESS_BOOK_ROOM);
1026         msg->cm_fields['N'] = strdup(NODENAME);
1027         msg->cm_fields['M'] = strdup("Purge this vCard\n");
1028
1029         snprintf(buf, sizeof buf, VCARD_EXT_FORMAT,
1030                         msg->cm_fields['A'], NODENAME);
1031         msg->cm_fields['E'] = strdup(buf);
1032
1033         msg->cm_fields['S'] = strdup("CANCEL");
1034
1035         CtdlSubmitMsg(msg, NULL, ADDRESS_BOOK_ROOM);
1036         CtdlFreeMessage(msg);
1037 }
1038
1039
1040 /*
1041  * Grab vCard directory stuff out of incoming network messages
1042  */
1043 int vcard_extract_from_network(struct CtdlMessage *msg, char *target_room) {
1044         char *ptr;
1045         int linelen;
1046
1047         if (msg == NULL) return(0);
1048
1049         if (strcasecmp(target_room, ADDRESS_BOOK_ROOM)) {
1050                 return(0);
1051         }
1052
1053         if (msg->cm_format_type != 4) return(0);
1054
1055         ptr = msg->cm_fields['M'];
1056         if (ptr == NULL) return(0);
1057         while (ptr != NULL) {
1058         
1059                 linelen = strcspn(ptr, "\n");
1060                 if (linelen == 0) return(0);    /* end of headers */    
1061                 
1062                 if (  (!strncasecmp(ptr, "Content-type: text/x-vcard", 26))
1063                    || (!strncasecmp(ptr, "Content-type: text/vcard", 24)) ) {
1064                         /* It's a vCard.  Add it to the directory. */
1065                         vcard_extract_internet_addresses(msg, CtdlDirectoryAddUser);
1066                         return(0);
1067                 }
1068
1069                 ptr = strchr((char *)ptr, '\n');
1070                 if (ptr != NULL) ++ptr;
1071         }
1072
1073         return(0);
1074 }
1075
1076
1077
1078 /* 
1079  * When a vCard is being removed from the Global Address Book room, remove it
1080  * from the directory as well.
1081  */
1082 void vcard_delete_remove(char *room, long msgnum) {
1083         struct CtdlMessage *msg;
1084         char *ptr;
1085         int linelen;
1086
1087         if (msgnum <= 0L) return;
1088         
1089         if (room == NULL) return;
1090
1091         if (strcasecmp(room, ADDRESS_BOOK_ROOM)) {
1092                 return;
1093         }
1094
1095         msg = CtdlFetchMessage(msgnum, 1);
1096         if (msg == NULL) return;
1097
1098         ptr = msg->cm_fields['M'];
1099         if (ptr == NULL) goto EOH;
1100         while (ptr != NULL) {
1101                 linelen = strcspn(ptr, "\n");
1102                 if (linelen == 0) goto EOH;
1103                 
1104                 if (  (!strncasecmp(ptr, "Content-type: text/x-vcard", 26))
1105                    || (!strncasecmp(ptr, "Content-type: text/vcard", 24)) ) {
1106                         /* Bingo!  A vCard is being deleted. */
1107                         vcard_extract_internet_addresses(msg, CtdlDirectoryDelUser);
1108                         ctdl_vcard_to_directory(msg, V2L_DELETE);
1109                 }
1110                 ptr = strchr((char *)ptr, '\n');
1111                 if (ptr != NULL) ++ptr;
1112         }
1113
1114 EOH:    CtdlFreeMessage(msg);
1115 }
1116
1117
1118
1119 /*
1120  * Get Valid Screen Names
1121  */
1122 void cmd_gvsn(char *argbuf)
1123 {
1124         if (CtdlAccessCheck(ac_logged_in)) return;
1125
1126         cprintf("%d valid screen names:\n", LISTING_FOLLOWS);
1127         cprintf("%s\n", CC->user.fullname);
1128         if ( (!IsEmptyStr(CC->cs_inet_fn)) && (strcasecmp(CC->user.fullname, CC->cs_inet_fn)) ) {
1129                 cprintf("%s\n", CC->cs_inet_fn);
1130         }
1131         cprintf("000\n");
1132 }
1133
1134
1135 /*
1136  * Get Valid Email Addresses
1137  */
1138 void cmd_gvea(char *argbuf)
1139 {
1140         int num_secondary_emails = 0;
1141         int i;
1142         char buf[256];
1143
1144         if (CtdlAccessCheck(ac_logged_in)) return;
1145
1146         cprintf("%d valid email addresses:\n", LISTING_FOLLOWS);
1147         if (!IsEmptyStr(CC->cs_inet_email)) {
1148                 cprintf("%s\n", CC->cs_inet_email);
1149         }
1150         if (!IsEmptyStr(CC->cs_inet_other_emails)) {
1151                 num_secondary_emails = num_tokens(CC->cs_inet_other_emails, '|');
1152                 for (i=0; i<num_secondary_emails; ++i) {
1153                         extract_token(buf, CC->cs_inet_other_emails,i,'|',sizeof CC->cs_inet_other_emails);
1154                         cprintf("%s\n", buf);
1155                 }
1156         }
1157         cprintf("000\n");
1158 }
1159
1160
1161
1162
1163 /*
1164  * Callback function for cmd_dvca() that hunts for vCard content types
1165  * and outputs any email addresses found within.
1166  */
1167 void dvca_mime_callback(char *name, char *filename, char *partnum, char *disp,
1168                 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1169                 void *cbuserdata) {
1170
1171         struct vCard *v;
1172         char displayname[256];
1173         int displayname_len;
1174         char emailaddr[256];
1175         int i;
1176         int has_commas = 0;
1177
1178         if ( (strcasecmp(cbtype, "text/vcard")) && (strcasecmp(cbtype, "text/x-vcard")) ) {
1179                 return;
1180         }
1181
1182         v = vcard_load(content);
1183         if (v == NULL) return;
1184
1185         extract_friendly_name(displayname, sizeof displayname, v);
1186         extract_inet_email_addrs(emailaddr, sizeof emailaddr, NULL, 0, v, 0);
1187
1188         displayname_len = strlen(displayname);
1189         for (i=0; i<displayname_len; ++i) {
1190                 if (displayname[i] == '\"') displayname[i] = ' ';
1191                 if (displayname[i] == ';') displayname[i] = ',';
1192                 if (displayname[i] == ',') has_commas = 1;
1193         }
1194         striplt(displayname);
1195
1196         cprintf("%s%s%s <%s>\n",
1197                 (has_commas ? "\"" : ""),
1198                 displayname,
1199                 (has_commas ? "\"" : ""),
1200                 emailaddr
1201         );
1202
1203         vcard_free(v);
1204 }
1205
1206
1207 /*
1208  * Back end callback function for cmd_dvca()
1209  *
1210  * It's basically just passed a list of message numbers, which we're going
1211  * to fetch off the disk and then pass along to the MIME parser via another
1212  * layer of callback...
1213  */
1214 void dvca_callback(long msgnum, void *userdata) {
1215         struct CtdlMessage *msg = NULL;
1216
1217         msg = CtdlFetchMessage(msgnum, 1);
1218         if (msg == NULL) return;
1219         mime_parser(msg->cm_fields['M'],
1220                 NULL,
1221                 *dvca_mime_callback,    /* callback function */
1222                 NULL, NULL,
1223                 NULL,                   /* user data */
1224                 0
1225         );
1226         CtdlFreeMessage(msg);
1227 }
1228
1229
1230 /*
1231  * Dump VCard Addresses
1232  */
1233 void cmd_dvca(char *argbuf)
1234 {
1235         if (CtdlAccessCheck(ac_logged_in)) return;
1236
1237         cprintf("%d addresses:\n", LISTING_FOLLOWS);
1238         CtdlForEachMessage(MSGS_ALL, 0, NULL, NULL, NULL, dvca_callback, NULL);
1239         cprintf("000\n");
1240 }
1241
1242
1243 /*
1244  * Query Directory
1245  */
1246 void cmd_qdir(char *argbuf) {
1247         char citadel_addr[256];
1248         char internet_addr[256];
1249
1250         if (CtdlAccessCheck(ac_logged_in)) return;
1251
1252         extract_token(internet_addr, argbuf, 0, '|', sizeof internet_addr);
1253
1254         if (CtdlDirectoryLookup(citadel_addr, internet_addr, sizeof citadel_addr) != 0) {
1255                 cprintf("%d %s was not found.\n",
1256                         ERROR + NO_SUCH_USER, internet_addr);
1257                 return;
1258         }
1259
1260         cprintf("%d %s\n", CIT_OK, citadel_addr);
1261 }
1262
1263 /*
1264  * Query Directory, in fact an alias to match postfix tcp auth.
1265  */
1266 void check_get(void) {
1267         char internet_addr[256];
1268
1269         char cmdbuf[SIZ];
1270
1271         time(&CC->lastcmd);
1272         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1273         if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1274                 lprintf(CTDL_CRIT, "Client disconnected: ending session.\n");
1275                 CC->kill_me = 1;
1276                 return;
1277         }
1278         lprintf(CTDL_INFO, ": %s\n", cmdbuf);
1279         while (strlen(cmdbuf) < 3) strcat(cmdbuf, " ");
1280
1281         if (strcasecmp(cmdbuf, "GET "));
1282         {
1283                 struct recptypes *rcpt;
1284                 char *argbuf = &cmdbuf[4];
1285                 
1286                 extract_token(internet_addr, argbuf, 0, '|', sizeof internet_addr);
1287                 rcpt = validate_recipients(internet_addr);
1288                 if ((rcpt != NULL)&&
1289                         (
1290                          (*rcpt->recp_local != '\0')||
1291                          (*rcpt->recp_room != '\0')||
1292                          (*rcpt->recp_ignet != '\0')))
1293                 {
1294
1295                         cprintf("200 OK %s\n", internet_addr);
1296                         lprintf(CTDL_INFO, "sending 200 OK for the room %s\n", rcpt->display_recp);
1297                 }
1298                 else 
1299                 {
1300                         cprintf("500 REJECT noone here by that name.\n");
1301                         
1302                         lprintf(CTDL_INFO, "sending 500 REJECT noone here by that name: %s\n", internet_addr);
1303                 }
1304                 if (rcpt != NULL) free_recipients(rcpt);
1305         }
1306 }
1307
1308 void check_get_greeting(void) {
1309 /* dummy function, we have no greeting in this verry simple protocol. */
1310 }
1311
1312
1313 /*
1314  * We don't know if the Contacts room exists so we just create it at login
1315  */
1316 void vcard_create_room(void)
1317 {
1318         struct ctdlroom qr;
1319         struct visit vbuf;
1320
1321         /* Create the calendar room if it doesn't already exist */
1322         create_room(USERCONTACTSROOM, 4, "", 0, 1, 0, VIEW_ADDRESSBOOK);
1323
1324         /* Set expiration policy to manual; otherwise objects will be lost! */
1325         if (lgetroom(&qr, USERCONTACTSROOM)) {
1326                 lprintf(CTDL_ERR, "Couldn't get the user CONTACTS room!\n");
1327                 return;
1328         }
1329         qr.QRep.expire_mode = EXPIRE_MANUAL;
1330         qr.QRdefaultview = VIEW_ADDRESSBOOK;    /* 2 = address book view */
1331         lputroom(&qr);
1332
1333         /* Set the view to a calendar view */
1334         CtdlGetRelationship(&vbuf, &CC->user, &qr);
1335         vbuf.v_view = 2;        /* 2 = address book view */
1336         CtdlSetRelationship(&vbuf, &CC->user, &qr);
1337
1338         return;
1339 }
1340
1341
1342
1343
1344 /*
1345  * When a user logs in...
1346  */
1347 void vcard_session_login_hook(void) {
1348         struct vCard *v = NULL;
1349
1350         v = vcard_get_user(&CC->user);
1351         extract_inet_email_addrs(CC->cs_inet_email, sizeof CC->cs_inet_email,
1352                                 CC->cs_inet_other_emails, sizeof CC->cs_inet_other_emails,
1353                                 v, 1);
1354         extract_friendly_name(CC->cs_inet_fn, sizeof CC->cs_inet_fn, v);
1355         vcard_free(v);
1356
1357         vcard_create_room();
1358 }
1359
1360
1361 /* 
1362  * Turn an arbitrary RFC822 address into a struct vCard for possible
1363  * inclusion into an address book.
1364  */
1365 struct vCard *vcard_new_from_rfc822_addr(char *addr) {
1366         struct vCard *v;
1367         char user[256], node[256], name[256], email[256], n[256], uid[256];
1368         int i;
1369
1370         v = vcard_new();
1371         if (v == NULL) return(NULL);
1372
1373         process_rfc822_addr(addr, user, node, name);
1374         vcard_set_prop(v, "fn", name, 0);
1375
1376         vcard_fn_to_n(n, name, sizeof n);
1377         vcard_set_prop(v, "n", n, 0);
1378
1379         snprintf(email, sizeof email, "%s@%s", user, node);
1380         vcard_set_prop(v, "email;internet", email, 0);
1381
1382         snprintf(uid, sizeof uid, "collected: %s %s@%s", name, user, node);
1383         for (i=0; uid[i]; ++i) {
1384                 if (isspace(uid[i])) uid[i] = '_';
1385                 uid[i] = tolower(uid[i]);
1386         }
1387         vcard_set_prop(v, "UID", uid, 0);
1388
1389         return(v);
1390 }
1391
1392
1393
1394 /*
1395  * This is called by store_harvested_addresses() to remove from the
1396  * list any addresses we already have in our address book.
1397  */
1398 void strip_addresses_already_have(long msgnum, void *userdata) {
1399         char *collected_addresses;
1400         struct CtdlMessage *msg = NULL;
1401         struct vCard *v;
1402         char *value = NULL;
1403         int i, j;
1404         char addr[256], user[256], node[256], name[256];
1405
1406         collected_addresses = (char *)userdata;
1407
1408         msg = CtdlFetchMessage(msgnum, 1);
1409         if (msg == NULL) return;
1410         v = vcard_load(msg->cm_fields['M']);
1411         CtdlFreeMessage(msg);
1412
1413         i = 0;
1414         while (value = vcard_get_prop(v, "email", 1, i++, 0), value != NULL) {
1415
1416                 for (j=0; j<num_tokens(collected_addresses, ','); ++j) {
1417                         extract_token(addr, collected_addresses, j, ',', sizeof addr);
1418
1419                         /* Remove the address if we already have it! */
1420                         process_rfc822_addr(addr, user, node, name);
1421                         snprintf(addr, sizeof addr, "%s@%s", user, node);
1422                         if (!strcasecmp(value, addr)) {
1423                                 remove_token(collected_addresses, j, ',');
1424                         }
1425                 }
1426
1427         }
1428
1429         vcard_free(v);
1430 }
1431
1432
1433
1434 /*
1435  * Back end function for store_harvested_addresses()
1436  */
1437 void store_this_ha(struct addresses_to_be_filed *aptr) {
1438         struct CtdlMessage *vmsg = NULL;
1439         long vmsgnum = (-1L);
1440         char *ser = NULL;
1441         struct vCard *v = NULL;
1442         char recipient[256];
1443         int i;
1444
1445         /* First remove any addresses we already have in the address book */
1446         usergoto(aptr->roomname, 0, 0, NULL, NULL);
1447         CtdlForEachMessage(MSGS_ALL, 0, NULL, "^[Tt][Ee][Xx][Tt]/.*[Vv][Cc][Aa][Rr][Dd]$", NULL,
1448                 strip_addresses_already_have, aptr->collected_addresses);
1449
1450         if (!IsEmptyStr(aptr->collected_addresses))
1451            for (i=0; i<num_tokens(aptr->collected_addresses, ','); ++i) {
1452
1453                 /* Make a vCard out of each address */
1454                 extract_token(recipient, aptr->collected_addresses, i, ',', sizeof recipient);
1455                 striplt(recipient);
1456                 v = vcard_new_from_rfc822_addr(recipient);
1457                 if (v != NULL) {
1458                         vmsg = malloc(sizeof(struct CtdlMessage));
1459                         memset(vmsg, 0, sizeof(struct CtdlMessage));
1460                         vmsg->cm_magic = CTDLMESSAGE_MAGIC;
1461                         vmsg->cm_anon_type = MES_NORMAL;
1462                         vmsg->cm_format_type = FMT_RFC822;
1463                         vmsg->cm_fields['A'] = strdup("Citadel");
1464                         vmsg->cm_fields['E'] =  strdup(vcard_get_prop(v, "UID", 0, 0, 0));
1465                         ser = vcard_serialize(v);
1466                         if (ser != NULL) {
1467                                 vmsg->cm_fields['M'] = malloc(strlen(ser) + 1024);
1468                                 sprintf(vmsg->cm_fields['M'],
1469                                         "Content-type: " VCARD_MIME_TYPE
1470                                         "\r\n\r\n%s\r\n", ser);
1471                                 free(ser);
1472                         }
1473                         vcard_free(v);
1474
1475                         lprintf(CTDL_DEBUG, "Adding contact: %s\n", recipient);
1476                         vmsgnum = CtdlSubmitMsg(vmsg, NULL, aptr->roomname);
1477                         CtdlFreeMessage(vmsg);
1478                 }
1479         }
1480
1481         free(aptr->roomname);
1482         free(aptr->collected_addresses);
1483         free(aptr);
1484 }
1485
1486
1487 /*
1488  * When a user sends a message, we may harvest one or more email addresses
1489  * from the recipient list to be added to the user's address book.  But we
1490  * want to do this asynchronously so it doesn't keep the user waiting.
1491  */
1492 void store_harvested_addresses(void) {
1493
1494         struct addresses_to_be_filed *aptr = NULL;
1495
1496         if (atbf == NULL) return;
1497
1498         begin_critical_section(S_ATBF);
1499         while (atbf != NULL) {
1500                 aptr = atbf;
1501                 atbf = atbf->next;
1502                 end_critical_section(S_ATBF);
1503                 store_this_ha(aptr);
1504                 begin_critical_section(S_ATBF);
1505         }
1506         end_critical_section(S_ATBF);
1507 }
1508
1509
1510 /* 
1511  * Function to output vCard data as plain text.  Nobody uses MSG0 anymore, so
1512  * really this is just so we expose the vCard data to the full text indexer.
1513  */
1514 void vcard_fixed_output(char *ptr, int len) {
1515         char *serialized_vcard;
1516         struct vCard *v;
1517         char *key, *value;
1518         int i = 0;
1519
1520         serialized_vcard = malloc(len + 1);
1521         safestrncpy(serialized_vcard, ptr, len+1);
1522         v = vcard_load(serialized_vcard);
1523         free(serialized_vcard);
1524
1525         i = 0;
1526         while (key = vcard_get_prop(v, "", 0, i, 1), key != NULL) {
1527                 value = vcard_get_prop(v, "", 0, i++, 0);
1528                 cprintf("%s\n", value);
1529         }
1530
1531         vcard_free(v);
1532 }
1533
1534
1535 const char *CitadelServiceDICT_TCP="DICT_TCP";
1536
1537 CTDL_MODULE_INIT(vcard)
1538 {
1539         struct ctdlroom qr;
1540         char filename[256];
1541         FILE *fp;
1542
1543         CtdlRegisterSessionHook(vcard_session_login_hook, EVT_LOGIN);
1544         CtdlRegisterMessageHook(vcard_upload_beforesave, EVT_BEFORESAVE);
1545         CtdlRegisterMessageHook(vcard_upload_aftersave, EVT_AFTERSAVE);
1546         CtdlRegisterDeleteHook(vcard_delete_remove);
1547         CtdlRegisterProtoHook(cmd_regi, "REGI", "Enter registration info");
1548         CtdlRegisterProtoHook(cmd_greg, "GREG", "Get registration info");
1549         CtdlRegisterProtoHook(cmd_igab, "IGAB",
1550                                         "Initialize Global Address Book");
1551         CtdlRegisterProtoHook(cmd_qdir, "QDIR", "Query Directory");
1552         CtdlRegisterProtoHook(cmd_gvsn, "GVSN", "Get Valid Screen Names");
1553         CtdlRegisterProtoHook(cmd_gvea, "GVEA", "Get Valid Email Addresses");
1554         CtdlRegisterProtoHook(cmd_dvca, "DVCA", "Dump VCard Addresses");
1555         CtdlRegisterUserHook(vcard_newuser, EVT_NEWUSER);
1556         CtdlRegisterUserHook(vcard_purge, EVT_PURGEUSER);
1557         CtdlRegisterNetprocHook(vcard_extract_from_network);
1558         CtdlRegisterSessionHook(store_harvested_addresses, EVT_TIMER);
1559         CtdlRegisterFixedOutputHook("text/x-vcard", vcard_fixed_output);
1560         CtdlRegisterFixedOutputHook("text/vcard", vcard_fixed_output);
1561
1562         /* Create the Global ADdress Book room if necessary */
1563         create_room(ADDRESS_BOOK_ROOM, 3, "", 0, 1, 0, VIEW_ADDRESSBOOK);
1564
1565         /* Set expiration policy to manual; otherwise objects will be lost! */
1566         if (!lgetroom(&qr, ADDRESS_BOOK_ROOM)) {
1567                 qr.QRep.expire_mode = EXPIRE_MANUAL;
1568                 qr.QRdefaultview = VIEW_ADDRESSBOOK;    /* 2 = address book view */
1569                 lputroom(&qr);
1570
1571                 /*
1572                  * Also make sure it has a netconfig file, so the networker runs
1573                  * on this room even if we don't share it with any other nodes.
1574                  * This allows the CANCEL messages (i.e. "Purge this vCard") to be
1575                  * purged.
1576                  */
1577                 assoc_file_name(filename, sizeof filename, &qr, ctdl_netcfg_dir);
1578                 fp = fopen(filename, "a");
1579                 if (fp != NULL) fclose(fp);
1580                 chown(filename, CTDLUID, (-1));
1581         }
1582
1583         /* for postfix tcpdict */
1584         CtdlRegisterServiceHook(config.c_pftcpdict_port,        /* Postfix */
1585                                 NULL,
1586                                 check_get_greeting,
1587                                 check_get,
1588                                 NULL,
1589                                 CitadelServiceDICT_TCP);
1590         
1591         /* return our Subversion id for the Log */
1592         return "$Id$";
1593 }