* added message subject to all those tiny messages
[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,
326                                                 NULL, 0, "text/x-vcard", 1);
327
328                                 /* Make the author of the message the name of the user.
329                                  */
330                                 if (msg->cm_fields['A'] != NULL) {
331                                         free(msg->cm_fields['A']);
332                                 }
333                                 msg->cm_fields['A'] = strdup(usbuf.fullname);
334                         }
335
336                         /* Manipulate the vCard data structure */
337                         v = vcard_load(msg->cm_fields['M']);
338                         if (v != NULL) {
339
340                                 /* Insert or replace RFC2739-compliant free/busy URL */
341                                 if (yes_my_citadel_config) {
342                                         sprintf(buf, "http://%s/%s.vfb",
343                                                 config.c_fqdn,
344                                                 usbuf.fullname);
345                                         for (i=0; i<strlen(buf); ++i) {
346                                                 if (buf[i] == ' ') buf[i] = '_';
347                                         }
348                                         vcard_set_prop(v, "FBURL;PREF", buf, 0);
349                                 }
350
351                                 /* If this is an address book room, and the vCard has
352                                  * no UID, then give it one.
353                                  */
354                                 if (yes_any_vcard_room) {
355                                         s = vcard_get_prop(v, "UID", 0, 0, 0);
356                                         if (s == NULL) {
357                                                 generate_uuid(buf);
358                                                 vcard_set_prop(v, "UID", buf, 0);
359                                         }
360                                 }
361
362                                 /* Enforce local UID policy if applicable */
363                                 if (yes_my_citadel_config) {
364                                         snprintf(buf, sizeof buf, VCARD_EXT_FORMAT,
365                                                 msg->cm_fields['A'], NODENAME);
366                                         vcard_set_prop(v, "UID", buf, 0);
367                                 }
368
369                                 /* 
370                                  * Set the EUID of the message to the UID of the vCard.
371                                  */
372                                 if (msg->cm_fields['E'] != NULL) free(msg->cm_fields['E']);
373                                 s = vcard_get_prop(v, "UID", 0, 0, 0);
374                                 if (s != NULL) {
375                                         msg->cm_fields['E'] = strdup(s);
376                                         if (msg->cm_fields['U'] == NULL) {
377                                                 msg->cm_fields['U'] = strdup(s);
378                                         }
379                                 }
380
381                                 /*
382                                  * Set the Subject to the name in the vCard.
383                                  */
384                                 s = vcard_get_prop(v, "FN", 0, 0, 0);
385                                 if (s == NULL) {
386                                         s = vcard_get_prop(v, "N", 0, 0, 0);
387                                 }
388                                 if (s != NULL) {
389                                         if (msg->cm_fields['U'] != NULL) {
390                                                 free(msg->cm_fields['U']);
391                                         }
392                                         msg->cm_fields['U'] = strdup(s);
393                                 }
394
395                                 /* Re-serialize it back into the msg body */
396                                 ser = vcard_serialize(v);
397                                 if (ser != NULL) {
398                                         msg->cm_fields['M'] = realloc(
399                                                 msg->cm_fields['M'],
400                                                 strlen(ser) + 1024
401                                         );
402                                         sprintf(msg->cm_fields['M'],
403                                                 "Content-type: text/x-vcard"
404                                                 "\r\n\r\n%s\r\n", ser);
405                                         free(ser);
406                                 }
407                                 vcard_free(v);
408                         }
409
410                         /* Now allow the save to complete. */
411                         return(0);
412                 }
413
414                 ptr = strchr((char *)ptr, '\n');
415                 if (ptr != NULL) ++ptr;
416         }
417
418         return(0);
419 }
420
421
422
423 /*
424  * This handler detects whether the user is attempting to save a new
425  * vCard as part of his/her personal configuration, and handles the replace
426  * function accordingly (copy the vCard from the config room to the global
427  * address book).
428  */
429 int vcard_upload_aftersave(struct CtdlMessage *msg) {
430         char *ptr;
431         int linelen;
432         long I;
433         struct vCard *v;
434
435         if (!CC->logged_in) return(0);  /* Only do this if logged in. */
436
437         /* If this isn't the configuration room, or if this isn't a MIME
438          * message, don't bother.
439          */
440         if (msg->cm_fields['O'] == NULL) return(0);
441         if (strcasecmp(msg->cm_fields['O'], USERCONFIGROOM)) return(0);
442         if (msg->cm_format_type != 4) return(0);
443
444         ptr = msg->cm_fields['M'];
445         if (ptr == NULL) return(0);
446         while (ptr != NULL) {
447         
448                 linelen = strcspn(ptr, "\n");
449                 if (linelen == 0) return(0);    /* end of headers */    
450                 
451                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
452                         /* Bingo!  The user is uploading a new vCard, so
453                          * copy it to the Global Address Book room.
454                          */
455
456                         I = atol(msg->cm_fields['I']);
457                         if (I < 0L) return(0);
458
459                         /* Store our Internet return address in memory */
460                         v = vcard_load(msg->cm_fields['M']);
461                         extract_primary_inet_email(CC->cs_inet_email,
462                                                 sizeof CC->cs_inet_email, v);
463                         vcard_free(v);
464
465                         /* Put it in the Global Address Book room... */
466                         CtdlSaveMsgPointerInRoom(ADDRESS_BOOK_ROOM, I, 1, msg);
467
468                         /* ...and also in the directory database. */
469                         vcard_add_to_directory(I, NULL);
470
471                         /* Some sites want an Aide to be notified when a
472                          * user registers or re-registers...
473                          */
474                         set_mm_valid();
475
476                         /* ...which also means we need to flag the user */
477                         lgetuser(&CC->user, CC->curr_user);
478                         CC->user.flags |= (US_REGIS|US_NEEDVALID);
479                         lputuser(&CC->user);
480
481                         return(0);
482                 }
483
484                 ptr = strchr((char *)ptr, '\n');
485                 if (ptr != NULL) ++ptr;
486         }
487
488         return(0);
489 }
490
491
492
493 /*
494  * back end function used for callbacks
495  */
496 void vcard_gu_backend(long supplied_msgnum, void *userdata) {
497         long *msgnum;
498
499         msgnum = (long *) userdata;
500         *msgnum = supplied_msgnum;
501 }
502
503
504 /*
505  * If this user has a vcard on disk, read it into memory, otherwise allocate
506  * and return an empty vCard.
507  */
508 struct vCard *vcard_get_user(struct ctdluser *u) {
509         char hold_rm[ROOMNAMELEN];
510         char config_rm[ROOMNAMELEN];
511         struct CtdlMessage *msg;
512         struct vCard *v;
513         long VCmsgnum;
514
515         strcpy(hold_rm, CC->room.QRname);       /* save current room */
516         MailboxName(config_rm, sizeof config_rm, u, USERCONFIGROOM);
517
518         if (getroom(&CC->room, config_rm) != 0) {
519                 getroom(&CC->room, hold_rm);
520                 return vcard_new();
521         }
522
523         /* We want the last (and probably only) vcard in this room */
524         VCmsgnum = (-1);
525         CtdlForEachMessage(MSGS_LAST, 1, NULL, "text/x-vcard",
526                 NULL, vcard_gu_backend, (void *)&VCmsgnum );
527         getroom(&CC->room, hold_rm);    /* return to saved room */
528
529         if (VCmsgnum < 0L) return vcard_new();
530
531         msg = CtdlFetchMessage(VCmsgnum, 1);
532         if (msg == NULL) return vcard_new();
533
534         v = vcard_load(msg->cm_fields['M']);
535         CtdlFreeMessage(msg);
536         return v;
537 }
538
539
540 /*
541  * Store this user's vCard in the appropriate place
542  */
543 /*
544  * Write our config to disk
545  */
546 void vcard_write_user(struct ctdluser *u, struct vCard *v) {
547         char temp[PATH_MAX];
548         FILE *fp;
549         char *ser;
550
551         CtdlMakeTempFileName(temp, sizeof temp);
552         ser = vcard_serialize(v);
553
554         fp = fopen(temp, "w");
555         if (fp == NULL) return;
556         if (ser == NULL) {
557                 fprintf(fp, "begin:vcard\r\nend:vcard\r\n");
558         } else {
559                 fwrite(ser, strlen(ser), 1, fp);
560                 free(ser);
561         }
562         fclose(fp);
563
564         /* This handy API function does all the work for us.
565          * NOTE: normally we would want to set that last argument to 1, to
566          * force the system to delete the user's old vCard.  But it doesn't
567          * have to, because the vcard_upload_beforesave() hook above
568          * is going to notice what we're trying to do, and delete the old vCard.
569          */
570         CtdlWriteObject(USERCONFIGROOM, /* which room */
571                         "text/x-vcard", /* MIME type */
572                         temp,           /* temp file */
573                         u,              /* which user */
574                         0,              /* not binary */
575                         0,              /* don't delete others of this type */
576                         0);             /* no flags */
577
578         unlink(temp);
579 }
580
581
582
583 /*
584  * Old style "enter registration info" command.  This function simply honors
585  * the REGI protocol command, translates the entered parameters into a vCard,
586  * and enters the vCard into the user's configuration.
587  */
588 void cmd_regi(char *argbuf) {
589         int a,b,c;
590         char buf[SIZ];
591         struct vCard *my_vcard;
592
593         char tmpaddr[SIZ];
594         char tmpcity[SIZ];
595         char tmpstate[SIZ];
596         char tmpzip[SIZ];
597         char tmpaddress[SIZ];
598         char tmpcountry[SIZ];
599
600         unbuffer_output();
601
602         if (!(CC->logged_in)) {
603                 cprintf("%d Not logged in.\n",ERROR + NOT_LOGGED_IN);
604                 return;
605         }
606
607         my_vcard = vcard_get_user(&CC->user);
608         strcpy(tmpaddr, "");
609         strcpy(tmpcity, "");
610         strcpy(tmpstate, "");
611         strcpy(tmpzip, "");
612         strcpy(tmpcountry, "USA");
613
614         cprintf("%d Send registration...\n", SEND_LISTING);
615         a=0;
616         while (client_getln(buf, sizeof buf), strcmp(buf,"000")) {
617                 if (a==0) vcard_set_prop(my_vcard, "n", buf, 0);
618                 if (a==1) strcpy(tmpaddr, buf);
619                 if (a==2) strcpy(tmpcity, buf);
620                 if (a==3) strcpy(tmpstate, buf);
621                 if (a==4) {
622                         for (c=0; c<strlen(buf); ++c) {
623                                 if ((buf[c]>='0') && (buf[c]<='9')) {
624                                         b = strlen(tmpzip);
625                                         tmpzip[b] = buf[c];
626                                         tmpzip[b+1] = 0;
627                                 }
628                         }
629                 }
630                 if (a==5) vcard_set_prop(my_vcard, "tel;home", buf, 0);
631                 if (a==6) vcard_set_prop(my_vcard, "email;internet", buf, 0);
632                 if (a==7) strcpy(tmpcountry, buf);
633                 ++a;
634         }
635
636         snprintf(tmpaddress, sizeof tmpaddress, ";;%s;%s;%s;%s;%s",
637                 tmpaddr, tmpcity, tmpstate, tmpzip, tmpcountry);
638         vcard_set_prop(my_vcard, "adr", tmpaddress, 0);
639         vcard_write_user(&CC->user, my_vcard);
640         vcard_free(my_vcard);
641 }
642
643
644 /*
645  * Protocol command to fetch registration info for a user
646  */
647 void cmd_greg(char *argbuf)
648 {
649         struct ctdluser usbuf;
650         struct vCard *v;
651         char *s;
652         char who[USERNAME_SIZE];
653         char adr[256];
654         char buf[256];
655
656         extract_token(who, argbuf, 0, '|', sizeof who);
657
658         if (!(CC->logged_in)) {
659                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
660                 return;
661         }
662
663         if (!strcasecmp(who,"_SELF_")) strcpy(who,CC->curr_user);
664
665         if ((CC->user.axlevel < 6) && (strcasecmp(who,CC->curr_user))) {
666                 cprintf("%d Higher access required.\n",
667                         ERROR + HIGHER_ACCESS_REQUIRED);
668                 return;
669         }
670
671         if (getuser(&usbuf, who) != 0) {
672                 cprintf("%d '%s' not found.\n", ERROR + NO_SUCH_USER, who);
673                 return;
674         }
675
676         v = vcard_get_user(&usbuf);
677
678         cprintf("%d %s\n", LISTING_FOLLOWS, usbuf.fullname);
679         cprintf("%ld\n", usbuf.usernum);
680         cprintf("%s\n", usbuf.password);
681         s = vcard_get_prop(v, "n", 0, 0, 0);
682         cprintf("%s\n", s ? s : " ");   /* name */
683
684         s = vcard_get_prop(v, "adr", 0, 0, 0);
685         snprintf(adr, sizeof adr, "%s", s ? s : " ");/* address... */
686
687         extract_token(buf, adr, 2, ';', sizeof buf);
688         cprintf("%s\n", buf);                           /* street */
689         extract_token(buf, adr, 3, ';', sizeof buf);
690         cprintf("%s\n", buf);                           /* city */
691         extract_token(buf, adr, 4, ';', sizeof buf);
692         cprintf("%s\n", buf);                           /* state */
693         extract_token(buf, adr, 5, ';', sizeof buf);
694         cprintf("%s\n", buf);                           /* zip */
695
696         s = vcard_get_prop(v, "tel;home", 0, 0, 0);
697         if (s == NULL) s = vcard_get_prop(v, "tel", 1, 0, 0);
698         if (s != NULL) {
699                 cprintf("%s\n", s);
700         }
701         else {
702                 cprintf(" \n");
703         }
704
705         cprintf("%d\n", usbuf.axlevel);
706
707         s = vcard_get_prop(v, "email;internet", 0, 0, 0);
708         cprintf("%s\n", s ? s : " ");
709         s = vcard_get_prop(v, "adr", 0, 0, 0);
710         snprintf(adr, sizeof adr, "%s", s ? s : " ");/* address... */
711
712         extract_token(buf, adr, 6, ';', sizeof buf);
713         cprintf("%s\n", buf);                           /* country */
714         cprintf("000\n");
715 }
716
717
718
719 /*
720  * When a user is being created, create his/her vCard.
721  */
722 void vcard_newuser(struct ctdluser *usbuf) {
723         char vname[256];
724         char buf[256];
725         int i;
726         struct vCard *v;
727
728         vcard_fn_to_n(vname, usbuf->fullname, sizeof vname);
729         lprintf(CTDL_DEBUG, "Converted <%s> to <%s>\n", usbuf->fullname, vname);
730
731         /* Create and save the vCard */
732         v = vcard_new();
733         if (v == NULL) return;
734         sprintf(buf, "%s@%s", usbuf->fullname, config.c_fqdn);
735         for (i=0; i<strlen(buf); ++i) {
736                 if (buf[i] == ' ') buf[i] = '_';
737         }
738         vcard_add_prop(v, "fn", usbuf->fullname);
739         vcard_add_prop(v, "n", vname);
740         vcard_add_prop(v, "adr", "adr:;;_;_;_;00000;__");
741         vcard_add_prop(v, "email;internet", buf);
742         vcard_write_user(usbuf, v);
743         vcard_free(v);
744 }
745
746
747 /*
748  * When a user is being deleted, we have to remove his/her vCard.
749  * This is accomplished by issuing a message with 'CANCEL' in the S (special)
750  * field, and the same Exclusive ID as the existing card.
751  */
752 void vcard_purge(struct ctdluser *usbuf) {
753         struct CtdlMessage *msg;
754         char buf[SIZ];
755
756         msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
757         if (msg == NULL) return;
758         memset(msg, 0, sizeof(struct CtdlMessage));
759
760         msg->cm_magic = CTDLMESSAGE_MAGIC;
761         msg->cm_anon_type = MES_NORMAL;
762         msg->cm_format_type = 0;
763         msg->cm_fields['A'] = strdup(usbuf->fullname);
764         msg->cm_fields['O'] = strdup(ADDRESS_BOOK_ROOM);
765         msg->cm_fields['N'] = strdup(NODENAME);
766         msg->cm_fields['M'] = strdup("Purge this vCard\n");
767
768         snprintf(buf, sizeof buf, VCARD_EXT_FORMAT,
769                         msg->cm_fields['A'], NODENAME);
770         msg->cm_fields['E'] = strdup(buf);
771
772         msg->cm_fields['S'] = strdup("CANCEL");
773
774         CtdlSubmitMsg(msg, NULL, ADDRESS_BOOK_ROOM);
775         CtdlFreeMessage(msg);
776 }
777
778
779 /*
780  * Grab vCard directory stuff out of incoming network messages
781  */
782 int vcard_extract_from_network(struct CtdlMessage *msg, char *target_room) {
783         char *ptr;
784         int linelen;
785
786         if (msg == NULL) return(0);
787
788         if (strcasecmp(target_room, ADDRESS_BOOK_ROOM)) {
789                 return(0);
790         }
791
792         if (msg->cm_format_type != 4) return(0);
793
794         ptr = msg->cm_fields['M'];
795         if (ptr == NULL) return(0);
796         while (ptr != NULL) {
797         
798                 linelen = strcspn(ptr, "\n");
799                 if (linelen == 0) return(0);    /* end of headers */    
800                 
801                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
802                          /* It's a vCard.  Add it to the directory. */
803                         vcard_extract_internet_addresses(msg,
804                                                         CtdlDirectoryAddUser);
805                         return(0);
806                 }
807
808                 ptr = strchr((char *)ptr, '\n');
809                 if (ptr != NULL) ++ptr;
810         }
811
812         return(0);
813 }
814
815
816
817 /* 
818  * When a vCard is being removed from the Global Address Book room, remove it
819  * from the directory as well.
820  */
821 void vcard_delete_remove(char *room, long msgnum) {
822         struct CtdlMessage *msg;
823         char *ptr;
824         int linelen;
825
826         if (msgnum <= 0L) return;
827
828         if (strcasecmp(room, ADDRESS_BOOK_ROOM)) {
829                 return;
830         }
831
832         msg = CtdlFetchMessage(msgnum, 1);
833         if (msg == NULL) return;
834
835         ptr = msg->cm_fields['M'];
836         if (ptr == NULL) goto EOH;
837         while (ptr != NULL) {
838                 linelen = strcspn(ptr, "\n");
839                 if (linelen == 0) goto EOH;
840                 
841                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
842                         /* Bingo!  A vCard is being deleted.
843                         */
844                         vcard_extract_internet_addresses(msg,
845                                                         CtdlDirectoryDelUser);
846 #ifdef HAVE_LDAP
847                         ctdl_vcard_to_ldap(msg, V2L_DELETE);
848 #endif
849                 }
850                 ptr = strchr((char *)ptr, '\n');
851                 if (ptr != NULL) ++ptr;
852         }
853
854 EOH:    CtdlFreeMessage(msg);
855 }
856
857
858
859 /*
860  * Query Directory
861  */
862 void cmd_qdir(char *argbuf) {
863         char citadel_addr[256];
864         char internet_addr[256];
865
866         if (CtdlAccessCheck(ac_logged_in)) return;
867
868         extract_token(internet_addr, argbuf, 0, '|', sizeof internet_addr);
869
870         if (CtdlDirectoryLookup(citadel_addr, internet_addr, sizeof citadel_addr) != 0) {
871                 cprintf("%d %s was not found.\n",
872                         ERROR + NO_SUCH_USER, internet_addr);
873                 return;
874         }
875
876         cprintf("%d %s\n", CIT_OK, citadel_addr);
877 }
878
879 /*
880  * Query Directory, in fact an alias to match postfix tcp auth.
881  */
882 void check_get(void) {
883         char internet_addr[256];
884
885         char cmdbuf[SIZ];
886
887         time(&CC->lastcmd);
888         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
889         if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
890                 lprintf(CTDL_CRIT, "Client disconnected: ending session.\n");
891                 CC->kill_me = 1;
892                 return;
893         }
894         lprintf(CTDL_INFO, ": %s\n", cmdbuf);
895         while (strlen(cmdbuf) < 3) strcat(cmdbuf, " ");
896
897         if (strcasecmp(cmdbuf, "GET "));
898         {
899                 struct recptypes *rcpt;
900                 char *argbuf = &cmdbuf[4];
901                 
902                 extract_token(internet_addr, argbuf, 0, '|', sizeof internet_addr);
903                 rcpt = validate_recipients(internet_addr);
904                 if ((rcpt != NULL)&&
905                         (
906                          (*rcpt->recp_local != '\0')||
907                          (*rcpt->recp_room != '\0')||
908                          (*rcpt->recp_ignet != '\0')))
909                 {
910
911                         cprintf("200 OK %s\n", internet_addr);
912                         lprintf(CTDL_INFO, "sending 200 OK for the room %s\n", rcpt->display_recp);
913                 }
914                 else 
915                 {
916                         cprintf("500 REJECT noone here by that name.\n");
917                         
918                         lprintf(CTDL_INFO, "sending 500 REJECT noone here by that name: %s\n", internet_addr);
919                 }
920                 if (rcpt != NULL) free (rcpt);
921         }
922 ///     CC->kill_me = 1;
923 }
924
925 void check_get_greeting(void) {
926 /* dummy function, we have no greeting in this verry simple protocol. */
927 }
928
929
930 /*
931  * We don't know if the Contacts room exists so we just create it at login
932  */
933 void vcard_create_room(void)
934 {
935         struct ctdlroom qr;
936         struct visit vbuf;
937
938         /* Create the calendar room if it doesn't already exist */
939         create_room(USERCONTACTSROOM, 4, "", 0, 1, 0, VIEW_ADDRESSBOOK);
940
941         /* Set expiration policy to manual; otherwise objects will be lost! */
942         if (lgetroom(&qr, USERCONTACTSROOM)) {
943                 lprintf(CTDL_ERR, "Couldn't get the user CONTACTS room!\n");
944                 return;
945         }
946         qr.QRep.expire_mode = EXPIRE_MANUAL;
947         qr.QRdefaultview = VIEW_ADDRESSBOOK;    /* 2 = address book view */
948         lputroom(&qr);
949
950         /* Set the view to a calendar view */
951         CtdlGetRelationship(&vbuf, &CC->user, &qr);
952         vbuf.v_view = 2;        /* 2 = address book view */
953         CtdlSetRelationship(&vbuf, &CC->user, &qr);
954
955         return;
956 }
957
958
959
960
961 /*
962  * When a user logs in...
963  */
964 void vcard_session_login_hook(void) {
965         struct vCard *v;
966
967         v = vcard_get_user(&CC->user);
968         extract_primary_inet_email(CC->cs_inet_email,
969                                 sizeof CC->cs_inet_email, v);
970         vcard_free(v);
971
972         vcard_create_room();
973 }
974
975
976 /* 
977  * Turn an arbitrary RFC822 address into a struct vCard for possible
978  * inclusion into an address book.
979  */
980 struct vCard *vcard_new_from_rfc822_addr(char *addr) {
981         struct vCard *v;
982         char user[256], node[256], name[256], email[256], n[256], uid[256];
983         int i;
984
985         v = vcard_new();
986         if (v == NULL) return(NULL);
987
988         process_rfc822_addr(addr, user, node, name);
989         vcard_set_prop(v, "fn", name, 0);
990
991         vcard_fn_to_n(n, name, sizeof n);
992         vcard_set_prop(v, "n", n, 0);
993
994         snprintf(email, sizeof email, "%s@%s", user, node);
995         vcard_set_prop(v, "email;internet", email, 0);
996
997         snprintf(uid, sizeof uid, "collected: %s %s@%s", name, user, node);
998         for (i=0; i<strlen(uid); ++i) {
999                 if (isspace(uid[i])) uid[i] = '_';
1000                 uid[i] = tolower(uid[i]);
1001         }
1002         vcard_set_prop(v, "UID", uid, 0);
1003
1004         return(v);
1005 }
1006
1007
1008
1009 /*
1010  * This is called by store_harvested_addresses() to remove from the
1011  * list any addresses we already have in our address book.
1012  */
1013 void strip_addresses_already_have(long msgnum, void *userdata) {
1014         char *collected_addresses;
1015         struct CtdlMessage *msg;
1016         struct vCard *v;
1017         char *value = NULL;
1018         int i, j;
1019         char addr[256], user[256], node[256], name[256];
1020
1021         collected_addresses = (char *)userdata;
1022
1023         msg = CtdlFetchMessage(msgnum, 1);
1024         if (msg == NULL) return;
1025         v = vcard_load(msg->cm_fields['M']);
1026         CtdlFreeMessage(msg);
1027
1028         i = 0;
1029         while (value = vcard_get_prop(v, "email", 1, i++, 0), value != NULL) {
1030
1031                 for (j=0; j<num_tokens(collected_addresses, ','); ++j) {
1032                         extract_token(addr, collected_addresses, j, ',', sizeof addr);
1033
1034                         /* Remove the address if we already have it! */
1035                         process_rfc822_addr(addr, user, node, name);
1036                         snprintf(addr, sizeof addr, "%s@%s", user, node);
1037                         if (!strcasecmp(value, addr)) {
1038                                 remove_token(collected_addresses, j, ',');
1039                         }
1040                 }
1041
1042         }
1043
1044         vcard_free(v);
1045 }
1046
1047
1048
1049 /*
1050  * Back end function for store_harvested_addresses()
1051  */
1052 void store_this_ha(struct addresses_to_be_filed *aptr) {
1053         struct CtdlMessage *vmsg = NULL;
1054         long vmsgnum = (-1L);
1055         char *ser = NULL;
1056         struct vCard *v = NULL;
1057         char recipient[256];
1058         int i;
1059
1060         /* First remove any addresses we already have in the address book */
1061         usergoto(aptr->roomname, 0, 0, NULL, NULL);
1062         CtdlForEachMessage(MSGS_ALL, 0, NULL, "text/x-vcard", NULL,
1063                 strip_addresses_already_have, aptr->collected_addresses);
1064
1065         if (strlen(aptr->collected_addresses) > 0)
1066            for (i=0; i<num_tokens(aptr->collected_addresses, ','); ++i) {
1067
1068                 /* Make a vCard out of each address */
1069                 extract_token(recipient, aptr->collected_addresses, i, ',', sizeof recipient);
1070                 striplt(recipient);
1071                 v = vcard_new_from_rfc822_addr(recipient);
1072                 if (v != NULL) {
1073                         vmsg = malloc(sizeof(struct CtdlMessage));
1074                         memset(vmsg, 0, sizeof(struct CtdlMessage));
1075                         vmsg->cm_magic = CTDLMESSAGE_MAGIC;
1076                         vmsg->cm_anon_type = MES_NORMAL;
1077                         vmsg->cm_format_type = FMT_RFC822;
1078                         vmsg->cm_fields['A'] = strdup("Citadel");
1079                         vmsg->cm_fields['E'] =  strdup(vcard_get_prop(v, "UID", 0, 0, 0));
1080                         ser = vcard_serialize(v);
1081                         if (ser != NULL) {
1082                                 vmsg->cm_fields['M'] = malloc(strlen(ser) + 1024);
1083                                 sprintf(vmsg->cm_fields['M'],
1084                                         "Content-type: text/x-vcard"
1085                                         "\r\n\r\n%s\r\n", ser);
1086                                 free(ser);
1087                         }
1088                         vcard_free(v);
1089
1090                         lprintf(CTDL_DEBUG, "Adding contact: %s\n", recipient);
1091                         vmsgnum = CtdlSubmitMsg(vmsg, NULL, aptr->roomname);
1092                         CtdlFreeMessage(vmsg);
1093                 }
1094         }
1095
1096         free(aptr->roomname);
1097         free(aptr->collected_addresses);
1098         free(aptr);
1099 }
1100
1101
1102 /*
1103  * When a user sends a message, we may harvest one or more email addresses
1104  * from the recipient list to be added to the user's address book.  But we
1105  * want to do this asynchronously so it doesn't keep the user waiting.
1106  */
1107 void store_harvested_addresses(void) {
1108
1109         struct addresses_to_be_filed *aptr = NULL;
1110
1111         if (atbf == NULL) return;
1112
1113         begin_critical_section(S_ATBF);
1114         while (atbf != NULL) {
1115                 aptr = atbf;
1116                 atbf = atbf->next;
1117                 end_critical_section(S_ATBF);
1118                 store_this_ha(aptr);
1119                 begin_critical_section(S_ATBF);
1120         }
1121         end_critical_section(S_ATBF);
1122 }
1123
1124
1125 /* 
1126  * Function to output vCard data as plain text.  Nobody uses MSG0 anymore, so
1127  * really this is just so we expose the vCard data to the full text indexer.
1128  */
1129 void vcard_fixed_output(char *ptr, int len) {
1130         char *serialized_vcard;
1131         struct vCard *v;
1132         char *key, *value;
1133         int i = 0;
1134
1135         serialized_vcard = malloc(len + 1);
1136         safestrncpy(serialized_vcard, ptr, len+1);
1137         v = vcard_load(serialized_vcard);
1138         free(serialized_vcard);
1139
1140         i = 0;
1141         while (key = vcard_get_prop(v, "", 0, i, 1), key != NULL) {
1142                 value = vcard_get_prop(v, "", 0, i++, 0);
1143                 cprintf("%s\n", value);
1144         }
1145
1146         vcard_free(v);
1147 }
1148
1149
1150
1151 char *serv_vcard_init(void)
1152 {
1153         struct ctdlroom qr;
1154         char filename[256];
1155         FILE *fp;
1156
1157         CtdlRegisterSessionHook(vcard_session_login_hook, EVT_LOGIN);
1158         CtdlRegisterMessageHook(vcard_upload_beforesave, EVT_BEFORESAVE);
1159         CtdlRegisterMessageHook(vcard_upload_aftersave, EVT_AFTERSAVE);
1160         CtdlRegisterDeleteHook(vcard_delete_remove);
1161         CtdlRegisterProtoHook(cmd_regi, "REGI", "Enter registration info");
1162         CtdlRegisterProtoHook(cmd_greg, "GREG", "Get registration info");
1163         CtdlRegisterProtoHook(cmd_igab, "IGAB",
1164                                         "Initialize Global Address Book");
1165         CtdlRegisterProtoHook(cmd_qdir, "QDIR", "Query Directory");
1166         CtdlRegisterUserHook(vcard_newuser, EVT_NEWUSER);
1167         CtdlRegisterUserHook(vcard_purge, EVT_PURGEUSER);
1168         CtdlRegisterNetprocHook(vcard_extract_from_network);
1169         CtdlRegisterSessionHook(store_harvested_addresses, EVT_TIMER);
1170         CtdlRegisterFixedOutputHook("text/x-vcard", vcard_fixed_output);
1171
1172         /* Create the Global ADdress Book room if necessary */
1173         create_room(ADDRESS_BOOK_ROOM, 3, "", 0, 1, 0, VIEW_ADDRESSBOOK);
1174
1175         /* Set expiration policy to manual; otherwise objects will be lost! */
1176         if (!lgetroom(&qr, ADDRESS_BOOK_ROOM)) {
1177                 qr.QRep.expire_mode = EXPIRE_MANUAL;
1178                 qr.QRdefaultview = VIEW_ADDRESSBOOK;    /* 2 = address book view */
1179                 lputroom(&qr);
1180
1181                 /*
1182                  * Also make sure it has a netconfig file, so the networker runs
1183                  * on this room even if we don't share it with any other nodes.
1184                  * This allows the CANCEL messages (i.e. "Purge this vCard") to be
1185                  * purged.
1186                  */
1187                 assoc_file_name(filename, sizeof filename, &qr, ctdl_netcfg_dir);
1188                 fp = fopen(filename, "a");
1189                 if (fp != NULL) fclose(fp);
1190                 chown(filename, CTDLUID, (-1));
1191         }
1192
1193         return "$Id$";
1194 }
1195
1196
1197 char *serv_postfix_tcpdict(void)
1198 {
1199         CtdlRegisterServiceHook(config.c_pftcpdict_port,        /* Postfix */
1200                                 NULL,
1201                                 check_get_greeting,
1202                                 check_get,
1203                                 NULL);
1204         return "$Id$";
1205 }