2 * This module handles shared rooms, inter-Citadel mail, and outbound
3 * mailing list processing.
5 * Copyright (c) 2000-2011 by the citadel.org team
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.
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.
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
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.
41 #include <sys/types.h>
43 #if TIME_WITH_SYS_TIME
44 # include <sys/time.h>
48 # include <sys/time.h>
56 # if HAVE_SYS_SYSCALL_H
57 # include <sys/syscall.h>
64 #include <libcitadel.h>
67 #include "citserver.h"
73 #include "internet_addressing.h"
74 #include "serv_network.h"
75 #include "clientsocket.h"
77 #include "citadel_dirs.h"
86 #include "netconfig.h"
87 #include "ctdl_module.h"
89 struct CitContext networker_client_CC;
91 typedef enum _eNWCState {
106 typedef struct _async_networker {
108 DNSQueryParts HostLookup;
114 StrBuf *SpoolFileName;
115 StrBuf *tempFileName;
128 typedef eNextState(*NWClientHandler)(AsyncNetworker* NW);
129 eNextState nwc_get_one_host_ip(AsyncIO *IO);
131 eNextState nwc_connect_ip(AsyncIO *IO);
133 eNextState NWC_SendQUIT(AsyncNetworker *NW);
137 void DestroyNetworker(AsyncNetworker *NW)
141 #define NWC_DBG_SEND() syslog(LOG_DEBUG, "NW client[%ld]: > %s", NW->n, ChrPtr(NW->IO.SendBuf.Buf))
142 #define NWC_DBG_READ() syslog(LOG_DEBUG, "NW client[%ld]: < %s\n", NW->n, ChrPtr(NW->IO.IOBuf))
143 #define NWC_OK (strncasecmp(ChrPtr(NW->IO.IOBuf), "+OK", 3) == 0)
145 eNextState NWC_ReadGreeting(AsyncNetworker *NW)
147 char connected_to[SIZ];
149 /* Read the server greeting */
150 /* Check that the remote is who we think it is and warn the Aide if not */
151 extract_token (connected_to, ChrPtr(NW->IO.IOBuf), 1, ' ', sizeof connected_to);
152 if (strcmp(connected_to, ChrPtr(NW->node)) != 0)
154 StrBufPrintf(NW->IO.ErrMsg,
155 "Connected to node \"%s\" but I was expecting to connect to node \"%s\".",
156 connected_to, ChrPtr(NW->node));
157 syslog(LOG_ERR, "%s\n", ChrPtr(NW->IO.ErrMsg));
158 CtdlAideMessage(ChrPtr(NW->IO.ErrMsg), "Network error");
159 return eAbort;/// todo: aide message in anderer queue speichern
164 eNextState NWC_SendAuth(AsyncNetworker *NW)
166 /* We're talking to the correct node. Now identify ourselves. */
167 StrBufPrintf(NW->IO.SendBuf.Buf, "NETP %s|%s\n",
174 eNextState NWC_ReadAuthReply(AsyncNetworker *NW)
177 if (ChrPtr(NW->IO.IOBuf)[0] == '2')
183 StrBufPrintf(NW->IO.ErrMsg,
184 "Connected to node \"%s\" but my secret wasn't accurate.",
186 syslog(LOG_ERR, "%s\n", ChrPtr(NW->IO.ErrMsg));
187 CtdlAideMessage(ChrPtr(NW->IO.ErrMsg), "Network error");
193 eNextState NWC_SendNDOP(AsyncNetworker *NW)
195 NW->tempFileName = NewStrBuf();
196 NW->SpoolFileName = NewStrBuf();
197 StrBufPrintf(NW->tempFileName,
201 time(NULL),// TODO: get time from libev
203 StrBufPrintf(NW->SpoolFileName,
207 time(NULL),// TODO: get time from libev
210 /* We're talking to the correct node. Now identify ourselves. */
211 StrBufPlain(NW->IO.SendBuf.Buf, HKEY("NDOP\n"));
216 eNextState NWC_ReadNDOPReply(AsyncNetworker *NW)
219 if (ChrPtr(NW->IO.IOBuf)[0] == '2')
221 NW->download_len = atol (ChrPtr(NW->IO.IOBuf) + 4);
222 syslog(LOG_DEBUG, "Expecting to transfer %ld bytes\n", NW->download_len);
223 if (NW->download_len <= 0)
224 NW->State = eNUOP - 1;
233 eNextState NWC_SendREAD(AsyncNetworker *NW)
235 if (NW->bytes_received < NW->download_len)
238 * If shutting down we can exit here and unlink the temp file.
239 * this shouldn't loose us any messages.
241 if (server_shutting_down)
244 unlink(ChrPtr(NW->tempFileName));
247 StrBufPrintf(NW->IO.SendBuf.Buf, "READ %ld|%ld\n",
249 ((NW->download_len - NW->bytes_received > IGNET_PACKET_SIZE)
250 ? IGNET_PACKET_SIZE :
251 (NW->download_len - NW->bytes_received))
258 else {} // continue sending
262 eNextState NWC_ReadREADState(AsyncNetworker *NW)
265 if (ChrPtr(NW->IO.IOBuf)[0] == '6')
267 NW->BlobReadSize = atol(ChrPtr(NW->IO.IOBuf)+4);
268 /// TODO StrBufReadjustIOBuffer(NW->IO.RecvBuf, NW->BlobReadSize);
273 eNextState NWC_ReadREADBlob(AsyncNetworker *NW)
275 fwrite(ChrPtr(NW->IO.RecvBuf.Buf), NW->BlobReadSize, 1, NW->TmpFile);
276 NW->bytes_received += NW->BlobReadSize;
277 /// FlushIOBuffer(NW->IO.RecvBuf); /// TODO
278 if (NW->bytes_received < NW->download_len)
280 return eSendReply;/* now fetch next chunk*/
286 if (link(ChrPtr(NW->tempFileName), ChrPtr(NW->SpoolFileName)) != 0) {
288 "Could not link %s to %s: %s\n",
289 ChrPtr(NW->tempFileName),
290 ChrPtr(NW->SpoolFileName),
294 unlink(ChrPtr(NW->tempFileName));
295 return eSendReply; //// TODO: step forward.
300 eNextState NWC_SendCLOS(AsyncNetworker *NW)
302 StrBufPlain(NW->IO.SendBuf.Buf, HKEY("CLOS\n"));
303 unlink(ChrPtr(NW->tempFileName));
307 eNextState NWC_ReadCLOSReply(AsyncNetworker *NW)
310 return eTerminateConnection;
314 eNextState NWC_SendNUOP(AsyncNetworker *NW)
318 StrBufPrintf(NW->tempFileName,
322 NW->fd = open(ChrPtr(NW->tempFileName), O_RDONLY);
324 if (errno != ENOENT) {
326 "cannot open %s: %s\n",
327 ChrPtr(NW->tempFileName),
331 return NWC_SendQUIT(NW);
334 if (fstat(NW->fd, &statbuf) == -1) {
335 syslog(9, "FSTAT FAILED %s [%s]--\n",
336 ChrPtr(NW->tempFileName),
338 if (NW->fd > 0) close(NW->fd);
342 NW->download_len = statbuf.st_size;
343 if (NW->download_len == 0) {
345 "Nothing to send.\n");
347 return NWC_SendQUIT(NW);
350 NW->bytes_written = 0;
352 StrBufPlain(NW->IO.SendBuf.Buf, HKEY("NUOP\n"));
356 eNextState NWC_ReadNUOPReply(AsyncNetworker *NW)
359 /// if (ChrPtr(NW->IO.IOBuf)[0] == '2');;;; //// todo
363 eNextState NWC_SendWRIT(AsyncNetworker *NW)
365 StrBufPrintf(NW->IO.SendBuf.Buf, "WRIT %ld\n", NW->bytes_to_write);
369 eNextState NWC_ReadWRITReply(AsyncNetworker *NW)
372 if (ChrPtr(NW->IO.IOBuf)[0] != '7')
377 NW->BlobReadSize = atol(ChrPtr(NW->IO.IOBuf)+4);
381 eNextState NWC_SendBlob(AsyncNetworker *NW)
384 /// bytes_to_write -= thisblock;
385 /// bytes_written += thisblock;
390 eNextState NWC_SendUCLS(AsyncNetworker *NW)
392 StrBufPlain(NW->IO.SendBuf.Buf, HKEY("UCLS 1\n"));
396 eNextState NWC_ReadUCLS(AsyncNetworker *NW)
400 syslog(LOG_NOTICE, "Sent %ld octets to <%s>\n", NW->bytes_written, ChrPtr(NW->node));
401 /// syslog(LOG_DEBUG, "<%s\n", buf);
402 if (ChrPtr(NW->IO.IOBuf)[0] == '2') {
403 syslog(LOG_DEBUG, "Removing <%s>\n", ChrPtr(NW->tempFileName));
404 unlink(ChrPtr(NW->tempFileName));
409 eNextState NWC_SendQUIT(AsyncNetworker *NW)
411 StrBufPlain(NW->IO.SendBuf.Buf, HKEY("QUIT\n"));
413 network_talking_to(ChrPtr(NW->node), NTT_REMOVE);
417 eNextState NWC_ReadQUIT(AsyncNetworker *NW)
421 return eTerminateConnection;
425 NWClientHandler NWC_ReadHandlers[] = {
439 const long NWC_SendTimeouts[] = {
449 const ConstStr NWC[] = {
450 {HKEY("Connection broken during ")},
451 {HKEY("Connection broken during ")},
452 {HKEY("Connection broken during ")},
453 {HKEY("Connection broken during ")},
454 {HKEY("Connection broken during ")},
455 {HKEY("Connection broken during ")},
456 {HKEY("Connection broken during ")},
457 {HKEY("Connection broken during ")}
460 NWClientHandler NWC_SendHandlers[] = {
474 const long NWC_ReadTimeouts[] = {
490 eNextState nwc_get_one_host_ip_done(AsyncIO *IO)
492 AsyncNetworker *NW = IO->Data;
493 struct hostent *hostent;
497 hostent = NW->HostLookup.VParsedDNSReply;
498 if ((NW->HostLookup.DNSStatus == ARES_SUCCESS) &&
499 (hostent != NULL) ) {
500 memset(&NW->IO.ConnectMe->Addr, 0, sizeof(struct in6_addr));
501 if (NW->IO.ConnectMe->IPv6) {
502 memcpy(&NW->IO.ConnectMe->Addr.sin6_addr.s6_addr,
503 &hostent->h_addr_list[0],
504 sizeof(struct in6_addr));
506 NW->IO.ConnectMe->Addr.sin6_family = hostent->h_addrtype;
507 NW->IO.ConnectMe->Addr.sin6_port = htons(atol(ChrPtr(NW->port)));//// TODO use the one from the URL.
510 struct sockaddr_in *addr = (struct sockaddr_in*) &NW->IO.ConnectMe->Addr;
511 /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
512 // addr->sin_addr.s_addr = htonl((uint32_t)&hostent->h_addr_list[0]);
513 memcpy(&addr->sin_addr.s_addr,
514 hostent->h_addr_list[0],
517 addr->sin_family = hostent->h_addrtype;
518 addr->sin_port = htons(504);/// default citadel port
521 return nwc_connect_ip(IO);
528 eNextState nwc_get_one_host_ip(AsyncIO *IO)
530 AsyncNetworker *NW = IO->Data;
532 * here we start with the lookup of one host. it might be...
533 * - the relay host *sigh*
534 * - the direct hostname if there was no mx record
540 syslog(LOG_DEBUG, "NWC: %s\n", __FUNCTION__);
543 "NWC client[%ld]: looking up %s-Record %s : %d ...\n",
545 (NW->IO.ConnectMe->IPv6)? "aaaa": "a",
546 NW->IO.ConnectMe->Host,
547 NW->IO.ConnectMe->Port);
549 QueueQuery((NW->IO.ConnectMe->IPv6)? ns_t_aaaa : ns_t_a,
550 NW->IO.ConnectMe->Host,
553 nwc_get_one_host_ip_done);
554 IO->NextState = eReadDNSReply;
555 return IO->NextState;
558 * @brief lineread Handler; understands when to read more POP3 lines, and when this is a one-lined reply.
560 eReadState NWC_ReadServerStatus(AsyncIO *IO)
562 eReadState Finished = eBufferNotEmpty;
564 switch (IO->NextState) {
569 case eTerminateConnection:
571 Finished = eReadFail;
577 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
587 eNextState NWC_FailNetworkConnection(AsyncIO *IO)
589 return eTerminateConnection;
593 eNextState NWC_DispatchReadDone(AsyncIO *IO)
595 syslog(LOG_DEBUG, "NWC: %s\n", __FUNCTION__);
596 AsyncNetworker *NW = IO->Data;
599 rc = NWC_ReadHandlers[NW->State](NW);
602 ////NWCSetTimeout(rc, NW);
605 eNextState NWC_DispatchWriteDone(AsyncIO *IO)
607 syslog(LOG_DEBUG, "NWC: %s\n", __FUNCTION__);
608 AsyncNetworker *NW = IO->Data;
611 rc = NWC_SendHandlers[NW->State](NW);
612 ////NWCSetTimeout(rc, NW);
616 /*****************************************************************************/
617 /* Networker CLIENT ERROR CATCHERS */
618 /*****************************************************************************/
619 eNextState NWC_Terminate(AsyncIO *IO)
621 syslog(LOG_DEBUG, "Nw: %s\n", __FUNCTION__);
622 /// FinalizeNetworker(IO); TODO
626 eNextState NWC_Timeout(AsyncIO *IO)
628 // AsyncNetworker *NW = IO->Data;
630 syslog(LOG_DEBUG, "NW: %s\n", __FUNCTION__);
631 // StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State])); todo
632 return NWC_FailNetworkConnection(IO);
634 eNextState NWC_ConnFail(AsyncIO *IO)
636 /// AsyncNetworker *NW = IO->Data;
638 syslog(LOG_DEBUG, "NW: %s\n", __FUNCTION__);
639 //// StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State])); todo
640 return NWC_FailNetworkConnection(IO);
642 eNextState NWC_Shutdown(AsyncIO *IO)
644 syslog(LOG_DEBUG, "NW: %s\n", __FUNCTION__);
645 //// pop3aggr *pMsg = IO->Data;
647 ////pMsg->MyQEntry->Status = 3;
648 ///StrBufPlain(pMsg->MyQEntry->StatusMessage, HKEY("server shutdown during message retrieval."));
649 /// FinalizePOP3AggrRun(IO); todo
654 eNextState nwc_connect_ip(AsyncIO *IO)
656 AsyncNetworker *NW = IO->Data;
658 syslog(LOG_DEBUG, "NW: %s\n", __FUNCTION__);
659 syslog(LOG_DEBUG, "network: polling <%s>\n", ChrPtr(NW->node));
660 syslog(LOG_NOTICE, "Connecting to <%s> at %s:%s\n",
665 //// IO->ConnectMe = &NW->Pop3Host;
666 /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
668 /////// SetConnectStatus(IO);
670 return InitEventIO(IO, NW, 100, 100, 1); /*
676 void RunNetworker(AsyncNetworker *NW)
680 ParseURL(&NW->IO.ConnectMe, NW->Url, 504);
683 NW->IO.SendDone = NWC_DispatchWriteDone;
684 NW->IO.ReadDone = NWC_DispatchReadDone;
685 NW->IO.Terminate = NWC_Terminate;
686 NW->IO.LineReader = NWC_ReadServerStatus;
687 NW->IO.ConnFail = NWC_ConnFail;
688 NW->IO.Timeout = NWC_Timeout;
689 NW->IO.ShutdownAbort = NWC_Shutdown;
691 NW->IO.SendBuf.Buf = NewStrBufPlain(NULL, 1024);
692 NW->IO.RecvBuf.Buf = NewStrBufPlain(NULL, 1024);
693 NW->IO.IOBuf = NewStrBuf();
695 NW->IO.NextState = eReadMessage;
696 SubC = CloneContext (&networker_client_CC);
697 SubC->session_specific_data = (char*) NW;
698 NW->IO.CitContext = SubC;
700 if (NW->IO.ConnectMe->IsIP) {
701 QueueEventContext(&NW->IO,
704 else { /* uneducated admin has chosen to add DNS to the equation... */
705 QueueEventContext(&NW->IO,
706 nwc_get_one_host_ip);
711 * Poll other Citadel nodes and transfer inbound/outbound network data.
712 * Set "full" to nonzero to force a poll of every node, or to zero to poll
713 * only nodes to which we have data to send.
715 void network_poll_other_citadel_nodes(int full_poll, char *working_ignetcfg)
726 if ((working_ignetcfg == NULL) || (*working_ignetcfg == '\0')) {
727 syslog(LOG_DEBUG, "network: no neighbor nodes are configured - not polling.\n");
730 CfgData = NewStrBufPlain(working_ignetcfg, -1);
731 Line = NewStrBufPlain(NULL, StrLength(CfgData));
736 /* Use the string tokenizer to grab one line at a time */
737 StrBufSipLine(Line, CfgData, &CfgPtr);
738 Done = CfgPtr == StrBufNOTNULL;
739 if (StrLength(Line) > 0)
741 if(server_shutting_down)
742 return;/* TODO free stuff*/
745 NW = (AsyncNetworker*)malloc(sizeof(AsyncNetworker));
746 memset(NW, 0, sizeof(AsyncNetworker));
748 NW->node = NewStrBufPlain(NULL, StrLength(Line));
749 NW->host = NewStrBufPlain(NULL, StrLength(Line));
750 NW->port = NewStrBufPlain(NULL, StrLength(Line));
751 NW->secret = NewStrBufPlain(NULL, StrLength(Line));
753 StrBufExtract_NextToken(NW->node, Line, &lptr, '|');
754 StrBufExtract_NextToken(NW->secret, Line, &lptr, '|');
755 StrBufExtract_NextToken(NW->host, Line, &lptr, '|');
756 StrBufExtract_NextToken(NW->port, Line, &lptr, '|');
757 if ( (StrLength(NW->node) != 0) &&
758 (StrLength(NW->secret) != 0) &&
759 (StrLength(NW->host) != 0) &&
760 (StrLength(NW->port) != 0))
765 NW->SpoolFileName = NewStrBufPlain(ctdl_netout_dir, -1);
766 StrBufAppendBufPlain(NW->SpoolFileName, HKEY("/"), 0);
767 StrBufAppendBuf(NW->SpoolFileName, NW->node, 0);
768 if (access(ChrPtr(NW->SpoolFileName), R_OK) == 0) {
774 NW->Url = NewStrBufPlain(NULL, StrLength(Line));
775 StrBufPrintf(NW->Url, "citadel://:%s@%s:%s",
779 if (!network_talking_to(ChrPtr(NW->node), NTT_CHECK))
781 network_talking_to(ChrPtr(NW->node), NTT_ADD);
786 DestroyNetworker(NW);
793 void network_do_clientqueue(void)
795 char *working_ignetcfg;
796 int full_processing = 1;
797 static time_t last_run = 0L;
800 * Run the full set of processing tasks no more frequently
801 * than once every n seconds
803 if ( (time(NULL) - last_run) < config.c_net_freq ) {
805 syslog(LOG_DEBUG, "Network full processing in %ld seconds.\n",
806 config.c_net_freq - (time(NULL)- last_run)
810 working_ignetcfg = load_working_ignetcfg();
812 * Poll other Citadel nodes. Maybe. If "full_processing" is set
813 * then we poll everyone. Otherwise we only poll nodes we have stuff
816 network_poll_other_citadel_nodes(full_processing, working_ignetcfg);
817 if (working_ignetcfg)
818 free(working_ignetcfg);
826 CTDL_MODULE_INIT(network_client)
830 CtdlFillSystemContext(&networker_client_CC, "CitNetworker");
832 CtdlRegisterSessionHook(network_do_clientqueue, EVT_TIMER);
834 return "network_client";