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;
227 NW->TmpFile = fopen(ChrPtr(NW->SpoolFileName), "w");
228 if (NW->TmpFile == NULL)
231 "cannot open %s: %s\n",
232 ChrPtr(NW->SpoolFileName),
235 NW->State = eQUIT - 1;
246 eNextState NWC_SendREAD(AsyncNetworker *NW)
248 if (NW->bytes_received < NW->download_len)
251 * If shutting down we can exit here and unlink the temp file.
252 * this shouldn't loose us any messages.
254 if (server_shutting_down)
257 ////// unlink(ChrPtr(NW->tempFileName));
260 StrBufPrintf(NW->IO.SendBuf.Buf, "READ %ld|%ld\n",
262 ((NW->download_len - NW->bytes_received > IGNET_PACKET_SIZE)
263 ? IGNET_PACKET_SIZE :
264 (NW->download_len - NW->bytes_received))
271 else {} // continue sending
275 eNextState NWC_ReadREADState(AsyncNetworker *NW)
278 if (ChrPtr(NW->IO.IOBuf)[0] == '6')
280 NW->BlobReadSize = atol(ChrPtr(NW->IO.IOBuf)+4);
281 NW->bytes_received += NW->BlobReadSize;
282 /// TODO StrBufReadjustIOBuffer(NW->IO.RecvBuf, NW->BlobReadSize);
287 eNextState NWC_ReadREADBlob(AsyncNetworker *NW)
289 /// FlushIOBuffer(NW->IO.RecvBuf); /// TODO
290 fwrite(NW->IO.RecvBuf.ReadWritePointer,
294 if (NW->bytes_received < NW->download_len)
296 NW->State = eREAD - 1;
297 return eSendReply;/* now fetch next chunk*/
303 if (link(ChrPtr(NW->SpoolFileName), ChrPtr(NW->tempFileName)) != 0) {
305 "Could not link %s to %s: %s\n",
306 ChrPtr(NW->tempFileName),
307 ChrPtr(NW->SpoolFileName),
311 ///// unlink(ChrPtr(NW->tempFileName));
312 return eSendReply; //// TODO: step forward.
317 eNextState NWC_SendCLOS(AsyncNetworker *NW)
319 StrBufPlain(NW->IO.SendBuf.Buf, HKEY("CLOS\n"));
320 //// unlink(ChrPtr(NW->tempFileName));
324 eNextState NWC_ReadCLOSReply(AsyncNetworker *NW)
327 if (ChrPtr(NW->IO.IOBuf)[0] != '2')
328 return eTerminateConnection;
333 eNextState NWC_SendNUOP(AsyncNetworker *NW)
337 StrBufPrintf(NW->tempFileName,
341 NW->fd = open(ChrPtr(NW->tempFileName), O_RDONLY);
343 if (errno != ENOENT) {
345 "cannot open %s: %s\n",
346 ChrPtr(NW->tempFileName),
350 return NWC_SendQUIT(NW);
353 if (fstat(NW->fd, &statbuf) == -1) {
354 syslog(9, "FSTAT FAILED %s [%s]--\n",
355 ChrPtr(NW->tempFileName),
357 if (NW->fd > 0) close(NW->fd);
361 NW->download_len = statbuf.st_size;
362 if (NW->download_len == 0) {
364 "Nothing to send.\n");
366 return NWC_SendQUIT(NW);
369 NW->bytes_written = 0;
371 StrBufPlain(NW->IO.SendBuf.Buf, HKEY("NUOP\n"));
375 eNextState NWC_ReadNUOPReply(AsyncNetworker *NW)
378 if (ChrPtr(NW->IO.IOBuf)[0] != '2')
383 eNextState NWC_SendWRIT(AsyncNetworker *NW)
385 StrBufPrintf(NW->IO.SendBuf.Buf, "WRIT %ld\n", NW->bytes_to_write);
389 eNextState NWC_ReadWRITReply(AsyncNetworker *NW)
392 if (ChrPtr(NW->IO.IOBuf)[0] != '7')
397 NW->BlobReadSize = atol(ChrPtr(NW->IO.IOBuf)+4);
401 eNextState NWC_SendBlob(AsyncNetworker *NW)
404 /// bytes_to_write -= thisblock;
405 /// bytes_written += thisblock;
410 eNextState NWC_SendUCLS(AsyncNetworker *NW)
412 StrBufPlain(NW->IO.SendBuf.Buf, HKEY("UCLS 1\n"));
416 eNextState NWC_ReadUCLS(AsyncNetworker *NW)
420 syslog(LOG_NOTICE, "Sent %ld octets to <%s>\n", NW->bytes_written, ChrPtr(NW->node));
421 /// syslog(LOG_DEBUG, "<%s\n", buf);
422 if (ChrPtr(NW->IO.IOBuf)[0] == '2') {
423 syslog(LOG_DEBUG, "Removing <%s>\n", ChrPtr(NW->tempFileName));
424 /// unlink(ChrPtr(NW->tempFileName));
429 eNextState NWC_SendQUIT(AsyncNetworker *NW)
431 StrBufPlain(NW->IO.SendBuf.Buf, HKEY("QUIT\n"));
433 network_talking_to(ChrPtr(NW->node), NTT_REMOVE);
437 eNextState NWC_ReadQUIT(AsyncNetworker *NW)
441 return eTerminateConnection;
445 NWClientHandler NWC_ReadHandlers[] = {
459 const long NWC_SendTimeouts[] = {
469 const ConstStr NWC[] = {
470 {HKEY("Connection broken during ")},
471 {HKEY("Connection broken during ")},
472 {HKEY("Connection broken during ")},
473 {HKEY("Connection broken during ")},
474 {HKEY("Connection broken during ")},
475 {HKEY("Connection broken during ")},
476 {HKEY("Connection broken during ")},
477 {HKEY("Connection broken during ")}
480 NWClientHandler NWC_SendHandlers[] = {
494 const long NWC_ReadTimeouts[] = {
510 eNextState nwc_get_one_host_ip_done(AsyncIO *IO)
512 AsyncNetworker *NW = IO->Data;
513 struct hostent *hostent;
517 hostent = NW->HostLookup.VParsedDNSReply;
518 if ((NW->HostLookup.DNSStatus == ARES_SUCCESS) &&
519 (hostent != NULL) ) {
520 memset(&NW->IO.ConnectMe->Addr, 0, sizeof(struct in6_addr));
521 if (NW->IO.ConnectMe->IPv6) {
522 memcpy(&NW->IO.ConnectMe->Addr.sin6_addr.s6_addr,
523 &hostent->h_addr_list[0],
524 sizeof(struct in6_addr));
526 NW->IO.ConnectMe->Addr.sin6_family = hostent->h_addrtype;
527 NW->IO.ConnectMe->Addr.sin6_port = htons(atol(ChrPtr(NW->port)));//// TODO use the one from the URL.
530 struct sockaddr_in *addr = (struct sockaddr_in*) &NW->IO.ConnectMe->Addr;
531 /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
532 // addr->sin_addr.s_addr = htonl((uint32_t)&hostent->h_addr_list[0]);
533 memcpy(&addr->sin_addr.s_addr,
534 hostent->h_addr_list[0],
537 addr->sin_family = hostent->h_addrtype;
538 addr->sin_port = htons(504);/// default citadel port
541 return nwc_connect_ip(IO);
548 eNextState nwc_get_one_host_ip(AsyncIO *IO)
550 AsyncNetworker *NW = IO->Data;
552 * here we start with the lookup of one host. it might be...
553 * - the relay host *sigh*
554 * - the direct hostname if there was no mx record
560 syslog(LOG_DEBUG, "NWC: %s\n", __FUNCTION__);
563 "NWC client[%ld]: looking up %s-Record %s : %d ...\n",
565 (NW->IO.ConnectMe->IPv6)? "aaaa": "a",
566 NW->IO.ConnectMe->Host,
567 NW->IO.ConnectMe->Port);
569 QueueQuery((NW->IO.ConnectMe->IPv6)? ns_t_aaaa : ns_t_a,
570 NW->IO.ConnectMe->Host,
573 nwc_get_one_host_ip_done);
574 IO->NextState = eReadDNSReply;
575 return IO->NextState;
578 * @brief lineread Handler; understands when to read more POP3 lines, and when this is a one-lined reply.
580 eReadState NWC_ReadServerStatus(AsyncIO *IO)
582 AsyncNetworker *NW = IO->Data;
583 eReadState Finished = eBufferNotEmpty;
585 switch (IO->NextState) {
590 case eTerminateConnection:
592 Finished = eReadFail;
598 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
601 Finished = IOBufferStrLength(&IO->RecvBuf) >= NW->BlobReadSize;
609 eNextState NWC_FailNetworkConnection(AsyncIO *IO)
611 return eTerminateConnection;
615 eNextState NWC_DispatchReadDone(AsyncIO *IO)
617 syslog(LOG_DEBUG, "NWC: %s\n", __FUNCTION__);
618 AsyncNetworker *NW = IO->Data;
621 rc = NWC_ReadHandlers[NW->State](NW);
624 ////NWCSetTimeout(rc, NW);
627 eNextState NWC_DispatchWriteDone(AsyncIO *IO)
629 syslog(LOG_DEBUG, "NWC: %s\n", __FUNCTION__);
630 AsyncNetworker *NW = IO->Data;
633 rc = NWC_SendHandlers[NW->State](NW);
634 ////NWCSetTimeout(rc, NW);
638 /*****************************************************************************/
639 /* Networker CLIENT ERROR CATCHERS */
640 /*****************************************************************************/
641 eNextState NWC_Terminate(AsyncIO *IO)
643 syslog(LOG_DEBUG, "Nw: %s\n", __FUNCTION__);
644 /// FinalizeNetworker(IO); TODO
648 eNextState NWC_Timeout(AsyncIO *IO)
650 // AsyncNetworker *NW = IO->Data;
652 syslog(LOG_DEBUG, "NW: %s\n", __FUNCTION__);
653 // StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State])); todo
654 return NWC_FailNetworkConnection(IO);
656 eNextState NWC_ConnFail(AsyncIO *IO)
658 /// AsyncNetworker *NW = IO->Data;
660 syslog(LOG_DEBUG, "NW: %s\n", __FUNCTION__);
661 //// StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State])); todo
662 return NWC_FailNetworkConnection(IO);
664 eNextState NWC_DNSFail(AsyncIO *IO)
666 /// AsyncNetworker *NW = IO->Data;
668 syslog(LOG_DEBUG, "NW: %s\n", __FUNCTION__);
669 //// StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State])); todo
670 return NWC_FailNetworkConnection(IO);
672 eNextState NWC_Shutdown(AsyncIO *IO)
674 syslog(LOG_DEBUG, "NW: %s\n", __FUNCTION__);
675 //// pop3aggr *pMsg = IO->Data;
677 ////pMsg->MyQEntry->Status = 3;
678 ///StrBufPlain(pMsg->MyQEntry->StatusMessage, HKEY("server shutdown during message retrieval."));
679 /// FinalizePOP3AggrRun(IO); todo
684 eNextState nwc_connect_ip(AsyncIO *IO)
686 AsyncNetworker *NW = IO->Data;
688 syslog(LOG_DEBUG, "NW: %s\n", __FUNCTION__);
689 syslog(LOG_DEBUG, "network: polling <%s>\n", ChrPtr(NW->node));
690 syslog(LOG_NOTICE, "Connecting to <%s> at %s:%s\n",
695 //// IO->ConnectMe = &NW->Pop3Host;
696 /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
698 /////// SetConnectStatus(IO);
700 return InitEventIO(IO, NW, 100, 100, 1); /*
706 void RunNetworker(AsyncNetworker *NW)
710 ParseURL(&NW->IO.ConnectMe, NW->Url, 504);
713 NW->IO.SendDone = NWC_DispatchWriteDone;
714 NW->IO.ReadDone = NWC_DispatchReadDone;
715 NW->IO.Terminate = NWC_Terminate;
716 NW->IO.LineReader = NWC_ReadServerStatus;
717 NW->IO.ConnFail = NWC_ConnFail;
718 NW->IO.DNSFail = NWC_DNSFail;
719 NW->IO.Timeout = NWC_Timeout;
720 NW->IO.ShutdownAbort = NWC_Shutdown;
722 NW->IO.SendBuf.Buf = NewStrBufPlain(NULL, 1024);
723 NW->IO.RecvBuf.Buf = NewStrBufPlain(NULL, 1024);
724 NW->IO.IOBuf = NewStrBuf();
726 NW->IO.NextState = eReadMessage;
727 SubC = CloneContext (&networker_client_CC);
728 SubC->session_specific_data = (char*) NW;
729 NW->IO.CitContext = SubC;
731 if (NW->IO.ConnectMe->IsIP) {
732 QueueEventContext(&NW->IO,
735 else { /* uneducated admin has chosen to add DNS to the equation... */
736 QueueEventContext(&NW->IO,
737 nwc_get_one_host_ip);
742 * Poll other Citadel nodes and transfer inbound/outbound network data.
743 * Set "full" to nonzero to force a poll of every node, or to zero to poll
744 * only nodes to which we have data to send.
746 void network_poll_other_citadel_nodes(int full_poll, char *working_ignetcfg)
757 if ((working_ignetcfg == NULL) || (*working_ignetcfg == '\0')) {
758 syslog(LOG_DEBUG, "network: no neighbor nodes are configured - not polling.\n");
761 CfgData = NewStrBufPlain(working_ignetcfg, -1);
762 Line = NewStrBufPlain(NULL, StrLength(CfgData));
767 /* Use the string tokenizer to grab one line at a time */
768 StrBufSipLine(Line, CfgData, &CfgPtr);
769 Done = CfgPtr == StrBufNOTNULL;
770 if (StrLength(Line) > 0)
772 if(server_shutting_down)
773 return;/* TODO free stuff*/
776 NW = (AsyncNetworker*)malloc(sizeof(AsyncNetworker));
777 memset(NW, 0, sizeof(AsyncNetworker));
779 NW->node = NewStrBufPlain(NULL, StrLength(Line));
780 NW->host = NewStrBufPlain(NULL, StrLength(Line));
781 NW->port = NewStrBufPlain(NULL, StrLength(Line));
782 NW->secret = NewStrBufPlain(NULL, StrLength(Line));
784 StrBufExtract_NextToken(NW->node, Line, &lptr, '|');
785 StrBufExtract_NextToken(NW->secret, Line, &lptr, '|');
786 StrBufExtract_NextToken(NW->host, Line, &lptr, '|');
787 StrBufExtract_NextToken(NW->port, Line, &lptr, '|');
788 if ( (StrLength(NW->node) != 0) &&
789 (StrLength(NW->secret) != 0) &&
790 (StrLength(NW->host) != 0) &&
791 (StrLength(NW->port) != 0))
796 NW->SpoolFileName = NewStrBufPlain(ctdl_netout_dir, -1);
797 StrBufAppendBufPlain(NW->SpoolFileName, HKEY("/"), 0);
798 StrBufAppendBuf(NW->SpoolFileName, NW->node, 0);
799 if (access(ChrPtr(NW->SpoolFileName), R_OK) == 0) {
805 NW->Url = NewStrBufPlain(NULL, StrLength(Line));
806 StrBufPrintf(NW->Url, "citadel://:%s@%s:%s",
810 if (!network_talking_to(ChrPtr(NW->node), NTT_CHECK))
812 network_talking_to(ChrPtr(NW->node), NTT_ADD);
817 DestroyNetworker(NW);
824 void network_do_clientqueue(void)
826 char *working_ignetcfg;
827 int full_processing = 1;
828 static time_t last_run = 0L;
831 * Run the full set of processing tasks no more frequently
832 * than once every n seconds
834 if ( (time(NULL) - last_run) < config.c_net_freq ) {
836 syslog(LOG_DEBUG, "Network full processing in %ld seconds.\n",
837 config.c_net_freq - (time(NULL)- last_run)
841 working_ignetcfg = load_working_ignetcfg();
843 * Poll other Citadel nodes. Maybe. If "full_processing" is set
844 * then we poll everyone. Otherwise we only poll nodes we have stuff
847 network_poll_other_citadel_nodes(full_processing, working_ignetcfg);
848 if (working_ignetcfg)
849 free(working_ignetcfg);
857 CTDL_MODULE_INIT(network_client)
861 CtdlFillSystemContext(&networker_client_CC, "CitNetworker");
863 CtdlRegisterSessionHook(network_do_clientqueue, EVT_TIMER);
865 return "network_client";