forked from schollz/find
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fingerprint.go
200 lines (182 loc) · 6.52 KB
/
fingerprint.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
// Copyright 2015-2016 Zack Scholl. All rights reserved.
// Use of this source code is governed by a AGPL
// license that can be found in the LICENSE file.
// fingerprint.go contains structures and functions for handling fingerprints.
package main
import (
"encoding/json"
"fmt"
"log"
"strconv"
"net/http"
"path"
"strings"
"time"
"github.com/boltdb/bolt"
"github.com/gin-gonic/gin"
)
// Fingerprint is the prototypical information from the fingerprinting device
type Fingerprint struct {
Group string `json:"group"`
Username string `json:"username"`
Location string `json:"location"`
WifiFingerprint []Router `json:"wifi-fingerprint"`
}
// Router is the router information for each invdividual mac address
type Router struct {
Mac string `json:"mac"`
Rssi int `json:"rssi"`
}
var jsonExample = `{
"group": "whatevergroup",
"username": "iamauser",
"location": null,
"wififingerprint": [{
"mac": "AA:AA:AA:AA:AA:AA",
"rssi": -45
}, {
"mac": "BB:BB:BB:BB:BB:BB",
"rssi": -55
}]
}`
// compression 9 us -> 900 us
func dumpFingerprint(res Fingerprint) []byte {
dumped, _ := res.MarshalJSON()
return compressByte(dumped)
}
// compression 30 us -> 600 us
func loadFingerprint(jsonByte []byte) Fingerprint {
res := Fingerprint{}
res.UnmarshalJSON(decompressByte(jsonByte))
return res
}
func cleanFingerprint(res *Fingerprint) {
res.Group = strings.ToLower(res.Group)
res.Location = strings.ToLower(res.Location)
res.Username = strings.ToLower(res.Username)
deleteIndex := -1
for r := range res.WifiFingerprint {
if res.WifiFingerprint[r].Rssi >= 0 { // https://stackoverflow.com/questions/15797920/how-to-convert-wifi-signal-strength-from-quality-percent-to-rssi-dbm
res.WifiFingerprint[r].Rssi = int(res.WifiFingerprint[r].Rssi/2) - 100
}
if res.WifiFingerprint[r].Mac == "00:00:00:00:00:00" {
deleteIndex = r
}
}
if deleteIndex > -1 {
res.WifiFingerprint[deleteIndex] = res.WifiFingerprint[len(res.WifiFingerprint)-1]
res.WifiFingerprint = res.WifiFingerprint[:len(res.WifiFingerprint)-1]
}
}
func putFingerprintIntoDatabase(res Fingerprint, database string) error {
db, err := bolt.Open(path.Join(RuntimeArgs.SourcePath, res.Group+".db"), 0600, nil)
if err != nil {
log.Fatal(err)
}
defer db.Close()
err = db.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists([]byte(database))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
err = bucket.Put([]byte(timestamp), dumpFingerprint(res))
if err != nil {
return fmt.Errorf("could add to bucket: %s", err)
}
return err
})
return err
}
func trackFingerprintPOST(c *gin.Context) {
var jsonFingerprint Fingerprint
if c.BindJSON(&jsonFingerprint) == nil {
message, success, locationGuess, bayes := trackFingerprint(jsonFingerprint)
if success {
c.JSON(http.StatusOK, gin.H{"message": message, "success": true, "location": locationGuess, "bayes": bayes})
} else {
c.JSON(http.StatusOK, gin.H{"message": message, "success": false})
}
} else {
Warning.Println("Could not bind JSON")
c.JSON(http.StatusOK, gin.H{"message": "Could not bind JSON", "success": false})
}
}
func learnFingerprintPOST(c *gin.Context) {
var jsonFingerprint Fingerprint
if c.BindJSON(&jsonFingerprint) == nil {
message, success := learnFingerprint(jsonFingerprint)
c.JSON(http.StatusOK, gin.H{"message": message, "success": success})
} else {
Warning.Println("Could not bind JSON")
c.JSON(http.StatusOK, gin.H{"message": "Could not bind JSON", "success": false})
}
}
func learnFingerprint(jsonFingerprint Fingerprint) (string, bool) {
cleanFingerprint(&jsonFingerprint)
if len(jsonFingerprint.Group) == 0 {
return "Need to define your group name in request, see API", false
}
if len(jsonFingerprint.WifiFingerprint) == 0 {
return "No fingerprints found to insert, see API", false
}
putFingerprintIntoDatabase(jsonFingerprint, "fingerprints")
isLearning[strings.ToLower(jsonFingerprint.Group)] = true
message := "Inserted fingerprint containing " + strconv.Itoa(len(jsonFingerprint.WifiFingerprint)) + " APs for " + jsonFingerprint.Username + " at " + jsonFingerprint.Location
Debug.Println(message)
return message, true
}
func trackFingerprint(jsonFingerprint Fingerprint) (string, bool, string, map[string]float64) {
bayes := make(map[string]float64)
cleanFingerprint(&jsonFingerprint)
if !groupExists(jsonFingerprint.Group) || len(jsonFingerprint.Group) == 0 {
return "You should insert fingerprints before tracking", false, "", bayes
}
if len(jsonFingerprint.WifiFingerprint) == 0 {
return "No fingerprints found to track, see API", false, "", bayes
}
if len(jsonFingerprint.Username) == 0 {
return "No username defined, see API", false, "", bayes
}
if wasLearning, ok := isLearning[strings.ToLower(jsonFingerprint.Group)]; ok {
if wasLearning {
Debug.Println("Was learning, calculating priors")
group := strings.ToLower(jsonFingerprint.Group)
isLearning[group] = false
optimizePriorsThreaded(group)
if _, ok := usersCache[group]; ok {
if len(usersCache[group]) == 0 {
usersCache[group] = append([]string{}, strings.ToLower(jsonFingerprint.Username))
}
}
}
}
locationGuess, bayes := calculatePosterior(jsonFingerprint, *NewFullParameters())
jsonFingerprint.Location = locationGuess
putFingerprintIntoDatabase(jsonFingerprint, "fingerprints-track")
positions := [][]string{}
positions1 := []string{}
positions2 := []string{}
positions1 = append(positions1, locationGuess)
positions2 = append(positions2, " ")
positions = append(positions, positions1)
positions = append(positions, positions2)
var userJSON UserPositionJSON
userJSON.Location = locationGuess
userJSON.Bayes = bayes
userJSON.Time = time.Now().String()
userPositionCache[strings.ToLower(jsonFingerprint.Group)+strings.ToLower(jsonFingerprint.Username)] = userJSON
Debug.Println("Tracking fingerprint containing " + strconv.Itoa(len(jsonFingerprint.WifiFingerprint)) + " APs for " + jsonFingerprint.Username + " (" + jsonFingerprint.Group + ") at " + jsonFingerprint.Location + " (guess)")
if RuntimeArgs.Mqtt {
type FingerprintResponse struct {
LocationGuess string `json:"location"`
Bayes map[string]float64 `json:"bayes"`
}
mqttMessage, _ := json.Marshal(FingerprintResponse{
LocationGuess: locationGuess,
Bayes: bayes,
})
go sendMQTTLocation(string(mqttMessage), jsonFingerprint.Group, jsonFingerprint.Username)
}
return "Calculated location: " + locationGuess, true, locationGuess, bayes
}