From 20f0ffbe10701628b9847f2be4019a5a5aa14924 Mon Sep 17 00:00:00 2001
From: Edwin Balani <git@balani.xyz>
Date: Sun, 31 Mar 2024 21:48:16 +0100
Subject: [PATCH] Fix nil pointer dereference when TCP listener is configured

After 60526f60a842dac2a925c1bcf664ad65b6f0f968 (#31),
`irccat.tcp.Run(irccat.irc)` is called (if the config calls for it)
before, rather than after, `irccat.connectIRC()`, which changes
`irccat.irc` away from a nil pointer in the first place.  This pointer
is copied into the `irc` field of a TCPListener `l` by
`irccat.tcp.Run()`.

A panic won't actually happen until the TCP listener handles its first
message, if it ever comes, and in doing so passes the nil pointer
further down to `dispatcher.Send(l.irc, ...)`.

To fix, bring the call to `irccat.connectIRC()` forward again, to before
any listener setup is done at all.  This probably makes sense
stylistically too.
---
 main.go | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/main.go b/main.go
index 04da46f..60faaf1 100644
--- a/main.go
+++ b/main.go
@@ -70,6 +70,13 @@ func main() {
 	signal.Notify(irccat.signals, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
 	go irccat.signalHandler()
 
+	err = irccat.connectIRC(*debug)
+
+	if err != nil {
+		log.Criticalf("Error connecting to IRC server: %s", err)
+		return
+	}
+
 	if viper.IsSet("tcp.listen") {
 		irccat.tcp, err = tcplistener.New()
 		if err != nil {
@@ -79,13 +86,6 @@ func main() {
 		irccat.tcp.Run(irccat.irc)
 	}
 
-	err = irccat.connectIRC(*debug)
-
-	if err != nil {
-		log.Criticalf("Error connecting to IRC server: %s", err)
-		return
-	}
-
 	if viper.IsSet("http") {
 		httplistener.New(irccat.irc)
 	}