getting with the times, we dont need to wrap snprintf anymore
[citadel.git] / citadel / modules / network / serv_network.c
index bf5f1d3b946fb9b33efa73491743b1fa9f673cba..578a8e17e4e90fa35e843820d761ed152e1a56a3 100644 (file)
@@ -2,22 +2,16 @@
  * This module handles shared rooms, inter-Citadel mail, and outbound
  * mailing list processing.
  *
- * Copyright (c) 2000-2011 by the citadel.org team
+ * Copyright (c) 2000-2012 by the citadel.org team
  *
  *  This program is open source software; you can redistribute it and/or modify
- *  it under the terms of the GNU General Public License as published by
- *  the Free Software Foundation; either version 3 of the License, or
- *  (at your option) any later version.
+ *  it under the terms of the GNU General Public License, version 3.
  *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
  *
- *  You should have received a copy of the GNU General Public License
- *  along with this program; if not, write to the Free Software
- *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
  * ** NOTE **   A word on the S_NETCONFIGS semaphore:
  * This is a fairly high-level type of critical section.  It ensures that no
  * two threads work on the netconfigs files at the same time.  Since we do
 #include "file_ops.h"
 #include "citadel_dirs.h"
 #include "threads.h"
-
-#ifndef HAVE_SNPRINTF
-#include "snprintf.h"
-#endif
-
 #include "context.h"
 #include "netconfig.h"
 #include "netspool.h"
 #include "netmail.h"
 #include "ctdl_module.h"
 
+int NetQDebugEnabled = 0;
+struct CitContext networker_spool_CC;
 
+/* comes from lookup3.c from libcitadel... */
+extern uint32_t hashlittle( const void *key, size_t length, uint32_t initval);
 
+typedef struct __roomlists {
+       RoomProcList *rplist;
+       HashList *RoomsInterestedIn;
+}roomlists;
 /*
  * When we do network processing, it's accomplished in two passes; one to
  * gather a list of rooms and one to actually do them.  It's ok that rplist
  */
 struct RoomProcList *rplist = NULL;
 
+int GetNetworkedRoomNumbers(const char *DirName, HashList *DirList)
+{
+       DIR *filedir = NULL;
+       struct dirent *d;
+       struct dirent *filedir_entry;
+       long RoomNR;
+       long Count = 0;
+               
+       filedir = opendir (DirName);
+       if (filedir == NULL) {
+               return 0;
+       }
+
+       d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
+       if (d == NULL) {
+               return 0;
+       }
 
+       while ((readdir_r(filedir, d, &filedir_entry) == 0) &&
+              (filedir_entry != NULL))
+       {
+               RoomNR = atol(filedir_entry->d_name);
+               if (RoomNR != 0) {
+                       Count++;
+                       Put(DirList, LKEY(RoomNR), &Count, reference_free_handler);
+               }
+       }
+       free(d);
+       closedir(filedir);
+       return Count;
+}
 
 
 
@@ -112,8 +139,9 @@ struct RoomProcList *rplist = NULL;
  * message from being entered into the database multiple times if it happens
  * to arrive multiple times by accident.
  */
-int network_usetable(struct CtdlMessage *msg) {
-
+int network_usetable(struct CtdlMessage *msg)
+{
+       struct CitContext *CCC = CC;
        char msgid[SIZ];
        struct cdbdata *cdbut;
        struct UseTable ut;
@@ -144,7 +172,7 @@ int network_usetable(struct CtdlMessage *msg) {
        cdbut = cdb_fetch(CDB_USETABLE, msgid, strlen(msgid));
        if (cdbut != NULL) {
                cdb_free(cdbut);
-               syslog(LOG_DEBUG, "network_usetable() : we already have %s\n", msgid);
+               QN_syslog(LOG_DEBUG, "network_usetable() : we already have %s\n", msgid);
                return(1);
        }
 
@@ -169,7 +197,9 @@ int network_usetable(struct CtdlMessage *msg) {
  * ignoring anything we know about which messages have already undergone
  * network processing.  This can be used to bring a new node into sync.
  */
-int network_sync_to(char *target_node) {
+int network_sync_to(char *target_node, long len)
+{
+       struct CitContext *CCC = CC;
        SpoolControl sc;
        int num_spooled = 0;
        int found_node = 0;
@@ -188,32 +218,43 @@ int network_sync_to(char *target_node) {
                end_critical_section(S_NETCONFIGS);
                return(-1);
        }
-       while (fgets(buf, sizeof buf, fp) != NULL) {
+       while (fgets(buf, sizeof buf, fp) != NULL)
+       {
                buf[strlen(buf)-1] = 0;
+
                extract_token(sc_type, buf, 0, '|', sizeof sc_type);
+               if (strcasecmp(sc_type, "ignet_push_share"))
+                       continue;
+
                extract_token(sc_node, buf, 1, '|', sizeof sc_node);
+               if (strcasecmp(sc_node, target_node))
+                       continue;
+
                extract_token(sc_room, buf, 2, '|', sizeof sc_room);
-               if ( (!strcasecmp(sc_type, "ignet_push_share"))
-                  && (!strcasecmp(sc_node, target_node)) ) {
-                       found_node = 1;
+               found_node = 1;
                        
-                       /* Concise syntax because we don't need a full linked-list */
-                       memset(&sc, 0, sizeof(SpoolControl));
-                       sc.ignet_push_shares = (maplist *)
-                               malloc(sizeof(maplist));
-                       sc.ignet_push_shares->next = NULL;
-                       safestrncpy(sc.ignet_push_shares->remote_nodename,
-                               sc_node,
-                               sizeof sc.ignet_push_shares->remote_nodename);
-                       safestrncpy(sc.ignet_push_shares->remote_roomname,
-                               sc_room,
-                               sizeof sc.ignet_push_shares->remote_roomname);
-               }
+               /* Concise syntax because we don't need a full linked-list */
+               memset(&sc, 0, sizeof(SpoolControl));
+               sc.ignet_push_shares = (maplist *)
+                       malloc(sizeof(maplist));
+               sc.ignet_push_shares->next = NULL;
+               safestrncpy(sc.ignet_push_shares->remote_nodename,
+                           sc_node,
+                           sizeof sc.ignet_push_shares->remote_nodename);
+               safestrncpy(sc.ignet_push_shares->remote_roomname,
+                           sc_room,
+                           sizeof sc.ignet_push_shares->remote_roomname);
        }
        fclose(fp);
        end_critical_section(S_NETCONFIGS);
 
-       if (!found_node) return(-1);
+       if (!found_node) {
+               free(sc.ignet_push_shares);
+               return(-1);
+       }
+
+       sc.working_ignetcfg = load_ignetcfg();
+       sc.the_netmap = read_network_map();
 
        /* Send ALL messages */
        num_spooled = CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
@@ -222,8 +263,11 @@ int network_sync_to(char *target_node) {
        /* Concise cleanup because we know there's only one node in the sc */
        free(sc.ignet_push_shares);
 
-       syslog(LOG_NOTICE, "Synchronized %d messages to <%s>\n",
-               num_spooled, target_node);
+       DeleteHash(&sc.working_ignetcfg);
+       DeleteHash(&sc.the_netmap);
+
+       QN_syslog(LOG_NOTICE, "Synchronized %d messages to <%s>\n",
+                 num_spooled, target_node);
        return(num_spooled);
 }
 
@@ -233,12 +277,13 @@ int network_sync_to(char *target_node) {
  */
 void cmd_nsyn(char *argbuf) {
        int num_spooled;
+       long len;
        char target_node[256];
 
        if (CtdlAccessCheck(ac_aide)) return;
 
-       extract_token(target_node, argbuf, 0, '|', sizeof target_node);
-       num_spooled = network_sync_to(target_node);
+       len = extract_token(target_node, argbuf, 0, '|', sizeof target_node);
+       num_spooled = network_sync_to(target_node, len);
        if (num_spooled >= 0) {
                cprintf("%d Spooled %d messages.\n", CIT_OK, num_spooled);
        }
@@ -250,59 +295,102 @@ void cmd_nsyn(char *argbuf) {
 
 
 
+/*
+ * Batch up and send all outbound traffic from the current room
+ */
+void network_queue_interesting_rooms(struct ctdlroom *qrbuf, void *data) {
+       int i;
+       struct RoomProcList *ptr;
+       long QRNum = qrbuf->QRnumber;
+       void *v;
+       roomlists *RP = (roomlists*) data;
+
+       if (!GetHash(RP->RoomsInterestedIn, LKEY(QRNum), &v))
+               return;
+
+       ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
+       if (ptr == NULL) return;
+
+       ptr->namelen = strlen(qrbuf->QRname);
+       if (ptr->namelen > ROOMNAMELEN)
+               ptr->namelen = ROOMNAMELEN - 1;
+
+       memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
+       ptr->name[ptr->namelen] = '\0';
+       ptr->QRNum = qrbuf->QRnumber;
+
+       for (i = 0; i < ptr->namelen; i++)
+       {
+               ptr->lcname[i] = tolower(ptr->name[i]);
+       }
+
+       ptr->lcname[ptr->namelen] = '\0';
+       ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
+       ptr->next = RP->rplist;
+       RP->rplist = ptr;
+}
+
 /*
  * Batch up and send all outbound traffic from the current room
  */
 void network_queue_room(struct ctdlroom *qrbuf, void *data) {
+       int i;
        struct RoomProcList *ptr;
 
+       if (qrbuf->QRdefaultview == VIEW_QUEUE)
+               return;
        ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
        if (ptr == NULL) return;
 
-       safestrncpy(ptr->name, qrbuf->QRname, sizeof ptr->name);
+       ptr->namelen = strlen(qrbuf->QRname);
+       if (ptr->namelen > ROOMNAMELEN)
+               ptr->namelen = ROOMNAMELEN - 1;
+
+       memcpy (ptr->name, qrbuf->QRname, ptr->namelen);
+       ptr->name[ptr->namelen] = '\0';
+       ptr->QRNum = qrbuf->QRnumber;
+
+       for (i = 0; i < ptr->namelen; i++)
+       {
+               ptr->lcname[i] = tolower(ptr->name[i]);
+       }
+       ptr->lcname[ptr->namelen] = '\0';
+       ptr->key = hashlittle(ptr->lcname, ptr->namelen, 9872345);
+
        begin_critical_section(S_RPLIST);
        ptr->next = rplist;
        rplist = ptr;
        end_critical_section(S_RPLIST);
 }
 
-void destroy_network_queue_room(void)
+void destroy_network_queue_room(RoomProcList *rplist)
 {
        struct RoomProcList *cur, *p;
-       NetMap *nmcur, *nmp;
 
        cur = rplist;
-       begin_critical_section(S_RPLIST);
        while (cur != NULL)
        {
                p = cur->next;
                free (cur);
                cur = p;                
        }
-       rplist = NULL;
-       end_critical_section(S_RPLIST);
-
-       nmcur = the_netmap;
-       while (nmcur != NULL)
-       {
-               nmp = nmcur->next;
-               free (nmcur);
-               nmcur = nmp;            
-       }
-       the_netmap = NULL;
-       if (working_ignetcfg != NULL)
-               free (working_ignetcfg);
-       working_ignetcfg = NULL;
 }
 
-
+void destroy_network_queue_room_locked (void)
+{
+       begin_critical_section(S_RPLIST);
+       destroy_network_queue_room(rplist);
+       end_critical_section(S_RPLIST);
+}
 
 
 
 /*
  * Bounce a message back to the sender
  */
-void network_bounce(struct CtdlMessage *msg, char *reason) {
+void network_bounce(struct CtdlMessage *msg, char *reason)
+{
+       struct CitContext *CCC = CC;
        char *oldpath = NULL;
        char buf[SIZ];
        char bouncesource[SIZ];
@@ -312,7 +400,7 @@ void network_bounce(struct CtdlMessage *msg, char *reason) {
        static int serialnum = 0;
        size_t size;
 
-       syslog(LOG_DEBUG, "entering network_bounce()\n");
+       QNM_syslog(LOG_DEBUG, "entering network_bounce()\n");
 
        if (msg == NULL) return;
 
@@ -401,7 +489,7 @@ void network_bounce(struct CtdlMessage *msg, char *reason) {
        /* Clean up */
        if (valid != NULL) free_recipients(valid);
        CtdlFreeMessage(msg);
-       syslog(LOG_DEBUG, "leaving network_bounce()\n");
+       QNM_syslog(LOG_DEBUG, "leaving network_bounce()\n");
 }
 
 
@@ -415,11 +503,16 @@ void network_bounce(struct CtdlMessage *msg, char *reason) {
  * 
  * Run through the rooms doing various types of network stuff.
  */
-void network_do_queue(void) {
+void network_do_queue(void)
+{
+       struct CitContext *CCC = CC;
        static int doing_queue = 0;
        static time_t last_run = 0L;
-       struct RoomProcList *ptr;
        int full_processing = 1;
+       HashList *working_ignetcfg;
+       HashList *the_netmap = NULL;
+       int netmap_changed = 0;
+       roomlists RL;
 
        /*
         * Run the full set of processing tasks no more frequently
@@ -428,7 +521,7 @@ void network_do_queue(void) {
        if ( (time(NULL) - last_run) < config.c_net_freq ) {
                full_processing = 0;
                syslog(LOG_DEBUG, "Network full processing in %ld seconds.\n",
-                       config.c_net_freq - (time(NULL)- last_run)
+                      config.c_net_freq - (time(NULL)- last_run)
                );
        }
 
@@ -443,68 +536,100 @@ void network_do_queue(void) {
        }
        doing_queue = 1;
 
+       become_session(&networker_spool_CC);
+       begin_critical_section(S_RPLIST);
+       RL.rplist = rplist;
+       rplist = NULL;
+       end_critical_section(S_RPLIST);
+
+       RL.RoomsInterestedIn = NewHash(1, lFlathash);
+       if (full_processing &&
+           (GetNetworkedRoomNumbers(ctdl_netcfg_dir, RL.RoomsInterestedIn)==0))
+       {
+               doing_queue = 0;
+               DeleteHash(&RL.RoomsInterestedIn);
+               if (RL.rplist == NULL)
+                       return;
+       }
        /* Load the IGnet Configuration into memory */
-       load_working_ignetcfg();
+       working_ignetcfg = load_ignetcfg();
 
        /*
         * Load the network map and filter list into memory.
         */
-       read_network_map();
-       load_network_filter_list();
+       if (!server_shutting_down)
+               the_netmap = read_network_map();
+       if (!server_shutting_down)
+               load_network_filter_list();
 
        /* 
         * Go ahead and run the queue
         */
        if (full_processing && !server_shutting_down) {
-               syslog(LOG_DEBUG, "network: loading outbound queue\n");
-               CtdlForEachRoom(network_queue_room, NULL);
-       }
-
-       if (rplist != NULL) {
-               syslog(LOG_DEBUG, "network: running outbound queue\n");
-               while (rplist != NULL && !server_shutting_down) {
-                       char spoolroomname[ROOMNAMELEN];
-                       safestrncpy(spoolroomname, rplist->name, sizeof spoolroomname);
-                       begin_critical_section(S_RPLIST);
-
-                       /* pop this record off the list */
-                       ptr = rplist;
-                       rplist = rplist->next;
-                       free(ptr);
-
-                       /* invalidate any duplicate entries to prevent double processing */
-                       for (ptr=rplist; ptr!=NULL; ptr=ptr->next) {
-                               if (!strcasecmp(ptr->name, spoolroomname)) {
-                                       ptr->name[0] = 0;
+               QNM_syslog(LOG_DEBUG, "network: loading outbound queue");
+               CtdlForEachRoom(network_queue_interesting_rooms, &RL);
+       }
+
+       if ((RL.rplist != NULL) && (!server_shutting_down)) {
+               RoomProcList *ptr, *cmp;
+               ptr = RL.rplist;
+               QNM_syslog(LOG_DEBUG, "network: running outbound queue");
+               while (ptr != NULL && !server_shutting_down) {
+                       
+                       cmp = ptr->next;
+
+                       while (cmp != NULL) {
+                               if ((cmp->namelen > 0) &&
+                                   (cmp->key == ptr->key) &&
+                                   (cmp->namelen == ptr->namelen) &&
+                                   (strcmp(cmp->lcname, ptr->lcname) == 0))
+                               {
+                                       cmp->namelen = 0;
                                }
+                               cmp = cmp->next;
                        }
 
-                       end_critical_section(S_RPLIST);
-                       if (spoolroomname[0] != 0) {
-                               network_spoolout_room(spoolroomname);
+                       if (ptr->namelen > 0) {
+                               network_spoolout_room(ptr, 
+                                                     working_ignetcfg,
+                                                     the_netmap);
                        }
+                       ptr = ptr->next;
                }
        }
 
        /* If there is anything in the inbound queue, process it */
        if (!server_shutting_down) {
-               network_do_spoolin();
+               network_do_spoolin(working_ignetcfg, 
+                                  the_netmap,
+                                  &netmap_changed);
        }
 
-       /* Save the network map back to disk */
-       write_network_map();
-
        /* Free the filter list in memory */
        free_netfilter_list();
 
-       network_consolidate_spoolout();
+       /* Save the network map back to disk */
+       if (netmap_changed) {
+               StrBuf *MapStr = SerializeNetworkMap(the_netmap);
+               CtdlPutSysConfig(IGNETMAP, SmashStrBuf(&MapStr));
+       }
+
+       /* combine singe message files into one spool entry per remote node. */
+       network_consolidate_spoolout(working_ignetcfg, the_netmap);
 
-       syslog(LOG_DEBUG, "network: queue run completed\n");
+       /* shut down. */
+
+       DeleteHash(&the_netmap);
+
+       DeleteHash(&working_ignetcfg);
+
+       QNM_syslog(LOG_DEBUG, "network: queue run completed");
 
        if (full_processing) {
                last_run = time(NULL);
        }
-
+       DeleteHash(&RL.RoomsInterestedIn);
+       destroy_network_queue_room(RL.rplist);
        doing_queue = 0;
 }
 
@@ -517,18 +642,112 @@ int network_room_handler (struct ctdlroom *room)
        return 0;
 }
 
+int NTTDebugEnabled = 0;
+
+/*
+ * network_talking_to()  --  concurrency checker
+ */
+static HashList *nttlist = NULL;
+int network_talking_to(const char *nodename, long len, int operation) {
+
+       int retval = 0;
+       HashPos *Pos = NULL;
+       void *vdata;
+
+       begin_critical_section(S_NTTLIST);
+
+       switch(operation) {
+
+               case NTT_ADD:
+                       if (nttlist == NULL) 
+                               nttlist = NewHash(1, NULL);
+                       Put(nttlist, nodename, len, NewStrBufPlain(nodename, len), HFreeStrBuf);
+                       if (NTTDebugEnabled) syslog(LOG_DEBUG, "nttlist: added <%s>\n", nodename);
+                       break;
+               case NTT_REMOVE:
+                       if ((nttlist == NULL) ||
+                           (GetCount(nttlist) == 0))
+                               break;
+                       Pos = GetNewHashPos(nttlist, 1);
+                       if (GetHashPosFromKey (nttlist, nodename, len, Pos))
+                               DeleteEntryFromHash(nttlist, Pos);
+                       DeleteHashPos(&Pos);
+                       if (NTTDebugEnabled) syslog(LOG_DEBUG, "nttlist: removed <%s>\n", nodename);
+
+                       break;
+
+               case NTT_CHECK:
+                       if ((nttlist == NULL) ||
+                           (GetCount(nttlist) == 0))
+                               break;
+                       if (GetHash(nttlist, nodename, len, &vdata))
+                               retval ++;
+                       if (NTTDebugEnabled) syslog(LOG_DEBUG, "nttlist: have [%d] <%s>\n", retval, nodename);
+                       break;
+       }
+
+       end_critical_section(S_NTTLIST);
+       return(retval);
+}
+
+void cleanup_nttlist(void)
+{
+        begin_critical_section(S_NTTLIST);
+       DeleteHash(&nttlist);
+        end_critical_section(S_NTTLIST);
+}
+
+
+
+void network_logout_hook(void)
+{
+       CitContext *CCC = MyContext();
+
+       /*
+        * If we were talking to a network node, we're not anymore...
+        */
+       if (!IsEmptyStr(CCC->net_node)) {
+               network_talking_to(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
+               CCC->net_node[0] = '\0';
+       }
+}
+void network_cleanup_function(void)
+{
+       struct CitContext *CCC = CC;
+
+       if (!IsEmptyStr(CCC->net_node)) {
+               network_talking_to(CCC->net_node, strlen(CCC->net_node), NTT_REMOVE);
+               CCC->net_node[0] = '\0';
+       }
+}
+
 
 /*
  * Module entry point
  */
+void SetNTTDebugEnabled(const int n)
+{
+       NTTDebugEnabled = n;
+}
+void SetNetQDebugEnabled(const int n)
+{
+       NetQDebugEnabled = n;
+}
+
 CTDL_MODULE_INIT(network)
 {
        if (!threading)
        {
+               CtdlFillSystemContext(&networker_spool_CC, "CitNetSpool");
+               CtdlRegisterDebugFlagHook(HKEY("networktalkingto"), SetNTTDebugEnabled, &NTTDebugEnabled);
+               CtdlRegisterDebugFlagHook(HKEY("networkqueue"), SetNetQDebugEnabled, &NetQDebugEnabled);
+               CtdlRegisterCleanupHook(cleanup_nttlist);
+               CtdlRegisterSessionHook(network_cleanup_function, EVT_STOP, PRIO_STOP + 30);
+                CtdlRegisterSessionHook(network_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 10);
                CtdlRegisterProtoHook(cmd_nsyn, "NSYN", "Synchronize room to node");
                CtdlRegisterRoomHook(network_room_handler);
-               CtdlRegisterCleanupHook(destroy_network_queue_room);
-               CtdlRegisterSessionHook(network_do_queue, EVT_TIMER);
+               CtdlRegisterCleanupHook(destroy_network_queue_room_locked);
+               CtdlRegisterSessionHook(network_do_queue, EVT_TIMER, PRIO_QUEUE + 10);
        }
        return "network";
 }