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