* The EUID index is now built, and replication checks are being performed
[citadel.git] / citadel / serv_vcard.c
1 /*
2  * $Id$
3  * 
4  * A server-side module for Citadel which supports address book information
5  * using the standard vCard format.
6  * 
7  * Copyright (c) 1999-2002 / released under the GNU General Public License
8  */
9
10 /*
11  * Format of the "Exclusive ID" field of the message containing a user's
12  * vCard.  Doesn't matter what it really looks like as long as it's both
13  * unique and consistent (because we use it for replication checking to
14  * delete the old vCard network-wide when the user enters a new one).
15  */
16 #define VCARD_EXT_FORMAT        "Citadel vCard: personal card for %s at %s"
17
18
19 #include "sysdep.h"
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <stdio.h>
23 #include <fcntl.h>
24 #include <signal.h>
25 #include <pwd.h>
26 #include <errno.h>
27 #include <ctype.h>
28 #include <sys/types.h>
29
30 #if TIME_WITH_SYS_TIME
31 # include <sys/time.h>
32 # include <time.h>
33 #else
34 # if HAVE_SYS_TIME_H
35 #  include <sys/time.h>
36 # else
37 #  include <time.h>
38 # endif
39 #endif
40
41 #include <sys/wait.h>
42 #include <string.h>
43 #include <limits.h>
44 #include "citadel.h"
45 #include "server.h"
46 #include "sysdep_decls.h"
47 #include "citserver.h"
48 #include "support.h"
49 #include "config.h"
50 #include "control.h"
51 #include "serv_extensions.h"
52 #include "room_ops.h"
53 #include "user_ops.h"
54 #include "policy.h"
55 #include "database.h"
56 #include "msgbase.h"
57 #include "internet_addressing.h"
58 #include "tools.h"
59 #include "vcard.h"
60 #include "serv_ldap.h"
61
62 /*
63  * set global flag calling for an aide to validate new users
64  */
65 void set_mm_valid(void) {
66         begin_critical_section(S_CONTROL);
67         get_control();
68         CitControl.MMflags = CitControl.MMflags | MM_VALID ;
69         put_control();
70         end_critical_section(S_CONTROL);
71 }
72
73
74
75 /*
76  * Extract Internet e-mail addresses from a message containing a vCard, and
77  * perform a callback for any found.
78  */
79 void vcard_extract_internet_addresses(struct CtdlMessage *msg,
80                                 void (*callback)(char *, char *) ) {
81         struct vCard *v;
82         char *s;
83         char *addr;
84         char citadel_address[SIZ];
85         int instance = 0;
86         int found_something = 0;
87
88         if (msg->cm_fields['A'] == NULL) return;
89         if (msg->cm_fields['N'] == NULL) return;
90         snprintf(citadel_address, sizeof citadel_address, "%s @ %s",
91                 msg->cm_fields['A'], msg->cm_fields['N']);
92
93         v = vcard_load(msg->cm_fields['M']);
94         if (v == NULL) return;
95
96         /* Go through the vCard searching for *all* instances of
97          * the "email;internet" key
98          */
99         do {
100                 s = vcard_get_prop(v, "email;internet", 0, instance++, 0);
101                 if (s != NULL) {
102                         addr = strdup(s);
103                         striplt(addr);
104                         if (strlen(addr) > 0) {
105                                 if (callback != NULL) {
106                                         callback(addr, citadel_address);
107                                 }
108                         }
109                         free(addr);
110                         found_something = 1;
111                 }
112                 else {
113                         found_something = 0;
114                 }
115         } while(found_something);
116
117         vcard_free(v);
118 }
119
120
121
122 /*
123  * Callback for vcard_add_to_directory()
124  * (Lotsa ugly nested callbacks.  Oh well.)
125  */
126 void vcard_directory_add_user(char *internet_addr, char *citadel_addr) {
127         char buf[SIZ];
128
129         /* We have to validate that we're not stepping on someone else's
130          * email address ... but only if we're logged in.  Otherwise it's
131          * probably just the networker or something.
132          */
133         if (CC->logged_in) {
134                 lprintf(CTDL_DEBUG, "Checking for <%s>...\n", internet_addr);
135                 if (CtdlDirectoryLookup(buf, internet_addr, sizeof buf) == 0) {
136                         if (strcasecmp(buf, citadel_addr)) {
137                                 /* This address belongs to someone else.
138                                  * Bail out silently without saving.
139                                  */
140                                 lprintf(CTDL_DEBUG, "DOOP!\n");
141                                 return;
142                         }
143                 }
144         }
145         lprintf(CTDL_INFO, "Adding %s (%s) to directory\n",
146                         citadel_addr, internet_addr);
147         CtdlDirectoryAddUser(internet_addr, citadel_addr);
148 }
149
150
151 /*
152  * Back end function for cmd_igab()
153  */
154 void vcard_add_to_directory(long msgnum, void *data) {
155         struct CtdlMessage *msg;
156
157         msg = CtdlFetchMessage(msgnum, 1);
158         if (msg != NULL) {
159                 vcard_extract_internet_addresses(msg, vcard_directory_add_user);
160         }
161
162 #ifdef HAVE_LDAP
163         ctdl_vcard_to_ldap(msg, V2L_WRITE);
164 #endif
165
166         CtdlFreeMessage(msg);
167 }
168
169
170 /*
171  * Initialize Global Adress Book
172  */
173 void cmd_igab(char *argbuf) {
174         char hold_rm[ROOMNAMELEN];
175
176         if (CtdlAccessCheck(ac_aide)) return;
177
178         strcpy(hold_rm, CC->room.QRname);       /* save current room */
179
180         if (getroom(&CC->room, ADDRESS_BOOK_ROOM) != 0) {
181                 getroom(&CC->room, hold_rm);
182                 cprintf("%d cannot get address book room\n", ERROR + ROOM_NOT_FOUND);
183                 return;
184         }
185
186         /* Empty the existing database first.
187          */
188         CtdlDirectoryInit();
189
190         /* We want *all* vCards in this room */
191         CtdlForEachMessage(MSGS_ALL, 0, "text/x-vcard",
192                 NULL, vcard_add_to_directory, NULL);
193
194         getroom(&CC->room, hold_rm);    /* return to saved room */
195         cprintf("%d Directory has been rebuilt.\n", CIT_OK);
196 }
197
198
199
200
201 /*
202  * See if there is a valid Internet address in a vCard to use for outbound
203  * Internet messages.  If there is, stick it in CC->cs_inet_email.
204  */
205 void vcard_populate_cs_inet_email(struct vCard *v) {
206         char *s, *addr;
207         int continue_searching = 1;
208         int instance = 0;
209
210         /* Go through the vCard searching for *all* instances of
211          * the "email;internet" key
212          */
213         do {
214                 s = vcard_get_prop(v, "email;internet", 0, instance++, 0);
215                 if (s != NULL) {
216                         continue_searching = 1;
217                         addr = strdup(s);
218                         striplt(addr);
219                         if (strlen(addr) > 0) {
220                                 if (IsDirectory(addr)) {
221                                         continue_searching = 0;
222                                         safestrncpy(CC->cs_inet_email,
223                                                 addr,
224                                                 sizeof(CC->cs_inet_email)
225                                         );
226                                 }
227                         }
228                         free(addr);
229                 }
230                 else {
231                         continue_searching = 0;
232                 }
233         } while(continue_searching);
234 }
235
236
237
238 /*
239  * This handler detects whether the user is attempting to save a new
240  * vCard as part of his/her personal configuration, and handles the replace
241  * function accordingly (delete the user's existing vCard in the config room
242  * and in the global address book).
243  */
244 int vcard_upload_beforesave(struct CtdlMessage *msg) {
245         char *ptr;
246         char *s;
247         int linelen;
248         char buf[SIZ];
249         struct ctdluser usbuf;
250         long what_user;
251         struct vCard *v = NULL;
252         char *ser = NULL;
253         int i = 0;
254         int yes_my_citadel_config = 0;
255         int yes_any_vcard_room = 0;
256
257         if (!CC->logged_in) return(0);  /* Only do this if logged in. */
258
259         /* Is this some user's "My Citadel Config" room? */
260         if ( (CC->room.QRflags && QR_MAILBOX)
261            && (!strcasecmp(&CC->room.QRname[11], USERCONFIGROOM)) ) {
262                 /* Yes, we want to do this */
263                 yes_my_citadel_config = 1;
264         }
265
266         /* Is this a room with an address book in it? */
267         if (CC->curr_view == VIEW_ADDRESSBOOK) {
268                 yes_any_vcard_room = 1;
269         }
270
271         /* If neither condition exists, don't run this hook. */
272         if ( (!yes_my_citadel_config) && (!yes_any_vcard_room) ) {
273                 return(0);
274         }
275
276         /* If this isn't a MIME message, don't bother. */
277         if (msg->cm_format_type != 4) return(0);
278
279         /* Ok, if we got this far, look into the situation further... */
280
281         ptr = msg->cm_fields['M'];
282         if (ptr == NULL) return(0);
283         while (ptr != NULL) {
284         
285                 linelen = strcspn(ptr, "\n");
286                 if (linelen == 0) return(0);    /* end of headers */    
287                 
288                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
289
290
291                         if (yes_my_citadel_config) {
292                                 /* Bingo!  The user is uploading a new vCard, so
293                                  * delete the old one.  First, figure out which user
294                                  * is being re-registered...
295                                  */
296                                 what_user = atol(CC->room.QRname);
297         
298                                 if (what_user == CC->user.usernum) {
299                                         /* It's the logged in user.  That was easy. */
300                                         memcpy(&usbuf, &CC->user,
301                                                 sizeof(struct ctdluser) );
302                                 }
303                                 
304                                 else if (getuserbynumber(&usbuf, what_user) == 0) {
305                                         /* We fetched a valid user record */
306                                 }
307                         
308                                 else {
309                                         /* No user with that number! */
310                                         return(0);
311                                 }
312         
313                                 /* Delete the user's old vCard.  This would probably
314                                  * get taken care of by the replication check, but we
315                                  * want to make sure there is absolutely only one
316                                  * vCard in the user's config room at all times.
317                                  */
318                                 CtdlDeleteMessages(CC->room.QRname,
319                                                 0L, "text/x-vcard", 1);
320
321                                 /* Make the author of the message the name of the user.
322                                  */
323                                 if (msg->cm_fields['A'] != NULL) {
324                                         free(msg->cm_fields['A']);
325                                 }
326                                 msg->cm_fields['A'] = strdup(usbuf.fullname);
327                         }
328
329                         /* Manipulate the vCard data structure */
330                         v = vcard_load(msg->cm_fields['M']);
331                         if (v != NULL) {
332
333                                 /* Insert or replace RFC2739-compliant free/busy URL */
334                                 if (yes_my_citadel_config) {
335                                         sprintf(buf, "http://%s/%s.vfb",
336                                                 config.c_fqdn,
337                                                 usbuf.fullname);
338                                         for (i=0; i<strlen(buf); ++i) {
339                                                 if (buf[i] == ' ') buf[i] = '_';
340                                         }
341                                         vcard_set_prop(v, "FBURL;PREF", buf, 0);
342                                 }
343
344                                 /* If this is an address book room, and the vCard has
345                                  * no UID, then give it one.
346                                  */
347                                 if (yes_any_vcard_room) {
348                                         s = vcard_get_prop(v, "UID", 0, 0, 0);
349                                         if (s == NULL) {
350                                                 generate_uuid(buf);
351                                                 vcard_set_prop(v, "UID", buf, 0);
352                                         }
353                                 }
354
355                                 /* Enforce local UID policy if applicable */
356                                 if (yes_my_citadel_config) {
357                                         snprintf(buf, sizeof buf, VCARD_EXT_FORMAT,
358                                                 msg->cm_fields['A'], NODENAME);
359                                         vcard_set_prop(v, "UID", buf, 0);
360                                 }
361
362                                 /* 
363                                  * Set the EUID of the message to the UID of the vCard.
364                                  */
365                                 if (msg->cm_fields['E'] != NULL) free(msg->cm_fields['E']);
366                                 s = vcard_get_prop(v, "UID", 0, 0, 0);
367                                 if (s != NULL) {
368                                         msg->cm_fields['E'] = strdup(s);
369                                         if (msg->cm_fields['U'] == NULL) {
370                                                 msg->cm_fields['U'] = strdup(s);
371                                         }
372                                 }
373
374                                 /*
375                                  * Set the Subject to the name in the vCard.
376                                  */
377                                 s = vcard_get_prop(v, "FN", 0, 0, 0);
378                                 if (s == NULL) {
379                                         s = vcard_get_prop(v, "N", 0, 0, 0);
380                                 }
381                                 if (s != NULL) {
382                                         if (msg->cm_fields['U'] != NULL) {
383                                                 free(msg->cm_fields['U']);
384                                         }
385                                         msg->cm_fields['U'] = strdup(s);
386                                 }
387
388                                 /* Re-serialize it back into the msg body */
389                                 ser = vcard_serialize(v);
390                                 if (ser != NULL) {
391                                         msg->cm_fields['M'] = realloc(
392                                                 msg->cm_fields['M'],
393                                                 strlen(ser) + 1024
394                                         );
395                                         sprintf(msg->cm_fields['M'],
396                                                 "Content-type: text/x-vcard"
397                                                 "\r\n\r\n%s\r\n", ser);
398                                         free(ser);
399                                 }
400                                 vcard_free(v);
401                         }
402
403                         /* Now allow the save to complete. */
404                         return(0);
405                 }
406
407                 ptr = strchr((char *)ptr, '\n');
408                 if (ptr != NULL) ++ptr;
409         }
410
411         return(0);
412 }
413
414
415
416 /*
417  * This handler detects whether the user is attempting to save a new
418  * vCard as part of his/her personal configuration, and handles the replace
419  * function accordingly (copy the vCard from the config room to the global
420  * address book).
421  */
422 int vcard_upload_aftersave(struct CtdlMessage *msg) {
423         char *ptr;
424         int linelen;
425         long I;
426         struct vCard *v;
427
428         if (!CC->logged_in) return(0);  /* Only do this if logged in. */
429
430         /* If this isn't the configuration room, or if this isn't a MIME
431          * message, don't bother.
432          */
433         if (msg->cm_fields['O'] == NULL) return(0);
434         if (strcasecmp(msg->cm_fields['O'], USERCONFIGROOM)) return(0);
435         if (msg->cm_format_type != 4) return(0);
436
437         ptr = msg->cm_fields['M'];
438         if (ptr == NULL) return(0);
439         while (ptr != NULL) {
440         
441                 linelen = strcspn(ptr, "\n");
442                 if (linelen == 0) return(0);    /* end of headers */    
443                 
444                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
445                         /* Bingo!  The user is uploading a new vCard, so
446                          * copy it to the Global Address Book room.
447                          */
448
449                         I = atol(msg->cm_fields['I']);
450                         if (I < 0L) return(0);
451
452                         /* Store our Internet return address in memory */
453                         v = vcard_load(msg->cm_fields['M']);
454                         vcard_populate_cs_inet_email(v);
455                         vcard_free(v);
456
457                         /* Put it in the Global Address Book room... */
458                         CtdlSaveMsgPointerInRoom(ADDRESS_BOOK_ROOM, I, 1, msg);
459
460                         /* ...and also in the directory database. */
461                         vcard_add_to_directory(I, NULL);
462
463                         /* Some sites want an Aide to be notified when a
464                          * user registers or re-registers...
465                          */
466                         set_mm_valid();
467
468                         /* ...which also means we need to flag the user */
469                         lgetuser(&CC->user, CC->curr_user);
470                         CC->user.flags |= (US_REGIS|US_NEEDVALID);
471                         lputuser(&CC->user);
472
473                         return(0);
474                 }
475
476                 ptr = strchr((char *)ptr, '\n');
477                 if (ptr != NULL) ++ptr;
478         }
479
480         return(0);
481 }
482
483
484
485 /*
486  * back end function used for callbacks
487  */
488 void vcard_gu_backend(long supplied_msgnum, void *userdata) {
489         long *msgnum;
490
491         msgnum = (long *) userdata;
492         *msgnum = supplied_msgnum;
493 }
494
495
496 /*
497  * If this user has a vcard on disk, read it into memory, otherwise allocate
498  * and return an empty vCard.
499  */
500 struct vCard *vcard_get_user(struct ctdluser *u) {
501         char hold_rm[ROOMNAMELEN];
502         char config_rm[ROOMNAMELEN];
503         struct CtdlMessage *msg;
504         struct vCard *v;
505         long VCmsgnum;
506
507         strcpy(hold_rm, CC->room.QRname);       /* save current room */
508         MailboxName(config_rm, sizeof config_rm, u, USERCONFIGROOM);
509
510         if (getroom(&CC->room, config_rm) != 0) {
511                 getroom(&CC->room, hold_rm);
512                 return vcard_new();
513         }
514
515         /* We want the last (and probably only) vcard in this room */
516         VCmsgnum = (-1);
517         CtdlForEachMessage(MSGS_LAST, 1, "text/x-vcard",
518                 NULL, vcard_gu_backend, (void *)&VCmsgnum );
519         getroom(&CC->room, hold_rm);    /* return to saved room */
520
521         if (VCmsgnum < 0L) return vcard_new();
522
523         msg = CtdlFetchMessage(VCmsgnum, 1);
524         if (msg == NULL) return vcard_new();
525
526         v = vcard_load(msg->cm_fields['M']);
527         CtdlFreeMessage(msg);
528         return v;
529 }
530
531
532 /*
533  * Store this user's vCard in the appropriate place
534  */
535 /*
536  * Write our config to disk
537  */
538 void vcard_write_user(struct ctdluser *u, struct vCard *v) {
539         char temp[PATH_MAX];
540         FILE *fp;
541         char *ser;
542
543         strcpy(temp, tmpnam(NULL));
544         ser = vcard_serialize(v);
545
546         fp = fopen(temp, "w");
547         if (fp == NULL) return;
548         if (ser == NULL) {
549                 fprintf(fp, "begin:vcard\r\nend:vcard\r\n");
550         } else {
551                 fwrite(ser, strlen(ser), 1, fp);
552                 free(ser);
553         }
554         fclose(fp);
555
556         /* This handy API function does all the work for us.
557          * NOTE: normally we would want to set that last argument to 1, to
558          * force the system to delete the user's old vCard.  But it doesn't
559          * have to, because the vcard_upload_beforesave() hook above
560          * is going to notice what we're trying to do, and delete the old vCard.
561          */
562         CtdlWriteObject(USERCONFIGROOM, /* which room */
563                         "text/x-vcard", /* MIME type */
564                         temp,           /* temp file */
565                         u,              /* which user */
566                         0,              /* not binary */
567                         0,              /* don't delete others of this type */
568                         0);             /* no flags */
569
570         unlink(temp);
571 }
572
573
574
575 /*
576  * Old style "enter registration info" command.  This function simply honors
577  * the REGI protocol command, translates the entered parameters into a vCard,
578  * and enters the vCard into the user's configuration.
579  */
580 void cmd_regi(char *argbuf) {
581         int a,b,c;
582         char buf[SIZ];
583         struct vCard *my_vcard;
584
585         char tmpaddr[SIZ];
586         char tmpcity[SIZ];
587         char tmpstate[SIZ];
588         char tmpzip[SIZ];
589         char tmpaddress[SIZ];
590         char tmpcountry[SIZ];
591
592         unbuffer_output();
593
594         if (!(CC->logged_in)) {
595                 cprintf("%d Not logged in.\n",ERROR + NOT_LOGGED_IN);
596                 return;
597         }
598
599         my_vcard = vcard_get_user(&CC->user);
600         strcpy(tmpaddr, "");
601         strcpy(tmpcity, "");
602         strcpy(tmpstate, "");
603         strcpy(tmpzip, "");
604         strcpy(tmpcountry, "USA");
605
606         cprintf("%d Send registration...\n", SEND_LISTING);
607         a=0;
608         while (client_getln(buf, sizeof buf), strcmp(buf,"000")) {
609                 if (a==0) vcard_set_prop(my_vcard, "n", buf, 0);
610                 if (a==1) strcpy(tmpaddr, buf);
611                 if (a==2) strcpy(tmpcity, buf);
612                 if (a==3) strcpy(tmpstate, buf);
613                 if (a==4) {
614                         for (c=0; c<strlen(buf); ++c) {
615                                 if ((buf[c]>='0') && (buf[c]<='9')) {
616                                         b = strlen(tmpzip);
617                                         tmpzip[b] = buf[c];
618                                         tmpzip[b+1] = 0;
619                                 }
620                         }
621                 }
622                 if (a==5) vcard_set_prop(my_vcard, "tel;home", buf, 0);
623                 if (a==6) vcard_set_prop(my_vcard, "email;internet", buf, 0);
624                 if (a==7) strcpy(tmpcountry, buf);
625                 ++a;
626         }
627
628         snprintf(tmpaddress, sizeof tmpaddress, ";;%s;%s;%s;%s;%s",
629                 tmpaddr, tmpcity, tmpstate, tmpzip, tmpcountry);
630         vcard_set_prop(my_vcard, "adr", tmpaddress, 0);
631         vcard_write_user(&CC->user, my_vcard);
632         vcard_free(my_vcard);
633 }
634
635
636 /*
637  * Protocol command to fetch registration info for a user
638  */
639 void cmd_greg(char *argbuf)
640 {
641         struct ctdluser usbuf;
642         struct vCard *v;
643         char *s;
644         char who[USERNAME_SIZE];
645         char adr[256];
646         char buf[256];
647
648         extract_token(who, argbuf, 0, '|', sizeof who);
649
650         if (!(CC->logged_in)) {
651                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
652                 return;
653         }
654
655         if (!strcasecmp(who,"_SELF_")) strcpy(who,CC->curr_user);
656
657         if ((CC->user.axlevel < 6) && (strcasecmp(who,CC->curr_user))) {
658                 cprintf("%d Higher access required.\n",
659                         ERROR + HIGHER_ACCESS_REQUIRED);
660                 return;
661         }
662
663         if (getuser(&usbuf, who) != 0) {
664                 cprintf("%d '%s' not found.\n", ERROR + NO_SUCH_USER, who);
665                 return;
666         }
667
668         v = vcard_get_user(&usbuf);
669
670         cprintf("%d %s\n", LISTING_FOLLOWS, usbuf.fullname);
671         cprintf("%ld\n", usbuf.usernum);
672         cprintf("%s\n", usbuf.password);
673         s = vcard_get_prop(v, "n", 0, 0, 0);
674         cprintf("%s\n", s ? s : " ");   /* name */
675
676         s = vcard_get_prop(v, "adr", 0, 0, 0);
677         snprintf(adr, sizeof adr, "%s", s ? s : " ");/* address... */
678
679         extract_token(buf, adr, 2, ';', sizeof buf);
680         cprintf("%s\n", buf);                           /* street */
681         extract_token(buf, adr, 3, ';', sizeof buf);
682         cprintf("%s\n", buf);                           /* city */
683         extract_token(buf, adr, 4, ';', sizeof buf);
684         cprintf("%s\n", buf);                           /* state */
685         extract_token(buf, adr, 5, ';', sizeof buf);
686         cprintf("%s\n", buf);                           /* zip */
687
688         s = vcard_get_prop(v, "tel;home", 0, 0, 0);
689         if (s == NULL) s = vcard_get_prop(v, "tel", 1, 0, 0);
690         if (s != NULL) {
691                 cprintf("%s\n", s);
692         }
693         else {
694                 cprintf(" \n");
695         }
696
697         cprintf("%d\n", usbuf.axlevel);
698
699         s = vcard_get_prop(v, "email;internet", 0, 0, 0);
700         cprintf("%s\n", s ? s : " ");
701         s = vcard_get_prop(v, "adr", 0, 0, 0);
702         snprintf(adr, sizeof adr, "%s", s ? s : " ");/* address... */
703
704         extract_token(buf, adr, 6, ';', sizeof buf);
705         cprintf("%s\n", buf);                           /* country */
706         cprintf("000\n");
707 }
708
709
710
711 /*
712  * When a user is being created, create his/her vCard.
713  */
714 void vcard_newuser(struct ctdluser *usbuf) {
715         char vname[256];
716         char buf[256];
717         int i;
718         struct vCard *v;
719
720         vcard_fn_to_n(vname, usbuf->fullname, sizeof vname);
721         lprintf(CTDL_DEBUG, "Converted <%s> to <%s>\n", usbuf->fullname, vname);
722
723         /* Create and save the vCard */
724         v = vcard_new();
725         if (v == NULL) return;
726         sprintf(buf, "%s@%s", usbuf->fullname, config.c_fqdn);
727         for (i=0; i<strlen(buf); ++i) {
728                 if (buf[i] == ' ') buf[i] = '_';
729         }
730         vcard_add_prop(v, "fn", usbuf->fullname);
731         vcard_add_prop(v, "n", vname);
732         vcard_add_prop(v, "adr", "adr:;;_;_;_;00000;__");
733         vcard_add_prop(v, "email;internet", buf);
734         vcard_write_user(usbuf, v);
735         vcard_free(v);
736 }
737
738
739 /*
740  * When a user is being deleted, we have to remove his/her vCard.
741  * This is accomplished by issuing a message with 'CANCEL' in the S (special)
742  * field, and the same Exclusive ID as the existing card.
743  */
744 void vcard_purge(struct ctdluser *usbuf) {
745         struct CtdlMessage *msg;
746         char buf[SIZ];
747
748         msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
749         if (msg == NULL) return;
750         memset(msg, 0, sizeof(struct CtdlMessage));
751
752         msg->cm_magic = CTDLMESSAGE_MAGIC;
753         msg->cm_anon_type = MES_NORMAL;
754         msg->cm_format_type = 0;
755         msg->cm_fields['A'] = strdup(usbuf->fullname);
756         msg->cm_fields['O'] = strdup(ADDRESS_BOOK_ROOM);
757         msg->cm_fields['N'] = strdup(NODENAME);
758         msg->cm_fields['M'] = strdup("Purge this vCard\n");
759
760         snprintf(buf, sizeof buf, VCARD_EXT_FORMAT,
761                         msg->cm_fields['A'], NODENAME);
762         msg->cm_fields['E'] = strdup(buf);
763
764         msg->cm_fields['S'] = strdup("CANCEL");
765
766         CtdlSubmitMsg(msg, NULL, ADDRESS_BOOK_ROOM);
767         CtdlFreeMessage(msg);
768 }
769
770
771 /*
772  * Grab vCard directory stuff out of incoming network messages
773  */
774 int vcard_extract_from_network(struct CtdlMessage *msg, char *target_room) {
775         char *ptr;
776         int linelen;
777
778         if (msg == NULL) return(0);
779
780         if (strcasecmp(target_room, ADDRESS_BOOK_ROOM)) {
781                 return(0);
782         }
783
784         if (msg->cm_format_type != 4) return(0);
785
786         ptr = msg->cm_fields['M'];
787         if (ptr == NULL) return(0);
788         while (ptr != NULL) {
789         
790                 linelen = strcspn(ptr, "\n");
791                 if (linelen == 0) return(0);    /* end of headers */    
792                 
793                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
794                          /* It's a vCard.  Add it to the directory. */
795                         vcard_extract_internet_addresses(msg,
796                                                         CtdlDirectoryAddUser);
797                         return(0);
798                 }
799
800                 ptr = strchr((char *)ptr, '\n');
801                 if (ptr != NULL) ++ptr;
802         }
803
804         return(0);
805 }
806
807
808
809 /* 
810  * When a vCard is being removed from the Global Address Book room, remove it
811  * from the directory as well.
812  */
813 void vcard_delete_remove(char *room, long msgnum) {
814         struct CtdlMessage *msg;
815         char *ptr;
816         int linelen;
817
818         if (msgnum <= 0L) return;
819
820         if (strcasecmp(room, ADDRESS_BOOK_ROOM)) {
821                 return;
822         }
823
824         msg = CtdlFetchMessage(msgnum, 1);
825         if (msg == NULL) return;
826
827         ptr = msg->cm_fields['M'];
828         if (ptr == NULL) goto EOH;
829         while (ptr != NULL) {
830                 linelen = strcspn(ptr, "\n");
831                 if (linelen == 0) goto EOH;
832                 
833                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
834                         /* Bingo!  A vCard is being deleted.
835                         */
836                         vcard_extract_internet_addresses(msg,
837                                                         CtdlDirectoryDelUser);
838 #ifdef HAVE_LDAP
839                         ctdl_vcard_to_ldap(msg, V2L_DELETE);
840 #endif
841                 }
842                 ptr = strchr((char *)ptr, '\n');
843                 if (ptr != NULL) ++ptr;
844         }
845
846 EOH:    CtdlFreeMessage(msg);
847 }
848
849
850
851 /*
852  * Query Directory
853  */
854 void cmd_qdir(char *argbuf) {
855         char citadel_addr[256];
856         char internet_addr[256];
857
858         if (CtdlAccessCheck(ac_logged_in)) return;
859
860         extract_token(internet_addr, argbuf, 0, '|', sizeof internet_addr);
861
862         if (CtdlDirectoryLookup(citadel_addr, internet_addr, sizeof citadel_addr) != 0) {
863                 cprintf("%d %s was not found.\n",
864                         ERROR + NO_SUCH_USER, internet_addr);
865                 return;
866         }
867
868         cprintf("%d %s\n", CIT_OK, citadel_addr);
869 }
870
871
872 /*
873  * We don't know if the Contacts room exists so we just create it at login
874  */
875 void vcard_create_room(void)
876 {
877         struct ctdlroom qr;
878         struct visit vbuf;
879
880         /* Create the calendar room if it doesn't already exist */
881         create_room(USERCONTACTSROOM, 4, "", 0, 1, 0, VIEW_ADDRESSBOOK);
882
883         /* Set expiration policy to manual; otherwise objects will be lost! */
884         if (lgetroom(&qr, USERCONTACTSROOM)) {
885                 lprintf(CTDL_ERR, "Couldn't get the user CONTACTS room!\n");
886                 return;
887         }
888         qr.QRep.expire_mode = EXPIRE_MANUAL;
889         qr.QRdefaultview = VIEW_ADDRESSBOOK;    /* 2 = address book view */
890         lputroom(&qr);
891
892         /* Set the view to a calendar view */
893         CtdlGetRelationship(&vbuf, &CC->user, &qr);
894         vbuf.v_view = 2;        /* 2 = address book view */
895         CtdlSetRelationship(&vbuf, &CC->user, &qr);
896
897         return;
898 }
899
900
901
902
903 /*
904  * When a user logs in...
905  */
906 void vcard_session_login_hook(void) {
907         struct vCard *v;
908
909         v = vcard_get_user(&CC->user);
910         vcard_populate_cs_inet_email(v);
911
912         vcard_free(v);
913
914         vcard_create_room();
915 }
916
917
918 /* 
919  * Turn an arbitrary RFC822 address into a struct vCard for possible
920  * inclusion into an address book.
921  */
922 struct vCard *vcard_new_from_rfc822_addr(char *addr) {
923         struct vCard *v;
924         char user[256], node[256], name[256], email[256], n[256], uid[256];
925         int i;
926
927         v = vcard_new();
928         if (v == NULL) return(NULL);
929
930         process_rfc822_addr(addr, user, node, name);
931         vcard_set_prop(v, "fn", name, 0);
932
933         vcard_fn_to_n(n, name, sizeof n);
934         vcard_set_prop(v, "n", n, 0);
935
936         snprintf(email, sizeof email, "%s@%s", user, node);
937         vcard_set_prop(v, "email;internet", email, 0);
938
939         snprintf(uid, sizeof uid, "collected: %s %s@%s", name, user, node);
940         for (i=0; i<strlen(uid); ++i) {
941                 if (isspace(uid[i])) uid[i] = '_';
942                 uid[i] = tolower(uid[i]);
943         }
944         vcard_set_prop(v, "UID", uid, 0);
945
946         return(v);
947 }
948
949
950
951 /*
952  * This is called by store_harvested_addresses() to remove from the
953  * list any addresses we already have in our address book.
954  */
955 void strip_addresses_already_have(long msgnum, void *userdata) {
956         char *collected_addresses;
957         struct CtdlMessage *msg;
958         struct vCard *v;
959         char *value = NULL;
960         int i, j;
961         char addr[256], user[256], node[256], name[256];
962
963         collected_addresses = (char *)userdata;
964
965         msg = CtdlFetchMessage(msgnum, 1);
966         if (msg == NULL) return;
967         v = vcard_load(msg->cm_fields['M']);
968         CtdlFreeMessage(msg);
969
970         i = 0;
971         while (value = vcard_get_prop(v, "email", 1, i++, 0), value != NULL) {
972
973                 for (j=0; j<num_tokens(collected_addresses, ','); ++j) {
974                         extract_token(addr, collected_addresses, j, ',', sizeof addr);
975
976                         /* Remove the address if we already have it! */
977                         process_rfc822_addr(addr, user, node, name);
978                         snprintf(addr, sizeof addr, "%s@%s", user, node);
979                         if (!strcasecmp(value, addr)) {
980                                 remove_token(collected_addresses, j, ',');
981                         }
982                 }
983
984         }
985
986         vcard_free(v);
987 }
988
989
990
991 /*
992  * Back end function for store_harvested_addresses()
993  */
994 void store_this_ha(struct addresses_to_be_filed *aptr) {
995         struct CtdlMessage *vmsg = NULL;
996         long vmsgnum = (-1L);
997         char *ser = NULL;
998         struct vCard *v = NULL;
999         char recipient[256];
1000         int i;
1001
1002         /* First remove any addresses we already have in the address book */
1003         usergoto(aptr->roomname, 0, 0, NULL, NULL);
1004         CtdlForEachMessage(MSGS_ALL, 0, "text/x-vcard", NULL,
1005                 strip_addresses_already_have, aptr->collected_addresses);
1006
1007         if (strlen(aptr->collected_addresses) > 0)
1008            for (i=0; i<num_tokens(aptr->collected_addresses, ','); ++i) {
1009
1010                 /* Make a vCard out of each address */
1011                 extract_token(recipient, aptr->collected_addresses, i, ',', sizeof recipient);
1012                 striplt(recipient);
1013                 v = vcard_new_from_rfc822_addr(recipient);
1014                 if (v != NULL) {
1015                         vmsg = malloc(sizeof(struct CtdlMessage));
1016                         memset(vmsg, 0, sizeof(struct CtdlMessage));
1017                         vmsg->cm_magic = CTDLMESSAGE_MAGIC;
1018                         vmsg->cm_anon_type = MES_NORMAL;
1019                         vmsg->cm_format_type = FMT_RFC822;
1020                         vmsg->cm_fields['A'] = strdup("Citadel");
1021                         vmsg->cm_fields['E'] =  strdup(vcard_get_prop(v, "UID", 0, 0, 0));
1022                         ser = vcard_serialize(v);
1023                         if (ser != NULL) {
1024                                 vmsg->cm_fields['M'] = malloc(strlen(ser) + 1024);
1025                                 sprintf(vmsg->cm_fields['M'],
1026                                         "Content-type: text/x-vcard"
1027                                         "\r\n\r\n%s\r\n", ser);
1028                                 free(ser);
1029                         }
1030                         vcard_free(v);
1031
1032                         lprintf(CTDL_DEBUG, "Adding contact: %s\n", recipient);
1033                         vmsgnum = CtdlSubmitMsg(vmsg, NULL, aptr->roomname);
1034                         CtdlFreeMessage(vmsg);
1035                 }
1036         }
1037
1038         free(aptr->roomname);
1039         free(aptr->collected_addresses);
1040         free(aptr);
1041 }
1042
1043
1044 /*
1045  * When a user sends a message, we may harvest one or more email addresses
1046  * from the recipient list to be added to the user's address book.  But we
1047  * want to do this asynchronously so it doesn't keep the user waiting.
1048  */
1049 void store_harvested_addresses(void) {
1050
1051         struct addresses_to_be_filed *aptr = NULL;
1052
1053         if (atbf == NULL) return;
1054
1055         begin_critical_section(S_ATBF);
1056         while (atbf != NULL) {
1057                 aptr = atbf;
1058                 atbf = atbf->next;
1059                 end_critical_section(S_ATBF);
1060                 store_this_ha(aptr);
1061                 begin_critical_section(S_ATBF);
1062         }
1063         end_critical_section(S_ATBF);
1064 }
1065
1066
1067 char *serv_vcard_init(void)
1068 {
1069         struct ctdlroom qr;
1070
1071         CtdlRegisterSessionHook(vcard_session_login_hook, EVT_LOGIN);
1072         CtdlRegisterMessageHook(vcard_upload_beforesave, EVT_BEFORESAVE);
1073         CtdlRegisterMessageHook(vcard_upload_aftersave, EVT_AFTERSAVE);
1074         CtdlRegisterDeleteHook(vcard_delete_remove);
1075         CtdlRegisterProtoHook(cmd_regi, "REGI", "Enter registration info");
1076         CtdlRegisterProtoHook(cmd_greg, "GREG", "Get registration info");
1077         CtdlRegisterProtoHook(cmd_igab, "IGAB",
1078                                         "Initialize Global Address Book");
1079         CtdlRegisterProtoHook(cmd_qdir, "QDIR", "Query Directory");
1080         CtdlRegisterUserHook(vcard_newuser, EVT_NEWUSER);
1081         CtdlRegisterUserHook(vcard_purge, EVT_PURGEUSER);
1082         CtdlRegisterNetprocHook(vcard_extract_from_network);
1083         CtdlRegisterSessionHook(store_harvested_addresses, EVT_TIMER);
1084
1085         /* Create the Global ADdress Book room if necessary */
1086         create_room(ADDRESS_BOOK_ROOM, 3, "", 0, 1, 0, VIEW_ADDRESSBOOK);
1087
1088         /* Set expiration policy to manual; otherwise objects will be lost! */
1089         if (!lgetroom(&qr, ADDRESS_BOOK_ROOM)) {
1090                 qr.QRep.expire_mode = EXPIRE_MANUAL;
1091                 qr.QRdefaultview = VIEW_ADDRESSBOOK;    /* 2 = address book view */
1092                 lputroom(&qr);
1093         }
1094
1095         return "$Id$";
1096 }