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