* Bounds checking in CtdlDirectoryLookup()
[citadel.git] / citadel / 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-2002 / released under the GNU General Public License
8  */
9
10 /*
11  * Where we keep messages containing the vCards that source our directory.  It
12  * makes no sense to change this, because you'd have to change it on every
13  * system on the network.  That would be stupid.
14  */
15 #define ADDRESS_BOOK_ROOM       "Global Address Book"
16
17 /*
18  * Format of the "Exclusive ID" field of the message containing a user's
19  * vCard.  Doesn't matter what it really looks like as long as it's both
20  * unique and consistent (because we use it for replication checking to
21  * delete the old vCard network-wide when the user enters a new one).
22  */
23 #define VCARD_EXT_FORMAT        "Citadel vCard: personal card for %s at %s"
24
25
26 #include "sysdep.h"
27 #include <stdlib.h>
28 #include <unistd.h>
29 #include <stdio.h>
30 #include <fcntl.h>
31 #include <signal.h>
32 #include <pwd.h>
33 #include <errno.h>
34 #include <sys/types.h>
35
36 #if TIME_WITH_SYS_TIME
37 # include <sys/time.h>
38 # include <time.h>
39 #else
40 # if HAVE_SYS_TIME_H
41 #  include <sys/time.h>
42 # else
43 #  include <time.h>
44 # endif
45 #endif
46
47 #include <sys/wait.h>
48 #include <string.h>
49 #include <limits.h>
50 #include "citadel.h"
51 #include "server.h"
52 #include "sysdep_decls.h"
53 #include "citserver.h"
54 #include "support.h"
55 #include "config.h"
56 #include "control.h"
57 #include "serv_extensions.h"
58 #include "room_ops.h"
59 #include "user_ops.h"
60 #include "policy.h"
61 #include "database.h"
62 #include "msgbase.h"
63 #include "internet_addressing.h"
64 #include "tools.h"
65 #include "vcard.h"
66 #include "serv_ldap.h"
67
68 /*
69  * set global flag calling for an aide to validate new users
70  */
71 void set_mm_valid(void) {
72         begin_critical_section(S_CONTROL);
73         get_control();
74         CitControl.MMflags = CitControl.MMflags | MM_VALID ;
75         put_control();
76         end_critical_section(S_CONTROL);
77 }
78
79
80
81 /*
82  * Extract Internet e-mail addresses from a message containing a vCard, and
83  * perform a callback for any found.
84  */
85 void vcard_extract_internet_addresses(struct CtdlMessage *msg,
86                                 void (*callback)(char *, char *) ) {
87         struct vCard *v;
88         char *s;
89         char *addr;
90         char citadel_address[SIZ];
91         int instance = 0;
92         int found_something = 0;
93
94         if (msg->cm_fields['A'] == NULL) return;
95         if (msg->cm_fields['N'] == NULL) return;
96         snprintf(citadel_address, sizeof citadel_address, "%s @ %s",
97                 msg->cm_fields['A'], msg->cm_fields['N']);
98
99         v = vcard_load(msg->cm_fields['M']);
100         if (v == NULL) return;
101
102         /* Go through the vCard searching for *all* instances of
103          * the "email;internet" key
104          */
105         do {
106                 s = vcard_get_prop(v, "email;internet", 0, instance++, 0);
107                 if (s != NULL) {
108                         addr = strdup(s);
109                         striplt(addr);
110                         if (strlen(addr) > 0) {
111                                 if (callback != NULL) {
112                                         callback(addr, citadel_address);
113                                 }
114                         }
115                         free(addr);
116                         found_something = 1;
117                 }
118                 else {
119                         found_something = 0;
120                 }
121         } while(found_something);
122
123         vcard_free(v);
124 }
125
126
127
128 /*
129  * Callback for vcard_add_to_directory()
130  * (Lotsa ugly nested callbacks.  Oh well.)
131  */
132 void vcard_directory_add_user(char *internet_addr, char *citadel_addr) {
133         char buf[SIZ];
134
135         /* We have to validate that we're not stepping on someone else's
136          * email address ... but only if we're logged in.  Otherwise it's
137          * probably just the networker or something.
138          */
139         if (CC->logged_in) {
140                 lprintf(CTDL_DEBUG, "Checking for <%s>...\n", internet_addr);
141                 if (CtdlDirectoryLookup(buf, internet_addr, sizeof buf) == 0) {
142                         if (strcasecmp(buf, citadel_addr)) {
143                                 /* This address belongs to someone else.
144                                  * Bail out silently without saving.
145                                  */
146                                 lprintf(CTDL_DEBUG, "DOOP!\n");
147                                 return;
148                         }
149                 }
150         }
151         lprintf(CTDL_INFO, "Adding %s (%s) to directory\n",
152                         citadel_addr, internet_addr);
153         CtdlDirectoryAddUser(internet_addr, citadel_addr);
154 }
155
156
157 /*
158  * Back end function for cmd_igab()
159  */
160 void vcard_add_to_directory(long msgnum, void *data) {
161         struct CtdlMessage *msg;
162
163         msg = CtdlFetchMessage(msgnum, 1);
164         if (msg != NULL) {
165                 vcard_extract_internet_addresses(msg, vcard_directory_add_user);
166         }
167
168 #ifdef HAVE_LDAP
169         ctdl_vcard_to_ldap(msg, V2L_WRITE);
170 #endif
171
172         CtdlFreeMessage(msg);
173 }
174
175
176 /*
177  * Initialize Global Adress Book
178  */
179 void cmd_igab(char *argbuf) {
180         char hold_rm[ROOMNAMELEN];
181
182         if (CtdlAccessCheck(ac_aide)) return;
183
184         strcpy(hold_rm, CC->room.QRname);       /* save current room */
185
186         if (getroom(&CC->room, ADDRESS_BOOK_ROOM) != 0) {
187                 getroom(&CC->room, hold_rm);
188                 cprintf("%d cannot get address book room\n", ERROR + ROOM_NOT_FOUND);
189                 return;
190         }
191
192         /* Empty the existing database first.
193          */
194         CtdlDirectoryInit();
195
196         /* We want *all* vCards in this room */
197         CtdlForEachMessage(MSGS_ALL, 0, "text/x-vcard",
198                 NULL, vcard_add_to_directory, NULL);
199
200         getroom(&CC->room, hold_rm);    /* return to saved room */
201         cprintf("%d Directory has been rebuilt.\n", CIT_OK);
202 }
203
204
205
206
207 /*
208  * See if there is a valid Internet address in a vCard to use for outbound
209  * Internet messages.  If there is, stick it in CC->cs_inet_email.
210  */
211 void vcard_populate_cs_inet_email(struct vCard *v) {
212         char *s, *addr;
213         int continue_searching = 1;
214         int instance = 0;
215
216         /* Go through the vCard searching for *all* instances of
217          * the "email;internet" key
218          */
219         do {
220                 s = vcard_get_prop(v, "email;internet", 0, instance++, 0);
221                 if (s != NULL) {
222                         continue_searching = 1;
223                         addr = strdup(s);
224                         striplt(addr);
225                         if (strlen(addr) > 0) {
226                                 if (IsDirectory(addr)) {
227                                         continue_searching = 0;
228                                         safestrncpy(CC->cs_inet_email,
229                                                 addr,
230                                                 sizeof(CC->cs_inet_email)
231                                         );
232                                 }
233                         }
234                         free(addr);
235                 }
236                 else {
237                         continue_searching = 0;
238                 }
239         } while(continue_searching);
240 }
241
242
243
244 /*
245  * This handler detects whether the user is attempting to save a new
246  * vCard as part of his/her personal configuration, and handles the replace
247  * function accordingly (delete the user's existing vCard in the config room
248  * and in the global address book).
249  */
250 int vcard_upload_beforesave(struct CtdlMessage *msg) {
251         char *ptr;
252         char *s;
253         int linelen;
254         char buf[SIZ];
255         struct ctdluser usbuf;
256         long what_user;
257         struct vCard *v = NULL;
258         char *ser = NULL;
259         int i = 0;
260         int yes_my_citadel_config = 0;
261         int yes_any_vcard_room = 0;
262
263         if (!CC->logged_in) return(0);  /* Only do this if logged in. */
264
265         /* Is this some user's "My Citadel Config" room? */
266         if ( (CC->room.QRflags && QR_MAILBOX)
267            && (!strcasecmp(&CC->room.QRname[11], USERCONFIGROOM)) ) {
268                 /* Yes, we want to do this */
269                 yes_my_citadel_config = 1;
270         }
271
272         /* Is this a room with an address book in it? */
273         if (CC->curr_view == VIEW_ADDRESSBOOK) {
274                 yes_any_vcard_room = 1;
275         }
276
277         /* If neither condition exists, don't run this hook. */
278         if ( (!yes_my_citadel_config) && (!yes_any_vcard_room) ) {
279                 return(0);
280         }
281
282         /* If this isn't a MIME message, don't bother. */
283         if (msg->cm_format_type != 4) return(0);
284
285         /* Ok, if we got this far, look into the situation further... */
286
287         ptr = msg->cm_fields['M'];
288         if (ptr == NULL) return(0);
289         while (ptr != NULL) {
290         
291                 linelen = strcspn(ptr, "\n");
292                 if (linelen == 0) return(0);    /* end of headers */    
293                 
294                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
295
296
297                         if (yes_my_citadel_config) {
298                                 /* Bingo!  The user is uploading a new vCard, so
299                                  * delete the old one.  First, figure out which user
300                                  * is being re-registered...
301                                  */
302                                 what_user = atol(CC->room.QRname);
303         
304                                 if (what_user == CC->user.usernum) {
305                                         /* It's the logged in user.  That was easy. */
306                                         memcpy(&usbuf, &CC->user,
307                                                 sizeof(struct ctdluser) );
308                                 }
309                                 
310                                 else if (getuserbynumber(&usbuf, what_user) == 0) {
311                                         /* We fetched a valid user record */
312                                 }
313                         
314                                 else {
315                                         /* No user with that number! */
316                                         return(0);
317                                 }
318         
319                                 /* Delete the user's old vCard.  This would probably
320                                  * get taken care of by the replication check, but we
321                                  * want to make sure there is absolutely only one
322                                  * vCard in the user's config room at all times.
323                                  */
324                                 CtdlDeleteMessages(CC->room.QRname,
325                                                 0L, "text/x-vcard", 1);
326
327                                 /* Make the author of the message the name of the user.
328                                  */
329                                 if (msg->cm_fields['A'] != NULL) {
330                                         free(msg->cm_fields['A']);
331                                 }
332                                 msg->cm_fields['A'] = strdup(usbuf.fullname);
333                         }
334
335                         /* Manipulate the vCard data structure */
336                         v = vcard_load(msg->cm_fields['M']);
337                         if (v != NULL) {
338
339                                 /* Insert or replace RFC2739-compliant free/busy URL */
340                                 if (yes_my_citadel_config) {
341                                         sprintf(buf, "http://%s/%s.vfb",
342                                                 config.c_fqdn,
343                                                 usbuf.fullname);
344                                         for (i=0; i<strlen(buf); ++i) {
345                                                 if (buf[i] == ' ') buf[i] = '_';
346                                         }
347                                         vcard_set_prop(v, "FBURL;PREF", buf, 0);
348                                 }
349
350                                 /* If this is an address book room, and the vCard has
351                                  * no UID, then give it one.
352                                  */
353                                 if (yes_any_vcard_room) {
354                                         s = vcard_get_prop(v, "UID", 0, 0, 0);
355                                         if (s == NULL) {
356                                                 generate_uuid(buf);
357                                                 vcard_set_prop(v, "UID", buf, 0);
358                                         }
359                                 }
360
361                                 /* Enforce local UID policy if applicable */
362                                 if (yes_my_citadel_config) {
363                                         snprintf(buf, sizeof buf, VCARD_EXT_FORMAT,
364                                                 msg->cm_fields['A'], NODENAME);
365                                         vcard_set_prop(v, "UID", buf, 0);
366                                 }
367
368                                 /* 
369                                  * Set the EUID of the message to the UID of the vCard.
370                                  */
371                                 if (msg->cm_fields['E'] != NULL) free(msg->cm_fields['E']);
372                                 s = vcard_get_prop(v, "UID", 0, 0, 0);
373                                 if (s != NULL) {
374                                         msg->cm_fields['E'] = strdup(s);
375                                         if (msg->cm_fields['U'] == NULL) {
376                                                 msg->cm_fields['U'] = strdup(s);
377                                         }
378                                 }
379
380                                 /*
381                                  * Set the Subject to the name in the vCard.
382                                  */
383                                 s = vcard_get_prop(v, "FN", 0, 0, 0);
384                                 if (s == NULL) {
385                                         s = vcard_get_prop(v, "N", 0, 0, 0);
386                                 }
387                                 if (s != NULL) {
388                                         if (msg->cm_fields['U'] != NULL) {
389                                                 free(msg->cm_fields['U']);
390                                         }
391                                         msg->cm_fields['U'] = strdup(s);
392                                 }
393
394                                 /* Re-serialize it back into the msg body */
395                                 ser = vcard_serialize(v);
396                                 if (ser != NULL) {
397                                         msg->cm_fields['M'] = realloc(
398                                                 msg->cm_fields['M'],
399                                                 strlen(ser) + 1024
400                                         );
401                                         sprintf(msg->cm_fields['M'],
402                                                 "Content-type: text/x-vcard"
403                                                 "\r\n\r\n%s\r\n", ser);
404                                         free(ser);
405                                 }
406                                 vcard_free(v);
407                         }
408
409                         /* Now allow the save to complete. */
410                         return(0);
411                 }
412
413                 ptr = strchr((char *)ptr, '\n');
414                 if (ptr != NULL) ++ptr;
415         }
416
417         return(0);
418 }
419
420
421
422 /*
423  * This handler detects whether the user is attempting to save a new
424  * vCard as part of his/her personal configuration, and handles the replace
425  * function accordingly (copy the vCard from the config room to the global
426  * address book).
427  */
428 int vcard_upload_aftersave(struct CtdlMessage *msg) {
429         char *ptr;
430         int linelen;
431         long I;
432         struct vCard *v;
433
434         if (!CC->logged_in) return(0);  /* Only do this if logged in. */
435
436         /* If this isn't the configuration room, or if this isn't a MIME
437          * message, don't bother.
438          */
439         if (msg->cm_fields['O'] == NULL) return(0);
440         if (strcasecmp(msg->cm_fields['O'], USERCONFIGROOM)) return(0);
441         if (msg->cm_format_type != 4) return(0);
442
443         ptr = msg->cm_fields['M'];
444         if (ptr == NULL) return(0);
445         while (ptr != NULL) {
446         
447                 linelen = strcspn(ptr, "\n");
448                 if (linelen == 0) return(0);    /* end of headers */    
449                 
450                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
451                         /* Bingo!  The user is uploading a new vCard, so
452                          * copy it to the Global Address Book room.
453                          */
454
455                         I = atol(msg->cm_fields['I']);
456                         if (I < 0L) return(0);
457
458                         /* Store our Internet return address in memory */
459                         v = vcard_load(msg->cm_fields['M']);
460                         vcard_populate_cs_inet_email(v);
461                         vcard_free(v);
462
463                         /* Put it in the Global Address Book room... */
464                         CtdlSaveMsgPointerInRoom(ADDRESS_BOOK_ROOM, I,
465                                 (SM_VERIFY_GOODNESS | SM_DO_REPL_CHECK) );
466
467                         /* ...and also in the directory database. */
468                         vcard_add_to_directory(I, NULL);
469
470                         /* Some sites want an Aide to be notified when a
471                          * user registers or re-registers...
472                          */
473                         set_mm_valid();
474
475                         /* ...which also means we need to flag the user */
476                         lgetuser(&CC->user, CC->curr_user);
477                         CC->user.flags |= (US_REGIS|US_NEEDVALID);
478                         lputuser(&CC->user);
479
480                         return(0);
481                 }
482
483                 ptr = strchr((char *)ptr, '\n');
484                 if (ptr != NULL) ++ptr;
485         }
486
487         return(0);
488 }
489
490
491
492 /*
493  * back end function used for callbacks
494  */
495 void vcard_gu_backend(long supplied_msgnum, void *userdata) {
496         long *msgnum;
497
498         msgnum = (long *) userdata;
499         *msgnum = supplied_msgnum;
500 }
501
502
503 /*
504  * If this user has a vcard on disk, read it into memory, otherwise allocate
505  * and return an empty vCard.
506  */
507 struct vCard *vcard_get_user(struct ctdluser *u) {
508         char hold_rm[ROOMNAMELEN];
509         char config_rm[ROOMNAMELEN];
510         struct CtdlMessage *msg;
511         struct vCard *v;
512         long VCmsgnum;
513
514         strcpy(hold_rm, CC->room.QRname);       /* save current room */
515         MailboxName(config_rm, sizeof config_rm, u, USERCONFIGROOM);
516
517         if (getroom(&CC->room, config_rm) != 0) {
518                 getroom(&CC->room, hold_rm);
519                 return vcard_new();
520         }
521
522         /* We want the last (and probably only) vcard in this room */
523         VCmsgnum = (-1);
524         CtdlForEachMessage(MSGS_LAST, 1, "text/x-vcard",
525                 NULL, vcard_gu_backend, (void *)&VCmsgnum );
526         getroom(&CC->room, hold_rm);    /* return to saved room */
527
528         if (VCmsgnum < 0L) return vcard_new();
529
530         msg = CtdlFetchMessage(VCmsgnum, 1);
531         if (msg == NULL) return vcard_new();
532
533         v = vcard_load(msg->cm_fields['M']);
534         CtdlFreeMessage(msg);
535         return v;
536 }
537
538
539 /*
540  * Store this user's vCard in the appropriate place
541  */
542 /*
543  * Write our config to disk
544  */
545 void vcard_write_user(struct ctdluser *u, struct vCard *v) {
546         char temp[PATH_MAX];
547         FILE *fp;
548         char *ser;
549
550         strcpy(temp, tmpnam(NULL));
551         ser = vcard_serialize(v);
552
553         fp = fopen(temp, "w");
554         if (fp == NULL) return;
555         if (ser == NULL) {
556                 fprintf(fp, "begin:vcard\r\nend:vcard\r\n");
557         } else {
558                 fwrite(ser, strlen(ser), 1, fp);
559                 free(ser);
560         }
561         fclose(fp);
562
563         /* This handy API function does all the work for us.
564          * NOTE: normally we would want to set that last argument to 1, to
565          * force the system to delete the user's old vCard.  But it doesn't
566          * have to, because the vcard_upload_beforesave() hook above
567          * is going to notice what we're trying to do, and delete the old vCard.
568          */
569         CtdlWriteObject(USERCONFIGROOM, /* which room */
570                         "text/x-vcard", /* MIME type */
571                         temp,           /* temp file */
572                         u,              /* which user */
573                         0,              /* not binary */
574                         0,              /* don't delete others of this type */
575                         0);             /* no flags */
576
577         unlink(temp);
578 }
579
580
581
582 /*
583  * Old style "enter registration info" command.  This function simply honors
584  * the REGI protocol command, translates the entered parameters into a vCard,
585  * and enters the vCard into the user's configuration.
586  */
587 void cmd_regi(char *argbuf) {
588         int a,b,c;
589         char buf[SIZ];
590         struct vCard *my_vcard;
591
592         char tmpaddr[SIZ];
593         char tmpcity[SIZ];
594         char tmpstate[SIZ];
595         char tmpzip[SIZ];
596         char tmpaddress[SIZ];
597         char tmpcountry[SIZ];
598
599         unbuffer_output();
600
601         if (!(CC->logged_in)) {
602                 cprintf("%d Not logged in.\n",ERROR + NOT_LOGGED_IN);
603                 return;
604         }
605
606         my_vcard = vcard_get_user(&CC->user);
607         strcpy(tmpaddr, "");
608         strcpy(tmpcity, "");
609         strcpy(tmpstate, "");
610         strcpy(tmpzip, "");
611         strcpy(tmpcountry, "USA");
612
613         cprintf("%d Send registration...\n", SEND_LISTING);
614         a=0;
615         while (client_getln(buf, sizeof buf), strcmp(buf,"000")) {
616                 if (a==0) vcard_set_prop(my_vcard, "n", buf, 0);
617                 if (a==1) strcpy(tmpaddr, buf);
618                 if (a==2) strcpy(tmpcity, buf);
619                 if (a==3) strcpy(tmpstate, buf);
620                 if (a==4) {
621                         for (c=0; c<strlen(buf); ++c) {
622                                 if ((buf[c]>='0') && (buf[c]<='9')) {
623                                         b = strlen(tmpzip);
624                                         tmpzip[b] = buf[c];
625                                         tmpzip[b+1] = 0;
626                                 }
627                         }
628                 }
629                 if (a==5) vcard_set_prop(my_vcard, "tel;home", buf, 0);
630                 if (a==6) vcard_set_prop(my_vcard, "email;internet", buf, 0);
631                 if (a==7) strcpy(tmpcountry, buf);
632                 ++a;
633         }
634
635         snprintf(tmpaddress, sizeof tmpaddress, ";;%s;%s;%s;%s;%s",
636                 tmpaddr, tmpcity, tmpstate, tmpzip, tmpcountry);
637         vcard_set_prop(my_vcard, "adr", tmpaddress, 0);
638         vcard_write_user(&CC->user, my_vcard);
639         vcard_free(my_vcard);
640 }
641
642
643 /*
644  * Protocol command to fetch registration info for a user
645  */
646 void cmd_greg(char *argbuf)
647 {
648         struct ctdluser usbuf;
649         struct vCard *v;
650         char *s;
651         char who[USERNAME_SIZE];
652         char adr[256];
653         char buf[256];
654
655         extract_token(who, argbuf, 0, '|', sizeof who);
656
657         if (!(CC->logged_in)) {
658                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
659                 return;
660         }
661
662         if (!strcasecmp(who,"_SELF_")) strcpy(who,CC->curr_user);
663
664         if ((CC->user.axlevel < 6) && (strcasecmp(who,CC->curr_user))) {
665                 cprintf("%d Higher access required.\n",
666                         ERROR + HIGHER_ACCESS_REQUIRED);
667                 return;
668         }
669
670         if (getuser(&usbuf, who) != 0) {
671                 cprintf("%d '%s' not found.\n", ERROR + NO_SUCH_USER, who);
672                 return;
673         }
674
675         v = vcard_get_user(&usbuf);
676
677         cprintf("%d %s\n", LISTING_FOLLOWS, usbuf.fullname);
678         cprintf("%ld\n", usbuf.usernum);
679         cprintf("%s\n", usbuf.password);
680         s = vcard_get_prop(v, "n", 0, 0, 0);
681         cprintf("%s\n", s ? s : " ");   /* name */
682
683         s = vcard_get_prop(v, "adr", 0, 0, 0);
684         snprintf(adr, sizeof adr, "%s", s ? s : " ");/* address... */
685
686         extract_token(buf, adr, 2, ';', sizeof buf);
687         cprintf("%s\n", buf);                           /* street */
688         extract_token(buf, adr, 3, ';', sizeof buf);
689         cprintf("%s\n", buf);                           /* city */
690         extract_token(buf, adr, 4, ';', sizeof buf);
691         cprintf("%s\n", buf);                           /* state */
692         extract_token(buf, adr, 5, ';', sizeof buf);
693         cprintf("%s\n", buf);                           /* zip */
694
695         s = vcard_get_prop(v, "tel;home", 0, 0, 0);
696         if (s == NULL) s = vcard_get_prop(v, "tel", 1, 0, 0);
697         if (s != NULL) {
698                 cprintf("%s\n", s);
699         }
700         else {
701                 cprintf(" \n");
702         }
703
704         cprintf("%d\n", usbuf.axlevel);
705
706         s = vcard_get_prop(v, "email;internet", 0, 0, 0);
707         cprintf("%s\n", s ? s : " ");
708         s = vcard_get_prop(v, "adr", 0, 0, 0);
709         snprintf(adr, sizeof adr, "%s", s ? s : " ");/* address... */
710
711         extract_token(buf, adr, 6, ';', sizeof buf);
712         cprintf("%s\n", buf);                           /* country */
713         cprintf("000\n");
714 }
715
716
717 /*
718  * When a user is being created, create his/her vCard.
719  */
720 void vcard_newuser(struct ctdluser *usbuf) {
721         char buf[256];
722         char vname[256];
723
724         char lastname[256];
725         char firstname[256];
726         char middlename[256];
727         char honorific_prefixes[256];
728         char honorific_suffixes[256];
729
730         struct vCard *v;
731         int i;
732
733         /* Try to intelligently convert the screen name to a
734          * fully expanded vCard name based on the number of
735          * words in the name
736          */
737         safestrncpy(lastname, "", sizeof lastname);
738         safestrncpy(firstname, "", sizeof firstname);
739         safestrncpy(middlename, "", sizeof middlename);
740         safestrncpy(honorific_prefixes, "", sizeof honorific_prefixes);
741         safestrncpy(honorific_suffixes, "", sizeof honorific_suffixes);
742
743         safestrncpy(buf, usbuf->fullname, sizeof buf);
744
745         /* Honorific suffixes */
746         if (num_tokens(buf, ',') > 1) {
747                 extract_token(honorific_suffixes, buf, (num_tokens(buf, ' ') - 1), ',',
748                         sizeof honorific_suffixes);
749                 remove_token(buf, (num_tokens(buf, ',') - 1), ',');
750         }
751
752         /* Find a last name */
753         extract_token(lastname, buf, (num_tokens(buf, ' ') - 1), ' ', sizeof lastname);
754         remove_token(buf, (num_tokens(buf, ' ') - 1), ' ');
755
756         /* Find honorific prefixes */
757         if (num_tokens(buf, ' ') > 2) {
758                 extract_token(honorific_prefixes, buf, 0, ' ', sizeof honorific_prefixes);
759                 remove_token(buf, 0, ' ');
760         }
761
762         /* Find a middle name */
763         if (num_tokens(buf, ' ') > 1) {
764                 extract_token(middlename, buf, (num_tokens(buf, ' ') - 1), ' ', sizeof middlename);
765                 remove_token(buf, (num_tokens(buf, ' ') - 1), ' ');
766         }
767
768         /* Anything left is probably the first name */
769         safestrncpy(firstname, buf, sizeof firstname);
770         striplt(firstname);
771
772         /* Compose the structured name */
773         snprintf(vname, sizeof vname, "%s;%s;%s;%s;%s", lastname, firstname, middlename,
774                 honorific_prefixes, honorific_suffixes);
775
776         lprintf(CTDL_DEBUG, "Converted <%s> to <%s>\n", usbuf->fullname, vname);
777
778         /* Create and save the vCard */
779         v = vcard_new();
780         if (v == NULL) return;
781         sprintf(buf, "%s@%s", usbuf->fullname, config.c_fqdn);
782         for (i=0; i<strlen(buf); ++i) {
783                 if (buf[i] == ' ') buf[i] = '_';
784         }
785         vcard_add_prop(v, "fn", usbuf->fullname);
786         vcard_add_prop(v, "n", vname);
787         vcard_add_prop(v, "adr", "adr:;;_;_;_;00000;__");
788         vcard_add_prop(v, "email;internet", buf);
789         vcard_write_user(usbuf, v);
790         vcard_free(v);
791 }
792
793
794 /*
795  * When a user is being deleted, we have to remove his/her vCard.
796  * This is accomplished by issuing a message with 'CANCEL' in the S (special)
797  * field, and the same Exclusive ID as the existing card.
798  */
799 void vcard_purge(struct ctdluser *usbuf) {
800         struct CtdlMessage *msg;
801         char buf[SIZ];
802
803         msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
804         if (msg == NULL) return;
805         memset(msg, 0, sizeof(struct CtdlMessage));
806
807         msg->cm_magic = CTDLMESSAGE_MAGIC;
808         msg->cm_anon_type = MES_NORMAL;
809         msg->cm_format_type = 0;
810         msg->cm_fields['A'] = strdup(usbuf->fullname);
811         msg->cm_fields['O'] = strdup(ADDRESS_BOOK_ROOM);
812         msg->cm_fields['N'] = strdup(NODENAME);
813         msg->cm_fields['M'] = strdup("Purge this vCard\n");
814
815         snprintf(buf, sizeof buf, VCARD_EXT_FORMAT,
816                         msg->cm_fields['A'], NODENAME);
817         msg->cm_fields['E'] = strdup(buf);
818
819         msg->cm_fields['S'] = strdup("CANCEL");
820
821         CtdlSubmitMsg(msg, NULL, ADDRESS_BOOK_ROOM);
822         CtdlFreeMessage(msg);
823 }
824
825
826 /*
827  * Grab vCard directory stuff out of incoming network messages
828  */
829 int vcard_extract_from_network(struct CtdlMessage *msg, char *target_room) {
830         char *ptr;
831         int linelen;
832
833         if (msg == NULL) return(0);
834
835         if (strcasecmp(target_room, ADDRESS_BOOK_ROOM)) {
836                 return(0);
837         }
838
839         if (msg->cm_format_type != 4) return(0);
840
841         ptr = msg->cm_fields['M'];
842         if (ptr == NULL) return(0);
843         while (ptr != NULL) {
844         
845                 linelen = strcspn(ptr, "\n");
846                 if (linelen == 0) return(0);    /* end of headers */    
847                 
848                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
849                          /* It's a vCard.  Add it to the directory. */
850                         vcard_extract_internet_addresses(msg,
851                                                         CtdlDirectoryAddUser);
852                         return(0);
853                 }
854
855                 ptr = strchr((char *)ptr, '\n');
856                 if (ptr != NULL) ++ptr;
857         }
858
859         return(0);
860 }
861
862
863
864 /* 
865  * When a vCard is being removed from the Global Address Book room, remove it
866  * from the directory as well.
867  */
868 void vcard_delete_remove(char *room, long msgnum) {
869         struct CtdlMessage *msg;
870         char *ptr;
871         int linelen;
872
873         if (msgnum <= 0L) return;
874
875         if (strcasecmp(room, ADDRESS_BOOK_ROOM)) {
876                 return;
877         }
878
879         msg = CtdlFetchMessage(msgnum, 1);
880         if (msg == NULL) return;
881
882         ptr = msg->cm_fields['M'];
883         if (ptr == NULL) goto EOH;
884         while (ptr != NULL) {
885                 linelen = strcspn(ptr, "\n");
886                 if (linelen == 0) goto EOH;
887                 
888                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
889                         /* Bingo!  A vCard is being deleted.
890                         */
891                         vcard_extract_internet_addresses(msg,
892                                                         CtdlDirectoryDelUser);
893 #ifdef HAVE_LDAP
894                         ctdl_vcard_to_ldap(msg, V2L_DELETE);
895 #endif
896                 }
897                 ptr = strchr((char *)ptr, '\n');
898                 if (ptr != NULL) ++ptr;
899         }
900
901 EOH:    CtdlFreeMessage(msg);
902 }
903
904
905
906 /*
907  * Query Directory
908  */
909 void cmd_qdir(char *argbuf) {
910         char citadel_addr[256];
911         char internet_addr[256];
912
913         if (CtdlAccessCheck(ac_logged_in)) return;
914
915         extract_token(internet_addr, argbuf, 0, '|', sizeof internet_addr);
916
917         if (CtdlDirectoryLookup(citadel_addr, internet_addr, sizeof citadel_addr) != 0) {
918                 cprintf("%d %s was not found.\n",
919                         ERROR + NO_SUCH_USER, internet_addr);
920                 return;
921         }
922
923         cprintf("%d %s\n", CIT_OK, citadel_addr);
924 }
925
926
927 /*
928  * We don't know if the Contacts room exists so we just create it at login
929  */
930 void vcard_create_room(void)
931 {
932         struct ctdlroom qr;
933         struct visit vbuf;
934
935         /* Create the calendar room if it doesn't already exist */
936         create_room(USERCONTACTSROOM, 4, "", 0, 1, 0, VIEW_ADDRESSBOOK);
937
938         /* Set expiration policy to manual; otherwise objects will be lost! */
939         if (lgetroom(&qr, USERCONTACTSROOM)) {
940                 lprintf(CTDL_ERR, "Couldn't get the user CONTACTS room!\n");
941                 return;
942         }
943         qr.QRep.expire_mode = EXPIRE_MANUAL;
944         qr.QRdefaultview = VIEW_ADDRESSBOOK;    /* 2 = address book view */
945         lputroom(&qr);
946
947         /* Set the view to a calendar view */
948         CtdlGetRelationship(&vbuf, &CC->user, &qr);
949         vbuf.v_view = 2;        /* 2 = address book view */
950         CtdlSetRelationship(&vbuf, &CC->user, &qr);
951
952         return;
953 }
954
955
956
957
958 /*
959  * When a user logs in...
960  */
961 void vcard_session_login_hook(void) {
962         struct vCard *v;
963
964         v = vcard_get_user(&CC->user);
965         vcard_populate_cs_inet_email(v);
966
967         vcard_free(v);
968
969         vcard_create_room();
970 }
971
972
973
974 char *serv_vcard_init(void)
975 {
976         struct ctdlroom qr;
977
978         CtdlRegisterSessionHook(vcard_session_login_hook, EVT_LOGIN);
979         CtdlRegisterMessageHook(vcard_upload_beforesave, EVT_BEFORESAVE);
980         CtdlRegisterMessageHook(vcard_upload_aftersave, EVT_AFTERSAVE);
981         CtdlRegisterDeleteHook(vcard_delete_remove);
982         CtdlRegisterProtoHook(cmd_regi, "REGI", "Enter registration info");
983         CtdlRegisterProtoHook(cmd_greg, "GREG", "Get registration info");
984         CtdlRegisterProtoHook(cmd_igab, "IGAB",
985                                         "Initialize Global Address Book");
986         CtdlRegisterProtoHook(cmd_qdir, "QDIR", "Query Directory");
987         CtdlRegisterUserHook(vcard_newuser, EVT_NEWUSER);
988         CtdlRegisterUserHook(vcard_purge, EVT_PURGEUSER);
989         CtdlRegisterNetprocHook(vcard_extract_from_network);
990
991         /* Create the Global ADdress Book room if necessary */
992         create_room(ADDRESS_BOOK_ROOM, 3, "", 0, 1, 0, VIEW_ADDRESSBOOK);
993
994         /* Set expiration policy to manual; otherwise objects will be lost! */
995         if (!lgetroom(&qr, ADDRESS_BOOK_ROOM)) {
996                 qr.QRep.expire_mode = EXPIRE_MANUAL;
997                 qr.QRdefaultview = VIEW_ADDRESSBOOK;    /* 2 = address book view */
998                 lputroom(&qr);
999         }
1000
1001         return "$Id$";
1002 }