This repository has been archived by the owner on Dec 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.go
125 lines (104 loc) · 2.45 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package main
import (
"crypto/tls"
"flag"
"fmt"
"log"
"net"
"os"
"os/signal"
"github.com/pkg/errors"
"github.com/tadeokondrak/ircdiscord/internal/server"
)
func listen(port int) (net.Listener, error) {
if port == 0 {
port = 6667
}
addr := fmt.Sprintf(":%d", port)
listener, err := net.Listen("tcp", addr)
if err != nil {
return nil, errors.Wrap(err,
"failed to create listener")
}
return listener, nil
}
func listenTLS(port int, certfile, keyfile string) (net.Listener, error) {
if certfile == "" || keyfile == "" {
return nil, errors.New(
"certfile and keyfile are required for TLS")
}
cert, err := tls.LoadX509KeyPair(certfile, keyfile)
if err != nil {
return nil, errors.Wrap(err, "failed to load keypair")
}
config := &tls.Config{Certificates: []tls.Certificate{cert}}
if port == 0 {
port = 6697
}
addr := fmt.Sprintf(":%d", port)
listener, err := tls.Listen("tcp", addr, config)
if err != nil {
return nil, errors.Wrap(err,
"failed to create listener")
}
return listener, nil
}
func main() {
var (
debug bool
ircDebug bool
discordDebug bool
port int
tlsEnabled bool
certfile string
keyfile string
)
flag.BoolVar(&debug, "debug", false,
"enable verbose logging")
flag.BoolVar(&ircDebug, "ircdebug", false,
"enable verbose logging of irc communication")
flag.BoolVar(&discordDebug, "discorddebug", false,
"enable verbose logging of discord communication")
flag.IntVar(&port, "port", 0,
"port to run on, defaults to 6667/6697 depending on tls")
flag.BoolVar(&tlsEnabled, "tls", false, "enable tls encryption")
flag.StringVar(&certfile, "cert", "", "tls certificate file")
flag.StringVar(&keyfile, "key", "", "tls key file")
flag.Parse()
if !debug {
log.SetFlags(0)
} else {
log.SetFlags(log.Lshortfile)
}
var ln net.Listener
if !tlsEnabled {
var err error
ln, err = listen(port)
if err != nil {
log.Fatalln(err)
}
} else {
var err error
ln, err = listenTLS(port, certfile, keyfile)
if err != nil {
log.Fatalln(err)
}
}
server := server.New(ln, debug, ircDebug, discordDebug)
defer server.Close()
errors := make(chan error)
go func() {
if err := server.Run(); err != nil {
errors <- err
}
}()
log.Printf("listening on %v", ln.Addr())
sigch := make(chan os.Signal, 1)
signal.Notify(sigch, os.Interrupt)
select {
case err := <-errors:
log.Println(err)
case sig := <-sigch:
log.Printf("received signal '%v'", sig)
}
}