4f487561f275f441ab3afeb396fabeb9e8913e53
[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-2001 / 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 "Extended 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 "dynloader.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
67 struct vcard_internal_info {
68         long msgnum;
69 };
70
71 /* Message number symbol used internally by these functions */
72 unsigned long SYM_VCARD;
73 #define VC ((struct vcard_internal_info *)CtdlGetUserData(SYM_VCARD))
74
75
76 /*
77  * Extract Internet e-mail addresses from a message containing a vCard, and
78  * perform a callback for any found.
79  */
80 void vcard_extract_internet_addresses(struct CtdlMessage *msg,
81                                 void (*callback)(char *, char *) ) {
82         struct vCard *v;
83         char *s;
84         char *addr;
85         char citadel_address[SIZ];
86         int instance = 0;
87         int found_something = 0;
88
89         if (msg->cm_fields['A'] == NULL) return;
90         if (msg->cm_fields['N'] == NULL) return;
91         sprintf(citadel_address, "%s @ %s",
92                 msg->cm_fields['A'], msg->cm_fields['N']);
93
94         v = vcard_load(msg->cm_fields['M']);
95         if (v == NULL) return;
96
97         /* Go through the vCard searching for *all* instances of
98          * the "email;internet" key
99          */
100         do {
101                 s = vcard_get_prop(v, "email;internet", 0, instance++);
102                 if (s != NULL) {
103                         addr = strdoop(s);
104                         striplt(addr);
105                         if (strlen(addr) > 0) {
106                                 if (callback != NULL) {
107                                         callback(addr, citadel_address);
108                                 }
109                         }
110                         phree(addr);
111                         found_something = 1;
112                 }
113                 else {
114                         found_something = 0;
115                 }
116         } while(found_something);
117
118         vcard_free(v);
119 }
120
121 /*
122  * Back end function for cmd_igab()
123  */
124 void vcard_add_to_directory(long msgnum, void *data) {
125         struct CtdlMessage *msg;
126
127         msg = CtdlFetchMessage(msgnum);
128         if (msg != NULL) {
129                 vcard_extract_internet_addresses(msg, CtdlDirectoryAddUser);
130         }
131
132         CtdlFreeMessage(msg);
133 }
134
135
136 /*
137  * Initialize Global Adress Book
138  */
139 void cmd_igab(char *argbuf) {
140         char hold_rm[ROOMNAMELEN];
141
142         if (CtdlAccessCheck(ac_aide)) return;
143
144         strcpy(hold_rm, CC->quickroom.QRname);  /* save current room */
145
146         if (getroom(&CC->quickroom, ADDRESS_BOOK_ROOM) != 0) {
147                 getroom(&CC->quickroom, hold_rm);
148                 cprintf("%d cannot get address book room\n", ERROR);
149                 return;
150         }
151
152         /* Empty the existing database first.
153          */
154         CtdlDirectoryInit();
155
156         /* We want the last (and probably only) vcard in this room */
157         CtdlForEachMessage(MSGS_ALL, 0, (-127), "text/x-vcard",
158                 NULL, vcard_add_to_directory, NULL);
159
160         getroom(&CC->quickroom, hold_rm);       /* return to saved room */
161         cprintf("%d Directory has been rebuilt.\n", OK);
162 }
163
164
165
166 /*
167  * This handler detects whether the user is attempting to save a new
168  * vCard as part of his/her personal configuration, and handles the replace
169  * function accordingly (delete the user's existing vCard in the config room
170  * and in the global address book).
171  */
172 int vcard_upload_beforesave(struct CtdlMessage *msg) {
173         char *ptr;
174         int linelen;
175         char config_rm[ROOMNAMELEN];
176         char buf[SIZ];
177
178         if (!CC->logged_in) return(0);  /* Only do this if logged in. */
179
180         /* If this isn't the configuration room, or if this isn't a MIME
181          * message, don't bother.  (Check for NULL room first, otherwise
182          * some messages will cause it to crash!!)
183          */
184         if (msg->cm_fields['O'] == NULL) return(0);
185         if (strcasecmp(msg->cm_fields['O'], USERCONFIGROOM)) return(0);
186         if (msg->cm_format_type != 4) return(0);
187
188         ptr = msg->cm_fields['M'];
189         if (ptr == NULL) return(0);
190         while (ptr != NULL) {
191         
192                 linelen = strcspn(ptr, "\n");
193                 if (linelen == 0) return(0);    /* end of headers */    
194                 
195                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
196                         /* Bingo!  The user is uploading a new vCard, so
197                          * delete the old one.
198                          */
199
200                         /* Delete the user's old vCard.  This would probably
201                          * get taken care of by the replication check, but we
202                          * want to make sure there is absolutely only one
203                          * vCard in the user's config room at all times.
204                          * 
205                          * FIXME ... this needs to be tweaked to allow an admin
206                          * to make changes to another user's vCard instead of
207                          * assuming that it's always the user saving his own.
208                          */
209                         MailboxName(config_rm, &CC->usersupp, USERCONFIGROOM);
210                         CtdlDeleteMessages(config_rm, 0L, "text/x-vcard");
211
212                         /* Set the Extended-ID to a standardized one so the
213                          * replication always works correctly
214                          */
215                         if (msg->cm_fields['E'] != NULL)
216                                 phree(msg->cm_fields['E']);
217
218                         sprintf(buf, VCARD_EXT_FORMAT,
219                                 msg->cm_fields['A'], NODENAME);
220                         msg->cm_fields['E'] = strdoop(buf);
221
222                         /* Now allow the save to complete. */
223                         return(0);
224                 }
225
226                 ptr = strchr((char *)ptr, '\n');
227                 if (ptr != NULL) ++ptr;
228         }
229
230         return(0);
231 }
232
233
234
235 /*
236  * This handler detects whether the user is attempting to save a new
237  * vCard as part of his/her personal configuration, and handles the replace
238  * function accordingly (copy the vCard from the config room to the global
239  * address book).
240  */
241 int vcard_upload_aftersave(struct CtdlMessage *msg) {
242         char *ptr;
243         int linelen;
244         long I;
245
246         if (!CC->logged_in) return(0);  /* Only do this if logged in. */
247
248         /* If this isn't the configuration room, or if this isn't a MIME
249          * message, don't bother.
250          */
251         if (msg->cm_fields['O'] == NULL) return(0);
252         if (strcasecmp(msg->cm_fields['O'], USERCONFIGROOM)) return(0);
253         if (msg->cm_format_type != 4) return(0);
254
255         ptr = msg->cm_fields['M'];
256         if (ptr == NULL) return(0);
257         while (ptr != NULL) {
258         
259                 linelen = strcspn(ptr, "\n");
260                 if (linelen == 0) return(0);    /* end of headers */    
261                 
262                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
263                         /* Bingo!  The user is uploading a new vCard, so
264                          * copy it to the Global Address Book room.
265                          */
266
267                         I = atol(msg->cm_fields['I']);
268                         if (I < 0L) return(0);
269
270                         /* Put it in the Global Address Book room... */
271                         CtdlSaveMsgPointerInRoom(ADDRESS_BOOK_ROOM, I,
272                                 (SM_VERIFY_GOODNESS | SM_DO_REPL_CHECK) );
273
274                         /* ...and also in the directory database. */
275                         vcard_add_to_directory(I, NULL);
276
277                         return(0);
278                 }
279
280                 ptr = strchr((char *)ptr, '\n');
281                 if (ptr != NULL) ++ptr;
282         }
283
284         return(0);
285 }
286
287
288
289 /*
290  * back end function used for callbacks
291  */
292 void vcard_gu_backend(long msgnum, void *userdata) {
293         VC->msgnum = msgnum;
294 }
295
296
297 /*
298  * If this user has a vcard on disk, read it into memory, otherwise allocate
299  * and return an empty vCard.
300  */
301 struct vCard *vcard_get_user(struct usersupp *u) {
302         char hold_rm[ROOMNAMELEN];
303         char config_rm[ROOMNAMELEN];
304         struct CtdlMessage *msg;
305         struct vCard *v;
306
307         strcpy(hold_rm, CC->quickroom.QRname);  /* save current room */
308         MailboxName(config_rm, u, USERCONFIGROOM);
309
310         if (getroom(&CC->quickroom, config_rm) != 0) {
311                 getroom(&CC->quickroom, hold_rm);
312                 return vcard_new();
313         }
314
315         /* We want the last (and probably only) vcard in this room */
316         VC->msgnum = (-1);
317         CtdlForEachMessage(MSGS_LAST, 1, (-127), "text/x-vcard",
318                 NULL, vcard_gu_backend, NULL);
319         getroom(&CC->quickroom, hold_rm);       /* return to saved room */
320
321         if (VC->msgnum < 0L) return vcard_new();
322
323         msg = CtdlFetchMessage(VC->msgnum);
324         if (msg == NULL) return vcard_new();
325
326         v = vcard_load(msg->cm_fields['M']);
327         CtdlFreeMessage(msg);
328         return v;
329 }
330
331
332 /*
333  * Store this user's vCard in the appropriate place
334  */
335 /*
336  * Write our config to disk
337  */
338 void vcard_write_user(struct usersupp *u, struct vCard *v) {
339         char temp[PATH_MAX];
340         FILE *fp;
341         char *ser;
342
343         strcpy(temp, tmpnam(NULL));
344         ser = vcard_serialize(v);
345
346         fp = fopen(temp, "w");
347         if (fp == NULL) return;
348         if (ser == NULL) {
349                 fprintf(fp, "begin:vcard\r\nend:vcard\r\n");
350         } else {
351                 fwrite(ser, strlen(ser), 1, fp);
352                 phree(ser);
353         }
354         fclose(fp);
355
356         /* This handy API function does all the work for us.
357          * NOTE: normally we would want to set that last argument to 1, to
358          * force the system to delete the user's old vCard.  But it doesn't
359          * have to, because the vcard_upload_beforesave() hook above
360          * is going to notice what we're trying to do, and delete the old vCard.
361          */
362         CtdlWriteObject(USERCONFIGROOM, /* which room */
363                         "text/x-vcard", /* MIME type */
364                         temp,           /* temp file */
365                         u,              /* which user */
366                         0,              /* not binary */
367                         0,              /* don't delete others of this type */
368                         0);             /* no flags */
369
370         unlink(temp);
371 }
372
373
374
375 /*
376  * Old style "enter registration info" command.  This function simply honors
377  * the REGI protocol command, translates the entered parameters into a vCard,
378  * and enters the vCard into the user's configuration.
379  */
380 void cmd_regi(char *argbuf) {
381         int a,b,c;
382         char buf[SIZ];
383         struct vCard *my_vcard;
384
385         char tmpaddr[SIZ];
386         char tmpcity[SIZ];
387         char tmpstate[SIZ];
388         char tmpzip[SIZ];
389         char tmpaddress[SIZ];
390         char tmpcountry[SIZ];
391
392         if (!(CC->logged_in)) {
393                 cprintf("%d Not logged in.\n",ERROR+NOT_LOGGED_IN);
394                 return;
395         }
396
397         my_vcard = vcard_get_user(&CC->usersupp);
398         strcpy(tmpaddr, "");
399         strcpy(tmpcity, "");
400         strcpy(tmpstate, "");
401         strcpy(tmpzip, "");
402         strcpy(tmpcountry, "USA");
403
404         cprintf("%d Send registration...\n", SEND_LISTING);
405         a=0;
406         while (client_gets(buf), strcmp(buf,"000")) {
407                 if (a==0) vcard_set_prop(my_vcard, "n", buf, 0);
408                 if (a==1) strcpy(tmpaddr, buf);
409                 if (a==2) strcpy(tmpcity, buf);
410                 if (a==3) strcpy(tmpstate, buf);
411                 if (a==4) {
412                         for (c=0; c<strlen(buf); ++c) {
413                                 if ((buf[c]>='0') && (buf[c]<='9')) {
414                                         b = strlen(tmpzip);
415                                         tmpzip[b] = buf[c];
416                                         tmpzip[b+1] = 0;
417                                 }
418                         }
419                 }
420                 if (a==5) vcard_set_prop(my_vcard, "tel;home", buf, 0);
421                 if (a==6) vcard_set_prop(my_vcard, "email;internet", buf, 0);
422                 if (a==7) strcpy(tmpcountry, buf);
423                 ++a;
424         }
425
426         sprintf(tmpaddress, ";;%s;%s;%s;%s;%s",
427                 tmpaddr, tmpcity, tmpstate, tmpzip, tmpcountry);
428         vcard_set_prop(my_vcard, "adr", tmpaddress, 0);
429         vcard_write_user(&CC->usersupp, my_vcard);
430         vcard_free(my_vcard);
431
432         lgetuser(&CC->usersupp, CC->curr_user);
433         CC->usersupp.flags=(CC->usersupp.flags|US_REGIS|US_NEEDVALID);
434         lputuser(&CC->usersupp);
435
436         /* set global flag calling for validation */
437         begin_critical_section(S_CONTROL);
438         get_control();
439         CitControl.MMflags = CitControl.MMflags | MM_VALID ;
440         put_control();
441         end_critical_section(S_CONTROL);
442 }
443
444
445
446 /*
447  * Protocol command to fetch registration info for a user
448  */
449 void cmd_greg(char *argbuf)
450 {
451         struct usersupp usbuf;
452         struct vCard *v;
453         char *s;
454         char who[SIZ];
455         char adr[SIZ];
456         char buf[SIZ];
457
458         extract(who, argbuf, 0);
459
460         if (!(CC->logged_in)) {
461                 cprintf("%d Not logged in.\n", ERROR+NOT_LOGGED_IN);
462                 return;
463         }
464
465         if (!strcasecmp(who,"_SELF_")) strcpy(who,CC->curr_user);
466
467         if ((CC->usersupp.axlevel < 6) && (strcasecmp(who,CC->curr_user))) {
468                 cprintf("%d Higher access required.\n",
469                         ERROR+HIGHER_ACCESS_REQUIRED);
470                 return;
471         }
472
473         if (getuser(&usbuf, who) != 0) {
474                 cprintf("%d '%s' not found.\n", ERROR+NO_SUCH_USER, who);
475                 return;
476         }
477
478         v = vcard_get_user(&usbuf);
479
480         cprintf("%d %s\n", LISTING_FOLLOWS, usbuf.fullname);
481         cprintf("%ld\n", usbuf.usernum);
482         cprintf("%s\n", usbuf.password);
483         s = vcard_get_prop(v, "n", 0, 0);
484         cprintf("%s\n", s ? s : " ");   /* name */
485
486         s = vcard_get_prop(v, "adr", 0, 0);
487         sprintf(adr, "%s", s ? s : " ");/* address... */
488
489         extract_token(buf, adr, 2, ';');
490         cprintf("%s\n", buf);                           /* street */
491         extract_token(buf, adr, 3, ';');
492         cprintf("%s\n", buf);                           /* city */
493         extract_token(buf, adr, 4, ';');
494         cprintf("%s\n", buf);                           /* state */
495         extract_token(buf, adr, 5, ';');
496         cprintf("%s\n", buf);                           /* zip */
497
498         s = vcard_get_prop(v, "tel;home", 0, 0);
499         if (s == NULL) s = vcard_get_prop(v, "tel", 1, 0);
500         if (s != NULL) {
501                 cprintf("%s\n", s);
502         }
503         else {
504                 cprintf(" \n");
505         }
506
507         cprintf("%d\n", usbuf.axlevel);
508
509         s = vcard_get_prop(v, "email;internet", 0, 0);
510         cprintf("%s\n", s ? s : " ");
511         s = vcard_get_prop(v, "adr", 0, 0);
512         sprintf(adr, "%s", s ? s : " ");/* address... */
513
514         extract_token(buf, adr, 6, ';');
515         cprintf("%s\n", buf);                           /* country */
516         cprintf("000\n");
517 }
518
519
520 /*
521  * When a user is being deleted, we have to remove his/her vCard.
522  * This is accomplished by issuing a message with 'CANCEL' in the S (special)
523  * field, and the same Extended ID as the existing card.
524  */
525 void vcard_purge(char *username, long usernum) {
526         struct CtdlMessage *msg;
527         char buf[SIZ];
528
529         msg = (struct CtdlMessage *) mallok(sizeof(struct CtdlMessage));
530         if (msg == NULL) return;
531         memset(msg, 0, sizeof(struct CtdlMessage));
532
533         msg->cm_magic = CTDLMESSAGE_MAGIC;
534         msg->cm_anon_type = MES_NORMAL;
535         msg->cm_format_type = 0;
536         msg->cm_fields['A'] = strdoop(username);
537         msg->cm_fields['O'] = strdoop(ADDRESS_BOOK_ROOM);
538         msg->cm_fields['N'] = strdoop(NODENAME);
539         msg->cm_fields['M'] = strdoop("Purge this vCard\n");
540
541         sprintf(buf, VCARD_EXT_FORMAT, msg->cm_fields['A'], NODENAME);
542         msg->cm_fields['E'] = strdoop(buf);
543
544         msg->cm_fields['S'] = strdoop("CANCEL");
545
546         CtdlSubmitMsg(msg, NULL, ADDRESS_BOOK_ROOM);
547         CtdlFreeMessage(msg);
548 }
549
550
551 /*
552  * Grab vCard directory stuff out of incoming network messages
553  */
554 int vcard_extract_from_network(struct CtdlMessage *msg, char *target_room) {
555         char *ptr;
556         int linelen;
557
558         if (msg == NULL) return(0);
559
560         if (strcasecmp(target_room, ADDRESS_BOOK_ROOM)) {
561                 return(0);
562         }
563
564         if (msg->cm_format_type != 4) return(0);
565
566         ptr = msg->cm_fields['M'];
567         if (ptr == NULL) return(0);
568         while (ptr != NULL) {
569         
570                 linelen = strcspn(ptr, "\n");
571                 if (linelen == 0) return(0);    /* end of headers */    
572                 
573                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
574                          /* It's a vCard.  Add it to the directory. */
575                         vcard_extract_internet_addresses(msg,
576                                                         CtdlDirectoryAddUser);
577                         return(0);
578                 }
579
580                 ptr = strchr((char *)ptr, '\n');
581                 if (ptr != NULL) ++ptr;
582         }
583
584         return(0);
585 }
586
587
588
589 /*
590  * Session startup, allocate some per-session data
591  */
592 void vcard_session_startup_hook(void) {
593         CtdlAllocUserData(SYM_VCARD, sizeof(struct vcard_internal_info));
594 }
595
596
597 char *Dynamic_Module_Init(void)
598 {
599         SYM_VCARD = CtdlGetDynamicSymbol();
600         CtdlRegisterSessionHook(vcard_session_startup_hook, EVT_START);
601         CtdlRegisterMessageHook(vcard_upload_beforesave, EVT_BEFORESAVE);
602         CtdlRegisterMessageHook(vcard_upload_aftersave, EVT_AFTERSAVE);
603         CtdlRegisterProtoHook(cmd_regi, "REGI", "Enter registration info");
604         CtdlRegisterProtoHook(cmd_greg, "GREG", "Get registration info");
605         CtdlRegisterProtoHook(cmd_igab, "IGAB",
606                                         "Initialize Global Address Book");
607         CtdlRegisterUserHook(vcard_purge, EVT_PURGEUSER);
608         create_room(ADDRESS_BOOK_ROOM, 3, "", 0, 1);
609         CtdlRegisterNetprocHook(vcard_extract_from_network);
610         return "$Id$";
611 }