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