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