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