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