]> Cypherpunks.ru repositories - govpn.git/blob - src/cypherpunks.ru/govpn/stats.go
Use convenient simpler Go 1.9's sync.Map
[govpn.git] / src / cypherpunks.ru / govpn / stats.go
1 /*
2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-2017 Sergey Matveev <stargrave@stargrave.org>
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 package govpn
20
21 import (
22         "encoding/json"
23         "log"
24         "net"
25         "sync"
26         "time"
27 )
28
29 const (
30         RWTimeout = 10 * time.Second
31 )
32
33 // StatsProcessor is assumed to be run in background. It accepts
34 // connection on statsPort, reads anything one send to them and show
35 // information about known peers in serialized JSON format. peers
36 // argument is a reference to the map with references to the peers as
37 // values. Map is used here because of ease of adding and removing
38 // elements in it.
39 func StatsProcessor(statsPort net.Listener, peers *sync.Map) {
40         var conn net.Conn
41         var err error
42         var data []byte
43         buf := make([]byte, 2<<8)
44         for {
45                 conn, err = statsPort.Accept()
46                 if err != nil {
47                         log.Println("Error during accepting connection", err.Error())
48                         continue
49                 }
50                 conn.SetDeadline(time.Now().Add(RWTimeout))
51                 conn.Read(buf)
52                 conn.Write([]byte("HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n"))
53                 var peersList []*Peer
54                 peers.Range(func(_, peerI interface{}) bool {
55                         peersList = append(peersList, *peerI.(**Peer))
56                         return true
57                 })
58                 data, err = json.Marshal(peersList)
59                 if err != nil {
60                         panic(err)
61                 }
62                 conn.Write(data)
63                 conn.Close()
64         }
65 }