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