Networker Increase logging on startup
[citadel.git] / citadel / modules / network / serv_networkclient.c
1 /*
2  * This module handles shared rooms, inter-Citadel mail, and outbound
3  * mailing list processing.
4  *
5  * Copyright (c) 2000-2011 by the citadel.org team
6  *
7  *  This program is open source software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 3 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  * ** NOTE **   A word on the S_NETCONFIGS semaphore:
22  * This is a fairly high-level type of critical section.  It ensures that no
23  * two threads work on the netconfigs files at the same time.  Since we do
24  * so many things inside these, here are the rules:
25  *  1. begin_critical_section(S_NETCONFIGS) *before* begin_ any others.
26  *  2. Do *not* perform any I/O with the client during these sections.
27  *
28  */
29
30
31 #include "sysdep.h"
32 #include <stdlib.h>
33 #include <unistd.h>
34 #include <stdio.h>
35 #include <fcntl.h>
36 #include <ctype.h>
37 #include <signal.h>
38 #include <pwd.h>
39 #include <errno.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <dirent.h>
43 #if TIME_WITH_SYS_TIME
44 # include <sys/time.h>
45 # include <time.h>
46 #else
47 # if HAVE_SYS_TIME_H
48 #  include <sys/time.h>
49 # else
50 #  include <time.h>
51 # endif
52 #endif
53 #ifdef HAVE_SYSCALL_H
54 # include <syscall.h>
55 #else 
56 # if HAVE_SYS_SYSCALL_H
57 #  include <sys/syscall.h>
58 # endif
59 #endif
60
61 #include <sys/wait.h>
62 #include <string.h>
63 #include <limits.h>
64 #include <libcitadel.h>
65 #include "citadel.h"
66 #include "server.h"
67 #include "citserver.h"
68 #include "support.h"
69 #include "config.h"
70 #include "user_ops.h"
71 #include "database.h"
72 #include "msgbase.h"
73 #include "internet_addressing.h"
74 #include "serv_network.h"
75 #include "clientsocket.h"
76 #include "file_ops.h"
77 #include "citadel_dirs.h"
78 #include "threads.h"
79
80 #ifndef HAVE_SNPRINTF
81 #include "snprintf.h"
82 #endif
83
84 #include "context.h"
85
86 #include "netconfig.h"
87 #include "ctdl_module.h"
88
89 struct CitContext networker_client_CC;
90
91 #define NODE ChrPtr(((AsyncNetworker*)IO->Data)->node)
92 #define N ((AsyncNetworker*)IO->Data)->n
93
94 #define EVN_syslog(LEVEL, FORMAT, ...) \
95         syslog(LEVEL, \
96                "IO[%ld]CC[%d]NW[%s][%ld]" FORMAT, \
97                IO->ID, CCID, NODE, N, __VA_ARGS__)
98
99 #define EVNM_syslog(LEVEL, FORMAT) \
100         syslog(LEVEL, \
101                "IO[%ld]CC[%d]NW[%s][%ld]" FORMAT, \
102                IO->ID, CCID, NODE, N)
103
104 #define EVNCS_syslog(LEVEL, FORMAT, ...) \
105         syslog(LEVEL, "IO[%ld]NW[%s][%ld]" FORMAT, \
106                IO->ID, NODE, N, __VA_ARGS__)
107
108 #define EVNCSM_syslog(LEVEL, FORMAT) \
109         syslog(LEVEL, "IO[%ld]NW[%s][%ld]" FORMAT, \
110                IO->ID, NODE, N)
111
112
113 typedef enum _eNWCState {
114         eeGreating,
115         eAuth,
116         eNDOP,
117         eREAD,
118         eReadBLOB,
119         eCLOS,
120         eNUOP,
121         eWRIT,
122         eWriteBLOB,
123         eUCLS,
124         eQUIT
125 }eNWCState;
126
127
128 typedef struct _async_networker {
129         AsyncIO IO;
130         DNSQueryParts HostLookup;
131         eNWCState State;
132         long n;
133         StrBuf *SpoolFileName;
134         StrBuf *tempFileName;
135         StrBuf *node;
136         StrBuf *host;
137         StrBuf *port;
138         StrBuf *secret;
139         StrBuf          *Url;
140 } AsyncNetworker;
141
142 typedef eNextState(*NWClientHandler)(AsyncNetworker* NW);
143 eNextState nwc_get_one_host_ip(AsyncIO *IO);
144
145 eNextState nwc_connect_ip(AsyncIO *IO);
146
147 eNextState NWC_SendQUIT(AsyncNetworker *NW);
148 eNextState NWC_DispatchWriteDone(AsyncIO *IO);
149
150 void DeleteNetworker(void *vptr)
151 {
152         AsyncNetworker *NW = (AsyncNetworker *)vptr;
153         FreeStrBuf(&NW->SpoolFileName);
154         FreeStrBuf(&NW->tempFileName);
155         FreeStrBuf(&NW->node);
156         FreeStrBuf(&NW->host);
157         FreeStrBuf(&NW->port);
158         FreeStrBuf(&NW->secret);
159         FreeStrBuf(&NW->Url);
160         FreeAsyncIOContents(&NW->IO);
161         free(NW);
162 }
163
164 #define NWC_DBG_SEND() EVN_syslog(LOG_DEBUG, ": > %s", ChrPtr(NW->IO.SendBuf.Buf))
165 #define NWC_DBG_READ() EVN_syslog(LOG_DEBUG, ": < %s\n", ChrPtr(NW->IO.IOBuf))
166 #define NWC_OK (strncasecmp(ChrPtr(NW->IO.IOBuf), "+OK", 3) == 0)
167
168 eNextState FinalizeNetworker(AsyncIO *IO)
169 {
170         AsyncNetworker *NW = (AsyncNetworker *)IO->Data;
171
172         network_talking_to(SKEY(NW->node), NTT_REMOVE);
173
174         DeleteNetworker(IO->Data);
175         return eAbort;
176 }
177
178 eNextState NWC_ReadGreeting(AsyncNetworker *NW)
179 {
180         char connected_to[SIZ];
181         AsyncIO *IO = &NW->IO;
182         NWC_DBG_READ();
183         /* Read the server greeting */
184         /* Check that the remote is who we think it is and warn the Aide if not */
185         extract_token (connected_to, ChrPtr(NW->IO.IOBuf), 1, ' ', sizeof connected_to);
186         if (strcmp(connected_to, ChrPtr(NW->node)) != 0)
187         {
188                 StrBufPrintf(NW->IO.ErrMsg,
189                              "Connected to node \"%s\" but I was expecting to connect to node \"%s\".",
190                              connected_to, ChrPtr(NW->node));
191                 EVN_syslog(LOG_ERR, "%s\n", ChrPtr(NW->IO.ErrMsg));
192                 CtdlAideMessage(ChrPtr(NW->IO.ErrMsg), "Network error");
193                 return eAbort;/// todo: aide message in anderer queue speichern
194         }
195         return eSendReply;
196 }
197
198 eNextState NWC_SendAuth(AsyncNetworker *NW)
199 {
200         AsyncIO *IO = &NW->IO;
201         /* We're talking to the correct node.  Now identify ourselves. */
202         StrBufPrintf(NW->IO.SendBuf.Buf, "NETP %s|%s\n", 
203                      config.c_nodename, 
204                      ChrPtr(NW->secret));
205         NWC_DBG_SEND();
206         return eSendReply;
207 }
208
209 eNextState NWC_ReadAuthReply(AsyncNetworker *NW)
210 {
211         AsyncIO *IO = &NW->IO;
212         NWC_DBG_READ();
213         if (ChrPtr(NW->IO.IOBuf)[0] == '2')
214         {
215                 return eSendReply;
216         }
217         else
218         {
219                 StrBufPrintf(NW->IO.ErrMsg,
220                              "Connected to node \"%s\" but my secret wasn't accurate.",
221                              ChrPtr(NW->node));
222                 EVN_syslog(LOG_ERR, "%s\n", ChrPtr(NW->IO.ErrMsg));
223                 CtdlAideMessage(ChrPtr(NW->IO.ErrMsg), "Network error");
224                 
225                 return eAbort;
226         }
227 }
228
229 eNextState NWC_SendNDOP(AsyncNetworker *NW)
230 {
231         AsyncIO *IO = &NW->IO;
232         NW->tempFileName = NewStrBuf();
233         NW->SpoolFileName = NewStrBuf();
234         StrBufPrintf(NW->tempFileName, 
235                      "%s/%s.%lx%x",
236                      ctdl_netin_dir,
237                      ChrPtr(NW->node),
238                      time(NULL),// TODO: get time from libev
239                      rand());
240         StrBufPrintf(NW->SpoolFileName, 
241                      "%s/%s.%lx%x",
242                      ctdl_nettmp_dir,
243                      ChrPtr(NW->node),
244                      time(NULL),// TODO: get time from libev
245                      rand());
246
247         /* We're talking to the correct node.  Now identify ourselves. */
248         StrBufPlain(NW->IO.SendBuf.Buf, HKEY("NDOP\n"));
249         NWC_DBG_SEND();
250         return eSendReply;
251 }
252
253 eNextState NWC_ReadNDOPReply(AsyncNetworker *NW)
254 {
255         AsyncIO *IO = &NW->IO;
256         int TotalSendSize;
257         NWC_DBG_READ();
258         if (ChrPtr(NW->IO.IOBuf)[0] == '2')
259         {
260
261                 NW->IO.IOB.TotalSentAlready = 0;
262                 TotalSendSize = atol (ChrPtr(NW->IO.IOBuf) + 4);
263                 EVN_syslog(LOG_DEBUG, "Expecting to transfer %ld bytes\n", NW->IO.IOB.TotalSendSize);
264                 if (TotalSendSize <= 0) {
265                         NW->State = eNUOP - 1;
266                 }
267                 else {
268                         int fd;
269                         fd = open(ChrPtr(NW->SpoolFileName), 
270                                   O_EXCL|O_CREAT|O_NONBLOCK|O_WRONLY, 
271                                   S_IRUSR|S_IWUSR);
272                         if (fd < 0)
273                         {
274                                 EVN_syslog(LOG_CRIT,
275                                        "cannot open %s: %s\n", 
276                                        ChrPtr(NW->SpoolFileName), 
277                                        strerror(errno));
278
279                                 NW->State = eQUIT - 1;
280                                 return eAbort;
281                         }
282                         FDIOBufferInit(&NW->IO.IOB, &NW->IO.RecvBuf, fd, TotalSendSize);
283                 }
284                 return eSendReply;
285         }
286         else
287         {
288                 return eAbort;
289         }
290 }
291
292 eNextState NWC_SendREAD(AsyncNetworker *NW)
293 {
294         AsyncIO *IO = &NW->IO;
295         eNextState rc;
296
297         if (NW->IO.IOB.TotalSentAlready < NW->IO.IOB.TotalSendSize)
298         {
299                 /*
300                  * If shutting down we can exit here and unlink the temp file.
301                  * this shouldn't loose us any messages.
302                  */
303                 if (server_shutting_down)
304                 {
305                         FDIOBufferDelete(&NW->IO.IOB);
306                         unlink(ChrPtr(NW->tempFileName));
307                         return eAbort;
308                 }
309                 StrBufPrintf(NW->IO.SendBuf.Buf, "READ %ld|%ld\n",
310                              NW->IO.IOB.TotalSentAlready,
311                              NW->IO.IOB.TotalSendSize);
312 /*
313                              ((NW->IO.IOB.TotalSendSize - NW->IO.IOB.TotalSentAlready > IGNET_PACKET_SIZE)
314                               ? IGNET_PACKET_SIZE : 
315                               (NW->IO.IOB.TotalSendSize - NW->IO.IOB.TotalSentAlready))
316                         );
317 */
318                 NWC_DBG_SEND();
319                 return eSendReply;
320         }
321         else 
322         {
323                 NW->State = eCLOS;
324                 rc = NWC_DispatchWriteDone(&NW->IO);
325                 NWC_DBG_SEND();
326
327                 return rc;
328         }
329 }
330
331 eNextState NWC_ReadREADState(AsyncNetworker *NW)
332 {
333         AsyncIO *IO = &NW->IO;
334         NWC_DBG_READ();
335         if (ChrPtr(NW->IO.IOBuf)[0] == '6')
336         {
337                 NW->IO.IOB.ChunkSendRemain = 
338                         NW->IO.IOB.ChunkSize = atol(ChrPtr(NW->IO.IOBuf)+4);
339                 return eReadFile;
340         }
341         return eAbort;
342 }
343 eNextState NWC_ReadREADBlobDone(AsyncNetworker *NW);
344 eNextState NWC_ReadREADBlob(AsyncNetworker *NW)
345 {
346         AsyncIO *IO = &NW->IO;
347         NWC_DBG_READ();
348         if (NW->IO.IOB.TotalSendSize == NW->IO.IOB.TotalSentAlready)
349         {
350                 NW->State ++;
351
352                 FDIOBufferDelete(&NW->IO.IOB);
353                 
354                 if (link(ChrPtr(NW->SpoolFileName), ChrPtr(NW->tempFileName)) != 0) {
355                         EVN_syslog(LOG_ALERT, 
356                                "Could not link %s to %s: %s\n",
357                                ChrPtr(NW->tempFileName), 
358                                ChrPtr(NW->SpoolFileName), 
359                                strerror(errno));
360                 }
361         
362                 unlink(ChrPtr(NW->tempFileName));
363                 return NWC_DispatchWriteDone(&NW->IO);
364         }
365         else {
366                 NW->State --;
367                 NW->IO.IOB.ChunkSendRemain = NW->IO.IOB.ChunkSize;
368                 return NWC_DispatchWriteDone(&NW->IO);
369         }
370 }
371
372 eNextState NWC_ReadREADBlobDone(AsyncNetworker *NW)
373 {
374         AsyncIO *IO = &NW->IO;
375         NWC_DBG_READ();
376         if (NW->IO.IOB.TotalSendSize == NW->IO.IOB.TotalSentAlready)
377         {
378                 NW->State ++;
379
380                 FDIOBufferDelete(&NW->IO.IOB);
381                 
382                 if (link(ChrPtr(NW->SpoolFileName), ChrPtr(NW->tempFileName)) != 0) {
383                         EVN_syslog(LOG_ALERT, 
384                                "Could not link %s to %s: %s\n",
385                                ChrPtr(NW->tempFileName), 
386                                ChrPtr(NW->SpoolFileName), 
387                                strerror(errno));
388                 }
389         
390                 unlink(ChrPtr(NW->tempFileName));
391                 return NWC_DispatchWriteDone(&NW->IO);
392         }
393         else {
394                 NW->State --;
395                 NW->IO.IOB.ChunkSendRemain = NW->IO.IOB.ChunkSize;
396                 return NWC_DispatchWriteDone(&NW->IO);
397         }
398 }
399 eNextState NWC_SendCLOS(AsyncNetworker *NW)
400 {
401         AsyncIO *IO = &NW->IO;
402         StrBufPlain(NW->IO.SendBuf.Buf, HKEY("CLOS\n"));
403         NWC_DBG_SEND();
404         return eSendReply;
405 }
406
407 eNextState NWC_ReadCLOSReply(AsyncNetworker *NW)
408 {
409         AsyncIO *IO = &NW->IO;
410         NWC_DBG_READ();
411         if (ChrPtr(NW->IO.IOBuf)[0] != '2')
412                 return eTerminateConnection;
413         return eSendReply;
414 }
415
416
417 eNextState NWC_SendNUOP(AsyncNetworker *NW)
418 {
419         AsyncIO *IO = &NW->IO;
420         eNextState rc;
421         long TotalSendSize;
422         struct stat statbuf;
423         int fd;
424
425         StrBufPrintf(NW->tempFileName,
426                      "%s/%s",
427                      ctdl_netout_dir,
428                      ChrPtr(NW->node));
429         fd = open(ChrPtr(NW->tempFileName), O_RDONLY);
430         if (fd < 0) {
431                 if (errno != ENOENT) {
432                         EVN_syslog(LOG_CRIT,
433                                "cannot open %s: %s\n", 
434                                ChrPtr(NW->tempFileName), 
435                                strerror(errno));
436                 }
437                 NW->State = eQUIT;
438                 rc = NWC_SendQUIT(NW);
439                 NWC_DBG_SEND();
440         }
441
442         if (fstat(fd, &statbuf) == -1) {
443                 EVN_syslog(LOG_CRIT, "FSTAT FAILED %s [%s]--\n", 
444                            ChrPtr(NW->tempFileName), 
445                            strerror(errno));
446                 if (fd > 0) close(fd);
447                 return eAbort;
448         }
449         TotalSendSize = statbuf.st_size;
450         if (TotalSendSize == 0) {
451                 EVNM_syslog(LOG_DEBUG,
452                        "Nothing to send.\n");
453                 NW->State = eQUIT;
454                 rc = NWC_SendQUIT(NW);
455                 NWC_DBG_SEND();
456                 return rc;
457         }
458         FDIOBufferInit(&NW->IO.IOB, &NW->IO.SendBuf, fd, TotalSendSize);
459
460         StrBufPlain(NW->IO.SendBuf.Buf, HKEY("NUOP\n"));
461         NWC_DBG_SEND();
462         return eSendReply;
463
464 }
465 eNextState NWC_ReadNUOPReply(AsyncNetworker *NW)
466 {
467         AsyncIO *IO = &NW->IO;
468         NWC_DBG_READ();
469         if (ChrPtr(NW->IO.IOBuf)[0] != '2')
470                 return eAbort;
471         return eSendReply;
472 }
473
474 eNextState NWC_SendWRIT(AsyncNetworker *NW)
475 {
476         AsyncIO *IO = &NW->IO;
477         StrBufPrintf(NW->IO.SendBuf.Buf, "WRIT %ld\n", 
478                      NW->IO.IOB.TotalSendSize - NW->IO.IOB.TotalSentAlready);
479         NWC_DBG_SEND();
480         return eSendReply;
481 }
482 eNextState NWC_ReadWRITReply(AsyncNetworker *NW)
483 {
484         AsyncIO *IO = &NW->IO;
485         NWC_DBG_READ();
486         if (ChrPtr(NW->IO.IOBuf)[0] != '7')
487         {
488                 return eAbort;
489         }
490
491         NW->IO.IOB.ChunkSendRemain = 
492                 NW->IO.IOB.ChunkSize = atol(ChrPtr(NW->IO.IOBuf)+4);
493         return eSendFile;
494 }
495
496 eNextState NWC_SendBlobDone(AsyncNetworker *NW)
497 {
498         AsyncIO *IO = &NW->IO;
499         eNextState rc;
500         if (NW->IO.IOB.TotalSendSize == NW->IO.IOB.TotalSentAlready)
501         {
502                 NW->State ++;
503
504                 FDIOBufferDelete(&NW->IO.IOB);
505                 rc =  NWC_DispatchWriteDone(&NW->IO);
506                 NW->State --;
507                 return rc;
508         }
509         else {
510                 NW->State --;
511                 NW->IO.IOB.ChunkSendRemain = NW->IO.IOB.ChunkSize;
512                 return NWC_DispatchWriteDone(&NW->IO);
513         }
514 }
515
516 eNextState NWC_SendUCLS(AsyncNetworker *NW)
517 {
518         AsyncIO *IO = &NW->IO;
519         StrBufPlain(NW->IO.SendBuf.Buf, HKEY("UCLS 1\n"));
520         NWC_DBG_SEND();
521         return eSendReply;
522
523 }
524 eNextState NWC_ReadUCLS(AsyncNetworker *NW)
525 {
526         AsyncIO *IO = &NW->IO;
527         NWC_DBG_READ();
528
529         EVN_syslog(LOG_NOTICE, "Sent %ld octets to <%s>\n", NW->IO.IOB.ChunkSize, ChrPtr(NW->node));
530         if (ChrPtr(NW->IO.IOBuf)[0] == '2') {
531                 EVN_syslog(LOG_DEBUG, "Removing <%s>\n", ChrPtr(NW->tempFileName));
532                 unlink(ChrPtr(NW->tempFileName));
533         }
534         return eSendReply;
535 }
536
537 eNextState NWC_SendQUIT(AsyncNetworker *NW)
538 {
539         AsyncIO *IO = &NW->IO;
540         StrBufPlain(NW->IO.SendBuf.Buf, HKEY("QUIT\n"));
541
542         NWC_DBG_SEND();
543         return eSendReply;
544 }
545
546 eNextState NWC_ReadQUIT(AsyncNetworker *NW)
547 {
548         AsyncIO *IO = &NW->IO;
549         NWC_DBG_READ();
550
551         return eAbort;
552 }
553
554
555 NWClientHandler NWC_ReadHandlers[] = {
556         NWC_ReadGreeting,
557         NWC_ReadAuthReply,
558         NWC_ReadNDOPReply,
559         NWC_ReadREADState,
560         NWC_ReadREADBlob,
561         NWC_ReadCLOSReply,
562         NWC_ReadNUOPReply,
563         NWC_ReadWRITReply,
564         NWC_SendBlobDone,
565         NWC_ReadUCLS,
566         NWC_ReadQUIT};
567
568 long NWC_ConnTimeout = 100;
569
570 const long NWC_SendTimeouts[] = {
571         100,
572         100,
573         100,
574         100,
575         100,
576         100,
577         100,
578         100
579 };
580 const ConstStr NWC[] = {
581         {HKEY("Connection broken during ")},
582         {HKEY("Connection broken during ")},
583         {HKEY("Connection broken during ")},
584         {HKEY("Connection broken during ")},
585         {HKEY("Connection broken during ")},
586         {HKEY("Connection broken during ")},
587         {HKEY("Connection broken during ")},
588         {HKEY("Connection broken during ")}
589 };
590
591 NWClientHandler NWC_SendHandlers[] = {
592         NULL,
593         NWC_SendAuth,
594         NWC_SendNDOP,
595         NWC_SendREAD,
596         NWC_ReadREADBlobDone,
597         NWC_SendCLOS,
598         NWC_SendNUOP,
599         NWC_SendWRIT,
600         NWC_SendBlobDone,
601         NWC_SendUCLS,
602         NWC_SendQUIT
603 };
604
605 const long NWC_ReadTimeouts[] = {
606         100,
607         100,
608         100,
609         100,
610         100,
611         100,
612         100,
613         100,
614         100,
615         100
616 };
617
618
619
620
621 eNextState nwc_get_one_host_ip_done(AsyncIO *IO)
622 {
623         AsyncNetworker *NW = IO->Data;
624         struct hostent *hostent;
625
626         QueryCbDone(IO);
627
628         hostent = NW->HostLookup.VParsedDNSReply;
629         if ((NW->HostLookup.DNSStatus == ARES_SUCCESS) && 
630             (hostent != NULL) ) {
631                 memset(&NW->IO.ConnectMe->Addr, 0, sizeof(struct in6_addr));
632                 if (NW->IO.ConnectMe->IPv6) {
633                         memcpy(&NW->IO.ConnectMe->Addr.sin6_addr.s6_addr, 
634                                &hostent->h_addr_list[0],
635                                sizeof(struct in6_addr));
636                         
637                         NW->IO.ConnectMe->Addr.sin6_family = hostent->h_addrtype;
638                         NW->IO.ConnectMe->Addr.sin6_port   = htons(atol(ChrPtr(NW->port)));//// TODO use the one from the URL.
639                 }
640                 else {
641                         struct sockaddr_in *addr = (struct sockaddr_in*) &NW->IO.ConnectMe->Addr;
642                         /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
643 //                      addr->sin_addr.s_addr = htonl((uint32_t)&hostent->h_addr_list[0]);
644                         memcpy(&addr->sin_addr.s_addr, 
645                                hostent->h_addr_list[0], 
646                                sizeof(uint32_t));
647                         
648                         addr->sin_family = hostent->h_addrtype;
649                         addr->sin_port   = htons(504);/// default citadel port
650                         
651                 }
652                 return nwc_connect_ip(IO);
653         }
654         else
655                 return eAbort;
656 }
657
658
659 eNextState nwc_get_one_host_ip(AsyncIO *IO)
660 {
661         AsyncNetworker *NW = IO->Data;
662         /* 
663          * here we start with the lookup of one host.
664          */ 
665
666         EVN_syslog(LOG_DEBUG, "NWC: %s\n", __FUNCTION__);
667
668         EVN_syslog(LOG_DEBUG, 
669                    "NWC client[%ld]: looking up %s-Record %s : %d ...\n", 
670                    NW->n, 
671                    (NW->IO.ConnectMe->IPv6)? "aaaa": "a",
672                    NW->IO.ConnectMe->Host, 
673                    NW->IO.ConnectMe->Port);
674
675         QueueQuery((NW->IO.ConnectMe->IPv6)? ns_t_aaaa : ns_t_a, 
676                    NW->IO.ConnectMe->Host, 
677                    &NW->IO, 
678                    &NW->HostLookup, 
679                    nwc_get_one_host_ip_done);
680         IO->NextState = eReadDNSReply;
681         return IO->NextState;
682 }
683 /**
684  * @brief lineread Handler; understands when to read more POP3 lines, and when this is a one-lined reply.
685  */
686 eReadState NWC_ReadServerStatus(AsyncIO *IO)
687 {
688 //      AsyncNetworker *NW = IO->Data;
689         eReadState Finished = eBufferNotEmpty; 
690
691         switch (IO->NextState) {
692         case eSendDNSQuery:
693         case eReadDNSReply:
694         case eDBQuery:
695         case eConnect:
696         case eTerminateConnection:
697         case eAbort:
698                 Finished = eReadFail;
699                 break;
700         case eSendReply: 
701         case eSendMore:
702         case eReadMore:
703         case eReadMessage: 
704                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
705                 break;
706         case eReadFile:
707         case eSendFile:
708         case eReadPayload:
709                 break;
710         }
711         return Finished;
712 }
713
714
715
716 eNextState NWC_FailNetworkConnection(AsyncIO *IO)
717 {
718         return eAbort;
719 }
720
721 void NWC_SetTimeout(eNextState NextTCPState, AsyncNetworker *NW)
722 {
723         AsyncIO *IO = &NW->IO;
724         double Timeout = 0.0;
725
726         EVN_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
727
728         switch (NextTCPState) {
729         case eSendReply:
730         case eSendMore:
731                 break;
732         case eReadFile:
733         case eReadMessage:
734                 Timeout = NWC_ReadTimeouts[NW->State];
735                 break;
736         case eReadPayload:
737                 Timeout = 100000;
738                 /* TODO!!! */
739                 break;
740         case eSendDNSQuery:
741         case eReadDNSReply:
742         case eConnect:
743         case eSendFile:
744 //TODO
745         case eTerminateConnection:
746         case eDBQuery:
747         case eAbort:
748         case eReadMore://// TODO
749                 return;
750         }
751         SetNextTimeout(&NW->IO, Timeout);
752 }
753
754
755 eNextState NWC_DispatchReadDone(AsyncIO *IO)
756 {
757         EVN_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
758         AsyncNetworker *NW = IO->Data;
759         eNextState rc;
760
761         rc = NWC_ReadHandlers[NW->State](NW);
762         if (rc != eReadMore)
763                 NW->State++;
764         NWC_SetTimeout(rc, NW);
765         return rc;
766 }
767 eNextState NWC_DispatchWriteDone(AsyncIO *IO)
768 {
769         EVN_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
770         AsyncNetworker *NW = IO->Data;
771         eNextState rc;
772
773         rc = NWC_SendHandlers[NW->State](NW);
774         NWC_SetTimeout(rc, NW);
775         return rc;
776 }
777
778 /*****************************************************************************/
779 /*                     Networker CLIENT ERROR CATCHERS                       */
780 /*****************************************************************************/
781 eNextState NWC_Terminate(AsyncIO *IO)
782 {
783         EVN_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
784         FinalizeNetworker(IO);
785         return eAbort;
786 }
787
788 eNextState NWC_Timeout(AsyncIO *IO)
789 {
790         EVN_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
791
792         return NWC_FailNetworkConnection(IO);
793 }
794 eNextState NWC_ConnFail(AsyncIO *IO)
795 {
796 ///     AsyncNetworker *NW = IO->Data;
797
798         EVN_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
799 ////    StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State])); todo
800         return NWC_FailNetworkConnection(IO);
801 }
802 eNextState NWC_DNSFail(AsyncIO *IO)
803 {
804 ///     AsyncNetworker *NW = IO->Data;
805
806         EVN_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
807 ////    StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State])); todo
808         return NWC_FailNetworkConnection(IO);
809 }
810 eNextState NWC_Shutdown(AsyncIO *IO)
811 {
812         EVN_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
813 ////    pop3aggr *pMsg = IO->Data;
814
815         FinalizeNetworker(IO);
816         return eAbort;
817 }
818
819
820 eNextState nwc_connect_ip(AsyncIO *IO)
821 {
822         AsyncNetworker *NW = IO->Data;
823
824         EVN_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
825         EVN_syslog(LOG_NOTICE, "Connecting to <%s> at %s:%s\n", 
826                    ChrPtr(NW->node), 
827                    ChrPtr(NW->host),
828                    ChrPtr(NW->port));
829         
830         return EvConnectSock(IO,
831                              NWC_ConnTimeout,
832                              NWC_ReadTimeouts[0],
833                              1);
834 }
835
836 static int NetworkerCount = 0;
837 void RunNetworker(AsyncNetworker *NW)
838 {
839         AsyncIO *IO = &NW->IO;
840
841         NW->n = NetworkerCount++;
842         network_talking_to(SKEY(NW->node), NTT_ADD);
843         EVN_syslog(LOG_DEBUG, "network: polling <%s>\n", ChrPtr(NW->node));
844         ParseURL(&NW->IO.ConnectMe, NW->Url, 504);
845
846         InitIOStruct(&NW->IO,
847                      NW,
848                      eReadMessage,
849                      NWC_ReadServerStatus,
850                      NWC_DNSFail,
851                      NWC_DispatchWriteDone,
852                      NWC_DispatchReadDone,
853                      NWC_Terminate,
854                      NWC_ConnFail,
855                      NWC_Timeout,
856                      NWC_Shutdown);
857
858         safestrncpy(((CitContext *)NW->IO.CitContext)->cs_host, 
859                     ChrPtr(NW->host),
860                     sizeof(((CitContext *)NW->IO.CitContext)->cs_host)); 
861
862         if (NW->IO.ConnectMe->IsIP) {
863                 QueueEventContext(&NW->IO,
864                                   nwc_connect_ip);
865         }
866         else { /* uneducated admin has chosen to add DNS to the equation... */
867                 QueueEventContext(&NW->IO,
868                                   nwc_get_one_host_ip);
869         }
870 }
871
872 /*
873  * Poll other Citadel nodes and transfer inbound/outbound network data.
874  * Set "full" to nonzero to force a poll of every node, or to zero to poll
875  * only nodes to which we have data to send.
876  */
877 void network_poll_other_citadel_nodes(int full_poll, char *working_ignetcfg)
878 {
879         AsyncNetworker *NW;
880         StrBuf *CfgData;
881         StrBuf *Line;
882         const char *lptr;
883         const char *CfgPtr;
884         int Done;
885         
886         int poll = 0;
887         
888         if ((working_ignetcfg == NULL) || (*working_ignetcfg == '\0')) {
889                 syslog(LOG_DEBUG, "network: no neighbor nodes are configured - not polling.\n");
890                 return;
891         }
892         become_session(&networker_client_CC);
893
894         CfgData = NewStrBufPlain(working_ignetcfg, -1);
895         Line = NewStrBufPlain(NULL, StrLength(CfgData));
896         Done = 0;
897         CfgPtr = NULL;
898         while (!Done)
899         {
900                 /* Use the string tokenizer to grab one line at a time */
901                 StrBufSipLine(Line, CfgData, &CfgPtr);
902                 Done = CfgPtr == StrBufNOTNULL;
903                 if (StrLength(Line) > 0)
904                 {
905                         if(server_shutting_down)
906                                 return;/* TODO free stuff*/
907                         lptr = NULL;
908                         poll = 0;
909                         NW = (AsyncNetworker*)malloc(sizeof(AsyncNetworker));
910                         memset(NW, 0, sizeof(AsyncNetworker));
911                         
912                         NW->node = NewStrBufPlain(NULL, StrLength(Line));
913                         NW->host = NewStrBufPlain(NULL, StrLength(Line));
914                         NW->port = NewStrBufPlain(NULL, StrLength(Line));
915                         NW->secret = NewStrBufPlain(NULL, StrLength(Line));
916                         
917                         StrBufExtract_NextToken(NW->node, Line, &lptr, '|');
918                         StrBufExtract_NextToken(NW->secret, Line, &lptr, '|');
919                         StrBufExtract_NextToken(NW->host, Line, &lptr, '|');
920                         StrBufExtract_NextToken(NW->port, Line, &lptr, '|');
921                         if ( (StrLength(NW->node) != 0) && 
922                              (StrLength(NW->secret) != 0) &&
923                              (StrLength(NW->host) != 0) &&
924                              (StrLength(NW->port) != 0))
925                         {
926                                 poll = full_poll;
927                                 if (poll == 0)
928                                 {
929                                         NW->SpoolFileName = NewStrBufPlain(ctdl_netout_dir, -1);
930                                         StrBufAppendBufPlain(NW->SpoolFileName, HKEY("/"), 0);
931                                         StrBufAppendBuf(NW->SpoolFileName, NW->node, 0);
932                                         if (access(ChrPtr(NW->SpoolFileName), R_OK) == 0) {
933                                                 poll = 1;
934                                         }
935                                 }
936                         }
937                         if (poll && (StrLength (NW->host) > 0) && (!strcmp(ChrPtr(NW->host), "0.0.0.0")))
938                         {
939                                 NW->Url = NewStrBufPlain(NULL, StrLength(Line));
940                                 StrBufPrintf(NW->Url, "citadel://:%s@%s:%s", 
941                                              ChrPtr(NW->secret),
942                                              ChrPtr(NW->host),
943                                              ChrPtr(NW->port));
944                                 if (!network_talking_to(SKEY(NW->node), NTT_CHECK))
945                                 {
946                                         RunNetworker(NW);
947                                         continue;
948                                 }
949                         }
950                         DeleteNetworker(NW);
951                 }
952         }
953         FreeStrBuf(&CfgData);
954         FreeStrBuf(&Line);
955
956 }
957
958
959 void network_do_clientqueue(void)
960 {
961         char *working_ignetcfg;
962         int full_processing = 1;
963         static time_t last_run = 0L;
964
965         /*
966          * Run the full set of processing tasks no more frequently
967          * than once every n seconds
968          */
969         if ( (time(NULL) - last_run) < config.c_net_freq ) {
970                 full_processing = 0;
971                 syslog(LOG_DEBUG, "Network full processing in %ld seconds.\n",
972                         config.c_net_freq - (time(NULL)- last_run)
973                 );
974         }
975
976         working_ignetcfg = load_working_ignetcfg();
977         /*
978          * Poll other Citadel nodes.  Maybe.  If "full_processing" is set
979          * then we poll everyone.  Otherwise we only poll nodes we have stuff
980          * to send to.
981          */
982         network_poll_other_citadel_nodes(full_processing, working_ignetcfg);
983         if (working_ignetcfg)
984                 free(working_ignetcfg);
985 }
986
987
988
989 /*
990  * Module entry point
991  */
992 CTDL_MODULE_INIT(network_client)
993 {
994         if (!threading)
995         {
996                 CtdlFillSystemContext(&networker_client_CC, "CitNetworker");
997                 
998                 CtdlRegisterSessionHook(network_do_clientqueue, EVT_TIMER);
999         }
1000         return "network_client";
1001 }