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