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