forked from s-rah/onionscan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crawldb.go
313 lines (266 loc) · 8.96 KB
/
crawldb.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package crawldb
import (
"encoding/json"
"errors"
"fmt"
"github.com/HouzuoGuo/tiedot/db"
"github.com/s-rah/onionscan/model"
"log"
"time"
)
// CrawlDB is the main interface for persistent storage in OnionScan
type CrawlDB struct {
myDB *db.DB
}
// NewDB creates new new CrawlDB instance. If the database does not exist at the
// given dbdir, it will be created.
func (cdb *CrawlDB) NewDB(dbdir string) {
db, err := db.OpenDB(dbdir)
if err != nil {
panic(err)
}
cdb.myDB = db
//If we have just created this db then it will be empty
if len(cdb.myDB.AllCols()) == 0 {
cdb.Initialize()
}
}
// Initialize sets up a new database - should only be called when creating a
// new database.
// There is a lot of indexing here, which may seem overkill - but on a large
// OnionScan run these indexes take up < 100MB each - which is really cheap
// when compared with their search potential.
func (cdb *CrawlDB) Initialize() {
log.Printf("Creating Database Bucket crawls...")
if err := cdb.myDB.Create("crawls"); err != nil {
panic(err)
}
// Allow searching by the URL
log.Printf("Indexing URL in crawls...")
crawls := cdb.myDB.Use("crawls")
if err := crawls.Index([]string{"URL"}); err != nil {
panic(err)
}
log.Printf("Creating Database Bucket relationships...")
if err := cdb.myDB.Create("relationships"); err != nil {
panic(err)
}
// Allowing searching by the Identifier String
log.Printf("Indexing Identifier in relationships...")
rels := cdb.myDB.Use("relationships")
if err := rels.Index([]string{"Identifier"}); err != nil {
panic(err)
}
// Allowing searching by the Onion String
log.Printf("Indexing Onion in relationships...")
if err := rels.Index([]string{"Onion"}); err != nil {
panic(err)
}
// Allowing searching by the Type String
log.Printf("Indexing Type in relationships...")
if err := rels.Index([]string{"Type"}); err != nil {
panic(err)
}
// Allowing searching by the From String
log.Printf("Indexing From in relationships...")
if err := rels.Index([]string{"From"}); err != nil {
panic(err)
}
log.Printf("Database Setup Complete")
}
// CrawlRecord defines a spider entry in the database
type CrawlRecord struct {
URL string
Timestamp time.Time
Page model.Page
}
// InsertCrawlRecord adds a new spider entry to the database and returns the
// record id.
func (cdb *CrawlDB) InsertCrawlRecord(url string, page *model.Page) (int, error) {
crawls := cdb.myDB.Use("crawls")
docID, err := crawls.Insert(map[string]interface{}{
"URL": url,
"Timestamp": time.Now(),
"Page": page})
return docID, err
}
// GetCrawlRecord returns a CrawlRecord from the database given an ID.
func (cdb *CrawlDB) GetCrawlRecord(id int) (CrawlRecord, error) {
crawls := cdb.myDB.Use("crawls")
readBack, err := crawls.Read(id)
if err == nil {
out, err := json.Marshal(readBack)
if err == nil {
var crawlRecord CrawlRecord
json.Unmarshal(out, &crawlRecord)
return crawlRecord, nil
}
return CrawlRecord{}, err
}
return CrawlRecord{}, err
}
// HasCrawlRecord returns true if a given URL is associated with a crawl record
// in the database. Only records created after the given duration are considered.
func (cdb *CrawlDB) HasCrawlRecord(url string, duration time.Duration) (bool, int) {
var query interface{}
before := time.Now().Add(duration)
q := fmt.Sprintf(`{"eq":"%v", "in": ["URL"]}`, url)
json.Unmarshal([]byte(q), &query)
queryResult := make(map[int]struct{}) // query result (document IDs) goes into map keys
crawls := cdb.myDB.Use("crawls")
if err := db.EvalQuery(query, crawls, &queryResult); err != nil {
panic(err)
}
for id := range queryResult {
// To get query result document, simply read it
readBack, err := crawls.Read(id)
if err == nil {
out, err := json.Marshal(readBack)
if err == nil {
var crawlRecord CrawlRecord
json.Unmarshal(out, &crawlRecord)
if crawlRecord.Timestamp.After(before) {
return true, id
}
}
}
}
return false, 0
}
// Relationship defines a correltion record in the Database.
type Relationship struct {
ID int
Onion string
From string
Type string
Identifier string
FirstSeen time.Time
LastSeen time.Time
}
// InsertRelationship creates a new Relationship in the database.
func (cdb *CrawlDB) InsertRelationship(onion string, from string, identiferType string, identifier string) (int, error) {
rels, err := cdb.GetRelationshipsWithOnion(onion)
// If we have seen this before, we will update rather than adding a
// new relationship
if err == nil {
for _, rel := range rels {
if rel.From == from && rel.Identifier == identifier && rel.Type == identiferType {
// Update the Relationships
log.Printf("Updating %s --- %s ---> %s (%s)", onion, from, identifier, identiferType)
relationships := cdb.myDB.Use("relationships")
err := relationships.Update(rel.ID, map[string]interface{}{
"Onion": onion,
"From": from,
"Type": identiferType,
"Identifier": identifier,
"FirstSeen": rel.FirstSeen,
"LastSeen": time.Now()})
return rel.ID, err
}
}
}
// Otherwise Insert New
log.Printf("Inserting %s --- %s ---> %s (%s)", onion, from, identifier, identiferType)
relationships := cdb.myDB.Use("relationships")
docID, err := relationships.Insert(map[string]interface{}{
"Onion": onion,
"From": from,
"Type": identiferType,
"Identifier": identifier,
"FirstSeen": time.Now(),
"LastSeen": time.Now()})
return docID, err
}
// GetRelationshipsWithOnion returns all relationships with an Onion field matching
// the onion parameter.
func (cdb *CrawlDB) GetRelationshipsWithOnion(onion string) ([]Relationship, error) {
return cdb.queryDB("Onion", onion)
}
// GetUserRelationshipFromOnion reconstructs a user relationship from a given
// identifier. fromonion is used as a filter to ensure that only user relationships
// from a given onion are reconstructed.
func (cdb *CrawlDB) GetUserRelationshipFromOnion(identifier string, fromonion string) (map[string]Relationship, error) {
results, err := cdb.GetRelationshipsWithOnion(identifier)
if err != nil {
return nil, err
}
relationships := make(map[string]Relationship)
for _, result := range results {
if result.From == fromonion {
relationships[result.Type] = result
}
}
return relationships, nil
}
// GetAllRelationshipsCount returns the total number of relationships stored in
// the database.
func (cdb *CrawlDB) GetAllRelationshipsCount() int {
queryResult := make(map[int]struct{}) // query result (document IDs) goes into map keys
relationships := cdb.myDB.Use("relationships")
if err := db.EvalAllIDs(relationships, &queryResult); err != nil {
return 0
}
return len(queryResult)
}
// GetRelationshipsCount returns the total number of relationships for a given
// identifier.
func (cdb *CrawlDB) GetRelationshipsCount(identifier string) int {
var query interface{}
q := fmt.Sprintf(`{"eq":"%v", "in": ["Identifier"]}`, identifier)
json.Unmarshal([]byte(q), &query)
queryResult := make(map[int]struct{}) // query result (document IDs) goes into map keys
relationships := cdb.myDB.Use("relationships")
if err := db.EvalQuery(query, relationships, &queryResult); err != nil {
return 0
}
return len(queryResult)
}
// GetRelationshipsWithIdentifier returns all relatioships associated with a
// given identifier.
func (cdb *CrawlDB) GetRelationshipsWithIdentifier(identifier string) ([]Relationship, error) {
types, _ := cdb.queryDB("Type", identifier)
froms, _ := cdb.queryDB("From", identifier)
identifiers, _ := cdb.queryDB("Identifier", identifier)
queryResult := append(types, froms...)
queryResult = append(queryResult, identifiers...)
return queryResult, nil
}
func (cdb *CrawlDB) queryDB(field string, value string) ([]Relationship, error) {
var query interface{}
q := fmt.Sprintf(`{"eq":"%v", "in": ["%v"]}`, value, field)
json.Unmarshal([]byte(q), &query)
queryResult := make(map[int]struct{}) // query result (document IDs) goes into map keys
relationships := cdb.myDB.Use("relationships")
if err := db.EvalQuery(query, relationships, &queryResult); err != nil {
return nil, err
}
var rels []Relationship
for id := range queryResult {
// To get query result document, simply read it
readBack, err := relationships.Read(id)
if err == nil {
out, err := json.Marshal(readBack)
if err == nil {
var relationship Relationship
json.Unmarshal(out, &relationship)
relationship.ID = id
rels = append(rels, relationship)
}
}
}
return rels, nil
}
// DeleteRelationship deletes a relationship given the quad.
func (cdb *CrawlDB) DeleteRelationship(onion string, from string, identiferType string, identifier string) error {
relationships := cdb.myDB.Use("relationships")
rels, err := cdb.GetRelationshipsWithOnion(onion)
if err == nil {
for _, rel := range rels {
if rel.From == from && rel.Type == identiferType && rel.Identifier == identifier {
err := relationships.Delete(rel.ID)
return err
}
}
}
return errors.New("could not find record to delete")
}