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