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