chiark / gitweb /
fwd: Improve `source' and `target' lifecycle management.
[fwd] / source.c
index 5256e872b80e130b138bba6ac28b6da1c21482c9..f515ae28bd2910adc6bd716642dee014ab47ac52 100644 (file)
--- a/source.c
+++ b/source.c
@@ -7,30 +7,24 @@
 
 /*----- Licensing notice --------------------------------------------------*
  *
- * This file is part of the `fw' port forwarder.
+ * This file is part of the `fwd' port forwarder.
  *
- * `fw' is free software; you can redistribute it and/or modify
+ * `fwd' is free 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 2 of the License, or
  * (at your option) any later version.
  *
- * `fw' is distributed in the hope that it will be useful,
+ * `fwd' 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 `fw'; if not, write to the Free Software Foundation,
+ * along with `fwd'; if not, write to the Free Software Foundation,
  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  */
 
-/*----- Header files ------------------------------------------------------*/
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "source.h"
+#include "fwd.h"
 
 /*----- Static variables --------------------------------------------------*/
 
@@ -51,11 +45,15 @@ static source *sources = 0;
 
 void source_add(source *s)
 {
+  assert(s->ops->shutdown);
+  assert(!(s->f&SF_ACTIVE));
   s->next = sources;
   s->prev = 0;
   if (sources)
     sources->prev = s;
   sources = s;
+  s->f |= SF_ACTIVE;
+  source_inc(s);
 }
 
 /* --- @source_remove@ --- *
@@ -69,12 +67,45 @@ void source_add(source *s)
 
 void source_remove(source *s)
 {
+  assert(s->f&SF_ACTIVE);
   if (s->next)
     s->next->prev = s->prev;
   if (s->prev)
     s->prev->next = s->next;
   else
     sources = s->next;
+  s->f &= ~SF_ACTIVE;
+  source_dec(s);
+}
+
+/* --- @source_inc@ --- *
+ *
+ * Arguments:  @source *s@ = pointer to a source
+ *
+ * Returns:    ---
+ *
+ * Use:                Increments a source's refcount.
+ */
+
+void source_inc(source *s) { s->ref++; }
+
+/* --- @source_dec@ --- *
+ *
+ * Arguments:  @source *s@ = pointer to a source
+ *
+ * Returns:    ---
+ *
+ * Use:                Decrements a source's refcount, destroying it if necessary.
+ */
+
+void source_dec(source *s)
+{
+  assert(s->ref > 0);
+  s->ref--;
+  if (!s->ref) {
+    if (s->f&SF_ACTIVE) s->ops->shutdown(s);
+    s->ops->destroy(s);
+  }
 }
 
 /* --- @source_killall@ --- *
@@ -92,7 +123,7 @@ void source_killall(void)
   while (s) {
     source *ss = s;
     s = s->next;
-    ss->ops->destroy(ss);
+    ss->ops->shutdown(ss);
   }
   sources = 0;
 }