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