moved whitespace around
[citadel.git] / citadel / server / modules / vcard / serv_vcard.c
1 // A server-side module for Citadel which supports address book information
2 // using the standard vCard format.
3 // 
4 // Copyright (c) 1999-2023 by the citadel.org team
5 //
6 // This program is open source software.  Use, duplication, or disclosure
7 // is subject to the terms of the GNU General Public License, version 3.
8
9 // Format of the "Exclusive ID" field of the message containing a user's
10 // vCard.  Doesn't matter what it really looks like as long as it's both
11 // unique and consistent (because we use it for replication checking to
12 // delete the old vCard network-wide when the user enters a new one).
13 #define VCARD_EXT_FORMAT        "Citadel vCard: personal card for %s at %s"
14
15 // Citadel will accept either text/vcard or text/x-vcard as the MIME type
16 // for a vCard.  The following definition determines which one it *generates*
17 // when serializing.
18 #define VCARD_MIME_TYPE         "text/x-vcard"
19
20 #include "../../sysdep.h"
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <stdio.h>
24 #include <fcntl.h>
25 #include <signal.h>
26 #include <pwd.h>
27 #include <errno.h>
28 #include <ctype.h>
29 #include <sys/types.h>
30 #include <time.h>
31 #include <sys/wait.h>
32 #include <string.h>
33 #include <limits.h>
34 #include <libcitadel.h>
35 #include "../../citadel_defs.h"
36 #include "../../server.h"
37 #include "../../citserver.h"
38 #include "../../support.h"
39 #include "../../config.h"
40 #include "../../control.h"
41 #include "../../user_ops.h"
42 #include "../../database.h"
43 #include "../../msgbase.h"
44 #include "../../room_ops.h"
45 #include "../../internet_addressing.h"
46 #include "../../serv_vcard.h"
47 #include "../../citadel_ldap.h"
48 #include "../../ctdl_module.h"
49
50 // set global flag calling for an aide to validate new users
51 void set_mm_valid(void) {
52         int flags = 0;
53
54         begin_critical_section(S_CONTROL);
55         flags = CtdlGetConfigInt("MMflags");
56         flags = flags | MM_VALID ;
57         CtdlSetConfigInt("MMflags", flags);
58         end_critical_section(S_CONTROL);
59 }
60
61
62 ///TODO: gettext!
63 #define _(a) a
64
65 // See if there is a valid Internet address in a vCard to use for outbound
66 // Internet messages.  If there is, stick it in the buffer.
67 void extract_inet_email_addrs(char *emailaddrbuf, size_t emailaddrbuf_len,
68                               char *secemailaddrbuf, size_t secemailaddrbuf_len,
69                               struct vCard *v,
70                               int local_addrs_only
71 ) {
72         char *s, *k, *addr;
73         int instance = 0;
74         int IsDirectoryAddress;
75         int saved_instance = 0;
76
77         // Go through the vCard searching for *all* Internet email addresses
78         while (s = vcard_get_prop(v, "email", 1, instance, 0),  s != NULL) {
79                 k = vcard_get_prop(v, "email", 1, instance, 1);
80                 if ( (s != NULL) && (k != NULL) && (bmstrcasestr(k, "internet")) ) {
81                         addr = strdup(s);
82                         string_trim(addr);
83                         if (!IsEmptyStr(addr)) {
84                                 IsDirectoryAddress = IsDirectory(addr, 1);
85
86                                 syslog(LOG_DEBUG, "EVQ: addr=<%s> IsDirectoryAddress=<%d> local_addrs_only=<%d>", addr, IsDirectoryAddress, local_addrs_only);
87
88                                 if ( IsDirectoryAddress || !local_addrs_only) {
89                                         ++saved_instance;
90                                         if ((saved_instance == 1) && (emailaddrbuf != NULL)) {
91                                                 safestrncpy(emailaddrbuf, addr, emailaddrbuf_len);
92                                         }
93                                         else if ((saved_instance == 2) && (secemailaddrbuf != NULL)) {
94                                                 safestrncpy(secemailaddrbuf, addr, secemailaddrbuf_len);
95                                         }
96                                         else if ((saved_instance > 2) && (secemailaddrbuf != NULL)) {
97                                                 if ( (strlen(addr) + strlen(secemailaddrbuf) + 2) 
98                                                 < secemailaddrbuf_len ) {
99                                                         strcat(secemailaddrbuf, "|");
100                                                         strcat(secemailaddrbuf, addr);
101                                                 }
102                                         }
103                                 }
104                                 if (!IsDirectoryAddress && local_addrs_only) {
105                                         StrBufAppendPrintf(CC->StatusMessage, "\n%d|", ERROR+ ILLEGAL_VALUE);
106                                         StrBufAppendBufPlain(CC->StatusMessage, addr, -1, 0);
107                                         StrBufAppendBufPlain(CC->StatusMessage, HKEY("|"), 0);
108                                         StrBufAppendBufPlain(CC->StatusMessage, _("unable to add this emailaddress; its not matching our domain."), -1, 0);
109                                 }
110                         }
111                         free(addr);
112                 }
113                 ++instance;
114         }
115 }
116
117
118 // See if there is a name / screen name / friendly name  in a vCard to use for outbound
119 // Internet messages.  If there is, stick it in the buffer.
120 void extract_friendly_name(char *namebuf, size_t namebuf_len, struct vCard *v) {
121         char *s;
122
123         s = vcard_get_prop(v, "fn", 1, 0, 0);
124         if (s == NULL) {
125                 s = vcard_get_prop(v, "n", 1, 0, 0);
126         }
127
128         if (s != NULL) {
129                 safestrncpy(namebuf, s, namebuf_len);
130         }
131 }
132
133
134 // Callback function for vcard_upload_beforesave() hunts for the real vcard in the MIME structure
135 void vcard_extract_vcard(char *name, char *filename, char *partnum, char *disp,
136                    void *content, char *cbtype, char *cbcharset, size_t length,
137                    char *encoding, char *cbid, void *cbuserdata)
138 {
139         struct vCard **v = (struct vCard **) cbuserdata;
140
141         if (  (!strcasecmp(cbtype, "text/x-vcard"))
142            || (!strcasecmp(cbtype, "text/vcard")) ) {
143
144                 syslog(LOG_DEBUG, "vcard: part %s contains a vCard!  Loading...", partnum);
145                 if (*v != NULL) {
146                         vcard_free(*v);
147                 }
148                 *v = vcard_load(content);
149         }
150 }
151
152
153 // This handler detects whether the user is attempting to save a new
154 // vCard as part of his/her personal configuration, and handles the replace
155 // function accordingly (delete the user's existing vCard in the config room
156 // and in the global address book).
157 int vcard_upload_beforesave(struct CtdlMessage *msg, struct recptypes *recp) {
158         char *s;
159         char buf[SIZ];
160         struct ctdluser usbuf;
161         long what_user;
162         struct vCard *v = NULL;
163         char *ser = NULL;
164         int i = 0;
165         int yes_my_citadel_config = 0;
166         int yes_any_vcard_room = 0;
167
168         if ((!CC->logged_in) && (CC->vcard_updated_by_ldap==0)) return(0);      // Only do this if logged in, or if ldap changed the vcard.
169
170         // Is this some user's "My Citadel Config" room?
171         if (((CC->room.QRflags & QR_MAILBOX) != 0) && (!strcasecmp(&CC->room.QRname[11], USERCONFIGROOM)) ) {
172                 // Yes, we want to do this
173                 yes_my_citadel_config = 1;
174 #ifdef VCARD_SAVES_BY_AIDES_ONLY
175                 // Prevent non-aides from performing registration changes, but ldap is ok.
176                 if ((CC->user.axlevel < AxAideU) && (CC->vcard_updated_by_ldap==0)) {
177                         return(1);
178                 }
179 #endif
180
181         }
182
183         // Is this a room with an address book in it?
184         if (CC->room.QRdefaultview == VIEW_ADDRESSBOOK) {
185                 yes_any_vcard_room = 1;
186         }
187
188         // If neither condition exists, don't run this hook.
189         if ( (!yes_my_citadel_config) && (!yes_any_vcard_room) ) {
190                 return(0);
191         }
192
193         // If this isn't a MIME message, don't bother.
194         if (msg->cm_format_type != 4) return(0);
195
196         // Ok, if we got this far, look into the situation further...
197
198         if (CM_IsEmpty(msg, eMessageText)) return(0);
199
200         mime_parser(CM_RANGE(msg, eMessageText),
201                     *vcard_extract_vcard,
202                     NULL, NULL,
203                     &v,         // user data ptr - put the vcard here
204                     0
205         );
206
207         if (v == NULL) return(0);       // no vCards were found in this message
208
209         // If users cannot create their own accounts, they cannot re-register either.
210         if ( (yes_my_citadel_config) &&
211              (CtdlGetConfigInt("c_disable_newu")) &&
212              (CC->user.axlevel < AxAideU) &&
213              (CC->vcard_updated_by_ldap==0) )
214         {
215                 return(1);
216         }
217
218         vcard_get_prop(v, "fn", 1, 0, 0);
219
220
221         if (yes_my_citadel_config) {
222                 // Bingo!  The user is uploading a new vCard, so delete the old one.
223                 // First, figure out which user is being re-registered...
224                 what_user = atol(CC->room.QRname);
225
226                 if (what_user == CC->user.usernum) {
227                         // It's the logged in user.  That was easy.
228                         memcpy(&usbuf, &CC->user, sizeof(struct ctdluser));
229                 }
230                 
231                 else if (CtdlGetUserByNumber(&usbuf, what_user) == 0) {
232                         // We fetched a valid user record
233                 }
234
235                 else {
236                         // somebody set up us the bomb!
237                         yes_my_citadel_config = 0;
238                 }
239         }
240         
241         if (yes_my_citadel_config) {
242                 // Delete the user's old vCard.  This would probably get taken care of by the replication check, but we
243                 // want to make sure there is absolutely only one vCard in the user's config room at all times.
244                 CtdlDeleteMessages(CC->room.QRname, NULL, 0, "[Tt][Ee][Xx][Tt]/.*[Vv][Cc][Aa][Rr][Dd]$");
245
246                 // Make the author of the message the name of the user.
247                 if (!IsEmptyStr(usbuf.fullname)) {
248                         CM_SetField(msg, eAuthor, usbuf.fullname);
249                 }
250         }
251
252         // Insert or replace RFC2739-compliant free/busy URL
253         if (yes_my_citadel_config) {
254                 sprintf(buf, "http://%s/%s.vfb",
255                         CtdlGetConfigStr("c_fqdn"),
256                         usbuf.fullname);
257                 for (i=0; buf[i]; ++i) {
258                         if (buf[i] == ' ') buf[i] = '_';
259                 }
260                 vcard_set_prop(v, "FBURL;PREF", buf, 0);
261         }
262
263
264         s = vcard_get_prop(v, "UID", 1, 0, 0);
265         if (s == NULL) { // Note LDAP auth sets UID from the LDAP UUID, use that if it exists.
266                 if (yes_my_citadel_config) {
267                         // Enforce local UID policy if applicable
268                         snprintf(buf, sizeof buf, VCARD_EXT_FORMAT, msg->cm_fields[eAuthor], NODENAME);
269                 }
270                 else {
271                         // If the vCard has no UID, then give it one.
272                         generate_uuid(buf);
273                 }
274                 vcard_set_prop(v, "UID", buf, 0);
275         }
276
277
278         /* 
279          * Set the EUID of the message to the UID of the vCard.
280          */
281         CM_FlushField(msg, eExclusiveID);
282
283         s = vcard_get_prop(v, "UID", 1, 0, 0);
284         if (!IsEmptyStr(s)) {
285                 CM_SetField(msg, eExclusiveID, s);
286                 if (CM_IsEmpty(msg, eMsgSubject)) {
287                         CM_CopyField(msg, eMsgSubject, eExclusiveID);
288                 }
289         }
290
291         /*
292          * Set the Subject to the name in the vCard.
293          */
294         s = vcard_get_prop(v, "FN", 1, 0, 0);
295         if (s == NULL) {
296                 s = vcard_get_prop(v, "N", 1, 0, 0);
297         }
298         if (!IsEmptyStr(s)) {
299                 CM_SetField(msg, eMsgSubject, s);
300         }
301
302         /* Re-serialize it back into the msg body */
303         ser = vcard_serialize(v);
304         if (!IsEmptyStr(ser)) {
305                 StrBuf *buf;
306                 long serlen;
307
308                 serlen = strlen(ser);
309                 buf = NewStrBufPlain(NULL, serlen + 1024);
310
311                 StrBufAppendBufPlain(buf, HKEY("Content-type: " VCARD_MIME_TYPE "\r\n\r\n"), 0);
312                 StrBufAppendBufPlain(buf, ser, serlen, 0);
313                 StrBufAppendBufPlain(buf, HKEY("\r\n"), 0);
314                 CM_SetAsFieldSB(msg, eMessageText, &buf);
315                 free(ser);
316         }
317
318         /* Now allow the save to complete. */
319         vcard_free(v);
320         return(0);
321 }
322
323
324 /*
325  * This handler detects whether the user is attempting to save a new
326  * vCard as part of his/her personal configuration, and handles the replace
327  * function accordingly (copy the vCard from the config room to the global
328  * address book).
329  */
330 int vcard_upload_aftersave(struct CtdlMessage *msg, struct recptypes *recp) {
331         char *ptr;
332         int linelen;
333         long I;
334         struct vCard *v;
335         int is_UserConf=0;
336         int is_MY_UserConf=0;
337         int is_GAB=0;
338         char roomname[ROOMNAMELEN];
339
340         if (msg->cm_format_type != 4) return(0);
341         if ((!CC->logged_in) && (CC->vcard_updated_by_ldap==0)) return(0);      /* Only do this if logged in, or if ldap changed the vcard. */
342
343         /* We're interested in user config rooms only. */
344
345         if ( !IsEmptyStr(CC->room.QRname) &&
346              (strlen(CC->room.QRname) >= 12) &&
347              (!strcasecmp(&CC->room.QRname[11], USERCONFIGROOM)) ) {
348                 is_UserConf = 1;        /* It's someone's config room */
349         }
350         CtdlMailboxName(roomname, sizeof roomname, &CC->user, USERCONFIGROOM);
351         if (!strcasecmp(CC->room.QRname, roomname)) {
352                 is_UserConf = 1;
353                 is_MY_UserConf = 1;     /* It's MY config room */
354         }
355         if (!strcasecmp(CC->room.QRname, ADDRESS_BOOK_ROOM)) {
356                 is_GAB = 1;             /* It's the Global Address Book */
357         }
358
359         if (!is_UserConf && !is_GAB) return(0);
360
361         if (CM_IsEmpty(msg, eMessageText))
362                 return 0;
363
364         ptr = msg->cm_fields[eMessageText];
365
366         CC->vcard_updated_by_ldap=0;  /* As this will write LDAP's previous changes, disallow LDAP change auth until next LDAP change. */ 
367
368         NewStrBufDupAppendFlush(&CC->StatusMessage, NULL, NULL, 0);
369
370         StrBufPrintf(CC->StatusMessage, "%d\n", LISTING_FOLLOWS);
371
372         while (ptr != NULL) {
373         
374                 linelen = strcspn(ptr, "\n");
375                 if (linelen == 0) return(0);    /* end of headers */    
376                 
377                 if (  (!strncasecmp(ptr, "Content-type: text/x-vcard", 26))
378                    || (!strncasecmp(ptr, "Content-type: text/vcard", 24)) ) {
379                         /*
380                          * Bingo!  The user is uploading a new vCard, so
381                          * copy it to the Global Address Book room.
382                          */
383
384                         I = atol(msg->cm_fields[eVltMsgNum]);
385                         if (I <= 0L) return(0);
386
387                         /* Store our friendly/display name in memory */
388                         if (is_MY_UserConf) {
389                                 v = vcard_load(msg->cm_fields[eMessageText]);
390                                 extract_friendly_name(CC->cs_inet_fn, sizeof CC->cs_inet_fn, v);
391                                 vcard_free(v);
392                         }
393
394                         if (!is_GAB)
395                         {       // This is not the GAB
396                                 /* Put it in the Global Address Book room... */
397                                 CtdlSaveMsgPointerInRoom(ADDRESS_BOOK_ROOM, I, 1, msg);
398                         }
399
400                         /* Some sites want an Aide to be notified when a
401                          * user registers or re-registers
402                          * But if the user was an Aide or was edited by an Aide then we can
403                          * Assume they don't need validating.
404                          */
405                         if (CC->user.axlevel >= AxAideU) {
406                                 CtdlLockGetCurrentUser();
407                                 CC->user.flags |= US_REGIS;
408                                 CtdlPutCurrentUserLock();
409                                 return (0);
410                         }
411                         
412                         set_mm_valid();
413
414                         /* ...which also means we need to flag the user */
415                         CtdlLockGetCurrentUser();
416                         CC->user.flags |= (US_REGIS|US_NEEDVALID);
417                         CtdlPutCurrentUserLock();
418
419                         return(0);
420                 }
421
422                 ptr = strchr((char *)ptr, '\n');
423                 if (ptr != NULL) ++ptr;
424         }
425
426         return(0);
427 }
428
429
430
431 /*
432  * back end function used for callbacks
433  */
434 void vcard_gu_backend(long supplied_msgnum, void *userdata) {
435         long *msgnum;
436
437         msgnum = (long *) userdata;
438         *msgnum = supplied_msgnum;
439 }
440
441
442 /*
443  * If this user has a vcard on disk, read it into memory, otherwise allocate
444  * and return an empty vCard.
445  */
446 struct vCard *vcard_get_user(struct ctdluser *u) {
447         char hold_rm[ROOMNAMELEN];
448         char config_rm[ROOMNAMELEN];
449         struct CtdlMessage *msg = NULL;
450         struct vCard *v;
451         long VCmsgnum;
452
453         strcpy(hold_rm, CC->room.QRname);       /* save current room */
454         CtdlMailboxName(config_rm, sizeof config_rm, u, USERCONFIGROOM);
455
456         if (CtdlGetRoom(&CC->room, config_rm) != 0) {
457                 CtdlGetRoom(&CC->room, hold_rm);
458                 return vcard_new();
459         }
460
461         /* We want the last (and probably only) vcard in this room */
462         VCmsgnum = (-1);
463         CtdlForEachMessage(MSGS_LAST, 1, NULL, "[Tt][Ee][Xx][Tt]/.*[Vv][Cc][Aa][Rr][Dd]$",
464                 NULL, vcard_gu_backend, (void *)&VCmsgnum );
465         CtdlGetRoom(&CC->room, hold_rm);        /* return to saved room */
466
467         if (VCmsgnum < 0L) return vcard_new();
468
469         msg = CtdlFetchMessage(VCmsgnum, 1);
470         if (msg == NULL) return vcard_new();
471
472         v = vcard_load(msg->cm_fields[eMessageText]);
473         CM_Free(msg);
474         return v;
475 }
476
477
478 /*
479  * Store this user's vCard in the appropriate place
480  */
481 /*
482  * Write our config to disk
483  */
484 void vcard_write_user(struct ctdluser *u, struct vCard *v) {
485         char *ser;
486
487         ser = vcard_serialize(v);
488         if (ser == NULL) {
489                 ser = strdup("begin:vcard\r\nend:vcard\r\n");
490         }
491         if (ser == NULL) return;
492
493         /* This handy API function does all the work for us.
494          * NOTE: normally we would want to set that last argument to 1, to
495          * force the system to delete the user's old vCard.  But it doesn't
496          * have to, because the vcard_upload_beforesave() hook above
497          * is going to notice what we're trying to do, and delete the old vCard.
498          */
499         CtdlWriteObject(USERCONFIGROOM,         /* which room */
500                         VCARD_MIME_TYPE,        /* MIME type */
501                         ser,                    /* data */
502                         strlen(ser)+1,          /* length */
503                         u,                      /* which user */
504                         0,                      /* not binary */
505                         0);                     /* no flags */
506
507         free(ser);
508 }
509
510
511
512 /*
513  * Old style "enter registration info" command.  This function simply honors
514  * the REGI protocol command, translates the entered parameters into a vCard,
515  * and enters the vCard into the user's configuration.
516  */
517 void cmd_regi(char *argbuf) {
518         int a,b,c;
519         char buf[SIZ];
520         struct vCard *my_vcard;
521
522         char tmpaddr[SIZ];
523         char tmpcity[SIZ];
524         char tmpstate[SIZ];
525         char tmpzip[SIZ];
526         char tmpaddress[SIZ];
527         char tmpcountry[SIZ];
528
529         unbuffer_output();
530
531         if (!(CC->logged_in)) {
532                 cprintf("%d Not logged in.\n",ERROR + NOT_LOGGED_IN);
533                 return;
534         }
535
536         /* If users cannot create their own accounts, they cannot re-register either. */
537         if ( (CtdlGetConfigInt("c_disable_newu")) && (CC->user.axlevel < AxAideU) ) {
538                 cprintf("%d Self-service registration is not allowed here.\n",
539                         ERROR + HIGHER_ACCESS_REQUIRED);
540         }
541
542         my_vcard = vcard_get_user(&CC->user);
543         strcpy(tmpaddr, "");
544         strcpy(tmpcity, "");
545         strcpy(tmpstate, "");
546         strcpy(tmpzip, "");
547         strcpy(tmpcountry, "USA");
548
549         cprintf("%d Send registration...\n", SEND_LISTING);
550         a=0;
551         while (client_getln(buf, sizeof buf), strcmp(buf,"000")) {
552                 if (a==0) vcard_set_prop(my_vcard, "n", buf, 0);
553                 if (a==1) strcpy(tmpaddr, buf);
554                 if (a==2) strcpy(tmpcity, buf);
555                 if (a==3) strcpy(tmpstate, buf);
556                 if (a==4) {
557                         for (c=0; buf[c]; ++c) {
558                                 if ((buf[c]>='0') && (buf[c]<='9')) {
559                                         b = strlen(tmpzip);
560                                         tmpzip[b] = buf[c];
561                                         tmpzip[b+1] = 0;
562                                 }
563                         }
564                 }
565                 if (a==5) vcard_set_prop(my_vcard, "tel", buf, 0);
566                 if (a==6) vcard_set_prop(my_vcard, "email;internet", buf, 0);
567                 if (a==7) strcpy(tmpcountry, buf);
568                 ++a;
569         }
570
571         snprintf(tmpaddress, sizeof tmpaddress, ";;%s;%s;%s;%s;%s",
572                 tmpaddr, tmpcity, tmpstate, tmpzip, tmpcountry);
573         vcard_set_prop(my_vcard, "adr", tmpaddress, 0);
574         vcard_write_user(&CC->user, my_vcard);
575         vcard_free(my_vcard);
576 }
577
578
579 /*
580  * Protocol command to fetch registration info for a user
581  */
582 void cmd_greg(char *argbuf)
583 {
584         struct ctdluser usbuf;
585         struct vCard *v;
586         char *s;
587         char who[USERNAME_SIZE];
588         char adr[256];
589         char buf[256];
590
591         extract_token(who, argbuf, 0, '|', sizeof who);
592
593         if (!(CC->logged_in)) {
594                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
595                 return;
596         }
597
598         if (!strcasecmp(who,"_SELF_")) strcpy(who,CC->curr_user);
599
600         if ((CC->user.axlevel < AxAideU) && (strcasecmp(who,CC->curr_user))) {
601                 cprintf("%d Higher access required.\n", ERROR + HIGHER_ACCESS_REQUIRED);
602                 return;
603         }
604
605         if (CtdlGetUser(&usbuf, who) != 0) {
606                 cprintf("%d '%s' not found.\n", ERROR + NO_SUCH_USER, who);
607                 return;
608         }
609
610         v = vcard_get_user(&usbuf);
611
612         cprintf("%d %s\n", LISTING_FOLLOWS, usbuf.fullname);
613         cprintf("%ld\n", usbuf.usernum);
614         cprintf("%s\n", usbuf.password);
615         s = vcard_get_prop(v, "n", 1, 0, 0);
616         cprintf("%s\n", s ? s : " ");                   /* name */
617         s = vcard_get_prop(v, "adr", 1, 0, 0);
618         snprintf(adr, sizeof adr, "%s", s ? s : " ");   /* address */
619         extract_token(buf, adr, 2, ';', sizeof buf);
620         cprintf("%s\n", buf);                           /* street */
621         extract_token(buf, adr, 3, ';', sizeof buf);
622         cprintf("%s\n", buf);                           /* city */
623         extract_token(buf, adr, 4, ';', sizeof buf);
624         cprintf("%s\n", buf);                           /* state */
625         extract_token(buf, adr, 5, ';', sizeof buf);
626         cprintf("%s\n", buf);                           /* zip */
627
628         s = vcard_get_prop(v, "tel", 1, 0, 0);
629         if (s == NULL) s = vcard_get_prop(v, "tel", 1, 0, 0);
630         if (s != NULL) {
631                 cprintf("%s\n", s);
632         }
633         else {
634                 cprintf(" \n");
635         }
636
637         cprintf("%d\n", usbuf.axlevel);
638
639         s = vcard_get_prop(v, "email;internet", 0, 0, 0);
640         cprintf("%s\n", s ? s : " ");
641         s = vcard_get_prop(v, "adr", 0, 0, 0);
642         snprintf(adr, sizeof adr, "%s", s ? s : " ");/* address... */
643
644         extract_token(buf, adr, 6, ';', sizeof buf);
645         cprintf("%s\n", buf);                           /* country */
646         cprintf("000\n");
647         vcard_free(v);
648 }
649
650
651
652 /*
653  * When a user is being created, create his/her vCard.
654  */
655 void vcard_newuser(struct ctdluser *usbuf) {
656         char vname[256];
657         char buf[256];
658         int i;
659         struct vCard *v;
660         int need_default_vcard;
661
662         need_default_vcard =1;
663         vcard_fn_to_n(vname, usbuf->fullname, sizeof vname);
664         syslog(LOG_DEBUG, "vcard: converted <%s> to <%s>", usbuf->fullname, vname);
665
666         /* Create and save the vCard */
667         v = vcard_new();
668         if (v == NULL) return;
669         vcard_add_prop(v, "fn", usbuf->fullname);
670         vcard_add_prop(v, "n", vname);
671         vcard_add_prop(v, "adr", "adr:;;_;_;_;00000;__");
672
673 #ifdef HAVE_GETPWUID_R
674         /* If using host auth mode, we add an email address based on the login */
675         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
676                 struct passwd pwd;
677                 char pwd_buffer[SIZ];
678                 struct passwd *result = NULL;
679                 syslog(LOG_DEBUG, "vcard: searching for uid %d", usbuf->uid);
680                 if (getpwuid_r(usbuf->uid, &pwd, pwd_buffer, sizeof pwd_buffer, &result) == 0) {
681                         snprintf(buf, sizeof buf, "%s@%s", pwd.pw_name, CtdlGetConfigStr("c_fqdn"));
682                         vcard_add_prop(v, "email;internet", buf);
683                         need_default_vcard = 0;
684                 }
685         }
686 #endif
687
688         /*
689          * Is this an LDAP session?  If so, copy various LDAP attributes from the directory entry
690          * into the user's vCard.
691          */
692         if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
693                 //uid_t ldap_uid;
694                 int found_user;
695                 char ldap_cn[512];
696                 char ldap_dn[512];
697
698                 syslog(LOG_DEBUG, "\033[31m FIXME BORK BORK BORK try lookup by uid , or maybe dn?\033[0m");
699
700                 found_user = CtdlTryUserLDAP(usbuf->fullname, ldap_dn, sizeof ldap_dn, ldap_cn, sizeof ldap_cn, &usbuf->uid);
701                 if (found_user == 0) {
702                         if (Ctdl_LDAP_to_vCard(ldap_dn, v)) {
703                                 /* Allow global address book and internet directory update without login long enough to write this. */
704                                 CC->vcard_updated_by_ldap++;  /* Otherwise we'll only update the user config. */
705                                 need_default_vcard = 0;
706                                 syslog(LOG_DEBUG, "vcard: LDAP Created Initial vCard for %s\n",usbuf->fullname);
707                         }
708                 }
709         }
710
711         if (need_default_vcard!=0) {
712                 /* Everyone gets an email address based on their display name */
713                 snprintf(buf, sizeof buf, "%s@%s", usbuf->fullname, CtdlGetConfigStr("c_fqdn"));
714                 for (i=0; buf[i]; ++i) {
715                         if (buf[i] == ' ') buf[i] = '_';
716                 }
717                 vcard_add_prop(v, "email;internet", buf);
718         }
719         vcard_write_user(usbuf, v);
720         vcard_free(v);
721 }
722
723
724 /*
725  * Get Valid Screen Names
726  */
727 void cmd_gvsn(char *argbuf)
728 {
729         if (CtdlAccessCheck(ac_logged_in)) return;
730
731         cprintf("%d valid screen names:\n", LISTING_FOLLOWS);
732         cprintf("%s\n", CC->user.fullname);
733         if ( (!IsEmptyStr(CC->cs_inet_fn)) && (strcasecmp(CC->user.fullname, CC->cs_inet_fn)) ) {
734                 cprintf("%s\n", CC->cs_inet_fn);
735         }
736         cprintf("000\n");
737 }
738
739
740 /*
741  * Get Valid Email Addresses
742  * FIXME this doesn't belong in serv_vcard.c anymore , maybe move it to internet_addressing.c
743  */
744 void cmd_gvea(char *argbuf)
745 {
746         int num_secondary_emails = 0;
747         int i;
748         char buf[256];
749
750         if (CtdlAccessCheck(ac_logged_in)) return;
751
752         cprintf("%d valid email addresses:\n", LISTING_FOLLOWS);
753         if (!IsEmptyStr(CC->cs_inet_email)) {
754                 cprintf("%s\n", CC->cs_inet_email);
755         }
756         if (!IsEmptyStr(CC->cs_inet_other_emails)) {
757                 num_secondary_emails = num_tokens(CC->cs_inet_other_emails, '|');
758                 for (i=0; i<num_secondary_emails; ++i) {
759                         extract_token(buf, CC->cs_inet_other_emails,i,'|',sizeof CC->cs_inet_other_emails);
760                         cprintf("%s\n", buf);
761                 }
762         }
763         cprintf("000\n");
764 }
765
766
767 /*
768  * Callback function for cmd_dvca() that hunts for vCard content types
769  * and outputs any email addresses found within.
770  */
771 void dvca_mime_callback(char *name, char *filename, char *partnum, char *disp,
772                 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
773                 char *cbid, void *cbuserdata) {
774
775         struct vCard *v;
776         char displayname[256] = "";
777         int displayname_len;
778         char emailaddr[256] = "";
779         int i;
780         int has_commas = 0;
781
782         if ( (strcasecmp(cbtype, "text/vcard")) && (strcasecmp(cbtype, "text/x-vcard")) ) {
783                 return;
784         }
785
786         v = vcard_load(content);
787         if (v == NULL) return;
788
789         extract_friendly_name(displayname, sizeof displayname, v);
790         extract_inet_email_addrs(emailaddr, sizeof emailaddr, NULL, 0, v, 0);
791
792         displayname_len = strlen(displayname);
793         for (i=0; i<displayname_len; ++i) {
794                 if (displayname[i] == '\"') displayname[i] = ' ';
795                 if (displayname[i] == ';') displayname[i] = ',';
796                 if (displayname[i] == ',') has_commas = 1;
797         }
798         string_trim(displayname);
799
800         cprintf("%s%s%s <%s>\n",
801                 (has_commas ? "\"" : ""),
802                 displayname,
803                 (has_commas ? "\"" : ""),
804                 emailaddr
805         );
806
807         vcard_free(v);
808 }
809
810
811 /*
812  * Back end callback function for cmd_dvca()
813  *
814  * It's basically just passed a list of message numbers, which we're going
815  * to fetch off the disk and then pass along to the MIME parser via another
816  * layer of callback...
817  */
818 void dvca_callback(long msgnum, void *userdata) {
819         struct CtdlMessage *msg = NULL;
820
821         msg = CtdlFetchMessage(msgnum, 1);
822         if (msg == NULL) return;
823         mime_parser(CM_RANGE(msg, eMessageText),
824                     *dvca_mime_callback,        /* callback function */
825                     NULL, NULL,
826                     NULL,                       /* user data */
827                     0
828                 );
829         CM_Free(msg);
830 }
831
832
833 // Dump VCard Addresses
834 void cmd_dvca(char *argbuf) {
835         if (CtdlAccessCheck(ac_logged_in)) return;
836
837         cprintf("%d addresses:\n", LISTING_FOLLOWS);
838         CtdlForEachMessage(MSGS_ALL, 0, NULL, NULL, NULL, dvca_callback, NULL);
839         cprintf("000\n");
840 }
841
842
843 // ReBuild Directory Index (this isn't really vcard-related anymore)
844 void cmd_rbdi(char *argbuf) {
845         if (CtdlAccessCheck(ac_aide)) return;
846         CtdlRebuildDirectoryIndex();
847         cprintf("%d Directory index has been rebuilt.\n", CIT_OK);
848 }
849
850
851 // Query Directory (this isn't really vcard-related anymore)
852 void cmd_qdir(char *argbuf) {
853         char citadel_addr[256];
854         char internet_addr[256];
855
856         if (CtdlAccessCheck(ac_logged_in)) return;
857
858         extract_token(internet_addr, argbuf, 0, '|', sizeof internet_addr);
859
860         if (CtdlDirectoryLookup(citadel_addr, internet_addr, sizeof citadel_addr) != 0) {
861                 cprintf("%d %s was not found.\n", ERROR + NO_SUCH_USER, internet_addr);
862                 return;
863         }
864
865         cprintf("%d %s\n", CIT_OK, citadel_addr);
866 }
867
868
869 // Query Directory, in fact an alias to match postfix tcp auth.
870 void check_get(void) {
871         char internet_addr[256];
872
873         char cmdbuf[SIZ];
874
875         time(&CC->lastcmd);
876         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
877         if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
878                 syslog(LOG_ERR, "vcard: client disconnected: ending session.");
879                 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
880                 return;
881         }
882         syslog(LOG_INFO, ": %s", cmdbuf);
883         while (strlen(cmdbuf) < 3) strcat(cmdbuf, " ");
884         syslog(LOG_INFO, "[ %s]", cmdbuf);
885         
886         if (strncasecmp(cmdbuf, "GET ", 4)==0)
887         {
888                 struct recptypes *rcpt;
889                 char *argbuf = &cmdbuf[4];
890                 
891                 extract_token(internet_addr, argbuf, 0, '|', sizeof internet_addr);
892                 rcpt = validate_recipients(internet_addr, CHECK_EXIST);
893                 if (    (rcpt != NULL) &&
894                         (
895                                 (*rcpt->recp_local != '\0') ||
896                                 (*rcpt->recp_room != '\0')
897                         )
898                 ) {
899                         cprintf("200 OK %s\n", internet_addr);
900                         syslog(LOG_INFO, "vcard: sending 200 OK for the room %s", rcpt->display_recp);
901                 }
902                 else 
903                 {
904                         cprintf("500 REJECT no one here by that name.\n");
905                         
906                         syslog(LOG_INFO, "vcard: sending 500 REJECT no one here by that name: %s", internet_addr);
907                 }
908                 if (rcpt != NULL) 
909                         free_recipients(rcpt);
910         }
911         else {
912                 cprintf("500 REJECT invalid Query.\n");
913                 syslog(LOG_INFO, "vcard: sending 500 REJECT invalid query: %s", internet_addr);
914         }
915 }
916
917
918 void check_get_greeting(void) {
919         // dummy function, we have no greeting in this very simple protocol.
920 }
921
922
923 // We don't know if the Contacts room exists so we just create it at login
924 void vcard_CtdlCreateRoom(void) {
925         struct ctdlroom qr;
926         struct visit vbuf;
927
928         // Create the calendar room if it doesn't already exist
929         CtdlCreateRoom(USERCONTACTSROOM, 4, "", 0, 1, 0, VIEW_ADDRESSBOOK);
930
931         // Set expiration policy to manual; otherwise objects will be lost!
932         if (CtdlGetRoomLock(&qr, USERCONTACTSROOM)) {
933                 syslog(LOG_ERR, "vcard: couldn't get the user CONTACTS room!");
934                 return;
935         }
936         qr.QRep.expire_mode = EXPIRE_MANUAL;
937         qr.QRdefaultview = VIEW_ADDRESSBOOK;    // 2 = address book view
938         CtdlPutRoomLock(&qr);
939
940         // Set the view to a calendar view
941         CtdlGetRelationship(&vbuf, &CC->user, &qr);
942         vbuf.v_view = 2;                        // 2 = address book view
943         CtdlSetRelationship(&vbuf, &CC->user, &qr);
944
945         return;
946 }
947
948
949 // When a user logs in...
950 void vcard_session_login_hook(void) {
951         struct vCard *v = NULL;
952
953         // Is this an LDAP session?  If so, copy various LDAP attributes from the directory entry
954         // into the user's vCard.
955         if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
956                 v = vcard_get_user(&CC->user);
957                 if (v) {
958                         if (Ctdl_LDAP_to_vCard(CC->ldap_dn, v)) {
959                                 CC->vcard_updated_by_ldap++; /* Make sure changes make it to the global address book and internet directory, not just the user config. */
960                                 syslog(LOG_DEBUG, "vcard: LDAP Detected vcard change");
961                                 vcard_write_user(&CC->user, v);
962                         }
963                 }
964         }
965
966         // Extract the user's friendly/screen name
967         // These are inserted into the session data for various message entry commands to use.
968         v = vcard_get_user(&CC->user);
969         if (v) {
970                 extract_friendly_name(CC->cs_inet_fn, sizeof CC->cs_inet_fn, v);
971                 vcard_free(v);
972         }
973
974         // Create the user's 'Contacts' room (personal address book) if it doesn't already exist.
975         vcard_CtdlCreateRoom();
976 }
977
978
979 // Turn an arbitrary RFC822 address into a struct vCard for possible
980 // inclusion into an address book.
981 struct vCard *vcard_new_from_rfc822_addr(char *addr) {
982         struct vCard *v;
983         char user[256], node[256], name[256], email[256], n[256], uid[256];
984         int i;
985
986         v = vcard_new();
987         if (v == NULL) return(NULL);
988
989         process_rfc822_addr(addr, user, node, name);
990         vcard_set_prop(v, "fn", name, 0);
991
992         vcard_fn_to_n(n, name, sizeof n);
993         vcard_set_prop(v, "n", n, 0);
994
995         snprintf(email, sizeof email, "%s@%s", user, node);
996         vcard_set_prop(v, "email;internet", email, 0);
997
998         snprintf(uid, sizeof uid, "collected: %s %s@%s", name, user, node);
999         for (i=0; uid[i]; ++i) {
1000                 if (isspace(uid[i])) uid[i] = '_';
1001                 uid[i] = tolower(uid[i]);
1002         }
1003         vcard_set_prop(v, "UID", uid, 0);
1004
1005         return(v);
1006 }
1007
1008
1009 // This is called by store_harvested_addresses() to remove from the
1010 // list any addresses we already have in our address book.
1011 void strip_addresses_already_have(long msgnum, void *userdata) {
1012         char *collected_addresses;
1013         struct CtdlMessage *msg = NULL;
1014         struct vCard *v;
1015         char *value = NULL;
1016         int i, j;
1017         char addr[256], user[256], node[256], name[256];
1018
1019         collected_addresses = (char *)userdata;
1020
1021         msg = CtdlFetchMessage(msgnum, 1);
1022         if (msg == NULL) return;
1023         v = vcard_load(msg->cm_fields[eMessageText]);
1024         CM_Free(msg);
1025
1026         i = 0;
1027         while (value = vcard_get_prop(v, "email", 1, i++, 0), value != NULL) {
1028
1029                 for (j=0; j<num_tokens(collected_addresses, ','); ++j) {
1030                         extract_token(addr, collected_addresses, j, ',', sizeof addr);
1031
1032                         // Remove the address if we already have it!
1033                         process_rfc822_addr(addr, user, node, name);
1034                         snprintf(addr, sizeof addr, "%s@%s", user, node);
1035                         if (!strcasecmp(value, addr)) {
1036                                 remove_token(collected_addresses, j, ',');
1037                         }
1038                 }
1039
1040         }
1041
1042         vcard_free(v);
1043 }
1044
1045
1046
1047 // Back end function for store_harvested_addresses()
1048 void store_this_ha(struct addresses_to_be_filed *aptr) {
1049         struct CtdlMessage *vmsg = NULL;
1050         char *ser = NULL;
1051         struct vCard *v = NULL;
1052         char recipient[256];
1053         int i;
1054
1055         // First remove any addresses we already have in the address book
1056         CtdlUserGoto(aptr->roomname, 0, 0, NULL, NULL, NULL, NULL);
1057         CtdlForEachMessage(MSGS_ALL, 0, NULL, "[Tt][Ee][Xx][Tt]/.*[Vv][Cc][Aa][Rr][Dd]$", NULL,
1058                 strip_addresses_already_have, aptr->collected_addresses);
1059
1060         if (!IsEmptyStr(aptr->collected_addresses))
1061            for (i=0; i<num_tokens(aptr->collected_addresses, ','); ++i) {
1062
1063                 /* Make a vCard out of each address */
1064                 extract_token(recipient, aptr->collected_addresses, i, ',', sizeof recipient);
1065                 string_trim(recipient);
1066                 v = vcard_new_from_rfc822_addr(recipient);
1067                 if (v != NULL) {
1068                         const char *s;
1069                         vmsg = malloc(sizeof(struct CtdlMessage));
1070                         memset(vmsg, 0, sizeof(struct CtdlMessage));
1071                         vmsg->cm_magic = CTDLMESSAGE_MAGIC;
1072                         vmsg->cm_anon_type = MES_NORMAL;
1073                         vmsg->cm_format_type = FMT_RFC822;
1074                         CM_SetField(vmsg, eAuthor, "Citadel");
1075                         s = vcard_get_prop(v, "UID", 1, 0, 0);
1076                         if (!IsEmptyStr(s)) {
1077                                 CM_SetField(vmsg, eExclusiveID, s);
1078                         }
1079                         ser = vcard_serialize(v);
1080                         if (ser != NULL) {
1081                                 StrBuf *buf;
1082                                 long serlen;
1083                                 
1084                                 serlen = strlen(ser);
1085                                 buf = NewStrBufPlain(NULL, serlen + 1024);
1086
1087                                 StrBufAppendBufPlain(buf, HKEY("Content-type: " VCARD_MIME_TYPE "\r\n\r\n"), 0);
1088                                 StrBufAppendBufPlain(buf, ser, serlen, 0);
1089                                 StrBufAppendBufPlain(buf, HKEY("\r\n"), 0);
1090                                 CM_SetAsFieldSB(vmsg, eMessageText, &buf);
1091                                 free(ser);
1092                         }
1093                         vcard_free(v);
1094
1095                         syslog(LOG_DEBUG, "vcard: adding contact: %s", recipient);
1096                         CtdlSubmitMsg(vmsg, NULL, aptr->roomname);
1097                         CM_Free(vmsg);
1098                 }
1099         }
1100
1101         free(aptr->roomname);
1102         free(aptr->collected_addresses);
1103         free(aptr);
1104 }
1105
1106
1107 /*
1108  * When a user sends a message, we may harvest one or more email addresses
1109  * from the recipient list to be added to the user's address book.  But we
1110  * want to do this asynchronously so it doesn't keep the user waiting.
1111  */
1112 void store_harvested_addresses(void) {
1113
1114         struct addresses_to_be_filed *aptr = NULL;
1115
1116         if (atbf == NULL) return;
1117
1118         begin_critical_section(S_ATBF);
1119         while (atbf != NULL) {
1120                 aptr = atbf;
1121                 atbf = atbf->next;
1122                 end_critical_section(S_ATBF);
1123                 store_this_ha(aptr);
1124                 begin_critical_section(S_ATBF);
1125         }
1126         end_critical_section(S_ATBF);
1127 }
1128
1129
1130 /* 
1131  * Function to output vCard data as plain text.  Nobody uses MSG0 anymore, so
1132  * really this is just so we expose the vCard data to the full text indexer.
1133  */
1134 void vcard_fixed_output(char *ptr, int len) {
1135         char *serialized_vcard;
1136         struct vCard *v;
1137         char *key, *value;
1138         int i = 0;
1139
1140         serialized_vcard = malloc(len + 1);
1141         safestrncpy(serialized_vcard, ptr, len+1);
1142         v = vcard_load(serialized_vcard);
1143         free(serialized_vcard);
1144
1145         i = 0;
1146         while (key = vcard_get_prop(v, "", 0, i, 1), key != NULL) {
1147                 value = vcard_get_prop(v, "", 0, i++, 0);
1148                 cprintf("%s\n", value);
1149         }
1150
1151         vcard_free(v);
1152 }
1153
1154 const char *CitadelServiceDICT_TCP="DICT_TCP";
1155
1156
1157 // Initialization function, called from modules_init.c
1158 char *ctdl_module_init_vcard(void) {
1159         struct ctdlroom qr;
1160
1161         if (!threading) {
1162                 CtdlRegisterSessionHook(vcard_session_login_hook, EVT_LOGIN, PRIO_LOGIN + 70);
1163                 CtdlRegisterMessageHook(vcard_upload_beforesave, EVT_BEFORESAVE);
1164                 CtdlRegisterMessageHook(vcard_upload_aftersave, EVT_AFTERSAVE);
1165                 CtdlRegisterProtoHook(cmd_regi, "REGI", "Enter registration info");
1166                 CtdlRegisterProtoHook(cmd_greg, "GREG", "Get registration info");
1167                 CtdlRegisterProtoHook(cmd_qdir, "QDIR", "Query Directory");
1168                 CtdlRegisterProtoHook(cmd_rbdi, "RBDI", "ReBuild Directory Index");
1169                 CtdlRegisterProtoHook(cmd_gvsn, "GVSN", "Get Valid Screen Names");
1170                 CtdlRegisterProtoHook(cmd_gvea, "GVEA", "Get Valid Email Addresses");
1171                 CtdlRegisterProtoHook(cmd_dvca, "DVCA", "Dump VCard Addresses");
1172                 CtdlRegisterUserHook(vcard_newuser, EVT_NEWUSER);
1173                 CtdlRegisterSessionHook(store_harvested_addresses, EVT_TIMER, PRIO_CLEANUP + 470);
1174                 CtdlRegisterFixedOutputHook("text/x-vcard", vcard_fixed_output);
1175                 CtdlRegisterFixedOutputHook("text/vcard", vcard_fixed_output);
1176
1177                 /* Create the Global Address Book room if necessary */
1178                 CtdlCreateRoom(ADDRESS_BOOK_ROOM, 3, "", 0, 1, 0, VIEW_ADDRESSBOOK);
1179
1180                 /* Set expiration policy to manual; otherwise objects will be lost! */
1181                 if (!CtdlGetRoomLock(&qr, ADDRESS_BOOK_ROOM)) {
1182                         qr.QRep.expire_mode = EXPIRE_MANUAL;
1183                         qr.QRdefaultview = VIEW_ADDRESSBOOK;                    // 2 = address book view
1184                         CtdlPutRoomLock(&qr);
1185                 }
1186
1187                 /* for postfix tcpdict */
1188                 CtdlRegisterServiceHook(CtdlGetConfigInt("c_pftcpdict_port"),   // Postfix
1189                                         NULL,
1190                                         check_get_greeting,
1191                                         check_get,
1192                                         NULL,
1193                                         CitadelServiceDICT_TCP
1194                 );
1195         }
1196
1197         /* return our module name for the log */
1198         return "vcard";
1199 }