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