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