2012-04-07 20:44:59 +02:00
|
|
|
package irc
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
2013-05-11 23:43:06 +02:00
|
|
|
"log"
|
2012-04-07 20:44:59 +02:00
|
|
|
"net"
|
2012-12-09 07:54:58 +01:00
|
|
|
"strings"
|
2012-04-07 20:44:59 +02:00
|
|
|
)
|
|
|
|
|
2013-05-11 23:43:06 +02:00
|
|
|
const (
|
2013-05-25 06:39:53 +02:00
|
|
|
DEBUG_NET = true
|
2013-05-11 23:43:06 +02:00
|
|
|
)
|
|
|
|
|
2012-04-18 03:16:57 +02:00
|
|
|
func readTrimmedLine(reader *bufio.Reader) (string, error) {
|
|
|
|
line, err := reader.ReadString('\n')
|
2012-12-12 07:34:22 +01:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return strings.TrimSpace(line), nil
|
2012-04-18 03:16:57 +02:00
|
|
|
}
|
|
|
|
|
2012-04-07 20:44:59 +02:00
|
|
|
// Adapt `net.Conn` to a `chan string`.
|
2012-04-18 03:16:57 +02:00
|
|
|
func StringReadChan(conn net.Conn) <-chan string {
|
2012-04-07 20:44:59 +02:00
|
|
|
ch := make(chan string)
|
2012-04-08 08:32:08 +02:00
|
|
|
reader := bufio.NewReader(conn)
|
2012-04-07 20:44:59 +02:00
|
|
|
go func() {
|
|
|
|
for {
|
2012-04-18 03:16:57 +02:00
|
|
|
line, err := readTrimmedLine(reader)
|
2012-04-07 20:44:59 +02:00
|
|
|
if err != nil {
|
|
|
|
break
|
|
|
|
}
|
2013-05-11 23:43:06 +02:00
|
|
|
if DEBUG_NET {
|
|
|
|
log.Printf("%s → %s", conn.RemoteAddr(), line)
|
|
|
|
}
|
2012-12-12 07:34:22 +01:00
|
|
|
ch <- line
|
2012-04-07 20:44:59 +02:00
|
|
|
}
|
2012-04-08 08:32:08 +02:00
|
|
|
close(ch)
|
2012-04-07 20:44:59 +02:00
|
|
|
}()
|
2012-04-08 08:32:08 +02:00
|
|
|
return ch
|
|
|
|
}
|
2012-04-07 20:44:59 +02:00
|
|
|
|
2012-04-18 03:16:57 +02:00
|
|
|
func StringWriteChan(conn net.Conn) chan<- string {
|
2012-04-08 08:32:08 +02:00
|
|
|
ch := make(chan string)
|
|
|
|
writer := bufio.NewWriter(conn)
|
2012-04-07 20:44:59 +02:00
|
|
|
go func() {
|
|
|
|
for str := range ch {
|
2013-05-11 23:43:06 +02:00
|
|
|
if DEBUG_NET {
|
|
|
|
log.Printf("%s ← %s", conn.RemoteAddr(), str)
|
|
|
|
}
|
|
|
|
if _, err := writer.WriteString(str + "\r\n"); err != nil {
|
2012-04-07 20:44:59 +02:00
|
|
|
break
|
|
|
|
}
|
2012-04-08 08:32:08 +02:00
|
|
|
writer.Flush()
|
2012-04-07 20:44:59 +02:00
|
|
|
}
|
2012-04-08 08:32:08 +02:00
|
|
|
close(ch)
|
2012-04-07 20:44:59 +02:00
|
|
|
}()
|
|
|
|
|
|
|
|
return ch
|
|
|
|
}
|
2012-12-09 07:54:58 +01:00
|
|
|
|
|
|
|
func LookupHostname(addr net.Addr) string {
|
|
|
|
addrStr := addr.String()
|
|
|
|
ipaddr, _, err := net.SplitHostPort(addrStr)
|
|
|
|
if err != nil {
|
|
|
|
return addrStr
|
|
|
|
}
|
|
|
|
names, err := net.LookupAddr(ipaddr)
|
|
|
|
if err != nil {
|
|
|
|
return ipaddr
|
|
|
|
}
|
|
|
|
return names[0]
|
|
|
|
}
|