]> code.citadel.org Git - citadel.git/blob - citadel/modules/vcard/serv_vcard.c
Big change to the ldap code to break its dependancy on serv_vcard.c and
[citadel.git] / citadel / modules / vcard / 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  * Citadel will accept either text/vcard or text/x-vcard as the MIME type
20  * for a vCard.  The following definition determines which one it *generates*
21  * when serializing.
22  */
23 #define VCARD_MIME_TYPE         "text/x-vcard"
24
25 #include "sysdep.h"
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <stdio.h>
29 #include <fcntl.h>
30 #include <signal.h>
31 #include <pwd.h>
32 #include <errno.h>
33 #include <ctype.h>
34 #include <sys/types.h>
35
36 #if TIME_WITH_SYS_TIME
37 # include <sys/time.h>
38 # include <time.h>
39 #else
40 # if HAVE_SYS_TIME_H
41 #  include <sys/time.h>
42 # else
43 #  include <time.h>
44 # endif
45 #endif
46
47 #include <sys/wait.h>
48 #include <string.h>
49 #include <limits.h>
50 #include "citadel.h"
51 #include "server.h"
52 #include "citserver.h"
53 #include "support.h"
54 #include "config.h"
55 #include "control.h"
56 #include "room_ops.h"
57 #include "user_ops.h"
58 #include "policy.h"
59 #include "database.h"
60 #include "msgbase.h"
61 #include "internet_addressing.h"
62 #include "tools.h"
63 #include "mime_parser.h"
64 #include "vcard.h"
65 #include "serv_vcard.h"
66
67 #include "ctdl_module.h"
68
69
70
71 /*
72  * set global flag calling for an aide to validate new users
73  */
74 void set_mm_valid(void) {
75         begin_critical_section(S_CONTROL);
76         get_control();
77         CitControl.MMflags = CitControl.MMflags | MM_VALID ;
78         put_control();
79         end_critical_section(S_CONTROL);
80 }
81
82
83
84 /*
85  * Extract Internet e-mail addresses from a message containing a vCard, and
86  * perform a callback for any found.
87  */
88 void vcard_extract_internet_addresses(struct CtdlMessage *msg,
89                                 void (*callback)(char *, char *) ) {
90         struct vCard *v;
91         char *s;
92         char *addr;
93         char citadel_address[SIZ];
94         int instance = 0;
95         int found_something = 0;
96
97         if (msg->cm_fields['A'] == NULL) return;
98         if (msg->cm_fields['N'] == NULL) return;
99         snprintf(citadel_address, sizeof citadel_address, "%s @ %s",
100                 msg->cm_fields['A'], msg->cm_fields['N']);
101
102         v = vcard_load(msg->cm_fields['M']);
103         if (v == NULL) return;
104
105         /* Go through the vCard searching for *all* instances of
106          * the "email;internet" key
107          */
108         do {
109                 s = vcard_get_prop(v, "email;internet", 0, instance++, 0);
110                 if (s != NULL) {
111                         addr = strdup(s);
112                         striplt(addr);
113                         if (!IsEmptyStr(addr)) {
114                                 if (callback != NULL) {
115                                         callback(addr, citadel_address);
116                                 }
117                         }
118                         free(addr);
119                         found_something = 1;
120                 }
121                 else {
122                         found_something = 0;
123                 }
124         } while(found_something);
125
126         vcard_free(v);
127 }
128
129
130 /* 
131  * vCard-to-LDAP conversions.
132  *
133  * If 'op' is set to V2L_WRITE, then write
134  * (add, or change if already exists) a directory entry to the
135  * LDAP server, based on the information supplied in a vCard.
136  *
137  * If 'op' is set to V2L_DELETE, then delete the entry from LDAP.
138  */
139  
140  
141 void ctdl_vcard_to_ldap(struct CtdlMessage *msg, int op) {
142         struct vCard *v = NULL;
143         int i;
144         int num_emails = 0;
145         int num_phones = 0;
146         int have_addr = 0;
147         int have_cn = 0;
148         
149         void *objectlist = NULL;
150
151         char givenname[128];
152         char sn[128];
153         char uid[256];
154         char street[256];
155         char city[128];
156         char state[3];
157         char zipcode[10];
158         char calFBURL[256];
159
160         if (msg == NULL) return;
161         if (msg->cm_fields['M'] == NULL) return;
162         if (msg->cm_fields['A'] == NULL) return;
163         if (msg->cm_fields['N'] == NULL) return;
164
165         /* Initialize variables */
166         strcpy(givenname, "");
167         strcpy(sn, "");
168         strcpy(calFBURL, "");
169
170         sprintf(uid, "%s@%s",
171                 msg->cm_fields['A'],
172                 msg->cm_fields['N']
173         );
174
175         /* Are we just deleting?  If so, it's simple... */
176         if (op == V2L_DELETE) {
177                 (void) CtdlDoDirectoryServiceFunc (msg->cm_fields['A'], msg->cm_fields['N'], NULL, "ldap", DIRECTORY_USER_DEL);
178                 return;
179         }
180
181         /*
182          * If we get to this point then it must be a V2L_WRITE operation.
183          */
184
185         /* First make sure the OU for the user's home Citadel host is created */
186         (void) CtdlDoDirectoryServiceFunc (NULL, msg->cm_fields['N'], NULL, "ldap", DIRECTORY_CREATE_HOST);
187         
188         /* Next create the directory service object */
189         (void) CtdlDoDirectoryServiceFunc(NULL, NULL, &objectlist, "ldap", DIRECTORY_CREATE_OBJECT);
190
191         /* The first LDAP attribute will be an 'objectclass' list.  Citadel
192          * doesn't do anything with this.  It's just there for compatibility
193          * with Kolab.
194          */
195         (void) CtdlDoDirectoryServiceFunc("objectclass", "citadelInetOrgPerson", &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
196
197         /* Convert the vCard fields to LDAP properties */
198         v = vcard_load(msg->cm_fields['M']);
199         if (v->numprops) for (i=0; i<(v->numprops); ++i) if (striplt(v->prop[i].value), strlen(v->prop[i].value) > 0) {
200
201                 if (!strcasecmp(v->prop[i].name, "n")) {
202                         extract_token(sn,               v->prop[i].value, 0, ';', sizeof sn);
203                         extract_token(givenname,        v->prop[i].value, 1, ';', sizeof givenname);
204                 }
205
206                 if (!strcasecmp(v->prop[i].name, "fn")) {
207                         (void) CtdlDoDirectoryServiceFunc("cn", v->prop[i].value, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
208                         have_cn = 1;
209                 }
210
211                 if (!strcasecmp(v->prop[i].name, "title")) {
212                         (void) CtdlDoDirectoryServiceFunc("title", v->prop[i].value, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
213                 }
214
215                 if (!strcasecmp(v->prop[i].name, "org")) {
216                         (void) CtdlDoDirectoryServiceFunc("o", v->prop[i].value, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
217                 }
218
219                 if ( (!strcasecmp(v->prop[i].name, "adr"))
220                    ||(!strncasecmp(v->prop[i].name, "adr;", 4)) ) {
221                         /* Unfortunately, we can only do a single address */
222                         if (!have_addr) {
223                                 have_addr = 1;
224                                 strcpy(street, "");
225                                 extract_token(&street[strlen(street)],
226                                         v->prop[i].value, 0, ';', (sizeof street - strlen(street))); /* po box */
227                                 strcat(street, " ");
228                                 extract_token(&street[strlen(street)],
229                                         v->prop[i].value, 1, ';', (sizeof street - strlen(street))); /* extend addr */
230                                 strcat(street, " ");
231                                 extract_token(&street[strlen(street)],
232                                         v->prop[i].value, 2, ';', (sizeof street - strlen(street))); /* street */
233                                 striplt(street);
234                                 extract_token(city, v->prop[i].value, 3, ';', sizeof city);
235                                 extract_token(state, v->prop[i].value, 4, ';', sizeof state);
236                                 extract_token(zipcode, v->prop[i].value, 5, ';', sizeof zipcode);
237
238                                 (void) CtdlDoDirectoryServiceFunc("street", street, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
239                                 (void) CtdlDoDirectoryServiceFunc("l", city, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
240                                 (void) CtdlDoDirectoryServiceFunc("st", state, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
241                                 (void) CtdlDoDirectoryServiceFunc("postalcode", zipcode, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
242                         }
243                 }
244
245                 if ( (!strcasecmp(v->prop[i].name, "tel"))
246                    ||(!strncasecmp(v->prop[i].name, "tel;", 4)) ) {
247                         ++num_phones;
248                         /* The first 'tel' property creates the 'telephoneNumber' attribute */
249                         if (num_phones == 1) {
250                                 (void) CtdlDoDirectoryServiceFunc("telephoneNumber", v->prop[i].value, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
251                         }
252                         /* Subsequent 'tel' properties *add to* the 'telephoneNumber' attribute */
253                         else {
254                                 (void) CtdlDoDirectoryServiceFunc("telephoneNumber", v->prop[i].value, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
255                         }
256                 }
257
258
259                 if ( (!strcasecmp(v->prop[i].name, "email"))
260                    ||(!strcasecmp(v->prop[i].name, "email;internet")) ) {
261         
262                         ++num_emails;
263                         lprintf(CTDL_DEBUG, "email addr %d\n", num_emails);
264
265                         /* The first email address creates the 'mail' attribute */
266                         if (num_emails == 1) {
267                                 (void) CtdlDoDirectoryServiceFunc("mail", v->prop[i].value, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
268                         }
269                         /* The second and subsequent email address creates the 'alias' attribute */
270                         else if (num_emails >= 2) {
271                                 (void) CtdlDoDirectoryServiceFunc("alias", v->prop[i].value, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
272                         }
273                 }
274
275                 /* Calendar free/busy URL (take the first one we find, but if a subsequent
276                  * one contains the "pref" designation then we go with that instead.)
277                  */
278                 if ( (!strcasecmp(v->prop[i].name, "fburl"))
279                    ||(!strncasecmp(v->prop[i].name, "fburl;", 6)) ) {
280                         if ( (IsEmptyStr(calFBURL))
281                            || (!strncasecmp(v->prop[i].name, "fburl;pref", 10)) ) {
282                                 safestrncpy(calFBURL, v->prop[i].value, sizeof calFBURL);
283                         }
284                 }
285
286         }
287         vcard_free(v);  /* Don't need this anymore. */
288
289         /* "sn" (surname) based on info in vCard */
290         (void) CtdlDoDirectoryServiceFunc("sn", sn, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
291
292         /* "givenname" (first name) based on info in vCard */
293         if (IsEmptyStr(givenname)) strcpy(givenname, "_");
294         if (IsEmptyStr(sn)) strcpy(sn, "_");
295         (void) CtdlDoDirectoryServiceFunc("givenname", givenname, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
296
297         /* "uid" is a Kolab compatibility thing.  We just do cituser@citnode */
298         (void) CtdlDoDirectoryServiceFunc("uid", uid, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
299
300         /* Add a "cn" (Common Name) attribute based on the user's screen name,
301          * but only there was no 'fn' (full name) property in the vCard 
302          */
303         if (!have_cn) {
304                 (void) CtdlDoDirectoryServiceFunc("cn", msg->cm_fields['A'], &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
305         }
306
307         /* Add a "calFBURL" attribute if a calendar free/busy URL exists */
308         if (!IsEmptyStr(calFBURL)) {
309                 (void) CtdlDoDirectoryServiceFunc("calFBURL", calFBURL, &objectlist, "ldap", DIRECTORY_ATTRIB_ADD);
310         }
311         
312         (void) CtdlDoDirectoryServiceFunc(msg->cm_fields['A'], msg->cm_fields['N'], &objectlist, "ldap", DIRECTORY_SAVE_OBJECT);
313
314         (void) CtdlDoDirectoryServiceFunc(NULL, NULL, &objectlist, "ldap", DIRECTORY_FREE_OBJECT);
315         lprintf(CTDL_DEBUG, "LDAP write operation complete.\n");
316 }
317
318
319
320 /*
321  * Callback for vcard_add_to_directory()
322  * (Lotsa ugly nested callbacks.  Oh well.)
323  */
324 void vcard_directory_add_user(char *internet_addr, char *citadel_addr) {
325         char buf[SIZ];
326
327         /* We have to validate that we're not stepping on someone else's
328          * email address ... but only if we're logged in.  Otherwise it's
329          * probably just the networker or something.
330          */
331         if (CC->logged_in) {
332                 lprintf(CTDL_DEBUG, "Checking for <%s>...\n", internet_addr);
333                 if (CtdlDirectoryLookup(buf, internet_addr, sizeof buf) == 0) {
334                         if (strcasecmp(buf, citadel_addr)) {
335                                 /* This address belongs to someone else.
336                                  * Bail out silently without saving.
337                                  */
338                                 lprintf(CTDL_DEBUG, "DOOP!\n");
339                                 return;
340                         }
341                 }
342         }
343         lprintf(CTDL_INFO, "Adding %s (%s) to directory\n",
344                         citadel_addr, internet_addr);
345         CtdlDirectoryAddUser(internet_addr, citadel_addr);
346 }
347
348
349 /*
350  * Back end function for cmd_igab()
351  */
352 void vcard_add_to_directory(long msgnum, void *data) {
353         struct CtdlMessage *msg;
354
355         msg = CtdlFetchMessage(msgnum, 1);
356         if (msg != NULL) {
357                 vcard_extract_internet_addresses(msg, vcard_directory_add_user);
358         }
359
360 #ifdef HAVE_LDAP
361         ctdl_vcard_to_ldap(msg, V2L_WRITE);
362 #endif
363
364         CtdlFreeMessage(msg);
365 }
366
367
368 /*
369  * Initialize Global Adress Book
370  */
371 void cmd_igab(char *argbuf) {
372         char hold_rm[ROOMNAMELEN];
373
374         if (CtdlAccessCheck(ac_aide)) return;
375
376         strcpy(hold_rm, CC->room.QRname);       /* save current room */
377
378         if (getroom(&CC->room, ADDRESS_BOOK_ROOM) != 0) {
379                 getroom(&CC->room, hold_rm);
380                 cprintf("%d cannot get address book room\n", ERROR + ROOM_NOT_FOUND);
381                 return;
382         }
383
384         /* Empty the existing database first.
385          */
386         CtdlDirectoryInit();
387
388         /* We want *all* vCards in this room */
389         CtdlForEachMessage(MSGS_ALL, 0, NULL, "^[Tt][Ee][Xx][Tt]/.*[Vv][Cc][Aa][Rr][Dd]$",
390                 NULL, vcard_add_to_directory, NULL);
391
392         getroom(&CC->room, hold_rm);    /* return to saved room */
393         cprintf("%d Directory has been rebuilt.\n", CIT_OK);
394 }
395
396
397
398
399 /*
400  * See if there is a valid Internet address in a vCard to use for outbound
401  * Internet messages.  If there is, stick it in the buffer.
402  */
403 void extract_inet_email_addrs(char *emailaddrbuf, size_t emailaddrbuf_len,
404                                 char *secemailaddrbuf, size_t secemailaddrbuf_len,
405                                 struct vCard *v, int local_addrs_only) {
406         char *s, *addr;
407         int instance = 0;
408         int saved_instance = 0;
409
410         /* Go through the vCard searching for *all* instances of
411          * the "email;internet" key
412          */
413         while (s = vcard_get_prop(v, "email;internet", 0, instance++, 0),  s != NULL) {
414                 addr = strdup(s);
415                 striplt(addr);
416                 if (!IsEmptyStr(addr)) {
417                         if ( (IsDirectory(addr, 1)) || 
418                              (!local_addrs_only) ) {
419                                 ++saved_instance;
420                                 if ((saved_instance == 1) && (emailaddrbuf != NULL)) {
421                                         safestrncpy(emailaddrbuf, addr, emailaddrbuf_len);
422                                 }
423                                 else if ((saved_instance == 2) && (secemailaddrbuf != NULL)) {
424                                         safestrncpy(secemailaddrbuf, addr, secemailaddrbuf_len);
425                                 }
426                                 else if ((saved_instance > 2) && (secemailaddrbuf != NULL)) {
427                                         if ( (strlen(addr) + strlen(secemailaddrbuf) + 2) 
428                                            < secemailaddrbuf_len ) {
429                                                 strcat(secemailaddrbuf, "|");
430                                                 strcat(secemailaddrbuf, addr);
431                                         }
432                                 }
433                         }
434                 }
435                 free(addr);
436         }
437 }
438
439
440
441 /*
442  * See if there is a name / screen name / friendly name  in a vCard to use for outbound
443  * Internet messages.  If there is, stick it in the buffer.
444  */
445 void extract_friendly_name(char *namebuf, size_t namebuf_len, struct vCard *v)
446 {
447         char *s;
448
449         s = vcard_get_prop(v, "fn", 0, 0, 0);
450         if (s == NULL) {
451                 s = vcard_get_prop(v, "n", 0, 0, 0);
452         }
453
454         if (s != NULL) {
455                 safestrncpy(namebuf, s, namebuf_len);
456         }
457 }
458
459
460 /*
461  * Callback function for vcard_upload_beforesave() hunts for the real vcard in the MIME structure
462  */
463 void vcard_extract_vcard(char *name, char *filename, char *partnum, char *disp,
464                    void *content, char *cbtype, char *cbcharset, size_t length,
465                    char *encoding, void *cbuserdata)
466 {
467         struct vCard **v = (struct vCard **) cbuserdata;
468
469         if (  (!strcasecmp(cbtype, "text/x-vcard"))
470            || (!strcasecmp(cbtype, "text/vcard")) ) {
471
472                 lprintf(CTDL_DEBUG, "Part %s contains a vCard!  Loading...\n", partnum);
473                 if (*v != NULL) {
474                         vcard_free(*v);
475                 }
476                 *v = vcard_load(content);
477         }
478 }
479
480
481 /*
482  * This handler detects whether the user is attempting to save a new
483  * vCard as part of his/her personal configuration, and handles the replace
484  * function accordingly (delete the user's existing vCard in the config room
485  * and in the global address book).
486  */
487 int vcard_upload_beforesave(struct CtdlMessage *msg) {
488         char *ptr;
489         char *s;
490         char buf[SIZ];
491         struct ctdluser usbuf;
492         long what_user;
493         struct vCard *v = NULL;
494         char *ser = NULL;
495         int i = 0;
496         int yes_my_citadel_config = 0;
497         int yes_any_vcard_room = 0;
498
499         if (!CC->logged_in) return(0);  /* Only do this if logged in. */
500
501         /* Is this some user's "My Citadel Config" room? */
502         if ( (CC->room.QRflags && QR_MAILBOX)
503            && (!strcasecmp(&CC->room.QRname[11], USERCONFIGROOM)) ) {
504                 /* Yes, we want to do this */
505                 yes_my_citadel_config = 1;
506
507 #ifdef VCARD_SAVES_BY_AIDES_ONLY
508                 /* Prevent non-aides from performing registration changes */
509                 if (CC->user.axlevel < 6) {
510                         return(1);
511                 }
512 #endif
513
514         }
515
516         /* Is this a room with an address book in it? */
517         if (CC->room.QRdefaultview == VIEW_ADDRESSBOOK) {
518                 yes_any_vcard_room = 1;
519         }
520
521         /* If neither condition exists, don't run this hook. */
522         if ( (!yes_my_citadel_config) && (!yes_any_vcard_room) ) {
523                 return(0);
524         }
525
526         /* If this isn't a MIME message, don't bother. */
527         if (msg->cm_format_type != 4) return(0);
528
529         /* Ok, if we got this far, look into the situation further... */
530
531         ptr = msg->cm_fields['M'];
532         if (ptr == NULL) return(0);
533
534         mime_parser(msg->cm_fields['M'],
535                 NULL,
536                 *vcard_extract_vcard,
537                 NULL, NULL,
538                 &v,             /* user data ptr - put the vcard here */
539                 0
540         );
541
542         if (v == NULL) return(0);       /* no vCards were found in this message */
543
544         /* If users cannot create their own accounts, they cannot re-register either. */
545         if ( (yes_my_citadel_config) && (config.c_disable_newu) && (CC->user.axlevel < 6) ) {
546                 return(1);
547         }
548
549         s = vcard_get_prop(v, "FN", 0, 0, 0);
550         if (s) lprintf(CTDL_DEBUG, "vCard beforesave hook running for <%s>\n", s);
551
552         if (yes_my_citadel_config) {
553                 /* Bingo!  The user is uploading a new vCard, so
554                  * delete the old one.  First, figure out which user
555                  * is being re-registered...
556                  */
557                 what_user = atol(CC->room.QRname);
558
559                 if (what_user == CC->user.usernum) {
560                         /* It's the logged in user.  That was easy. */
561                         memcpy(&usbuf, &CC->user, sizeof(struct ctdluser));
562                 }
563                 
564                 else if (getuserbynumber(&usbuf, what_user) == 0) {
565                         /* We fetched a valid user record */
566                 }
567
568                 else {
569                         /* somebody set up us the bomb! */
570                         yes_my_citadel_config = 0;
571                 }
572         }
573         
574         if (yes_my_citadel_config) {
575                 /* Delete the user's old vCard.  This would probably
576                  * get taken care of by the replication check, but we
577                  * want to make sure there is absolutely only one
578                  * vCard in the user's config room at all times.
579                  *
580                  */
581                 CtdlDeleteMessages(CC->room.QRname, NULL, 0, "^[Tt][Ee][Xx][Tt]/.*[Vv][Cc][Aa][Rr][Dd]$");
582
583                 /* Make the author of the message the name of the user. */
584                 if (msg->cm_fields['A'] != NULL) {
585                         free(msg->cm_fields['A']);
586                 }
587                 msg->cm_fields['A'] = strdup(usbuf.fullname);
588         }
589
590         /* Insert or replace RFC2739-compliant free/busy URL */
591         if (yes_my_citadel_config) {
592                 sprintf(buf, "http://%s/%s.vfb",
593                         config.c_fqdn,
594                         usbuf.fullname);
595                 for (i=0; buf[i]; ++i) {
596                         if (buf[i] == ' ') buf[i] = '_';
597                 }
598                 vcard_set_prop(v, "FBURL;PREF", buf, 0);
599         }
600
601         /* If the vCard has no UID, then give it one. */
602         s = vcard_get_prop(v, "UID", 0, 0, 0);
603         if (s == NULL) {
604                 generate_uuid(buf);
605                 vcard_set_prop(v, "UID", buf, 0);
606         }
607
608         /* Enforce local UID policy if applicable */
609         if (yes_my_citadel_config) {
610                 snprintf(buf, sizeof buf, VCARD_EXT_FORMAT, msg->cm_fields['A'], NODENAME);
611                 vcard_set_prop(v, "UID", buf, 0);
612         }
613
614         /* 
615          * Set the EUID of the message to the UID of the vCard.
616          */
617         if (msg->cm_fields['E'] != NULL) free(msg->cm_fields['E']);
618         s = vcard_get_prop(v, "UID", 0, 0, 0);
619         if (s != NULL) {
620                 msg->cm_fields['E'] = strdup(s);
621                 if (msg->cm_fields['U'] == NULL) {
622                         msg->cm_fields['U'] = strdup(s);
623                 }
624         }
625
626         /*
627          * Set the Subject to the name in the vCard.
628          */
629         s = vcard_get_prop(v, "FN", 0, 0, 0);
630         if (s == NULL) {
631                 s = vcard_get_prop(v, "N", 0, 0, 0);
632         }
633         if (s != NULL) {
634                 if (msg->cm_fields['U'] != NULL) {
635                         free(msg->cm_fields['U']);
636                 }
637                 msg->cm_fields['U'] = strdup(s);
638         }
639
640         /* Re-serialize it back into the msg body */
641         ser = vcard_serialize(v);
642         if (ser != NULL) {
643                 msg->cm_fields['M'] = realloc(msg->cm_fields['M'], strlen(ser) + 1024);
644                 sprintf(msg->cm_fields['M'],
645                         "Content-type: " VCARD_MIME_TYPE
646                         "\r\n\r\n%s\r\n", ser);
647                 free(ser);
648         }
649
650         /* Now allow the save to complete. */
651         vcard_free(v);
652         return(0);
653 }
654
655
656
657 /*
658  * This handler detects whether the user is attempting to save a new
659  * vCard as part of his/her personal configuration, and handles the replace
660  * function accordingly (copy the vCard from the config room to the global
661  * address book).
662  */
663 int vcard_upload_aftersave(struct CtdlMessage *msg) {
664         char *ptr;
665         int linelen;
666         long I;
667         struct vCard *v;
668
669         if (!CC->logged_in) return(0);  /* Only do this if logged in. */
670
671         /* If this isn't the configuration room, or if this isn't a MIME
672          * message, don't bother.
673          */
674         if (msg->cm_fields['O'] == NULL) return(0);
675         if (strcasecmp(msg->cm_fields['O'], USERCONFIGROOM)) return(0);
676         if (msg->cm_format_type != 4) return(0);
677
678         ptr = msg->cm_fields['M'];
679         if (ptr == NULL) return(0);
680         while (ptr != NULL) {
681         
682                 linelen = strcspn(ptr, "\n");
683                 if (linelen == 0) return(0);    /* end of headers */    
684                 
685                 if (  (!strncasecmp(ptr, "Content-type: text/x-vcard", 26))
686                    || (!strncasecmp(ptr, "Content-type: text/vcard", 24)) ) {
687                         /*
688                          * Bingo!  The user is uploading a new vCard, so
689                          * copy it to the Global Address Book room.
690                          */
691
692                         I = atol(msg->cm_fields['I']);
693                         if (I < 0L) return(0);
694
695                         /* Store our Internet return address in memory */
696                         v = vcard_load(msg->cm_fields['M']);
697                         extract_inet_email_addrs(CC->cs_inet_email, sizeof CC->cs_inet_email,
698                                                 CC->cs_inet_other_emails, sizeof CC->cs_inet_other_emails,
699                                                 v, 1);
700                         extract_friendly_name(CC->cs_inet_fn, sizeof CC->cs_inet_fn, v);
701                         vcard_free(v);
702
703                         /* Put it in the Global Address Book room... */
704                         CtdlSaveMsgPointerInRoom(ADDRESS_BOOK_ROOM, I, 1, msg);
705
706                         /* ...and also in the directory database. */
707                         vcard_add_to_directory(I, NULL);
708
709                         /* Some sites want an Aide to be notified when a
710                          * user registers or re-registers...
711                          */
712                         set_mm_valid();
713
714                         /* ...which also means we need to flag the user */
715                         lgetuser(&CC->user, CC->curr_user);
716                         CC->user.flags |= (US_REGIS|US_NEEDVALID);
717                         lputuser(&CC->user);
718
719                         return(0);
720                 }
721
722                 ptr = strchr((char *)ptr, '\n');
723                 if (ptr != NULL) ++ptr;
724         }
725
726         return(0);
727 }
728
729
730
731 /*
732  * back end function used for callbacks
733  */
734 void vcard_gu_backend(long supplied_msgnum, void *userdata) {
735         long *msgnum;
736
737         msgnum = (long *) userdata;
738         *msgnum = supplied_msgnum;
739 }
740
741
742 /*
743  * If this user has a vcard on disk, read it into memory, otherwise allocate
744  * and return an empty vCard.
745  */
746 struct vCard *vcard_get_user(struct ctdluser *u) {
747         char hold_rm[ROOMNAMELEN];
748         char config_rm[ROOMNAMELEN];
749         struct CtdlMessage *msg = NULL;
750         struct vCard *v;
751         long VCmsgnum;
752
753         strcpy(hold_rm, CC->room.QRname);       /* save current room */
754         MailboxName(config_rm, sizeof config_rm, u, USERCONFIGROOM);
755
756         if (getroom(&CC->room, config_rm) != 0) {
757                 getroom(&CC->room, hold_rm);
758                 return vcard_new();
759         }
760
761         /* We want the last (and probably only) vcard in this room */
762         VCmsgnum = (-1);
763         CtdlForEachMessage(MSGS_LAST, 1, NULL, "^[Tt][Ee][Xx][Tt]/.*[Vv][Cc][Aa][Rr][Dd]$",
764                 NULL, vcard_gu_backend, (void *)&VCmsgnum );
765         getroom(&CC->room, hold_rm);    /* return to saved room */
766
767         if (VCmsgnum < 0L) return vcard_new();
768
769         msg = CtdlFetchMessage(VCmsgnum, 1);
770         if (msg == NULL) return vcard_new();
771
772         v = vcard_load(msg->cm_fields['M']);
773         CtdlFreeMessage(msg);
774         return v;
775 }
776
777
778 /*
779  * Store this user's vCard in the appropriate place
780  */
781 /*
782  * Write our config to disk
783  */
784 void vcard_write_user(struct ctdluser *u, struct vCard *v) {
785         char temp[PATH_MAX];
786         FILE *fp;
787         char *ser;
788
789         CtdlMakeTempFileName(temp, sizeof temp);
790         ser = vcard_serialize(v);
791
792         fp = fopen(temp, "w");
793         if (fp == NULL) return;
794         if (ser == NULL) {
795                 fprintf(fp, "begin:vcard\r\nend:vcard\r\n");
796         } else {
797                 fwrite(ser, strlen(ser), 1, fp);
798                 free(ser);
799         }
800         fclose(fp);
801
802         /* This handy API function does all the work for us.
803          * NOTE: normally we would want to set that last argument to 1, to
804          * force the system to delete the user's old vCard.  But it doesn't
805          * have to, because the vcard_upload_beforesave() hook above
806          * is going to notice what we're trying to do, and delete the old vCard.
807          */
808         CtdlWriteObject(USERCONFIGROOM, /* which room */
809                         VCARD_MIME_TYPE,/* MIME type */
810                         temp,           /* temp file */
811                         u,              /* which user */
812                         0,              /* not binary */
813                         0,              /* don't delete others of this type */
814                         0);             /* no flags */
815
816         unlink(temp);
817 }
818
819
820
821 /*
822  * Old style "enter registration info" command.  This function simply honors
823  * the REGI protocol command, translates the entered parameters into a vCard,
824  * and enters the vCard into the user's configuration.
825  */
826 void cmd_regi(char *argbuf) {
827         int a,b,c;
828         char buf[SIZ];
829         struct vCard *my_vcard;
830
831         char tmpaddr[SIZ];
832         char tmpcity[SIZ];
833         char tmpstate[SIZ];
834         char tmpzip[SIZ];
835         char tmpaddress[SIZ];
836         char tmpcountry[SIZ];
837
838         unbuffer_output();
839
840         if (!(CC->logged_in)) {
841                 cprintf("%d Not logged in.\n",ERROR + NOT_LOGGED_IN);
842                 return;
843         }
844
845         /* If users cannot create their own accounts, they cannot re-register either. */
846         if ( (config.c_disable_newu) && (CC->user.axlevel < 6) ) {
847                 cprintf("%d Self-service registration is not allowed here.\n",
848                         ERROR + HIGHER_ACCESS_REQUIRED);
849         }
850
851         my_vcard = vcard_get_user(&CC->user);
852         strcpy(tmpaddr, "");
853         strcpy(tmpcity, "");
854         strcpy(tmpstate, "");
855         strcpy(tmpzip, "");
856         strcpy(tmpcountry, "USA");
857
858         cprintf("%d Send registration...\n", SEND_LISTING);
859         a=0;
860         while (client_getln(buf, sizeof buf), strcmp(buf,"000")) {
861                 if (a==0) vcard_set_prop(my_vcard, "n", buf, 0);
862                 if (a==1) strcpy(tmpaddr, buf);
863                 if (a==2) strcpy(tmpcity, buf);
864                 if (a==3) strcpy(tmpstate, buf);
865                 if (a==4) {
866                         for (c=0; buf[c]; ++c) {
867                                 if ((buf[c]>='0') && (buf[c]<='9')) {
868                                         b = strlen(tmpzip);
869                                         tmpzip[b] = buf[c];
870                                         tmpzip[b+1] = 0;
871                                 }
872                         }
873                 }
874                 if (a==5) vcard_set_prop(my_vcard, "tel;home", buf, 0);
875                 if (a==6) vcard_set_prop(my_vcard, "email;internet", buf, 0);
876                 if (a==7) strcpy(tmpcountry, buf);
877                 ++a;
878         }
879
880         snprintf(tmpaddress, sizeof tmpaddress, ";;%s;%s;%s;%s;%s",
881                 tmpaddr, tmpcity, tmpstate, tmpzip, tmpcountry);
882         vcard_set_prop(my_vcard, "adr", tmpaddress, 0);
883         vcard_write_user(&CC->user, my_vcard);
884         vcard_free(my_vcard);
885 }
886
887
888 /*
889  * Protocol command to fetch registration info for a user
890  */
891 void cmd_greg(char *argbuf)
892 {
893         struct ctdluser usbuf;
894         struct vCard *v;
895         char *s;
896         char who[USERNAME_SIZE];
897         char adr[256];
898         char buf[256];
899
900         extract_token(who, argbuf, 0, '|', sizeof who);
901
902         if (!(CC->logged_in)) {
903                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
904                 return;
905         }
906
907         if (!strcasecmp(who,"_SELF_")) strcpy(who,CC->curr_user);
908
909         if ((CC->user.axlevel < 6) && (strcasecmp(who,CC->curr_user))) {
910                 cprintf("%d Higher access required.\n",
911                         ERROR + HIGHER_ACCESS_REQUIRED);
912                 return;
913         }
914
915         if (getuser(&usbuf, who) != 0) {
916                 cprintf("%d '%s' not found.\n", ERROR + NO_SUCH_USER, who);
917                 return;
918         }
919
920         v = vcard_get_user(&usbuf);
921
922         cprintf("%d %s\n", LISTING_FOLLOWS, usbuf.fullname);
923         cprintf("%ld\n", usbuf.usernum);
924         cprintf("%s\n", usbuf.password);
925         s = vcard_get_prop(v, "n", 0, 0, 0);
926         cprintf("%s\n", s ? s : " ");   /* name */
927
928         s = vcard_get_prop(v, "adr", 0, 0, 0);
929         snprintf(adr, sizeof adr, "%s", s ? s : " ");/* address... */
930
931         extract_token(buf, adr, 2, ';', sizeof buf);
932         cprintf("%s\n", buf);                           /* street */
933         extract_token(buf, adr, 3, ';', sizeof buf);
934         cprintf("%s\n", buf);                           /* city */
935         extract_token(buf, adr, 4, ';', sizeof buf);
936         cprintf("%s\n", buf);                           /* state */
937         extract_token(buf, adr, 5, ';', sizeof buf);
938         cprintf("%s\n", buf);                           /* zip */
939
940         s = vcard_get_prop(v, "tel;home", 0, 0, 0);
941         if (s == NULL) s = vcard_get_prop(v, "tel", 1, 0, 0);
942         if (s != NULL) {
943                 cprintf("%s\n", s);
944         }
945         else {
946                 cprintf(" \n");
947         }
948
949         cprintf("%d\n", usbuf.axlevel);
950
951         s = vcard_get_prop(v, "email;internet", 0, 0, 0);
952         cprintf("%s\n", s ? s : " ");
953         s = vcard_get_prop(v, "adr", 0, 0, 0);
954         snprintf(adr, sizeof adr, "%s", s ? s : " ");/* address... */
955
956         extract_token(buf, adr, 6, ';', sizeof buf);
957         cprintf("%s\n", buf);                           /* country */
958         cprintf("000\n");
959         vcard_free(v);
960 }
961
962
963
964 /*
965  * When a user is being created, create his/her vCard.
966  */
967 void vcard_newuser(struct ctdluser *usbuf) {
968         char vname[256];
969         char buf[256];
970         int i;
971         struct vCard *v;
972
973         vcard_fn_to_n(vname, usbuf->fullname, sizeof vname);
974         lprintf(CTDL_DEBUG, "Converted <%s> to <%s>\n", usbuf->fullname, vname);
975
976         /* Create and save the vCard */
977         v = vcard_new();
978         if (v == NULL) return;
979         sprintf(buf, "%s@%s", usbuf->fullname, config.c_fqdn);
980         for (i=0; buf[i]; ++i) {
981                 if (buf[i] == ' ') buf[i] = '_';
982         }
983         vcard_add_prop(v, "fn", usbuf->fullname);
984         vcard_add_prop(v, "n", vname);
985         vcard_add_prop(v, "adr", "adr:;;_;_;_;00000;__");
986         vcard_add_prop(v, "email;internet", buf);
987         vcard_write_user(usbuf, v);
988         vcard_free(v);
989 }
990
991
992 /*
993  * When a user is being deleted, we have to remove his/her vCard.
994  * This is accomplished by issuing a message with 'CANCEL' in the S (special)
995  * field, and the same Exclusive ID as the existing card.
996  */
997 void vcard_purge(struct ctdluser *usbuf) {
998         struct CtdlMessage *msg;
999         char buf[SIZ];
1000
1001         msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1002         if (msg == NULL) return;
1003         memset(msg, 0, sizeof(struct CtdlMessage));
1004
1005         msg->cm_magic = CTDLMESSAGE_MAGIC;
1006         msg->cm_anon_type = MES_NORMAL;
1007         msg->cm_format_type = 0;
1008         msg->cm_fields['A'] = strdup(usbuf->fullname);
1009         msg->cm_fields['O'] = strdup(ADDRESS_BOOK_ROOM);
1010         msg->cm_fields['N'] = strdup(NODENAME);
1011         msg->cm_fields['M'] = strdup("Purge this vCard\n");
1012
1013         snprintf(buf, sizeof buf, VCARD_EXT_FORMAT,
1014                         msg->cm_fields['A'], NODENAME);
1015         msg->cm_fields['E'] = strdup(buf);
1016
1017         msg->cm_fields['S'] = strdup("CANCEL");
1018
1019         CtdlSubmitMsg(msg, NULL, ADDRESS_BOOK_ROOM);
1020         CtdlFreeMessage(msg);
1021 }
1022
1023
1024 /*
1025  * Grab vCard directory stuff out of incoming network messages
1026  */
1027 int vcard_extract_from_network(struct CtdlMessage *msg, char *target_room) {
1028         char *ptr;
1029         int linelen;
1030
1031         if (msg == NULL) return(0);
1032
1033         if (strcasecmp(target_room, ADDRESS_BOOK_ROOM)) {
1034                 return(0);
1035         }
1036
1037         if (msg->cm_format_type != 4) return(0);
1038
1039         ptr = msg->cm_fields['M'];
1040         if (ptr == NULL) return(0);
1041         while (ptr != NULL) {
1042         
1043                 linelen = strcspn(ptr, "\n");
1044                 if (linelen == 0) return(0);    /* end of headers */    
1045                 
1046                 if (  (!strncasecmp(ptr, "Content-type: text/x-vcard", 26))
1047                    || (!strncasecmp(ptr, "Content-type: text/vcard", 24)) ) {
1048                         /* It's a vCard.  Add it to the directory. */
1049                         vcard_extract_internet_addresses(msg, CtdlDirectoryAddUser);
1050                         return(0);
1051                 }
1052
1053                 ptr = strchr((char *)ptr, '\n');
1054                 if (ptr != NULL) ++ptr;
1055         }
1056
1057         return(0);
1058 }
1059
1060
1061
1062 /* 
1063  * When a vCard is being removed from the Global Address Book room, remove it
1064  * from the directory as well.
1065  */
1066 void vcard_delete_remove(char *room, long msgnum) {
1067         struct CtdlMessage *msg;
1068         char *ptr;
1069         int linelen;
1070
1071         if (msgnum <= 0L) return;
1072         
1073         if (room == NULL) return;
1074
1075         if (strcasecmp(room, ADDRESS_BOOK_ROOM)) {
1076                 return;
1077         }
1078
1079         msg = CtdlFetchMessage(msgnum, 1);
1080         if (msg == NULL) return;
1081
1082         ptr = msg->cm_fields['M'];
1083         if (ptr == NULL) goto EOH;
1084         while (ptr != NULL) {
1085                 linelen = strcspn(ptr, "\n");
1086                 if (linelen == 0) goto EOH;
1087                 
1088                 if (  (!strncasecmp(ptr, "Content-type: text/x-vcard", 26))
1089                    || (!strncasecmp(ptr, "Content-type: text/vcard", 24)) ) {
1090                         /* Bingo!  A vCard is being deleted. */
1091                         vcard_extract_internet_addresses(msg, CtdlDirectoryDelUser);
1092 #ifdef HAVE_LDAP
1093                         ctdl_vcard_to_ldap(msg, V2L_DELETE);
1094 #endif
1095                 }
1096                 ptr = strchr((char *)ptr, '\n');
1097                 if (ptr != NULL) ++ptr;
1098         }
1099
1100 EOH:    CtdlFreeMessage(msg);
1101 }
1102
1103
1104
1105 /*
1106  * Get Valid Screen Names
1107  */
1108 void cmd_gvsn(char *argbuf)
1109 {
1110         if (CtdlAccessCheck(ac_logged_in)) return;
1111
1112         cprintf("%d valid screen names:\n", LISTING_FOLLOWS);
1113         cprintf("%s\n", CC->user.fullname);
1114         if ( (!IsEmptyStr(CC->cs_inet_fn)) && (strcasecmp(CC->user.fullname, CC->cs_inet_fn)) ) {
1115                 cprintf("%s\n", CC->cs_inet_fn);
1116         }
1117         cprintf("000\n");
1118 }
1119
1120
1121 /*
1122  * Get Valid Email Addresses
1123  */
1124 void cmd_gvea(char *argbuf)
1125 {
1126         int num_secondary_emails = 0;
1127         int i;
1128         char buf[256];
1129
1130         if (CtdlAccessCheck(ac_logged_in)) return;
1131
1132         cprintf("%d valid email addresses:\n", LISTING_FOLLOWS);
1133         if (!IsEmptyStr(CC->cs_inet_email)) {
1134                 cprintf("%s\n", CC->cs_inet_email);
1135         }
1136         if (!IsEmptyStr(CC->cs_inet_other_emails)) {
1137                 num_secondary_emails = num_tokens(CC->cs_inet_other_emails, '|');
1138                 for (i=0; i<num_secondary_emails; ++i) {
1139                         extract_token(buf, CC->cs_inet_other_emails,i,'|',sizeof CC->cs_inet_other_emails);
1140                         cprintf("%s\n", buf);
1141                 }
1142         }
1143         cprintf("000\n");
1144 }
1145
1146
1147
1148
1149 /*
1150  * Callback function for cmd_dvca() that hunts for vCard content types
1151  * and outputs any email addresses found within.
1152  */
1153 void dvca_mime_callback(char *name, char *filename, char *partnum, char *disp,
1154                 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1155                 void *cbuserdata) {
1156
1157         struct vCard *v;
1158         char displayname[256];
1159         int displayname_len;
1160         char emailaddr[256];
1161         int i;
1162         int has_commas = 0;
1163
1164         if ( (strcasecmp(cbtype, "text/vcard")) && (strcasecmp(cbtype, "text/x-vcard")) ) {
1165                 return;
1166         }
1167
1168         v = vcard_load(content);
1169         if (v == NULL) return;
1170
1171         extract_friendly_name(displayname, sizeof displayname, v);
1172         extract_inet_email_addrs(emailaddr, sizeof emailaddr, NULL, 0, v, 0);
1173
1174         displayname_len = strlen(displayname);
1175         for (i=0; i<displayname_len; ++i) {
1176                 if (displayname[i] == '\"') displayname[i] = ' ';
1177                 if (displayname[i] == ';') displayname[i] = ',';
1178                 if (displayname[i] == ',') has_commas = 1;
1179         }
1180         striplt(displayname);
1181
1182         cprintf("%s%s%s <%s>\n",
1183                 (has_commas ? "\"" : ""),
1184                 displayname,
1185                 (has_commas ? "\"" : ""),
1186                 emailaddr
1187         );
1188
1189         vcard_free(v);
1190 }
1191
1192
1193 /*
1194  * Back end callback function for cmd_dvca()
1195  *
1196  * It's basically just passed a list of message numbers, which we're going
1197  * to fetch off the disk and then pass along to the MIME parser via another
1198  * layer of callback...
1199  */
1200 void dvca_callback(long msgnum, void *userdata) {
1201         struct CtdlMessage *msg = NULL;
1202
1203         msg = CtdlFetchMessage(msgnum, 1);
1204         if (msg == NULL) return;
1205         mime_parser(msg->cm_fields['M'],
1206                 NULL,
1207                 *dvca_mime_callback,    /* callback function */
1208                 NULL, NULL,
1209                 NULL,                   /* user data */
1210                 0
1211         );
1212         CtdlFreeMessage(msg);
1213 }
1214
1215
1216 /*
1217  * Dump VCard Addresses
1218  */
1219 void cmd_dvca(char *argbuf)
1220 {
1221         if (CtdlAccessCheck(ac_logged_in)) return;
1222
1223         cprintf("%d addresses:\n", LISTING_FOLLOWS);
1224         CtdlForEachMessage(MSGS_ALL, 0, NULL, NULL, NULL, dvca_callback, NULL);
1225         cprintf("000\n");
1226 }
1227
1228
1229 /*
1230  * Query Directory
1231  */
1232 void cmd_qdir(char *argbuf) {
1233         char citadel_addr[256];
1234         char internet_addr[256];
1235
1236         if (CtdlAccessCheck(ac_logged_in)) return;
1237
1238         extract_token(internet_addr, argbuf, 0, '|', sizeof internet_addr);
1239
1240         if (CtdlDirectoryLookup(citadel_addr, internet_addr, sizeof citadel_addr) != 0) {
1241                 cprintf("%d %s was not found.\n",
1242                         ERROR + NO_SUCH_USER, internet_addr);
1243                 return;
1244         }
1245
1246         cprintf("%d %s\n", CIT_OK, citadel_addr);
1247 }
1248
1249 /*
1250  * Query Directory, in fact an alias to match postfix tcp auth.
1251  */
1252 void check_get(void) {
1253         char internet_addr[256];
1254
1255         char cmdbuf[SIZ];
1256
1257         time(&CC->lastcmd);
1258         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1259         if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1260                 lprintf(CTDL_CRIT, "Client disconnected: ending session.\n");
1261                 CC->kill_me = 1;
1262                 return;
1263         }
1264         lprintf(CTDL_INFO, ": %s\n", cmdbuf);
1265         while (strlen(cmdbuf) < 3) strcat(cmdbuf, " ");
1266
1267         if (strcasecmp(cmdbuf, "GET "));
1268         {
1269                 struct recptypes *rcpt;
1270                 char *argbuf = &cmdbuf[4];
1271                 
1272                 extract_token(internet_addr, argbuf, 0, '|', sizeof internet_addr);
1273                 rcpt = validate_recipients(internet_addr);
1274                 if ((rcpt != NULL)&&
1275                         (
1276                          (*rcpt->recp_local != '\0')||
1277                          (*rcpt->recp_room != '\0')||
1278                          (*rcpt->recp_ignet != '\0')))
1279                 {
1280
1281                         cprintf("200 OK %s\n", internet_addr);
1282                         lprintf(CTDL_INFO, "sending 200 OK for the room %s\n", rcpt->display_recp);
1283                 }
1284                 else 
1285                 {
1286                         cprintf("500 REJECT noone here by that name.\n");
1287                         
1288                         lprintf(CTDL_INFO, "sending 500 REJECT noone here by that name: %s\n", internet_addr);
1289                 }
1290                 if (rcpt != NULL) free_recipients(rcpt);
1291         }
1292 }
1293
1294 void check_get_greeting(void) {
1295 /* dummy function, we have no greeting in this verry simple protocol. */
1296 }
1297
1298
1299 /*
1300  * We don't know if the Contacts room exists so we just create it at login
1301  */
1302 void vcard_create_room(void)
1303 {
1304         struct ctdlroom qr;
1305         struct visit vbuf;
1306
1307         /* Create the calendar room if it doesn't already exist */
1308         create_room(USERCONTACTSROOM, 4, "", 0, 1, 0, VIEW_ADDRESSBOOK);
1309
1310         /* Set expiration policy to manual; otherwise objects will be lost! */
1311         if (lgetroom(&qr, USERCONTACTSROOM)) {
1312                 lprintf(CTDL_ERR, "Couldn't get the user CONTACTS room!\n");
1313                 return;
1314         }
1315         qr.QRep.expire_mode = EXPIRE_MANUAL;
1316         qr.QRdefaultview = VIEW_ADDRESSBOOK;    /* 2 = address book view */
1317         lputroom(&qr);
1318
1319         /* Set the view to a calendar view */
1320         CtdlGetRelationship(&vbuf, &CC->user, &qr);
1321         vbuf.v_view = 2;        /* 2 = address book view */
1322         CtdlSetRelationship(&vbuf, &CC->user, &qr);
1323
1324         return;
1325 }
1326
1327
1328
1329
1330 /*
1331  * When a user logs in...
1332  */
1333 void vcard_session_login_hook(void) {
1334         struct vCard *v = NULL;
1335
1336         v = vcard_get_user(&CC->user);
1337         extract_inet_email_addrs(CC->cs_inet_email, sizeof CC->cs_inet_email,
1338                                 CC->cs_inet_other_emails, sizeof CC->cs_inet_other_emails,
1339                                 v, 1);
1340         extract_friendly_name(CC->cs_inet_fn, sizeof CC->cs_inet_fn, v);
1341         vcard_free(v);
1342
1343         vcard_create_room();
1344 }
1345
1346
1347 /* 
1348  * Turn an arbitrary RFC822 address into a struct vCard for possible
1349  * inclusion into an address book.
1350  */
1351 struct vCard *vcard_new_from_rfc822_addr(char *addr) {
1352         struct vCard *v;
1353         char user[256], node[256], name[256], email[256], n[256], uid[256];
1354         int i;
1355
1356         v = vcard_new();
1357         if (v == NULL) return(NULL);
1358
1359         process_rfc822_addr(addr, user, node, name);
1360         vcard_set_prop(v, "fn", name, 0);
1361
1362         vcard_fn_to_n(n, name, sizeof n);
1363         vcard_set_prop(v, "n", n, 0);
1364
1365         snprintf(email, sizeof email, "%s@%s", user, node);
1366         vcard_set_prop(v, "email;internet", email, 0);
1367
1368         snprintf(uid, sizeof uid, "collected: %s %s@%s", name, user, node);
1369         for (i=0; uid[i]; ++i) {
1370                 if (isspace(uid[i])) uid[i] = '_';
1371                 uid[i] = tolower(uid[i]);
1372         }
1373         vcard_set_prop(v, "UID", uid, 0);
1374
1375         return(v);
1376 }
1377
1378
1379
1380 /*
1381  * This is called by store_harvested_addresses() to remove from the
1382  * list any addresses we already have in our address book.
1383  */
1384 void strip_addresses_already_have(long msgnum, void *userdata) {
1385         char *collected_addresses;
1386         struct CtdlMessage *msg = NULL;
1387         struct vCard *v;
1388         char *value = NULL;
1389         int i, j;
1390         char addr[256], user[256], node[256], name[256];
1391
1392         collected_addresses = (char *)userdata;
1393
1394         msg = CtdlFetchMessage(msgnum, 1);
1395         if (msg == NULL) return;
1396         v = vcard_load(msg->cm_fields['M']);
1397         CtdlFreeMessage(msg);
1398
1399         i = 0;
1400         while (value = vcard_get_prop(v, "email", 1, i++, 0), value != NULL) {
1401
1402                 for (j=0; j<num_tokens(collected_addresses, ','); ++j) {
1403                         extract_token(addr, collected_addresses, j, ',', sizeof addr);
1404
1405                         /* Remove the address if we already have it! */
1406                         process_rfc822_addr(addr, user, node, name);
1407                         snprintf(addr, sizeof addr, "%s@%s", user, node);
1408                         if (!strcasecmp(value, addr)) {
1409                                 remove_token(collected_addresses, j, ',');
1410                         }
1411                 }
1412
1413         }
1414
1415         vcard_free(v);
1416 }
1417
1418
1419
1420 /*
1421  * Back end function for store_harvested_addresses()
1422  */
1423 void store_this_ha(struct addresses_to_be_filed *aptr) {
1424         struct CtdlMessage *vmsg = NULL;
1425         long vmsgnum = (-1L);
1426         char *ser = NULL;
1427         struct vCard *v = NULL;
1428         char recipient[256];
1429         int i;
1430
1431         /* First remove any addresses we already have in the address book */
1432         usergoto(aptr->roomname, 0, 0, NULL, NULL);
1433         CtdlForEachMessage(MSGS_ALL, 0, NULL, "^[Tt][Ee][Xx][Tt]/.*[Vv][Cc][Aa][Rr][Dd]$", NULL,
1434                 strip_addresses_already_have, aptr->collected_addresses);
1435
1436         if (!IsEmptyStr(aptr->collected_addresses))
1437            for (i=0; i<num_tokens(aptr->collected_addresses, ','); ++i) {
1438
1439                 /* Make a vCard out of each address */
1440                 extract_token(recipient, aptr->collected_addresses, i, ',', sizeof recipient);
1441                 striplt(recipient);
1442                 v = vcard_new_from_rfc822_addr(recipient);
1443                 if (v != NULL) {
1444                         vmsg = malloc(sizeof(struct CtdlMessage));
1445                         memset(vmsg, 0, sizeof(struct CtdlMessage));
1446                         vmsg->cm_magic = CTDLMESSAGE_MAGIC;
1447                         vmsg->cm_anon_type = MES_NORMAL;
1448                         vmsg->cm_format_type = FMT_RFC822;
1449                         vmsg->cm_fields['A'] = strdup("Citadel");
1450                         vmsg->cm_fields['E'] =  strdup(vcard_get_prop(v, "UID", 0, 0, 0));
1451                         ser = vcard_serialize(v);
1452                         if (ser != NULL) {
1453                                 vmsg->cm_fields['M'] = malloc(strlen(ser) + 1024);
1454                                 sprintf(vmsg->cm_fields['M'],
1455                                         "Content-type: " VCARD_MIME_TYPE
1456                                         "\r\n\r\n%s\r\n", ser);
1457                                 free(ser);
1458                         }
1459                         vcard_free(v);
1460
1461                         lprintf(CTDL_DEBUG, "Adding contact: %s\n", recipient);
1462                         vmsgnum = CtdlSubmitMsg(vmsg, NULL, aptr->roomname);
1463                         CtdlFreeMessage(vmsg);
1464                 }
1465         }
1466
1467         free(aptr->roomname);
1468         free(aptr->collected_addresses);
1469         free(aptr);
1470 }
1471
1472
1473 /*
1474  * When a user sends a message, we may harvest one or more email addresses
1475  * from the recipient list to be added to the user's address book.  But we
1476  * want to do this asynchronously so it doesn't keep the user waiting.
1477  */
1478 void store_harvested_addresses(void) {
1479
1480         struct addresses_to_be_filed *aptr = NULL;
1481
1482         if (atbf == NULL) return;
1483
1484         begin_critical_section(S_ATBF);
1485         while (atbf != NULL) {
1486                 aptr = atbf;
1487                 atbf = atbf->next;
1488                 end_critical_section(S_ATBF);
1489                 store_this_ha(aptr);
1490                 begin_critical_section(S_ATBF);
1491         }
1492         end_critical_section(S_ATBF);
1493 }
1494
1495
1496 /* 
1497  * Function to output vCard data as plain text.  Nobody uses MSG0 anymore, so
1498  * really this is just so we expose the vCard data to the full text indexer.
1499  */
1500 void vcard_fixed_output(char *ptr, int len) {
1501         char *serialized_vcard;
1502         struct vCard *v;
1503         char *key, *value;
1504         int i = 0;
1505
1506         serialized_vcard = malloc(len + 1);
1507         safestrncpy(serialized_vcard, ptr, len+1);
1508         v = vcard_load(serialized_vcard);
1509         free(serialized_vcard);
1510
1511         i = 0;
1512         while (key = vcard_get_prop(v, "", 0, i, 1), key != NULL) {
1513                 value = vcard_get_prop(v, "", 0, i++, 0);
1514                 cprintf("%s\n", value);
1515         }
1516
1517         vcard_free(v);
1518 }
1519
1520
1521 const char *CitadelServiceDICT_TCP="DICT_TCP";
1522
1523 CTDL_MODULE_INIT(vcard)
1524 {
1525         struct ctdlroom qr;
1526         char filename[256];
1527         FILE *fp;
1528
1529         CtdlRegisterSessionHook(vcard_session_login_hook, EVT_LOGIN);
1530         CtdlRegisterMessageHook(vcard_upload_beforesave, EVT_BEFORESAVE);
1531         CtdlRegisterMessageHook(vcard_upload_aftersave, EVT_AFTERSAVE);
1532         CtdlRegisterDeleteHook(vcard_delete_remove);
1533         CtdlRegisterProtoHook(cmd_regi, "REGI", "Enter registration info");
1534         CtdlRegisterProtoHook(cmd_greg, "GREG", "Get registration info");
1535         CtdlRegisterProtoHook(cmd_igab, "IGAB",
1536                                         "Initialize Global Address Book");
1537         CtdlRegisterProtoHook(cmd_qdir, "QDIR", "Query Directory");
1538         CtdlRegisterProtoHook(cmd_gvsn, "GVSN", "Get Valid Screen Names");
1539         CtdlRegisterProtoHook(cmd_gvea, "GVEA", "Get Valid Email Addresses");
1540         CtdlRegisterProtoHook(cmd_dvca, "DVCA", "Dump VCard Addresses");
1541         CtdlRegisterUserHook(vcard_newuser, EVT_NEWUSER);
1542         CtdlRegisterUserHook(vcard_purge, EVT_PURGEUSER);
1543         CtdlRegisterNetprocHook(vcard_extract_from_network);
1544         CtdlRegisterSessionHook(store_harvested_addresses, EVT_TIMER);
1545         CtdlRegisterFixedOutputHook("text/x-vcard", vcard_fixed_output);
1546         CtdlRegisterFixedOutputHook("text/vcard", vcard_fixed_output);
1547
1548         /* Create the Global ADdress Book room if necessary */
1549         create_room(ADDRESS_BOOK_ROOM, 3, "", 0, 1, 0, VIEW_ADDRESSBOOK);
1550
1551         /* Set expiration policy to manual; otherwise objects will be lost! */
1552         if (!lgetroom(&qr, ADDRESS_BOOK_ROOM)) {
1553                 qr.QRep.expire_mode = EXPIRE_MANUAL;
1554                 qr.QRdefaultview = VIEW_ADDRESSBOOK;    /* 2 = address book view */
1555                 lputroom(&qr);
1556
1557                 /*
1558                  * Also make sure it has a netconfig file, so the networker runs
1559                  * on this room even if we don't share it with any other nodes.
1560                  * This allows the CANCEL messages (i.e. "Purge this vCard") to be
1561                  * purged.
1562                  */
1563                 assoc_file_name(filename, sizeof filename, &qr, ctdl_netcfg_dir);
1564                 fp = fopen(filename, "a");
1565                 if (fp != NULL) fclose(fp);
1566                 chown(filename, CTDLUID, (-1));
1567         }
1568
1569         /* for postfix tcpdict */
1570         CtdlRegisterServiceHook(config.c_pftcpdict_port,        /* Postfix */
1571                                 NULL,
1572                                 check_get_greeting,
1573                                 check_get,
1574                                 NULL,
1575                                 CitadelServiceDICT_TCP);
1576         
1577         /* return our Subversion id for the Log */
1578         return "$Id$";
1579 }