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