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