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