055ef0f36f47172f589e426be9e5d33b84f0b8f3
[citadel.git] / citadel / serv_network.c
1 /*
2  * $Id$ 
3  *
4  * This module handles shared rooms, inter-Citadel mail, and outbound
5  * mailing list processing.
6  *
7  * Copyright (C) 2000-2002 by Art Cancro and others.
8  * This code is released under the terms of the GNU General Public License.
9  *
10  * ** NOTE **   A word on the S_NETCONFIGS semaphore:
11  * This is a fairly high-level type of critical section.  It ensures that no
12  * two threads work on the netconfigs files at the same time.  Since we do
13  * so many things inside these, here are the rules:
14  *  1. begin_critical_section(S_NETCONFIGS) *before* begin_ any others.
15  *  2. Do *not* perform any I/O with the client during these sections.
16  *
17  */
18
19 /*
20  * Duration of time (in seconds) after which pending list subscribe/unsubscribe
21  * requests that have not been confirmed will be deleted.
22  */
23 #define EXP     259200  /* three days */
24
25 #include "sysdep.h"
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <stdio.h>
29 #include <fcntl.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <pwd.h>
33 #include <errno.h>
34 #include <sys/stat.h>
35 #include <sys/types.h>
36 #include <dirent.h>
37 #if TIME_WITH_SYS_TIME
38 # include <sys/time.h>
39 # include <time.h>
40 #else
41 # if HAVE_SYS_TIME_H
42 #  include <sys/time.h>
43 # else
44 #  include <time.h>
45 # endif
46 #endif
47
48 #include <sys/wait.h>
49 #include <string.h>
50 #include <limits.h>
51 #include "citadel.h"
52 #include "server.h"
53 #include "sysdep_decls.h"
54 #include "citserver.h"
55 #include "support.h"
56 #include "config.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 "tools.h"
64 #include "internet_addressing.h"
65 #include "serv_network.h"
66 #include "clientsocket.h"
67 #include "file_ops.h"
68
69 #ifndef HAVE_SNPRINTF
70 #include "snprintf.h"
71 #endif
72
73 /* Nonzero while we are doing outbound network processing */
74 static int doing_queue = 0;
75
76 /*
77  * When we do network processing, it's accomplished in two passes; one to
78  * gather a list of rooms and one to actually do them.  It's ok that rplist
79  * is global; this process *only* runs as part of the housekeeping loop and
80  * therefore only one will run at a time.
81  */
82 struct RoomProcList *rplist = NULL;
83
84 /*
85  * We build a map of network nodes during processing.
86  */
87 struct NetMap *the_netmap = NULL;
88 int netmap_changed = 0;
89 char *working_ignetcfg = NULL;
90
91 /*
92  * Load or refresh the Citadel network (IGnet) configuration for this node.
93  */
94 void load_working_ignetcfg(void) {
95         char *cfg;
96         char *oldcfg;
97
98         cfg = CtdlGetSysConfig(IGNETCFG);
99         if (cfg == NULL) {
100                 cfg = strdup("");
101         }
102
103         oldcfg = working_ignetcfg;
104         working_ignetcfg = cfg;
105         if (oldcfg != NULL) {
106                 free(oldcfg);
107         }
108 }
109
110
111
112
113
114 /*
115  * Keep track of what messages to reject
116  */
117 struct FilterList *load_filter_list(void) {
118         char *serialized_list = NULL;
119         int i;
120         char buf[SIZ];
121         struct FilterList *newlist = NULL;
122         struct FilterList *nptr;
123
124         serialized_list = CtdlGetSysConfig(FILTERLIST);
125         if (serialized_list == NULL) return(NULL); /* if null, no entries */
126
127         /* Use the string tokenizer to grab one line at a time */
128         for (i=0; i<num_tokens(serialized_list, '\n'); ++i) {
129                 extract_token(buf, serialized_list, i, '\n', sizeof buf);
130                 nptr = (struct FilterList *) malloc(sizeof(struct FilterList));
131                 extract_token(nptr->fl_user, buf, 0, '|', sizeof nptr->fl_user);
132                 striplt(nptr->fl_user);
133                 extract_token(nptr->fl_room, buf, 1, '|', sizeof nptr->fl_room);
134                 striplt(nptr->fl_room);
135                 extract_token(nptr->fl_node, buf, 2, '|', sizeof nptr->fl_node);
136                 striplt(nptr->fl_node);
137
138                 /* Cowardly refuse to add an any/any/any entry that would
139                  * end up filtering every single message.
140                  */
141                 if (strlen(nptr->fl_user) + strlen(nptr->fl_room)
142                    + strlen(nptr->fl_node) == 0) {
143                         free(nptr);
144                 }
145                 else {
146                         nptr->next = newlist;
147                         newlist = nptr;
148                 }
149         }
150
151         free(serialized_list);
152         return newlist;
153 }
154
155
156 void free_filter_list(struct FilterList *fl) {
157         if (fl == NULL) return;
158         free_filter_list(fl->next);
159         free(fl);
160 }
161
162
163
164 /*
165  * Check the use table.  This is a list of messages which have recently
166  * arrived on the system.  It is maintained and queried to prevent the same
167  * message from being entered into the database multiple times if it happens
168  * to arrive multiple times by accident.
169  */
170 int network_usetable(struct CtdlMessage *msg) {
171
172         char msgid[SIZ];
173         struct cdbdata *cdbut;
174         struct UseTable ut;
175
176         /* Bail out if we can't generate a message ID */
177         if (msg == NULL) {
178                 return(0);
179         }
180         if (msg->cm_fields['I'] == NULL) {
181                 return(0);
182         }
183         if (strlen(msg->cm_fields['I']) == 0) {
184                 return(0);
185         }
186
187         /* Generate the message ID */
188         strcpy(msgid, msg->cm_fields['I']);
189         if (haschar(msgid, '@') == 0) {
190                 strcat(msgid, "@");
191                 if (msg->cm_fields['N'] != NULL) {
192                         strcat(msgid, msg->cm_fields['N']);
193                 }
194                 else {
195                         return(0);
196                 }
197         }
198
199         cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
200         if (cdbut != NULL) {
201                 cdb_free(cdbut);
202                 return(1);
203         }
204
205         /* If we got to this point, it's unique: add it. */
206         strcpy(ut.ut_msgid, msgid);
207         ut.ut_timestamp = time(NULL);
208         cdb_store(CDB_USETABLE, msgid, strlen(msgid),
209                 &ut, sizeof(struct UseTable) );
210         return(0);
211 }
212
213
214 /* 
215  * Read the network map from its configuration file into memory.
216  */
217 void read_network_map(void) {
218         char *serialized_map = NULL;
219         int i;
220         char buf[SIZ];
221         struct NetMap *nmptr;
222
223         serialized_map = CtdlGetSysConfig(IGNETMAP);
224         if (serialized_map == NULL) return;     /* if null, no entries */
225
226         /* Use the string tokenizer to grab one line at a time */
227         for (i=0; i<num_tokens(serialized_map, '\n'); ++i) {
228                 extract_token(buf, serialized_map, i, '\n', sizeof buf);
229                 nmptr = (struct NetMap *) malloc(sizeof(struct NetMap));
230                 extract_token(nmptr->nodename, buf, 0, '|', sizeof nmptr->nodename);
231                 nmptr->lastcontact = extract_long(buf, 1);
232                 extract_token(nmptr->nexthop, buf, 2, '|', sizeof nmptr->nexthop);
233                 nmptr->next = the_netmap;
234                 the_netmap = nmptr;
235         }
236
237         free(serialized_map);
238         netmap_changed = 0;
239 }
240
241
242 /*
243  * Write the network map from memory back to the configuration file.
244  */
245 void write_network_map(void) {
246         char *serialized_map = NULL;
247         struct NetMap *nmptr;
248
249
250         if (netmap_changed) {
251                 serialized_map = strdup("");
252         
253                 if (the_netmap != NULL) {
254                         for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
255                                 serialized_map = realloc(serialized_map,
256                                                         (strlen(serialized_map)+SIZ) );
257                                 if (strlen(nmptr->nodename) > 0) {
258                                         snprintf(&serialized_map[strlen(serialized_map)],
259                                                 SIZ,
260                                                 "%s|%ld|%s\n",
261                                                 nmptr->nodename,
262                                                 (long)nmptr->lastcontact,
263                                                 nmptr->nexthop);
264                                 }
265                         }
266                 }
267
268                 CtdlPutSysConfig(IGNETMAP, serialized_map);
269                 free(serialized_map);
270         }
271
272         /* Now free the list */
273         while (the_netmap != NULL) {
274                 nmptr = the_netmap->next;
275                 free(the_netmap);
276                 the_netmap = nmptr;
277         }
278         netmap_changed = 0;
279 }
280
281
282
283 /* 
284  * Check the network map and determine whether the supplied node name is
285  * valid.  If it is not a neighbor node, supply the name of a neighbor node
286  * which is the next hop.  If it *is* a neighbor node, we also fill in the
287  * shared secret.
288  */
289 int is_valid_node(char *nexthop, char *secret, char *node) {
290         int i;
291         char linebuf[SIZ];
292         char buf[SIZ];
293         int retval;
294         struct NetMap *nmptr;
295
296         if (node == NULL) {
297                 return(-1);
298         }
299
300         /*
301          * First try the neighbor nodes
302          */
303         if (working_ignetcfg == NULL) {
304                 lprintf(CTDL_ERR, "working_ignetcfg is NULL!\n");
305                 if (nexthop != NULL) {
306                         strcpy(nexthop, "");
307                 }
308                 return(-1);
309         }
310
311         retval = (-1);
312         if (nexthop != NULL) {
313                 strcpy(nexthop, "");
314         }
315
316         /* Use the string tokenizer to grab one line at a time */
317         for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
318                 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
319                 extract_token(buf, linebuf, 0, '|', sizeof buf);
320                 if (!strcasecmp(buf, node)) {
321                         if (nexthop != NULL) {
322                                 strcpy(nexthop, "");
323                         }
324                         if (secret != NULL) {
325                                 extract_token(secret, linebuf, 1, '|', 256);
326                         }
327                         retval = 0;
328                 }
329         }
330
331         if (retval == 0) {
332                 return(retval);         /* yup, it's a direct neighbor */
333         }
334
335         /*      
336          * If we get to this point we have to see if we know the next hop
337          */
338         if (the_netmap != NULL) {
339                 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
340                         if (!strcasecmp(nmptr->nodename, node)) {
341                                 if (nexthop != NULL) {
342                                         strcpy(nexthop, nmptr->nexthop);
343                                 }
344                                 return(0);
345                         }
346                 }
347         }
348
349         /*
350          * If we get to this point, the supplied node name is bogus.
351          */
352         lprintf(CTDL_ERR, "Invalid node name <%s>\n", node);
353         return(-1);
354 }
355
356
357
358
359
360 void cmd_gnet(char *argbuf) {
361         char filename[SIZ];
362         char buf[SIZ];
363         FILE *fp;
364
365         if (CtdlAccessCheck(ac_room_aide)) return;
366         assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
367         cprintf("%d Network settings for room #%ld <%s>\n",
368                 LISTING_FOLLOWS,
369                 CC->room.QRnumber, CC->room.QRname);
370
371         fp = fopen(filename, "r");
372         if (fp != NULL) {
373                 while (fgets(buf, sizeof buf, fp) != NULL) {
374                         buf[strlen(buf)-1] = 0;
375                         cprintf("%s\n", buf);
376                 }
377                 fclose(fp);
378         }
379
380         cprintf("000\n");
381 }
382
383
384 void cmd_snet(char *argbuf) {
385         char tempfilename[SIZ];
386         char filename[SIZ];
387         char buf[SIZ];
388         FILE *fp;
389
390         unbuffer_output();
391
392         if (CtdlAccessCheck(ac_room_aide)) return;
393         safestrncpy(tempfilename, tmpnam(NULL), sizeof tempfilename);
394         assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
395
396         fp = fopen(tempfilename, "w");
397         if (fp == NULL) {
398                 cprintf("%d Cannot open %s: %s\n",
399                         ERROR + INTERNAL_ERROR,
400                         tempfilename,
401                         strerror(errno));
402         }
403
404         cprintf("%d %s\n", SEND_LISTING, tempfilename);
405         while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
406                 fprintf(fp, "%s\n", buf);
407         }
408         fclose(fp);
409
410         /* Now copy the temp file to its permanent location
411          * (We use /bin/mv instead of link() because they may be on
412          * different filesystems)
413          */
414         unlink(filename);
415         snprintf(buf, sizeof buf, "/bin/mv %s %s", tempfilename, filename);
416         begin_critical_section(S_NETCONFIGS);
417         system(buf);
418         end_critical_section(S_NETCONFIGS);
419 }
420
421
422 /*
423  * Spools out one message from the list.
424  */
425 void network_spool_msg(long msgnum, void *userdata) {
426         struct SpoolControl *sc;
427         int err;
428         int i;
429         char *newpath = NULL;
430         char *instr = NULL;
431         size_t instr_len = SIZ;
432         struct CtdlMessage *msg = NULL;
433         struct CtdlMessage *imsg;
434         struct namelist *nptr;
435         struct maplist *mptr;
436         struct ser_ret sermsg;
437         FILE *fp;
438         char filename[SIZ];
439         char buf[SIZ];
440         int bang = 0;
441         int send = 1;
442         int delete_after_send = 0;      /* Set to 1 to delete after spooling */
443         long list_msgnum = 0L;
444         int ok_to_participate = 0;
445         char *end_of_headers = NULL;
446
447         sc = (struct SpoolControl *)userdata;
448
449         /*
450          * Process mailing list recipients
451          */
452         instr_len = SIZ;
453         if (sc->listrecps != NULL) {
454         
455                 /* First, copy it to the spoolout room */
456                 err = CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, msgnum, 0);
457                 if (err != 0) return;
458
459                 /* 
460                  * Figure out how big a buffer we need to allocate
461                  */
462                 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
463                         instr_len = instr_len + strlen(nptr->name);
464                 }
465         
466                 /*
467                  * allocate...
468                  */
469                 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
470                 instr = malloc(instr_len);
471                 if (instr == NULL) {
472                         lprintf(CTDL_EMERG,
473                                 "Cannot allocate %ld bytes for instr...\n",
474                                 (long)instr_len);
475                         abort();
476                 }
477                 snprintf(instr, instr_len,
478                         "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
479                         "bounceto|postmaster@%s\n" ,
480                         SPOOLMIME, msgnum, (long)time(NULL), config.c_fqdn );
481         
482                 /* Generate delivery instructions for each recipient */
483                 for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
484                         size_t tmp = strlen(instr);
485                         snprintf(&instr[tmp], instr_len - tmp,
486                                  "remote|%s|0||\n", nptr->name);
487                 }
488         
489                 /*
490                  * Generate a message from the instructions
491                  */
492                 imsg = malloc(sizeof(struct CtdlMessage));
493                 memset(imsg, 0, sizeof(struct CtdlMessage));
494                 imsg->cm_magic = CTDLMESSAGE_MAGIC;
495                 imsg->cm_anon_type = MES_NORMAL;
496                 imsg->cm_format_type = FMT_RFC822;
497                 imsg->cm_fields['A'] = strdup("Citadel");
498                 imsg->cm_fields['M'] = instr;
499         
500                 /* Save delivery instructions in spoolout room */
501                 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
502                 CtdlFreeMessage(imsg);
503         }
504
505         /*
506          * Process digest recipients
507          */
508         if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
509                 msg = CtdlFetchMessage(msgnum, 1);
510                 if (msg != NULL) {
511                         fprintf(sc->digestfp,   " -----------------------------------"
512                                                 "------------------------------------"
513                                                 "-------\n");
514                         fprintf(sc->digestfp, "From: ");
515                         if (msg->cm_fields['A'] != NULL) {
516                                 fprintf(sc->digestfp, "%s ", msg->cm_fields['A']);
517                         }
518                         if (msg->cm_fields['F'] != NULL) {
519                                 fprintf(sc->digestfp, "<%s> ", msg->cm_fields['F']);
520                         }
521                         else if (msg->cm_fields['N'] != NULL) {
522                                 fprintf(sc->digestfp, "@%s ", msg->cm_fields['N']);
523                         }
524                         fprintf(sc->digestfp, "\n");
525                         if (msg->cm_fields['U'] != NULL) {
526                                 fprintf(sc->digestfp, "Subject: %s\n", msg->cm_fields['U']);
527                         }
528
529                         CC->redirect_buffer = malloc(SIZ);
530                         CC->redirect_len = 0;
531                         CC->redirect_alloc = SIZ;
532
533                         safestrncpy(CC->preferred_formats, "text/plain", sizeof CC->preferred_formats);
534                         CtdlOutputPreLoadedMsg(msg, 0L, MT_MIME, HEADERS_NONE, 0, 0);
535
536                         end_of_headers = bmstrstr(CC->redirect_buffer, "\n\r\n", strncmp);
537                         if (end_of_headers == NULL) {
538                                 end_of_headers = bmstrstr(CC->redirect_buffer, "\n\n", strncmp);
539                         }
540                         if (end_of_headers == NULL) {
541                                 end_of_headers = CC->redirect_buffer;
542                         }
543                         striplt(end_of_headers);
544                         fprintf(sc->digestfp, "\n%s\n", end_of_headers);
545
546                         free(CC->redirect_buffer);
547                         CC->redirect_buffer = NULL;
548                         CC->redirect_len = 0;
549                         CC->redirect_alloc = 0;
550
551                         sc->num_msgs_spooled += 1;
552                         free(msg);
553                 }
554         }
555
556         /*
557          * Process client-side list participations for this room
558          */
559         instr_len = SIZ;
560         if (sc->participates != NULL) {
561                 msg = CtdlFetchMessage(msgnum, 1);
562                 if (msg != NULL) {
563
564                         /* Only send messages which originated on our own Citadel
565                          * network, otherwise we'll end up sending the remote
566                          * mailing list's messages back to it, which is rude...
567                          */
568                         ok_to_participate = 0;
569                         if (msg->cm_fields['N'] != NULL) {
570                                 if (!strcasecmp(msg->cm_fields['N'], config.c_nodename)) {
571                                         ok_to_participate = 1;
572                                 }
573                                 if (is_valid_node(NULL, NULL, msg->cm_fields['N']) == 0) {
574                                         ok_to_participate = 1;
575                                 }
576                         }
577                         if (ok_to_participate) {
578                                 if (msg->cm_fields['F'] != NULL) {
579                                         free(msg->cm_fields['F']);
580                                 }
581                                 msg->cm_fields['F'] = malloc(SIZ);
582                                 /* Replace the Internet email address of the actual
583                                 * author with the email address of the room itself,
584                                 * so the remote listserv doesn't reject us.
585                                 * FIXME ... I want to be able to pick any address
586                                 */
587                                 snprintf(msg->cm_fields['F'], SIZ,
588                                         "room_%s@%s", CC->room.QRname,
589                                         config.c_fqdn);
590                                 for (i=0; i<strlen(msg->cm_fields['F']); ++i) {
591                                         if (isspace(msg->cm_fields['F'][i])) {
592                                                 msg->cm_fields['F'][i] = '_';
593                                         }
594                                 }
595
596                                 /* Now save it and generate delivery instructions */
597                                 list_msgnum = CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM);
598
599                                 /* 
600                                  * Figure out how big a buffer we need to allocate
601                                  */
602                                 for (nptr = sc->participates; nptr != NULL; nptr = nptr->next) {
603                                         instr_len = instr_len + strlen(nptr->name);
604                                 }
605                         
606                                 /*
607                                  * allocate...
608                                  */
609                                 instr = malloc(instr_len);
610                                 if (instr == NULL) {
611                                         lprintf(CTDL_EMERG,
612                                                 "Cannot allocate %ld bytes for instr...\n",
613                                                 (long)instr_len);
614                                         abort();
615                                 }
616                                 snprintf(instr, instr_len,
617                                         "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
618                                         "bounceto|postmaster@%s\n" ,
619                                         SPOOLMIME, list_msgnum, (long)time(NULL), config.c_fqdn );
620                         
621                                 /* Generate delivery instructions for each recipient */
622                                 for (nptr = sc->participates; nptr != NULL; nptr = nptr->next) {
623                                         size_t tmp = strlen(instr);
624                                         snprintf(&instr[tmp], instr_len - tmp,
625                                                  "remote|%s|0||\n", nptr->name);
626                                 }
627                         
628                                 /*
629                                  * Generate a message from the instructions
630                                  */
631                                 imsg = malloc(sizeof(struct CtdlMessage));
632                                 memset(imsg, 0, sizeof(struct CtdlMessage));
633                                 imsg->cm_magic = CTDLMESSAGE_MAGIC;
634                                 imsg->cm_anon_type = MES_NORMAL;
635                                 imsg->cm_format_type = FMT_RFC822;
636                                 imsg->cm_fields['A'] = strdup("Citadel");
637                                 imsg->cm_fields['M'] = instr;
638                         
639                                 /* Save delivery instructions in spoolout room */
640                                 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
641                                 CtdlFreeMessage(imsg);
642                         }
643                         CtdlFreeMessage(msg);
644                 }
645         }
646         
647         /*
648          * Process IGnet push shares
649          */
650         if (sc->ignet_push_shares != NULL) {
651         
652                 msg = CtdlFetchMessage(msgnum, 1);
653                 if (msg != NULL) {
654                         size_t newpath_len;
655
656                         /* Prepend our node name to the Path field whenever
657                          * sending a message to another IGnet node
658                          */
659                         if (msg->cm_fields['P'] == NULL) {
660                                 msg->cm_fields['P'] = strdup("username");
661                         }
662                         newpath_len = strlen(msg->cm_fields['P']) +
663                                  strlen(config.c_nodename) + 2;
664                         newpath = malloc(newpath_len);
665                         snprintf(newpath, newpath_len, "%s!%s",
666                                  config.c_nodename, msg->cm_fields['P']);
667                         free(msg->cm_fields['P']);
668                         msg->cm_fields['P'] = newpath;
669
670                         /*
671                          * Determine if this message is set to be deleted
672                          * after sending out on the network
673                          */
674                         if (msg->cm_fields['S'] != NULL) {
675                                 if (!strcasecmp(msg->cm_fields['S'],
676                                    "CANCEL")) {
677                                         delete_after_send = 1;
678                                 }
679                         }
680
681                         /* Now send it to every node */
682                         for (mptr = sc->ignet_push_shares; mptr != NULL;
683                             mptr = mptr->next) {
684
685                                 send = 1;
686
687                                 /* Check for valid node name */
688                                 if (is_valid_node(NULL, NULL, mptr->remote_nodename) != 0) {
689                                         lprintf(CTDL_ERR, "Invalid node <%s>\n",
690                                                 mptr->remote_nodename);
691                                         send = 0;
692                                 }
693
694                                 /* Check for split horizon */
695                                 lprintf(CTDL_DEBUG, "Path is %s\n", msg->cm_fields['P']);
696                                 bang = num_tokens(msg->cm_fields['P'], '!');
697                                 if (bang > 1) for (i=0; i<(bang-1); ++i) {
698                                         extract_token(buf, msg->cm_fields['P'],
699                                                 i, '!', sizeof buf);
700                                         if (!strcasecmp(buf, mptr->remote_nodename)) {
701                                                 send = 0;
702                                         }
703                                 }
704
705                                 /* Send the message */
706                                 if (send == 1) {
707
708                                         /*
709                                          * Force the message to appear in the correct room
710                                          * on the far end by setting the C field correctly
711                                          */
712                                         if (msg->cm_fields['C'] != NULL) {
713                                                 free(msg->cm_fields['C']);
714                                         }
715                                         if (strlen(mptr->remote_roomname) > 0) {
716                                                 msg->cm_fields['C'] = strdup(mptr->remote_roomname);
717                                         }
718                                         else {
719                                                 msg->cm_fields['C'] = strdup(CC->room.QRname);
720                                         }
721
722                                         /* serialize it for transmission */
723                                         serialize_message(&sermsg, msg);
724
725                                         /* write it to the spool file */
726                                         snprintf(filename, sizeof filename,
727 #ifndef HAVE_SPOOL_DIR
728                                                          "."
729 #else
730                                                          SPOOL_DIR
731 #endif /* HAVE_SPOOL_DIR */
732                                                          "/network/spoolout/%s",
733                                                          mptr->remote_nodename);
734                                         lprintf(CTDL_DEBUG, "Appending to %s\n", filename);
735                                         fp = fopen(filename, "ab");
736                                         if (fp != NULL) {
737                                                 fwrite(sermsg.ser,
738                                                         sermsg.len, 1, fp);
739                                                 fclose(fp);
740                                         }
741                                         else {
742                                                 lprintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
743                                         }
744
745                                         /* free the serialized version */
746                                         free(sermsg.ser);
747                                 }
748                         }
749                         CtdlFreeMessage(msg);
750                 }
751         }
752
753         /* update lastsent */
754         sc->lastsent = msgnum;
755
756         /* Delete this message if delete-after-send is set */
757         if (delete_after_send) {
758                 CtdlDeleteMessages(CC->room.QRname, msgnum, "");
759         }
760
761 }
762         
763
764 /*
765  * Deliver digest messages
766  */
767 void network_deliver_digest(struct SpoolControl *sc) {
768         char buf[SIZ];
769         int i;
770         struct CtdlMessage *msg;
771         long msglen;
772         long msgnum;
773         char *instr = NULL;
774         size_t instr_len = SIZ;
775         struct CtdlMessage *imsg;
776         struct namelist *nptr;
777
778         if (sc->num_msgs_spooled < 1) {
779                 fclose(sc->digestfp);
780                 sc->digestfp = NULL;
781                 return;
782         }
783
784         msg = malloc(sizeof(struct CtdlMessage));
785         memset(msg, 0, sizeof(struct CtdlMessage));
786         msg->cm_magic = CTDLMESSAGE_MAGIC;
787         msg->cm_format_type = FMT_RFC822;
788         msg->cm_anon_type = MES_NORMAL;
789
790         sprintf(buf, "%ld", time(NULL));
791         msg->cm_fields['T'] = strdup(buf);
792         msg->cm_fields['A'] = strdup(CC->room.QRname);
793         snprintf(buf, sizeof buf, "[%s]", CC->room.QRname);
794         msg->cm_fields['U'] = strdup(buf);
795         sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
796         for (i=0; i<strlen(buf); ++i) {
797                 if (isspace(buf[i])) buf[i]='_';
798                 buf[i] = tolower(buf[i]);
799         }
800         msg->cm_fields['F'] = strdup(buf);
801
802         fseek(sc->digestfp, 0L, SEEK_END);
803         msglen = ftell(sc->digestfp);
804
805         msg->cm_fields['M'] = malloc(msglen + 1);
806         fseek(sc->digestfp, 0L, SEEK_SET);
807         fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
808         msg->cm_fields['M'][msglen] = 0;
809
810         fclose(sc->digestfp);
811         sc->digestfp = NULL;
812
813         msgnum = CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM);
814         CtdlFreeMessage(msg);
815
816         /* Now generate the delivery instructions */
817
818         /* 
819          * Figure out how big a buffer we need to allocate
820          */
821         for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
822                 instr_len = instr_len + strlen(nptr->name);
823         }
824         
825         /*
826          * allocate...
827          */
828         lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
829         instr = malloc(instr_len);
830         if (instr == NULL) {
831                 lprintf(CTDL_EMERG, "Cannot allocate %ld bytes for instr...\n",
832                         (long)instr_len);
833                 abort();
834         }
835         snprintf(instr, instr_len,
836                 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
837                 "bounceto|postmaster@%s\n" ,
838                 SPOOLMIME, msgnum, (long)time(NULL), config.c_fqdn );
839
840         /* Generate delivery instructions for each recipient */
841         for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
842                 size_t tmp = strlen(instr);
843                 snprintf(&instr[tmp], instr_len - tmp,
844                          "remote|%s|0||\n", nptr->name);
845         }
846
847         /*
848          * Generate a message from the instructions
849          */
850         imsg = malloc(sizeof(struct CtdlMessage));
851         memset(imsg, 0, sizeof(struct CtdlMessage));
852         imsg->cm_magic = CTDLMESSAGE_MAGIC;
853         imsg->cm_anon_type = MES_NORMAL;
854         imsg->cm_format_type = FMT_RFC822;
855         imsg->cm_fields['A'] = strdup("Citadel");
856         imsg->cm_fields['M'] = instr;
857
858         /* Save delivery instructions in spoolout room */
859         CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
860         CtdlFreeMessage(imsg);
861 }
862
863
864 /*
865  * Batch up and send all outbound traffic from the current room
866  */
867 void network_spoolout_room(char *room_to_spool) {
868         char filename[SIZ];
869         char buf[SIZ];
870         char instr[SIZ];
871         char nodename[256];
872         char roomname[ROOMNAMELEN];
873         char nexthop[256];
874         FILE *fp;
875         struct SpoolControl sc;
876         struct namelist *nptr = NULL;
877         struct maplist *mptr = NULL;
878         size_t miscsize = 0;
879         size_t linesize = 0;
880         int skipthisline = 0;
881         int i;
882
883         if (getroom(&CC->room, room_to_spool) != 0) {
884                 lprintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", room_to_spool);
885                 return;
886         }
887
888         memset(&sc, 0, sizeof(struct SpoolControl));
889         assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
890
891         begin_critical_section(S_NETCONFIGS);
892
893         fp = fopen(filename, "r");
894         if (fp == NULL) {
895                 end_critical_section(S_NETCONFIGS);
896                 return;
897         }
898
899         lprintf(CTDL_INFO, "Networking started for <%s>\n", CC->room.QRname);
900
901         while (fgets(buf, sizeof buf, fp) != NULL) {
902                 buf[strlen(buf)-1] = 0;
903
904                 extract_token(instr, buf, 0, '|', sizeof instr);
905                 if (!strcasecmp(instr, "lastsent")) {
906                         sc.lastsent = extract_long(buf, 1);
907                 }
908                 else if (!strcasecmp(instr, "listrecp")) {
909                         nptr = (struct namelist *)
910                                 malloc(sizeof(struct namelist));
911                         nptr->next = sc.listrecps;
912                         extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
913                         sc.listrecps = nptr;
914                 }
915                 else if (!strcasecmp(instr, "participate")) {
916                         nptr = (struct namelist *)
917                                 malloc(sizeof(struct namelist));
918                         nptr->next = sc.participates;
919                         extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
920                         sc.participates = nptr;
921                 }
922                 else if (!strcasecmp(instr, "digestrecp")) {
923                         nptr = (struct namelist *)
924                                 malloc(sizeof(struct namelist));
925                         nptr->next = sc.digestrecps;
926                         extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
927                         sc.digestrecps = nptr;
928                 }
929                 else if (!strcasecmp(instr, "ignet_push_share")) {
930                         /* by checking each node's validity, we automatically
931                          * purge nodes which do not exist from room network
932                          * configurations at this time.
933                          */
934                         extract_token(nodename, buf, 1, '|', sizeof nodename);
935                         extract_token(roomname, buf, 2, '|', sizeof roomname);
936                         strcpy(nexthop, "xxx");
937                         if (is_valid_node(nexthop, NULL, nodename) == 0) {
938                                 if (strlen(nexthop) == 0) {
939                                         mptr = (struct maplist *)
940                                                 malloc(sizeof(struct maplist));
941                                         mptr->next = sc.ignet_push_shares;
942                                         strcpy(mptr->remote_nodename, nodename);
943                                         strcpy(mptr->remote_roomname, roomname);
944                                         sc.ignet_push_shares = mptr;
945                                 }
946                         }
947                 }
948                 else {
949                         /* Preserve 'other' lines ... *unless* they happen to
950                          * be subscribe/unsubscribe pendings with expired
951                          * timestamps.
952                          */
953                         skipthisline = 0;
954                         if (!strncasecmp(buf, "subpending|", 11)) {
955                                 if (time(NULL) - extract_long(buf, 4) > EXP) {
956                                         skipthisline = 1;
957                                 }
958                         }
959                         if (!strncasecmp(buf, "unsubpending|", 13)) {
960                                 if (time(NULL) - extract_long(buf, 3) > EXP) {
961                                         skipthisline = 1;
962                                 }
963                         }
964
965                         if (skipthisline == 0) {
966                                 linesize = strlen(buf);
967                                 sc.misc = realloc(sc.misc,
968                                         (miscsize + linesize + 2) );
969                                 sprintf(&sc.misc[miscsize], "%s\n", buf);
970                                 miscsize = miscsize + linesize + 1;
971                         }
972                 }
973
974
975         }
976         fclose(fp);
977
978         /* If there are digest recipients, we have to build a digest */
979         if (sc.digestrecps != NULL) {
980                 sc.digestfp = tmpfile();
981                 fprintf(sc.digestfp, "Content-type: text/plain\n\n");
982         }
983
984         /* Do something useful */
985         CtdlForEachMessage(MSGS_GT, sc.lastsent, NULL, NULL,
986                 network_spool_msg, &sc);
987
988         /* If we wrote a digest, deliver it and then close it */
989         snprintf(buf, sizeof buf, "room_%s@%s",
990                 CC->room.QRname, config.c_fqdn);
991         for (i=0; i<strlen(buf); ++i) {
992                 buf[i] = tolower(buf[i]);
993                 if (isspace(buf[i])) buf[i] = '_';
994         }
995         if (sc.digestfp != NULL) {
996                 fprintf(sc.digestfp,    " -----------------------------------"
997                                         "------------------------------------"
998                                         "-------\n"
999                                         "You are subscribed to the '%s' "
1000                                         "list.\n"
1001                                         "To post to the list: %s\n",
1002                                         CC->room.QRname, buf
1003                 );
1004                 network_deliver_digest(&sc);    /* deliver and close */
1005         }
1006
1007         /* Now rewrite the config file */
1008         fp = fopen(filename, "w");
1009         if (fp == NULL) {
1010                 lprintf(CTDL_CRIT, "ERROR: cannot open %s: %s\n",
1011                         filename, strerror(errno));
1012         }
1013         else {
1014                 fprintf(fp, "lastsent|%ld\n", sc.lastsent);
1015
1016                 /* Write out the listrecps while freeing from memory at the
1017                  * same time.  Am I clever or what?  :)
1018                  */
1019                 while (sc.listrecps != NULL) {
1020                         fprintf(fp, "listrecp|%s\n", sc.listrecps->name);
1021                         nptr = sc.listrecps->next;
1022                         free(sc.listrecps);
1023                         sc.listrecps = nptr;
1024                 }
1025                 /* Do the same for digestrecps */
1026                 while (sc.digestrecps != NULL) {
1027                         fprintf(fp, "digestrecp|%s\n", sc.digestrecps->name);
1028                         nptr = sc.digestrecps->next;
1029                         free(sc.digestrecps);
1030                         sc.digestrecps = nptr;
1031                 }
1032                 /* Do the same for participates */
1033                 while (sc.participates != NULL) {
1034                         fprintf(fp, "participate|%s\n", sc.participates->name);
1035                         nptr = sc.participates->next;
1036                         free(sc.participates);
1037                         sc.participates = nptr;
1038                 }
1039                 while (sc.ignet_push_shares != NULL) {
1040                         /* by checking each node's validity, we automatically
1041                          * purge nodes which do not exist from room network
1042                          * configurations at this time.
1043                          */
1044                         if (is_valid_node(NULL, NULL, sc.ignet_push_shares->remote_nodename) == 0) {
1045                         }
1046                         fprintf(fp, "ignet_push_share|%s",
1047                                 sc.ignet_push_shares->remote_nodename);
1048                         if (strlen(sc.ignet_push_shares->remote_roomname) > 0) {
1049                                 fprintf(fp, "|%s", sc.ignet_push_shares->remote_roomname);
1050                         }
1051                         fprintf(fp, "\n");
1052                         mptr = sc.ignet_push_shares->next;
1053                         free(sc.ignet_push_shares);
1054                         sc.ignet_push_shares = mptr;
1055                 }
1056                 if (sc.misc != NULL) {
1057                         fwrite(sc.misc, strlen(sc.misc), 1, fp);
1058                 }
1059                 free(sc.misc);
1060
1061                 fclose(fp);
1062         }
1063         end_critical_section(S_NETCONFIGS);
1064 }
1065
1066
1067
1068 /*
1069  * Send the *entire* contents of the current room to one specific network node,
1070  * ignoring anything we know about which messages have already undergone
1071  * network processing.  This can be used to bring a new node into sync.
1072  */
1073 int network_sync_to(char *target_node) {
1074         struct SpoolControl sc;
1075         int num_spooled = 0;
1076         int found_node = 0;
1077         char buf[256];
1078         char sc_type[256];
1079         char sc_node[256];
1080         char sc_room[256];
1081         char filename[256];
1082         FILE *fp;
1083
1084         /* Grab the configuration line we're looking for */
1085         assoc_file_name(filename, sizeof filename, &CC->room, "netconfigs");
1086         begin_critical_section(S_NETCONFIGS);
1087         fp = fopen(filename, "r");
1088         if (fp == NULL) {
1089                 end_critical_section(S_NETCONFIGS);
1090                 return(-1);
1091         }
1092         while (fgets(buf, sizeof buf, fp) != NULL) {
1093                 buf[strlen(buf)-1] = 0;
1094                 extract_token(sc_type, buf, 0, '|', sizeof sc_type);
1095                 extract_token(sc_node, buf, 1, '|', sizeof sc_node);
1096                 extract_token(sc_room, buf, 2, '|', sizeof sc_room);
1097                 if ( (!strcasecmp(sc_type, "ignet_push_share"))
1098                    && (!strcasecmp(sc_node, target_node)) ) {
1099                         found_node = 1;
1100                         
1101                         /* Concise syntax because we don't need a full linked-list */
1102                         memset(&sc, 0, sizeof(struct SpoolControl));
1103                         sc.ignet_push_shares = (struct maplist *)
1104                                 malloc(sizeof(struct maplist));
1105                         sc.ignet_push_shares->next = NULL;
1106                         safestrncpy(sc.ignet_push_shares->remote_nodename,
1107                                 sc_node,
1108                                 sizeof sc.ignet_push_shares->remote_nodename);
1109                         safestrncpy(sc.ignet_push_shares->remote_roomname,
1110                                 sc_room,
1111                                 sizeof sc.ignet_push_shares->remote_roomname);
1112                 }
1113         }
1114         fclose(fp);
1115         end_critical_section(S_NETCONFIGS);
1116
1117         if (!found_node) return(-1);
1118
1119         /* Send ALL messages */
1120         num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL,
1121                 network_spool_msg, &sc);
1122
1123         /* Concise cleanup because we know there's only one node in the sc */
1124         free(sc.ignet_push_shares);
1125
1126         lprintf(CTDL_NOTICE, "Synchronized %d messages to <%s>\n",
1127                 num_spooled, target_node);
1128         return(num_spooled);
1129 }
1130
1131
1132 /*
1133  * Implements the NSYN command
1134  */
1135 void cmd_nsyn(char *argbuf) {
1136         int num_spooled;
1137         char target_node[256];
1138
1139         if (CtdlAccessCheck(ac_aide)) return;
1140
1141         extract_token(target_node, argbuf, 0, '|', sizeof target_node);
1142         num_spooled = network_sync_to(target_node);
1143         if (num_spooled >= 0) {
1144                 cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
1145         }
1146         else {
1147                 cprintf("%d No such room/node share exists.\n",
1148                         ERROR + ROOM_NOT_FOUND);
1149         }
1150 }
1151
1152
1153
1154 /*
1155  * Batch up and send all outbound traffic from the current room
1156  */
1157 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
1158         struct RoomProcList *ptr;
1159
1160         ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
1161         if (ptr == NULL) return;
1162
1163         safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
1164         ptr->next = rplist;
1165         rplist = ptr;
1166 }
1167
1168
1169 /*
1170  * Learn topology from path fields
1171  */
1172 void network_learn_topology(char *node, char *path) {
1173         char nexthop[256];
1174         struct NetMap *nmptr;
1175
1176         strcpy(nexthop, "");
1177
1178         if (num_tokens(path, '!') < 3) return;
1179         for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
1180                 if (!strcasecmp(nmptr->nodename, node)) {
1181                         extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1182                         nmptr->lastcontact = time(NULL);
1183                         ++netmap_changed;
1184                         return;
1185                 }
1186         }
1187
1188         /* If we got here then it's not in the map, so add it. */
1189         nmptr = (struct NetMap *) malloc(sizeof (struct NetMap));
1190         strcpy(nmptr->nodename, node);
1191         nmptr->lastcontact = time(NULL);
1192         extract_token(nmptr->nexthop, path, 0, '!', sizeof nmptr->nexthop);
1193         nmptr->next = the_netmap;
1194         the_netmap = nmptr;
1195         ++netmap_changed;
1196 }
1197
1198
1199
1200
1201 /*
1202  * Bounce a message back to the sender
1203  */
1204 void network_bounce(struct CtdlMessage *msg, char *reason) {
1205         char *oldpath = NULL;
1206         char buf[SIZ];
1207         char bouncesource[SIZ];
1208         char recipient[SIZ];
1209         struct recptypes *valid = NULL;
1210         char force_room[ROOMNAMELEN];
1211         static int serialnum = 0;
1212         size_t size;
1213
1214         lprintf(CTDL_DEBUG, "entering network_bounce()\n");
1215
1216         if (msg == NULL) return;
1217
1218         snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, config.c_nodename);
1219
1220         /* 
1221          * Give it a fresh message ID
1222          */
1223         if (msg->cm_fields['I'] != NULL) {
1224                 free(msg->cm_fields['I']);
1225         }
1226         snprintf(buf, sizeof buf, "%ld.%04lx.%04x@%s",
1227                 (long)time(NULL), (long)getpid(), ++serialnum, config.c_fqdn);
1228         msg->cm_fields['I'] = strdup(buf);
1229
1230         /*
1231          * FIXME ... right now we're just sending a bounce; we really want to
1232          * include the text of the bounced message.
1233          */
1234         if (msg->cm_fields['M'] != NULL) {
1235                 free(msg->cm_fields['M']);
1236         }
1237         msg->cm_fields['M'] = strdup(reason);
1238         msg->cm_format_type = 0;
1239
1240         /*
1241          * Turn the message around
1242          */
1243         if (msg->cm_fields['R'] == NULL) {
1244                 free(msg->cm_fields['R']);
1245         }
1246
1247         if (msg->cm_fields['D'] == NULL) {
1248                 free(msg->cm_fields['D']);
1249         }
1250
1251         snprintf(recipient, sizeof recipient, "%s@%s",
1252                 msg->cm_fields['A'], msg->cm_fields['N']);
1253
1254         if (msg->cm_fields['A'] == NULL) {
1255                 free(msg->cm_fields['A']);
1256         }
1257
1258         if (msg->cm_fields['N'] == NULL) {
1259                 free(msg->cm_fields['N']);
1260         }
1261
1262         if (msg->cm_fields['U'] == NULL) {
1263                 free(msg->cm_fields['U']);
1264         }
1265
1266         msg->cm_fields['A'] = strdup(BOUNCESOURCE);
1267         msg->cm_fields['N'] = strdup(config.c_nodename);
1268         msg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
1269
1270         /* prepend our node to the path */
1271         if (msg->cm_fields['P'] != NULL) {
1272                 oldpath = msg->cm_fields['P'];
1273                 msg->cm_fields['P'] = NULL;
1274         }
1275         else {
1276                 oldpath = strdup("unknown_user");
1277         }
1278         size = strlen(oldpath) + SIZ;
1279         msg->cm_fields['P'] = malloc(size);
1280         snprintf(msg->cm_fields['P'], size, "%s!%s", config.c_nodename, oldpath);
1281         free(oldpath);
1282
1283         /* Now submit the message */
1284         valid = validate_recipients(recipient);
1285         if (valid != NULL) if (valid->num_error > 0) {
1286                 free(valid);
1287                 valid = NULL;
1288         }
1289         if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
1290                 strcpy(force_room, config.c_aideroom);
1291         }
1292         else {
1293                 strcpy(force_room, "");
1294         }
1295         if ( (valid == NULL) && (strlen(force_room) == 0) ) {
1296                 strcpy(force_room, config.c_aideroom);
1297         }
1298         CtdlSubmitMsg(msg, valid, force_room);
1299
1300         /* Clean up */
1301         if (valid != NULL) free(valid);
1302         CtdlFreeMessage(msg);
1303         lprintf(CTDL_DEBUG, "leaving network_bounce()\n");
1304 }
1305
1306
1307
1308
1309 /*
1310  * Process a buffer containing a single message from a single file
1311  * from the inbound queue 
1312  */
1313 void network_process_buffer(char *buffer, long size) {
1314         struct CtdlMessage *msg;
1315         long pos;
1316         int field;
1317         struct recptypes *recp = NULL;
1318         char target_room[ROOMNAMELEN];
1319         struct ser_ret sermsg;
1320         char *oldpath = NULL;
1321         char filename[SIZ];
1322         FILE *fp;
1323         char nexthop[SIZ];
1324         unsigned char firstbyte;
1325         unsigned char lastbyte;
1326
1327         /* Validate just a little bit.  First byte should be FF and
1328          * last byte should be 00.
1329          */
1330         memcpy(&firstbyte, &buffer[0], 1);
1331         memcpy(&lastbyte, &buffer[size-1], 1);
1332         if ( (firstbyte != 255) || (lastbyte != 0) ) {
1333                 lprintf(CTDL_ERR, "Corrupt message!  Ignoring.\n");
1334                 return;
1335         }
1336
1337         /* Set default target room to trash */
1338         strcpy(target_room, TWITROOM);
1339
1340         /* Load the message into memory */
1341         msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1342         memset(msg, 0, sizeof(struct CtdlMessage));
1343         msg->cm_magic = CTDLMESSAGE_MAGIC;
1344         msg->cm_anon_type = buffer[1];
1345         msg->cm_format_type = buffer[2];
1346
1347         for (pos = 3; pos < size; ++pos) {
1348                 field = buffer[pos];
1349                 msg->cm_fields[field] = strdup(&buffer[pos+1]);
1350                 pos = pos + strlen(&buffer[(int)pos]);
1351         }
1352
1353         /* Check for message routing */
1354         if (msg->cm_fields['D'] != NULL) {
1355                 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
1356
1357                         /* route the message */
1358                         strcpy(nexthop, "");
1359                         if (is_valid_node(nexthop, NULL,
1360                            msg->cm_fields['D']) == 0) {
1361
1362                                 /* prepend our node to the path */
1363                                 if (msg->cm_fields['P'] != NULL) {
1364                                         oldpath = msg->cm_fields['P'];
1365                                         msg->cm_fields['P'] = NULL;
1366                                 }
1367                                 else {
1368                                         oldpath = strdup("unknown_user");
1369                                 }
1370                                 size = strlen(oldpath) + SIZ;
1371                                 msg->cm_fields['P'] = malloc(size);
1372                                 snprintf(msg->cm_fields['P'], size, "%s!%s",
1373                                         config.c_nodename, oldpath);
1374                                 free(oldpath);
1375
1376                                 /* serialize the message */
1377                                 serialize_message(&sermsg, msg);
1378
1379                                 /* now send it */
1380                                 if (strlen(nexthop) == 0) {
1381                                         strcpy(nexthop, msg->cm_fields['D']);
1382                                 }
1383                                 snprintf(filename, sizeof filename,
1384 #ifndef HAVE_SPOOL_DIR
1385                                                  "."
1386 #else
1387                                                  SPOOL_DIR
1388 #endif /* HAVE_SPOOL_DIR */
1389                                                  "/network/spoolout/%s", nexthop);
1390                                 lprintf(CTDL_DEBUG, "Appending to %s\n", filename);
1391                                 fp = fopen(filename, "ab");
1392                                 if (fp != NULL) {
1393                                         fwrite(sermsg.ser,
1394                                                 sermsg.len, 1, fp);
1395                                         fclose(fp);
1396                                 }
1397                                 else {
1398                                         lprintf(CTDL_ERR, "%s: %s\n", filename, strerror(errno));
1399                                 }
1400                                 free(sermsg.ser);
1401                                 CtdlFreeMessage(msg);
1402                                 return;
1403                         }
1404                         
1405                         else {  /* invalid destination node name */
1406
1407                                 network_bounce(msg,
1408 "A message you sent could not be delivered due to an invalid destination node"
1409 " name.  Please check the address and try sending the message again.\n");
1410                                 msg = NULL;
1411                                 return;
1412
1413                         }
1414                 }
1415         }
1416
1417         /*
1418          * Check to see if we already have a copy of this message, and
1419          * abort its processing if so.  (We used to post a warning to Aide>
1420          * every time this happened, but the network is now so densely
1421          * connected that it's inevitable.)
1422          */
1423         if (network_usetable(msg) != 0) {
1424                 return;
1425         }
1426
1427         /* Learn network topology from the path */
1428         if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
1429                 network_learn_topology(msg->cm_fields['N'], 
1430                                         msg->cm_fields['P']);
1431         }
1432
1433         /* Is the sending node giving us a very persuasive suggestion about
1434          * which room this message should be saved in?  If so, go with that.
1435          */
1436         if (msg->cm_fields['C'] != NULL) {
1437                 safestrncpy(target_room,
1438                         msg->cm_fields['C'],
1439                         sizeof target_room);
1440         }
1441
1442         /* Otherwise, does it have a recipient?  If so, validate it... */
1443         else if (msg->cm_fields['R'] != NULL) {
1444                 recp = validate_recipients(msg->cm_fields['R']);
1445                 if (recp != NULL) if (recp->num_error > 0) {
1446                         network_bounce(msg,
1447 "A message you sent could not be delivered due to an invalid address.\n"
1448 "Please check the address and try sending the message again.\n");
1449                         msg = NULL;
1450                         free(recp);
1451                         return;
1452                 }
1453                 strcpy(target_room, "");        /* no target room if mail */
1454         }
1455
1456         /* Our last shot at finding a home for this message is to see if
1457          * it has the O field (Originating room) set.
1458          */
1459         else if (msg->cm_fields['O'] != NULL) {
1460                 safestrncpy(target_room,
1461                         msg->cm_fields['O'],
1462                         sizeof target_room);
1463         }
1464
1465         /* Strip out fields that are only relevant during transit */
1466         if (msg->cm_fields['D'] != NULL) {
1467                 free(msg->cm_fields['D']);
1468                 msg->cm_fields['D'] = NULL;
1469         }
1470         if (msg->cm_fields['C'] != NULL) {
1471                 free(msg->cm_fields['C']);
1472                 msg->cm_fields['C'] = NULL;
1473         }
1474
1475         /* save the message into a room */
1476         if (PerformNetprocHooks(msg, target_room) == 0) {
1477                 msg->cm_flags = CM_SKIP_HOOKS;
1478                 CtdlSubmitMsg(msg, recp, target_room);
1479         }
1480         CtdlFreeMessage(msg);
1481         free(recp);
1482 }
1483
1484
1485 /*
1486  * Process a single message from a single file from the inbound queue 
1487  */
1488 void network_process_message(FILE *fp, long msgstart, long msgend) {
1489         long hold_pos;
1490         long size;
1491         char *buffer;
1492
1493         hold_pos = ftell(fp);
1494         size = msgend - msgstart + 1;
1495         buffer = malloc(size);
1496         if (buffer != NULL) {
1497                 fseek(fp, msgstart, SEEK_SET);
1498                 fread(buffer, size, 1, fp);
1499                 network_process_buffer(buffer, size);
1500                 free(buffer);
1501         }
1502
1503         fseek(fp, hold_pos, SEEK_SET);
1504 }
1505
1506
1507 /*
1508  * Process a single file from the inbound queue 
1509  */
1510 void network_process_file(char *filename) {
1511         FILE *fp;
1512         long msgstart = (-1L);
1513         long msgend = (-1L);
1514         long msgcur = 0L;
1515         int ch;
1516
1517
1518         fp = fopen(filename, "rb");
1519         if (fp == NULL) {
1520                 lprintf(CTDL_CRIT, "Error opening %s: %s\n",
1521                         filename, strerror(errno));
1522                 return;
1523         }
1524
1525         lprintf(CTDL_INFO, "network: processing <%s>\n", filename);
1526
1527         /* Look for messages in the data stream and break them out */
1528         while (ch = getc(fp), ch >= 0) {
1529         
1530                 if (ch == 255) {
1531                         if (msgstart >= 0L) {
1532                                 msgend = msgcur - 1;
1533                                 network_process_message(fp, msgstart, msgend);
1534                         }
1535                         msgstart = msgcur;
1536                 }
1537
1538                 ++msgcur;
1539         }
1540
1541         msgend = msgcur - 1;
1542         if (msgstart >= 0L) {
1543                 network_process_message(fp, msgstart, msgend);
1544         }
1545
1546         fclose(fp);
1547         unlink(filename);
1548 }
1549
1550
1551 /*
1552  * Process anything in the inbound queue
1553  */
1554 void network_do_spoolin(void) {
1555         DIR *dp;
1556         struct dirent *d;
1557         char filename[256];
1558
1559         dp = opendir(
1560 #ifndef HAVE_SPOOL_DIR
1561                                  "."
1562 #else
1563                                  SPOOL_DIR
1564 #endif /* HAVE_SPOOL_DIR */
1565                                  "/network/spoolin");
1566         if (dp == NULL) return;
1567
1568         while (d = readdir(dp), d != NULL) {
1569                 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
1570                         snprintf(filename, sizeof filename,
1571 #ifndef HAVE_SPOOL_DIR
1572                                          "."
1573 #else
1574                                          SPOOL_DIR
1575 #endif /* HAVE_SPOOL_DIR */
1576                                          "/network/spoolin/%s", d->d_name);
1577                         network_process_file(filename);
1578                 }
1579         }
1580
1581         closedir(dp);
1582 }
1583
1584 /*
1585  * Delete any files in the outbound queue that were intended
1586  * to be sent to nodes which no longer exist.
1587  */
1588 void network_purge_spoolout(void) {
1589         DIR *dp;
1590         struct dirent *d;
1591         char filename[256];
1592         char nexthop[256];
1593         int i;
1594
1595         dp = opendir(
1596 #ifndef HAVE_SPOOL_DIR
1597                                  "."
1598 #else
1599                                  SPOOL_DIR
1600 #endif /* HAVE_SPOOL_DIR */
1601                                  "/network/spoolout");
1602         if (dp == NULL) return;
1603
1604         while (d = readdir(dp), d != NULL) {
1605                 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1606                         continue;
1607                 snprintf(filename, sizeof filename,
1608 #ifndef HAVE_SPOOL_DIR
1609                                  "."
1610 #else
1611                                  SPOOL_DIR
1612 #endif /* HAVE_SPOOL_DIR */
1613                                  "/network/spoolout/%s", d->d_name);
1614
1615                 strcpy(nexthop, "");
1616                 i = is_valid_node(nexthop, NULL, d->d_name);
1617         
1618                 if ( (i != 0) || (strlen(nexthop) > 0) ) {
1619                         unlink(filename);
1620                 }
1621         }
1622
1623
1624         closedir(dp);
1625 }
1626
1627
1628 /*
1629  * receive network spool from the remote system
1630  */
1631 void receive_spool(int sock, char *remote_nodename) {
1632         long download_len;
1633         long bytes_received;
1634         char buf[SIZ];
1635         static char pbuf[IGNET_PACKET_SIZE];
1636         char tempfilename[PATH_MAX];
1637         long plen;
1638         FILE *fp;
1639
1640         strcpy(tempfilename, tmpnam(NULL));
1641         if (sock_puts(sock, "NDOP") < 0) return;
1642         if (sock_gets(sock, buf) < 0) return;
1643         lprintf(CTDL_DEBUG, "<%s\n", buf);
1644         if (buf[0] != '2') {
1645                 return;
1646         }
1647         download_len = extract_long(&buf[4], 0);
1648
1649         bytes_received = 0L;
1650         fp = fopen(tempfilename, "w");
1651         if (fp == NULL) {
1652                 lprintf(CTDL_CRIT, "cannot open download file locally: %s\n",
1653                         strerror(errno));
1654                 return;
1655         }
1656
1657         while (bytes_received < download_len) {
1658                 snprintf(buf, sizeof buf, "READ %ld|%ld",
1659                         bytes_received,
1660                      ((download_len - bytes_received > IGNET_PACKET_SIZE)
1661                  ? IGNET_PACKET_SIZE : (download_len - bytes_received)));
1662                 if (sock_puts(sock, buf) < 0) {
1663                         fclose(fp);
1664                         unlink(tempfilename);
1665                         return;
1666                 }
1667                 if (sock_gets(sock, buf) < 0) {
1668                         fclose(fp);
1669                         unlink(tempfilename);
1670                         return;
1671                 }
1672                 if (buf[0] == '6') {
1673                         plen = extract_long(&buf[4], 0);
1674                         if (sock_read(sock, pbuf, plen) < 0) {
1675                                 fclose(fp);
1676                                 unlink(tempfilename);
1677                                 return;
1678                         }
1679                         fwrite((char *) pbuf, plen, 1, fp);
1680                         bytes_received = bytes_received + plen;
1681                 }
1682         }
1683
1684         fclose(fp);
1685         if (sock_puts(sock, "CLOS") < 0) {
1686                 unlink(tempfilename);
1687                 return;
1688         }
1689         if (sock_gets(sock, buf) < 0) {
1690                 unlink(tempfilename);
1691                 return;
1692         }
1693         if (download_len > 0)
1694                 lprintf(CTDL_NOTICE, "Received %ld octets from <%s>",
1695                                 download_len, remote_nodename);
1696         lprintf(CTDL_DEBUG, "%s", buf);
1697         /* TODO: make move inline. forking is verry expensive. */
1698         snprintf(buf, sizeof buf, "mv %s "
1699 #ifndef HAVE_SPOOL_DIR
1700                          "."
1701 #else
1702                          SPOOL_DIR
1703 #endif /* HAVE_SPOOL_DIR */
1704                          "/network/spoolin/%s.%ld",
1705                          tempfilename, remote_nodename, (long) getpid());
1706         system(buf);
1707 }
1708
1709
1710
1711 /*
1712  * transmit network spool to the remote system
1713  */
1714 void transmit_spool(int sock, char *remote_nodename)
1715 {
1716         char buf[SIZ];
1717         char pbuf[4096];
1718         long plen;
1719         long bytes_to_write, thisblock, bytes_written;
1720         int fd;
1721         char sfname[128];
1722
1723         if (sock_puts(sock, "NUOP") < 0) return;
1724         if (sock_gets(sock, buf) < 0) return;
1725         lprintf(CTDL_DEBUG, "<%s\n", buf);
1726         if (buf[0] != '2') {
1727                 return;
1728         }
1729
1730         snprintf(sfname, sizeof sfname, 
1731 #ifndef HAVE_SPOOL_DIR
1732                          "."
1733 #else
1734                          SPOOL_DIR
1735 #endif /* HAVE_SPOOL_DIR */
1736                          "/network/spoolout/%s", remote_nodename);
1737         fd = open(sfname, O_RDONLY);
1738         if (fd < 0) {
1739                 if (errno != ENOENT) {
1740                         lprintf(CTDL_CRIT, "cannot open upload file locally: %s\n",
1741                                 strerror(errno));
1742                 }
1743                 return;
1744         }
1745         bytes_written = 0;
1746         while (plen = (long) read(fd, pbuf, IGNET_PACKET_SIZE), plen > 0L) {
1747                 bytes_to_write = plen;
1748                 while (bytes_to_write > 0L) {
1749                         snprintf(buf, sizeof buf, "WRIT %ld", bytes_to_write);
1750                         if (sock_puts(sock, buf) < 0) {
1751                                 close(fd);
1752                                 return;
1753                         }
1754                         if (sock_gets(sock, buf) < 0) {
1755                                 close(fd);
1756                                 return;
1757                         }
1758                         thisblock = atol(&buf[4]);
1759                         if (buf[0] == '7') {
1760                                 if (sock_write(sock, pbuf,
1761                                    (int) thisblock) < 0) {
1762                                         close(fd);
1763                                         return;
1764                                 }
1765                                 bytes_to_write -= thisblock;
1766                                 bytes_written += thisblock;
1767                         } else {
1768                                 goto ABORTUPL;
1769                         }
1770                 }
1771         }
1772
1773 ABORTUPL:
1774         close(fd);
1775         if (sock_puts(sock, "UCLS 1") < 0) return;
1776         if (sock_gets(sock, buf) < 0) return;
1777         lprintf(CTDL_NOTICE, "Sent %ld octets to <%s>\n",
1778                         bytes_written, remote_nodename);
1779         lprintf(CTDL_DEBUG, "<%s\n", buf);
1780         if (buf[0] == '2') {
1781                 lprintf(CTDL_DEBUG, "Removing <%s>\n", sfname);
1782                 unlink(sfname);
1783         }
1784 }
1785
1786
1787
1788 /*
1789  * Poll one Citadel node (called by network_poll_other_citadel_nodes() below)
1790  */
1791 void network_poll_node(char *node, char *secret, char *host, char *port) {
1792         int sock;
1793         char buf[SIZ];
1794
1795         if (network_talking_to(node, NTT_CHECK)) return;
1796         network_talking_to(node, NTT_ADD);
1797         lprintf(CTDL_NOTICE, "Connecting to <%s> at %s:%s\n", node, host, port);
1798
1799         sock = sock_connect(host, port, "tcp");
1800         if (sock < 0) {
1801                 lprintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
1802                 network_talking_to(node, NTT_REMOVE);
1803                 return;
1804         }
1805         
1806         lprintf(CTDL_DEBUG, "Connected!\n");
1807
1808         /* Read the server greeting */
1809         if (sock_gets(sock, buf) < 0) goto bail;
1810         lprintf(CTDL_DEBUG, ">%s\n", buf);
1811
1812         /* Identify ourselves */
1813         snprintf(buf, sizeof buf, "NETP %s|%s", config.c_nodename, secret);
1814         lprintf(CTDL_DEBUG, "<%s\n", buf);
1815         if (sock_puts(sock, buf) <0) goto bail;
1816         if (sock_gets(sock, buf) < 0) goto bail;
1817         lprintf(CTDL_DEBUG, ">%s\n", buf);
1818         if (buf[0] != '2') goto bail;
1819
1820         /* At this point we are authenticated. */
1821         receive_spool(sock, node);
1822         transmit_spool(sock, node);
1823
1824         sock_puts(sock, "QUIT");
1825 bail:   sock_close(sock);
1826         network_talking_to(node, NTT_REMOVE);
1827 }
1828
1829
1830
1831 /*
1832  * Poll other Citadel nodes and transfer inbound/outbound network data.
1833  * Set "full" to nonzero to force a poll of every node, or to zero to poll
1834  * only nodes to which we have data to send.
1835  */
1836 void network_poll_other_citadel_nodes(int full_poll) {
1837         int i;
1838         char linebuf[256];
1839         char node[SIZ];
1840         char host[256];
1841         char port[256];
1842         char secret[256];
1843         int poll = 0;
1844         char spoolfile[256];
1845
1846         if (working_ignetcfg == NULL) {
1847                 lprintf(CTDL_DEBUG, "No nodes defined - not polling\n");
1848                 return;
1849         }
1850
1851         /* Use the string tokenizer to grab one line at a time */
1852         for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
1853                 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
1854                 extract_token(node, linebuf, 0, '|', sizeof node);
1855                 extract_token(secret, linebuf, 1, '|', sizeof secret);
1856                 extract_token(host, linebuf, 2, '|', sizeof host);
1857                 extract_token(port, linebuf, 3, '|', sizeof port);
1858                 if ( (strlen(node) > 0) && (strlen(secret) > 0) 
1859                    && (strlen(host) > 0) && strlen(port) > 0) {
1860                         poll = full_poll;
1861                         if (poll == 0) {
1862                                 snprintf(spoolfile, sizeof spoolfile,
1863 #ifndef HAVE_SPOOL_DIR
1864                                                  "."
1865 #else
1866                                                  SPOOL_DIR
1867 #endif
1868                                                  "/network/spoolout/%s", node);
1869                                 if (access(spoolfile, R_OK) == 0) {
1870                                         poll = 1;
1871                                 }
1872                         }
1873                         if (poll) {
1874                                 network_poll_node(node, secret, host, port);
1875                         }
1876                 }
1877         }
1878
1879 }
1880
1881
1882
1883
1884 /*
1885  * It's ok if these directories already exist.  Just fail silently.
1886  */
1887 void create_spool_dirs(void) {
1888 #ifndef HAVE_SPOOL_DIR
1889         mkdir("./network", 0700);
1890         mkdir("./network/systems", 0700);
1891         mkdir("./network/spoolin", 0700);
1892         mkdir("./network/spoolout", 0700);
1893 #else
1894         mkdir(SPOOL_DIR "/network", 0700);
1895         mkdir(SPOOL_DIR "/network/systems", 0700);
1896         mkdir(SPOOL_DIR "/network/spoolin", 0700);
1897         mkdir(SPOOL_DIR "/network/spoolout", 0700);
1898 #endif /* HAVE_SPOOL_DIR */
1899 }
1900
1901
1902
1903
1904
1905 /*
1906  * network_do_queue()
1907  * 
1908  * Run through the rooms doing various types of network stuff.
1909  */
1910 void network_do_queue(void) {
1911         static time_t last_run = 0L;
1912         struct RoomProcList *ptr;
1913         int full_processing = 1;
1914
1915         /*
1916          * Run the full set of processing tasks no more frequently
1917          * than once every n seconds
1918          */
1919         if ( (time(NULL) - last_run) < config.c_net_freq ) {
1920                 full_processing = 0;
1921         }
1922
1923         create_spool_dirs();
1924
1925         /*
1926          * This is a simple concurrency check to make sure only one queue run
1927          * is done at a time.  We could do this with a mutex, but since we
1928          * don't really require extremely fine granularity here, we'll do it
1929          * with a static variable instead.
1930          */
1931         if (doing_queue) return;
1932         doing_queue = 1;
1933
1934         /* Load the IGnet Configuration into memory */
1935         load_working_ignetcfg();
1936
1937         /*
1938          * Poll other Citadel nodes.  Maybe.  If "full_processing" is set
1939          * then we poll everyone.  Otherwise we only poll nodes we have stuff
1940          * to send to.
1941          */
1942         network_poll_other_citadel_nodes(full_processing);
1943
1944         /*
1945          * Load the network map and filter list into memory.
1946          */
1947         read_network_map();
1948         filterlist = load_filter_list();
1949
1950         /* 
1951          * Go ahead and run the queue
1952          */
1953         if (full_processing) {
1954                 lprintf(CTDL_DEBUG, "network: loading outbound queue\n");
1955                 ForEachRoom(network_queue_room, NULL);
1956
1957                 lprintf(CTDL_DEBUG, "network: running outbound queue\n");
1958                 while (rplist != NULL) {
1959                         network_spoolout_room(rplist->name);
1960                         ptr = rplist;
1961                         rplist = rplist->next;
1962                         free(ptr);
1963                 }
1964         }
1965
1966         lprintf(CTDL_DEBUG, "network: processing inbound queue\n");
1967         network_do_spoolin();
1968
1969         /* Save the network map back to disk */
1970         write_network_map();
1971
1972         /* Free the filter list in memory */
1973         free_filter_list(filterlist);
1974         filterlist = NULL;
1975
1976         network_purge_spoolout();
1977
1978         lprintf(CTDL_DEBUG, "network: queue run completed\n");
1979
1980         if (full_processing) {
1981                 last_run = time(NULL);
1982         }
1983
1984         doing_queue = 0;
1985 }
1986
1987
1988 /*
1989  * cmd_netp() - authenticate to the server as another Citadel node polling
1990  *            for network traffic
1991  */
1992 void cmd_netp(char *cmdbuf)
1993 {
1994         char node[256];
1995         char pass[256];
1996         int v;
1997
1998         char secret[256];
1999         char nexthop[256];
2000
2001         /* Authenticate */
2002         extract_token(node, cmdbuf, 0, '|', sizeof node);
2003         extract_token(pass, cmdbuf, 1, '|', sizeof pass);
2004
2005         if (doing_queue) {
2006                 lprintf(CTDL_WARNING, "Network node <%s> refused - spooling", node);
2007                 cprintf("%d spooling - try again in a few minutes\n",
2008                         ERROR + RESOURCE_BUSY);
2009                 return;
2010         }
2011
2012         /* load the IGnet Configuration to check node validity */
2013         load_working_ignetcfg();
2014         v = is_valid_node(nexthop, secret, node);
2015
2016         if (v != 0) {
2017                 lprintf(CTDL_WARNING, "Unknown node <%s>\n", node);
2018                 cprintf("%d authentication failed\n",
2019                         ERROR + PASSWORD_REQUIRED);
2020                 return;
2021         }
2022
2023         if (strcasecmp(pass, secret)) {
2024                 lprintf(CTDL_WARNING, "Bad password for network node <%s>", node);
2025                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
2026                 return;
2027         }
2028
2029         if (network_talking_to(node, NTT_CHECK)) {
2030                 lprintf(CTDL_WARNING, "Duplicate session for network node <%s>", node);
2031                 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
2032                 return;
2033         }
2034
2035         safestrncpy(CC->net_node, node, sizeof CC->net_node);
2036         network_talking_to(node, NTT_ADD);
2037         lprintf(CTDL_NOTICE, "Network node <%s> logged in\n", CC->net_node);
2038         cprintf("%d authenticated as network node '%s'\n", CIT_OK,
2039                 CC->net_node);
2040 }
2041
2042 /*
2043  * Module entry point
2044  */
2045 char *serv_network_init(void)
2046 {
2047         create_spool_dirs();
2048         CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
2049         CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
2050         CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
2051         CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
2052         CtdlRegisterSessionHook(network_do_queue, EVT_TIMER);
2053         return "$Id$";
2054 }