d3736240771f873cd80349780651214a79ebdc96
[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                 if (NW->IO.ErrMsg == NULL)
189                         NW->IO.ErrMsg = NewStrBuf();
190                 StrBufPrintf(NW->IO.ErrMsg,
191                              "Connected to node \"%s\" but I was expecting to connect to node \"%s\".",
192                              connected_to, ChrPtr(NW->node));
193                 EVN_syslog(LOG_ERR, "%s\n", ChrPtr(NW->IO.ErrMsg));
194                 CtdlAideMessage(ChrPtr(NW->IO.ErrMsg), "Network error");
195                 return eAbort;/// todo: aide message in anderer queue speichern
196         }
197         return eSendReply;
198 }
199
200 eNextState NWC_SendAuth(AsyncNetworker *NW)
201 {
202         AsyncIO *IO = &NW->IO;
203         /* We're talking to the correct node.  Now identify ourselves. */
204         StrBufPrintf(NW->IO.SendBuf.Buf, "NETP %s|%s\n", 
205                      config.c_nodename, 
206                      ChrPtr(NW->secret));
207         NWC_DBG_SEND();
208         return eSendReply;
209 }
210
211 eNextState NWC_ReadAuthReply(AsyncNetworker *NW)
212 {
213         AsyncIO *IO = &NW->IO;
214         NWC_DBG_READ();
215         if (ChrPtr(NW->IO.IOBuf)[0] == '2')
216         {
217                 return eSendReply;
218         }
219         else
220         {
221                 if (NW->IO.ErrMsg == NULL)
222                         NW->IO.ErrMsg = NewStrBuf();
223                 StrBufPrintf(NW->IO.ErrMsg,
224                              "Connected to node \"%s\" but my secret wasn't accurate.",
225                              ChrPtr(NW->node));
226                 EVN_syslog(LOG_ERR, "%s\n", ChrPtr(NW->IO.ErrMsg));
227                 CtdlAideMessage(ChrPtr(NW->IO.ErrMsg), "Network error");
228                 
229                 return eAbort;
230         }
231 }
232
233 eNextState NWC_SendNDOP(AsyncNetworker *NW)
234 {
235         AsyncIO *IO = &NW->IO;
236         NW->tempFileName = NewStrBuf();
237         NW->SpoolFileName = NewStrBuf();
238         StrBufPrintf(NW->tempFileName, 
239                      "%s/%s.%lx%x",
240                      ctdl_netin_dir,
241                      ChrPtr(NW->node),
242                      time(NULL),// TODO: get time from libev
243                      rand());
244         StrBufPrintf(NW->SpoolFileName, 
245                      "%s/%s.%lx%x",
246                      ctdl_nettmp_dir,
247                      ChrPtr(NW->node),
248                      time(NULL),// TODO: get time from libev
249                      rand());
250
251         /* We're talking to the correct node.  Now identify ourselves. */
252         StrBufPlain(NW->IO.SendBuf.Buf, HKEY("NDOP\n"));
253         NWC_DBG_SEND();
254         return eSendReply;
255 }
256
257 eNextState NWC_ReadNDOPReply(AsyncNetworker *NW)
258 {
259         AsyncIO *IO = &NW->IO;
260         int TotalSendSize;
261         NWC_DBG_READ();
262         if (ChrPtr(NW->IO.IOBuf)[0] == '2')
263         {
264
265                 NW->IO.IOB.TotalSentAlready = 0;
266                 TotalSendSize = atol (ChrPtr(NW->IO.IOBuf) + 4);
267                 EVN_syslog(LOG_DEBUG, "Expecting to transfer %ld bytes\n", NW->IO.IOB.TotalSendSize);
268                 if (TotalSendSize <= 0) {
269                         NW->State = eNUOP - 1;
270                 }
271                 else {
272                         int fd;
273                         fd = open(ChrPtr(NW->SpoolFileName), 
274                                   O_EXCL|O_CREAT|O_NONBLOCK|O_WRONLY, 
275                                   S_IRUSR|S_IWUSR);
276                         if (fd < 0)
277                         {
278                                 EVN_syslog(LOG_CRIT,
279                                        "cannot open %s: %s\n", 
280                                        ChrPtr(NW->SpoolFileName), 
281                                        strerror(errno));
282
283                                 NW->State = eQUIT - 1;
284                                 return eAbort;
285                         }
286                         FDIOBufferInit(&NW->IO.IOB, &NW->IO.RecvBuf, fd, TotalSendSize);
287                 }
288                 return eSendReply;
289         }
290         else
291         {
292                 return eAbort;
293         }
294 }
295
296 eNextState NWC_SendREAD(AsyncNetworker *NW)
297 {
298         AsyncIO *IO = &NW->IO;
299         eNextState rc;
300
301         if (NW->IO.IOB.TotalSentAlready < NW->IO.IOB.TotalSendSize)
302         {
303                 /*
304                  * If shutting down we can exit here and unlink the temp file.
305                  * this shouldn't loose us any messages.
306                  */
307                 if (server_shutting_down)
308                 {
309                         FDIOBufferDelete(&NW->IO.IOB);
310                         unlink(ChrPtr(NW->tempFileName));
311                         return eAbort;
312                 }
313                 StrBufPrintf(NW->IO.SendBuf.Buf, "READ %ld|%ld\n",
314                              NW->IO.IOB.TotalSentAlready,
315                              NW->IO.IOB.TotalSendSize);
316 /*
317                              ((NW->IO.IOB.TotalSendSize - NW->IO.IOB.TotalSentAlready > IGNET_PACKET_SIZE)
318                               ? IGNET_PACKET_SIZE : 
319                               (NW->IO.IOB.TotalSendSize - NW->IO.IOB.TotalSentAlready))
320                         );
321 */
322                 NWC_DBG_SEND();
323                 return eSendReply;
324         }
325         else 
326         {
327                 NW->State = eCLOS;
328                 rc = NWC_DispatchWriteDone(&NW->IO);
329                 NWC_DBG_SEND();
330
331                 return rc;
332         }
333 }
334
335 eNextState NWC_ReadREADState(AsyncNetworker *NW)
336 {
337         AsyncIO *IO = &NW->IO;
338         NWC_DBG_READ();
339         if (ChrPtr(NW->IO.IOBuf)[0] == '6')
340         {
341                 NW->IO.IOB.ChunkSendRemain = 
342                         NW->IO.IOB.ChunkSize = atol(ChrPtr(NW->IO.IOBuf)+4);
343                 return eReadFile;
344         }
345         return eAbort;
346 }
347 eNextState NWC_ReadREADBlobDone(AsyncNetworker *NW);
348 eNextState NWC_ReadREADBlob(AsyncNetworker *NW)
349 {
350         eNextState rc;
351         AsyncIO *IO = &NW->IO;
352         NWC_DBG_READ();
353         if (NW->IO.IOB.TotalSendSize == NW->IO.IOB.TotalSentAlready)
354         {
355                 NW->State ++;
356
357                 FDIOBufferDelete(&NW->IO.IOB);
358                 
359                 if (link(ChrPtr(NW->SpoolFileName), ChrPtr(NW->tempFileName)) != 0) {
360                         EVN_syslog(LOG_ALERT, 
361                                "Could not link %s to %s: %s\n",
362                                ChrPtr(NW->tempFileName), 
363                                ChrPtr(NW->SpoolFileName), 
364                                strerror(errno));
365                 }
366         
367                 unlink(ChrPtr(NW->tempFileName));
368                 rc = NWC_DispatchWriteDone(&NW->IO);
369                 NW->State --;
370                 return rc;
371         }
372         else {
373                 NW->State --;
374                 NW->IO.IOB.ChunkSendRemain = NW->IO.IOB.ChunkSize;
375                 return NWC_DispatchWriteDone(&NW->IO);
376         }
377 }
378
379 eNextState NWC_ReadREADBlobDone(AsyncNetworker *NW)
380 {
381         eNextState rc;
382         AsyncIO *IO = &NW->IO;
383         NWC_DBG_READ();
384         if (NW->IO.IOB.TotalSendSize == NW->IO.IOB.TotalSentAlready)
385         {
386                 NW->State ++;
387
388                 FDIOBufferDelete(&NW->IO.IOB);
389                 
390                 if (link(ChrPtr(NW->SpoolFileName), ChrPtr(NW->tempFileName)) != 0) {
391                         EVN_syslog(LOG_ALERT, 
392                                "Could not link %s to %s: %s\n",
393                                ChrPtr(NW->tempFileName), 
394                                ChrPtr(NW->SpoolFileName), 
395                                strerror(errno));
396                 }
397         
398                 unlink(ChrPtr(NW->tempFileName));
399                 rc = NWC_DispatchWriteDone(&NW->IO);
400                 NW->State --;
401                 return rc;
402         }
403         else {
404                 NW->State --;
405                 NW->IO.IOB.ChunkSendRemain = NW->IO.IOB.ChunkSize;
406                 return NWC_DispatchWriteDone(&NW->IO);
407         }
408 }
409 eNextState NWC_SendCLOS(AsyncNetworker *NW)
410 {
411         AsyncIO *IO = &NW->IO;
412         StrBufPlain(NW->IO.SendBuf.Buf, HKEY("CLOS\n"));
413         NWC_DBG_SEND();
414         return eSendReply;
415 }
416
417 eNextState NWC_ReadCLOSReply(AsyncNetworker *NW)
418 {
419         AsyncIO *IO = &NW->IO;
420         NWC_DBG_READ();
421         if (ChrPtr(NW->IO.IOBuf)[0] != '2')
422                 return eTerminateConnection;
423         return eSendReply;
424 }
425
426
427 eNextState NWC_SendNUOP(AsyncNetworker *NW)
428 {
429         AsyncIO *IO = &NW->IO;
430         eNextState rc;
431         long TotalSendSize;
432         struct stat statbuf;
433         int fd;
434
435         StrBufPrintf(NW->tempFileName,
436                      "%s/%s",
437                      ctdl_netout_dir,
438                      ChrPtr(NW->node));
439         fd = open(ChrPtr(NW->tempFileName), O_RDONLY);
440         if (fd < 0) {
441                 if (errno != ENOENT) {
442                         EVN_syslog(LOG_CRIT,
443                                "cannot open %s: %s\n", 
444                                ChrPtr(NW->tempFileName), 
445                                strerror(errno));
446                 }
447                 NW->State = eQUIT;
448                 rc = NWC_SendQUIT(NW);
449                 NWC_DBG_SEND();
450                 return rc;
451         }
452
453         if (fstat(fd, &statbuf) == -1) {
454                 EVN_syslog(LOG_CRIT, "FSTAT FAILED %s [%s]--\n", 
455                            ChrPtr(NW->tempFileName), 
456                            strerror(errno));
457                 if (fd > 0) close(fd);
458                 return eAbort;
459         }
460         TotalSendSize = statbuf.st_size;
461         if (TotalSendSize == 0) {
462                 EVNM_syslog(LOG_DEBUG,
463                        "Nothing to send.\n");
464                 NW->State = eQUIT;
465                 rc = NWC_SendQUIT(NW);
466                 NWC_DBG_SEND();
467                 return rc;
468         }
469         FDIOBufferInit(&NW->IO.IOB, &NW->IO.SendBuf, fd, TotalSendSize);
470
471         StrBufPlain(NW->IO.SendBuf.Buf, HKEY("NUOP\n"));
472         NWC_DBG_SEND();
473         return eSendReply;
474
475 }
476 eNextState NWC_ReadNUOPReply(AsyncNetworker *NW)
477 {
478         AsyncIO *IO = &NW->IO;
479         NWC_DBG_READ();
480         if (ChrPtr(NW->IO.IOBuf)[0] != '2')
481                 return eAbort;
482         return eSendReply;
483 }
484
485 eNextState NWC_SendWRIT(AsyncNetworker *NW)
486 {
487         AsyncIO *IO = &NW->IO;
488         StrBufPrintf(NW->IO.SendBuf.Buf, "WRIT %ld\n", 
489                      NW->IO.IOB.TotalSendSize - NW->IO.IOB.TotalSentAlready);
490         NWC_DBG_SEND();
491         return eSendReply;
492 }
493 eNextState NWC_ReadWRITReply(AsyncNetworker *NW)
494 {
495         AsyncIO *IO = &NW->IO;
496         NWC_DBG_READ();
497         if (ChrPtr(NW->IO.IOBuf)[0] != '7')
498         {
499                 return eAbort;
500         }
501
502         NW->IO.IOB.ChunkSendRemain = 
503                 NW->IO.IOB.ChunkSize = atol(ChrPtr(NW->IO.IOBuf)+4);
504         return eSendFile;
505 }
506
507 eNextState NWC_SendBlobDone(AsyncNetworker *NW)
508 {
509         AsyncIO *IO = &NW->IO;
510         eNextState rc;
511         if (IO->IOB.TotalSendSize == NW->IO.IOB.TotalSentAlready)
512         {
513                 NW->State ++;
514
515                 FDIOBufferDelete(&IO->IOB);
516                 rc =  NWC_DispatchWriteDone(IO);
517                 NW->State --;
518                 return rc;
519         }
520         else {
521                 NW->State --;
522                 IO->IOB.ChunkSendRemain = IO->IOB.ChunkSize;
523                 rc = NWC_DispatchWriteDone(IO);
524                 NW->State --;
525                 return rc;
526         }
527 }
528
529 eNextState NWC_SendUCLS(AsyncNetworker *NW)
530 {
531         AsyncIO *IO = &NW->IO;
532         StrBufPlain(NW->IO.SendBuf.Buf, HKEY("UCLS 1\n"));
533         NWC_DBG_SEND();
534         return eSendReply;
535
536 }
537 eNextState NWC_ReadUCLS(AsyncNetworker *NW)
538 {
539         AsyncIO *IO = &NW->IO;
540         NWC_DBG_READ();
541
542         EVN_syslog(LOG_NOTICE, "Sent %ld octets to <%s>\n", NW->IO.IOB.ChunkSize, ChrPtr(NW->node));
543         if (ChrPtr(NW->IO.IOBuf)[0] == '2') {
544                 EVN_syslog(LOG_DEBUG, "Removing <%s>\n", ChrPtr(NW->tempFileName));
545                 unlink(ChrPtr(NW->tempFileName));
546         }
547         return eSendReply;
548 }
549
550 eNextState NWC_SendQUIT(AsyncNetworker *NW)
551 {
552         AsyncIO *IO = &NW->IO;
553         StrBufPlain(NW->IO.SendBuf.Buf, HKEY("QUIT\n"));
554
555         NWC_DBG_SEND();
556         return eSendReply;
557 }
558
559 eNextState NWC_ReadQUIT(AsyncNetworker *NW)
560 {
561         AsyncIO *IO = &NW->IO;
562         NWC_DBG_READ();
563
564         return eAbort;
565 }
566
567
568 NWClientHandler NWC_ReadHandlers[] = {
569         NWC_ReadGreeting,
570         NWC_ReadAuthReply,
571         NWC_ReadNDOPReply,
572         NWC_ReadREADState,
573         NWC_ReadREADBlob,
574         NWC_ReadCLOSReply,
575         NWC_ReadNUOPReply,
576         NWC_ReadWRITReply,
577         NWC_SendBlobDone,
578         NWC_ReadUCLS,
579         NWC_ReadQUIT};
580
581 long NWC_ConnTimeout = 100;
582
583 const long NWC_SendTimeouts[] = {
584         100,
585         100,
586         100,
587         100,
588         100,
589         100,
590         100,
591         100
592 };
593 const ConstStr NWC[] = {
594         {HKEY("Connection broken during ")},
595         {HKEY("Connection broken during ")},
596         {HKEY("Connection broken during ")},
597         {HKEY("Connection broken during ")},
598         {HKEY("Connection broken during ")},
599         {HKEY("Connection broken during ")},
600         {HKEY("Connection broken during ")},
601         {HKEY("Connection broken during ")}
602 };
603
604 NWClientHandler NWC_SendHandlers[] = {
605         NULL,
606         NWC_SendAuth,
607         NWC_SendNDOP,
608         NWC_SendREAD,
609         NWC_ReadREADBlobDone,
610         NWC_SendCLOS,
611         NWC_SendNUOP,
612         NWC_SendWRIT,
613         NWC_SendBlobDone,
614         NWC_SendUCLS,
615         NWC_SendQUIT
616 };
617
618 const long NWC_ReadTimeouts[] = {
619         100,
620         100,
621         100,
622         100,
623         100,
624         100,
625         100,
626         100,
627         100,
628         100
629 };
630
631
632
633
634 eNextState nwc_get_one_host_ip_done(AsyncIO *IO)
635 {
636         AsyncNetworker *NW = IO->Data;
637         struct hostent *hostent;
638
639         QueryCbDone(IO);
640
641         hostent = NW->HostLookup.VParsedDNSReply;
642         if ((NW->HostLookup.DNSStatus == ARES_SUCCESS) && 
643             (hostent != NULL) ) {
644                 memset(&NW->IO.ConnectMe->Addr, 0, sizeof(struct in6_addr));
645                 if (NW->IO.ConnectMe->IPv6) {
646                         memcpy(&NW->IO.ConnectMe->Addr.sin6_addr.s6_addr, 
647                                &hostent->h_addr_list[0],
648                                sizeof(struct in6_addr));
649                         
650                         NW->IO.ConnectMe->Addr.sin6_family = hostent->h_addrtype;
651                         NW->IO.ConnectMe->Addr.sin6_port   = htons(atol(ChrPtr(NW->port)));//// TODO use the one from the URL.
652                 }
653                 else {
654                         struct sockaddr_in *addr = (struct sockaddr_in*) &NW->IO.ConnectMe->Addr;
655                         /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
656 //                      addr->sin_addr.s_addr = htonl((uint32_t)&hostent->h_addr_list[0]);
657                         memcpy(&addr->sin_addr.s_addr, 
658                                hostent->h_addr_list[0], 
659                                sizeof(uint32_t));
660                         
661                         addr->sin_family = hostent->h_addrtype;
662                         addr->sin_port   = htons(504);/// default citadel port
663                         
664                 }
665                 return nwc_connect_ip(IO);
666         }
667         else
668                 return eAbort;
669 }
670
671
672 eNextState nwc_get_one_host_ip(AsyncIO *IO)
673 {
674         AsyncNetworker *NW = IO->Data;
675         /* 
676          * here we start with the lookup of one host.
677          */ 
678
679         EVN_syslog(LOG_DEBUG, "NWC: %s\n", __FUNCTION__);
680
681         EVN_syslog(LOG_DEBUG, 
682                    "NWC client[%ld]: looking up %s-Record %s : %d ...\n", 
683                    NW->n, 
684                    (NW->IO.ConnectMe->IPv6)? "aaaa": "a",
685                    NW->IO.ConnectMe->Host, 
686                    NW->IO.ConnectMe->Port);
687
688         QueueQuery((NW->IO.ConnectMe->IPv6)? ns_t_aaaa : ns_t_a, 
689                    NW->IO.ConnectMe->Host, 
690                    &NW->IO, 
691                    &NW->HostLookup, 
692                    nwc_get_one_host_ip_done);
693         IO->NextState = eReadDNSReply;
694         return IO->NextState;
695 }
696 /**
697  * @brief lineread Handler; understands when to read more POP3 lines, and when this is a one-lined reply.
698  */
699 eReadState NWC_ReadServerStatus(AsyncIO *IO)
700 {
701 //      AsyncNetworker *NW = IO->Data;
702         eReadState Finished = eBufferNotEmpty; 
703
704         switch (IO->NextState) {
705         case eSendDNSQuery:
706         case eReadDNSReply:
707         case eDBQuery:
708         case eConnect:
709         case eTerminateConnection:
710         case eAbort:
711                 Finished = eReadFail;
712                 break;
713         case eSendReply: 
714         case eSendMore:
715         case eReadMore:
716         case eReadMessage: 
717                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
718                 break;
719         case eReadFile:
720         case eSendFile:
721         case eReadPayload:
722                 break;
723         }
724         return Finished;
725 }
726
727
728
729 eNextState NWC_FailNetworkConnection(AsyncIO *IO)
730 {
731         return eAbort;
732 }
733
734 void NWC_SetTimeout(eNextState NextTCPState, AsyncNetworker *NW)
735 {
736         AsyncIO *IO = &NW->IO;
737         double Timeout = 0.0;
738
739         EVN_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
740
741         switch (NextTCPState) {
742         case eSendReply:
743         case eSendMore:
744                 break;
745         case eReadFile:
746         case eReadMessage:
747                 Timeout = NWC_ReadTimeouts[NW->State];
748                 break;
749         case eReadPayload:
750                 Timeout = 100000;
751                 /* TODO!!! */
752                 break;
753         case eSendDNSQuery:
754         case eReadDNSReply:
755         case eConnect:
756         case eSendFile:
757 //TODO
758         case eTerminateConnection:
759         case eDBQuery:
760         case eAbort:
761         case eReadMore://// TODO
762                 return;
763         }
764         SetNextTimeout(&NW->IO, Timeout);
765 }
766
767
768 eNextState NWC_DispatchReadDone(AsyncIO *IO)
769 {
770         EVN_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
771         AsyncNetworker *NW = IO->Data;
772         eNextState rc;
773
774         rc = NWC_ReadHandlers[NW->State](NW);
775         if (rc != eReadMore)
776                 NW->State++;
777         NWC_SetTimeout(rc, NW);
778         return rc;
779 }
780 eNextState NWC_DispatchWriteDone(AsyncIO *IO)
781 {
782         EVN_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
783         AsyncNetworker *NW = IO->Data;
784         eNextState rc;
785
786         rc = NWC_SendHandlers[NW->State](NW);
787         NWC_SetTimeout(rc, NW);
788         return rc;
789 }
790
791 /*****************************************************************************/
792 /*                     Networker CLIENT ERROR CATCHERS                       */
793 /*****************************************************************************/
794 eNextState NWC_Terminate(AsyncIO *IO)
795 {
796         EVN_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
797         FinalizeNetworker(IO);
798         return eAbort;
799 }
800
801 eNextState NWC_Timeout(AsyncIO *IO)
802 {
803         AsyncNetworker *NW = IO->Data;
804         EVN_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
805
806         if (NW->IO.ErrMsg == NULL)
807                 NW->IO.ErrMsg = NewStrBuf();
808         StrBufPrintf(NW->IO.ErrMsg, "Timeout while talking to %s \r\n", ChrPtr(NW->host));
809         return NWC_FailNetworkConnection(IO);
810 }
811 eNextState NWC_ConnFail(AsyncIO *IO)
812 {
813         AsyncNetworker *NW = IO->Data;
814
815         EVN_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
816         if (NW->IO.ErrMsg == NULL)
817                 NW->IO.ErrMsg = NewStrBuf();
818         StrBufPrintf(NW->IO.ErrMsg, "failed to connect %s \r\n", ChrPtr(NW->host));
819
820         return NWC_FailNetworkConnection(IO);
821 }
822 eNextState NWC_DNSFail(AsyncIO *IO)
823 {
824         AsyncNetworker *NW = IO->Data;
825
826         EVN_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
827         if (NW->IO.ErrMsg == NULL)
828                 NW->IO.ErrMsg = NewStrBuf();
829         StrBufPrintf(NW->IO.ErrMsg, "failed to look up %s \r\n", ChrPtr(NW->host));
830
831         return NWC_FailNetworkConnection(IO);
832 }
833 eNextState NWC_Shutdown(AsyncIO *IO)
834 {
835         EVN_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
836
837         FinalizeNetworker(IO);
838         return eAbort;
839 }
840
841
842 eNextState nwc_connect_ip(AsyncIO *IO)
843 {
844         AsyncNetworker *NW = IO->Data;
845
846         EVN_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
847         EVN_syslog(LOG_NOTICE, "Connecting to <%s> at %s:%s\n", 
848                    ChrPtr(NW->node), 
849                    ChrPtr(NW->host),
850                    ChrPtr(NW->port));
851         
852         return EvConnectSock(IO,
853                              NWC_ConnTimeout,
854                              NWC_ReadTimeouts[0],
855                              1);
856 }
857
858 static int NetworkerCount = 0;
859 void RunNetworker(AsyncNetworker *NW)
860 {
861         NW->n = NetworkerCount++;
862         network_talking_to(SKEY(NW->node), NTT_ADD);
863         syslog(LOG_DEBUG, "NW[%s][%ld]: polling\n", ChrPtr(NW->node), NW->n);
864         ParseURL(&NW->IO.ConnectMe, NW->Url, 504);
865
866         InitIOStruct(&NW->IO,
867                      NW,
868                      eReadMessage,
869                      NWC_ReadServerStatus,
870                      NWC_DNSFail,
871                      NWC_DispatchWriteDone,
872                      NWC_DispatchReadDone,
873                      NWC_Terminate,
874                      NWC_ConnFail,
875                      NWC_Timeout,
876                      NWC_Shutdown);
877
878         safestrncpy(((CitContext *)NW->IO.CitContext)->cs_host, 
879                     ChrPtr(NW->host),
880                     sizeof(((CitContext *)NW->IO.CitContext)->cs_host)); 
881
882         if (NW->IO.ConnectMe->IsIP) {
883                 QueueEventContext(&NW->IO,
884                                   nwc_connect_ip);
885         }
886         else { /* uneducated admin has chosen to add DNS to the equation... */
887                 QueueEventContext(&NW->IO,
888                                   nwc_get_one_host_ip);
889         }
890 }
891
892 /*
893  * Poll other Citadel nodes and transfer inbound/outbound network data.
894  * Set "full" to nonzero to force a poll of every node, or to zero to poll
895  * only nodes to which we have data to send.
896  */
897 void network_poll_other_citadel_nodes(int full_poll, char *working_ignetcfg)
898 {
899         AsyncNetworker *NW;
900         StrBuf *CfgData;
901         StrBuf *Line;
902         const char *lptr;
903         const char *CfgPtr;
904         int Done;
905         
906         int poll = 0;
907         
908         if ((working_ignetcfg == NULL) || (*working_ignetcfg == '\0')) {
909                 syslog(LOG_DEBUG, "network: no neighbor nodes are configured - not polling.\n");
910                 return;
911         }
912         become_session(&networker_client_CC);
913
914         CfgData = NewStrBufPlain(working_ignetcfg, -1);
915         Line = NewStrBufPlain(NULL, StrLength(CfgData));
916         Done = 0;
917         CfgPtr = NULL;
918         while (!Done)
919         {
920                 /* Use the string tokenizer to grab one line at a time */
921                 StrBufSipLine(Line, CfgData, &CfgPtr);
922                 Done = CfgPtr == StrBufNOTNULL;
923                 if (StrLength(Line) > 0)
924                 {
925                         if(server_shutting_down)
926                                 return;/* TODO free stuff*/
927                         lptr = NULL;
928                         poll = 0;
929                         NW = (AsyncNetworker*)malloc(sizeof(AsyncNetworker));
930                         memset(NW, 0, sizeof(AsyncNetworker));
931                         
932                         NW->node = NewStrBufPlain(NULL, StrLength(Line));
933                         NW->host = NewStrBufPlain(NULL, StrLength(Line));
934                         NW->port = NewStrBufPlain(NULL, StrLength(Line));
935                         NW->secret = NewStrBufPlain(NULL, StrLength(Line));
936                         
937                         StrBufExtract_NextToken(NW->node, Line, &lptr, '|');
938                         StrBufExtract_NextToken(NW->secret, Line, &lptr, '|');
939                         StrBufExtract_NextToken(NW->host, Line, &lptr, '|');
940                         StrBufExtract_NextToken(NW->port, Line, &lptr, '|');
941                         if ( (StrLength(NW->node) != 0) && 
942                              (StrLength(NW->secret) != 0) &&
943                              (StrLength(NW->host) != 0) &&
944                              (StrLength(NW->port) != 0))
945                         {
946                                 poll = full_poll;
947                                 if (poll == 0)
948                                 {
949                                         NW->SpoolFileName = NewStrBufPlain(ctdl_netout_dir, -1);
950                                         StrBufAppendBufPlain(NW->SpoolFileName, HKEY("/"), 0);
951                                         StrBufAppendBuf(NW->SpoolFileName, NW->node, 0);
952                                         if (access(ChrPtr(NW->SpoolFileName), R_OK) == 0) {
953                                                 poll = 1;
954                                         }
955                                 }
956                         }
957                         if (poll && 
958                             (StrLength(NW->host) > 0) && 
959                             strcmp("0.0.0.0", ChrPtr(NW->host)))
960                         {
961                                 NW->Url = NewStrBufPlain(NULL, StrLength(Line));
962                                 StrBufPrintf(NW->Url, "citadel://:%s@%s:%s", 
963                                              ChrPtr(NW->secret),
964                                              ChrPtr(NW->host),
965                                              ChrPtr(NW->port));
966                                 if (!network_talking_to(SKEY(NW->node), NTT_CHECK))
967                                 {
968                                         RunNetworker(NW);
969                                         continue;
970                                 }
971                         }
972                         DeleteNetworker(NW);
973                 }
974         }
975         FreeStrBuf(&CfgData);
976         FreeStrBuf(&Line);
977
978 }
979
980
981 void network_do_clientqueue(void)
982 {
983         char *working_ignetcfg;
984         int full_processing = 1;
985         static time_t last_run = 0L;
986
987         /*
988          * Run the full set of processing tasks no more frequently
989          * than once every n seconds
990          */
991         if ( (time(NULL) - last_run) < config.c_net_freq ) {
992                 full_processing = 0;
993                 syslog(LOG_DEBUG, "Network full processing in %ld seconds.\n",
994                         config.c_net_freq - (time(NULL)- last_run)
995                 );
996         }
997
998         working_ignetcfg = load_working_ignetcfg();
999         /*
1000          * Poll other Citadel nodes.  Maybe.  If "full_processing" is set
1001          * then we poll everyone.  Otherwise we only poll nodes we have stuff
1002          * to send to.
1003          */
1004         network_poll_other_citadel_nodes(full_processing, working_ignetcfg);
1005         if (working_ignetcfg)
1006                 free(working_ignetcfg);
1007 }
1008
1009
1010
1011 /*
1012  * Module entry point
1013  */
1014 CTDL_MODULE_INIT(network_client)
1015 {
1016         if (!threading)
1017         {
1018                 CtdlFillSystemContext(&networker_client_CC, "CitNetworker");
1019                 
1020                 CtdlRegisterSessionHook(network_do_clientqueue, EVT_TIMER);
1021         }
1022         return "network_client";
1023 }