summaryrefslogtreecommitdiff
path: root/src/main/java/org/torproject/onionoo/updater/DescriptorSource.java
blob: 3b2fb6cb93e035c076ed42791ed22db09e274779 (plain)
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
/* Copyright 2013--2018 The Tor Project
 * See LICENSE for licensing information */

package org.torproject.onionoo.updater;

import org.torproject.descriptor.Descriptor;
import org.torproject.descriptor.DescriptorCollector;
import org.torproject.onionoo.util.FormattingUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class DescriptorSource {

  private static final Logger log = LoggerFactory.getLogger(
      DescriptorSource.class);

  private final String[] collecTorHosts = new String[] {
      "collector.torproject.org", "collector2.torproject.org" };

  private final File inDir = new File("in");

  private final File inArchiveDir = new File(inDir, "archive");

  private final File statusDir = new File("status");

  private List<DescriptorQueue> descriptorQueues;

  private DescriptorQueue archiveDescriptorQueue;

  /** Instantiates a new descriptor source. */
  public DescriptorSource() {
    this.descriptorQueues = new ArrayList<>();
    this.descriptorListeners = new HashMap<>();
  }

  private List<DescriptorQueue> getDescriptorQueues(
      DescriptorType descriptorType,
      DescriptorHistory descriptorHistory) {
    List<DescriptorQueue> descriptorQueues = new ArrayList<>();
    for (String collecTorHost : this.collecTorHosts) {
      File inRecentDir = new File(inDir, collecTorHost + "/recent");
      File historiesDir = new File(this.statusDir, collecTorHost);
      DescriptorQueue descriptorQueue = new DescriptorQueue(
          inRecentDir, descriptorType, historiesDir);
      if (descriptorHistory != null) {
        descriptorQueue.readHistoryFile(descriptorHistory);
      }
      descriptorQueues.add(descriptorQueue);
      this.descriptorQueues.add(descriptorQueue);
    }
    return descriptorQueues;
  }

  private Map<DescriptorType, Set<DescriptorListener>>
      descriptorListeners;

  /** Registers a descriptor listener for a given descriptor type. */
  public void registerDescriptorListener(DescriptorListener listener,
      DescriptorType descriptorType) {
    if (!this.descriptorListeners.containsKey(descriptorType)) {
      this.descriptorListeners.put(descriptorType,
          new HashSet<DescriptorListener>());
    }
    this.descriptorListeners.get(descriptorType).add(listener);
  }

  /** Downloads descriptors from CollecTor. */
  public void downloadDescriptors() {
    List<String> remoteDirectoriesList = new ArrayList<>();
    for (DescriptorType descriptorType : DescriptorType.values()) {
      remoteDirectoriesList.add("/recent/" + descriptorType.getDir());
    }
    for (String collecTorHost : this.collecTorHosts) {
      String collecTorBaseUrl = "https://" + collecTorHost;
      String[] remoteDirectories = remoteDirectoriesList.toArray(new String[0]);
      long minLastModified = 0L;
      File localDirectory = new File(inDir, collecTorHost);
      boolean deleteExtraneousLocalFiles = true;
      DescriptorCollector dc = org.torproject.descriptor.DescriptorSourceFactory
          .createDescriptorCollector();
      dc.collectDescriptors(collecTorBaseUrl, remoteDirectories,
          minLastModified, localDirectory, deleteExtraneousLocalFiles);
    }
  }

  /** Reads archived and recent descriptors from disk and feeds them into
   * any registered listeners. */
  public void readDescriptors() {
    this.readArchivedDescriptors();
    log.debug("Reading recent {} ...", DescriptorType.RELAY_SERVER_DESCRIPTORS);
    this.readDescriptors(DescriptorType.RELAY_SERVER_DESCRIPTORS,
        DescriptorHistory.RELAY_SERVER_HISTORY, true);
    log.debug("Reading recent {} ...", DescriptorType.RELAY_EXTRA_INFOS);
    this.readDescriptors(DescriptorType.RELAY_EXTRA_INFOS,
        DescriptorHistory.RELAY_EXTRAINFO_HISTORY, true);
    log.debug("Reading recent {} ...", DescriptorType.EXIT_LISTS);
    this.readDescriptors(DescriptorType.EXIT_LISTS,
        DescriptorHistory.EXIT_LIST_HISTORY, true);
    log.debug("Reading recent {} ...", DescriptorType.RELAY_CONSENSUSES);
    this.readDescriptors(DescriptorType.RELAY_CONSENSUSES,
        DescriptorHistory.RELAY_CONSENSUS_HISTORY, true);
    log.debug("Reading recent {} ...",
        DescriptorType.BRIDGE_SERVER_DESCRIPTORS);
    this.readDescriptors(DescriptorType.BRIDGE_SERVER_DESCRIPTORS,
        DescriptorHistory.BRIDGE_SERVER_HISTORY, false);
    log.debug("Reading recent {} ...", DescriptorType.BRIDGE_EXTRA_INFOS);
    this.readDescriptors(DescriptorType.BRIDGE_EXTRA_INFOS,
        DescriptorHistory.BRIDGE_EXTRAINFO_HISTORY, false);
    log.debug("Reading recent {} ...", DescriptorType.BRIDGE_STATUSES);
    this.readDescriptors(DescriptorType.BRIDGE_STATUSES,
        DescriptorHistory.BRIDGE_STATUS_HISTORY, false);
  }

  private void readDescriptors(DescriptorType descriptorType,
      DescriptorHistory descriptorHistory, boolean relay) {
    if (!this.descriptorListeners.containsKey(descriptorType)) {
      return;
    }
    Set<DescriptorListener> descriptorListeners =
        this.descriptorListeners.get(descriptorType);
    for (DescriptorQueue descriptorQueue
        : this.getDescriptorQueues(descriptorType, descriptorHistory)) {
      Descriptor descriptor;
      while ((descriptor = descriptorQueue.nextDescriptor()) != null) {
        for (DescriptorListener descriptorListener : descriptorListeners) {
          descriptorListener.processDescriptor(descriptor, relay);
        }
      }
    }
    log.info("Read recent/{}.", descriptorType.getDir());
  }

  /** Reads archived descriptors from disk and feeds them into any
   * registered listeners. */
  public void readArchivedDescriptors() {
    if (!this.inArchiveDir.exists()) {
      return;
    }
    log.info("Reading archived descriptors...");
    this.archiveDescriptorQueue = new DescriptorQueue(this.inArchiveDir,
        null, this.statusDir);
    this.archiveDescriptorQueue.readHistoryFile(
        DescriptorHistory.ARCHIVED_HISTORY);
    Descriptor descriptor;
    while ((descriptor = this.archiveDescriptorQueue.nextDescriptor())
        != null) {
      DescriptorType descriptorType = null;
      boolean relay = false;
      for (String annotation : descriptor.getAnnotations()) {
        if (annotation.startsWith(
            "@type network-status-consensus-3 1.")) {
          descriptorType = DescriptorType.RELAY_CONSENSUSES;
          relay = true;
        } else if (annotation.startsWith("@type server-descriptor 1.")) {
          descriptorType = DescriptorType.RELAY_SERVER_DESCRIPTORS;
          relay = true;
        } else if (annotation.startsWith("@type extra-info 1.")) {
          descriptorType = DescriptorType.RELAY_EXTRA_INFOS;
          relay = true;
        } else if (annotation.startsWith("@type tordnsel 1.")) {
          descriptorType = DescriptorType.EXIT_LISTS;
          relay = true;
        } else if (annotation.startsWith(
            "@type bridge-network-status 1.")) {
          descriptorType = DescriptorType.BRIDGE_STATUSES;
          relay = false;
        } else if (annotation.startsWith(
            "@type bridge-server-descriptor 1.")) {
          descriptorType = DescriptorType.BRIDGE_SERVER_DESCRIPTORS;
          relay = false;
        } else if (annotation.startsWith("@type bridge-extra-info 1.")) {
          descriptorType = DescriptorType.BRIDGE_EXTRA_INFOS;
          relay = false;
        }
      }
      if (descriptorType == null) {
        log.warn("Unrecognized descriptor in "
            + this.inArchiveDir.getAbsolutePath() + " with annotations "
            + descriptor.getAnnotations() + ".  Skipping descriptor.");
        continue;
      }
      for (DescriptorListener descriptorListener :
          this.descriptorListeners.get(descriptorType)) {
        descriptorListener.processDescriptor(descriptor, relay);
      }
    }
    this.archiveDescriptorQueue.writeHistoryFile();
    log.info("Read archived descriptors");
  }

  /** Writes parse histories for recent descriptors to disk. */
  public void writeHistoryFiles() {
    log.debug("Writing parse histories for recent descriptors...");
    for (DescriptorQueue descriptorQueue : this.descriptorQueues) {
      descriptorQueue.writeHistoryFile();
    }
  }

  /** Returns a string with statistics on the number of processed
   * descriptors during the current execution. */
  public String getStatsString() {
    StringBuilder sb = new StringBuilder();
    sb.append("    ").append(this.descriptorQueues.size())
      .append(" descriptor ").append("queues created for recent descriptors\n");
    int historySizeBefore = 0;
    int historySizeAfter = 0;
    long descriptors = 0L;
    long bytes = 0L;
    for (DescriptorQueue descriptorQueue : this.descriptorQueues) {
      historySizeBefore += descriptorQueue.getHistorySizeBefore();
      historySizeAfter += descriptorQueue.getHistorySizeAfter();
      descriptors += descriptorQueue.getReturnedDescriptors();
      bytes += descriptorQueue.getReturnedBytes();
    }
    sb.append("    ").append(FormattingUtils.formatDecimalNumber(
        historySizeBefore)).append(" recent descriptors excluded from this ")
        .append("execution\n");
    sb.append("    ").append(FormattingUtils.formatDecimalNumber(descriptors))
        .append(" recent descriptors provided\n");
    sb.append("    ").append(FormattingUtils.formatBytes(bytes))
        .append(" of recent descriptors provided\n");
    sb.append("    ").append(FormattingUtils.formatDecimalNumber(
        historySizeAfter)).append(" recent descriptors excluded from next ")
        .append("execution\n");
    if (this.archiveDescriptorQueue != null) {
      sb.append("    ").append(FormattingUtils.formatDecimalNumber(
          this.archiveDescriptorQueue.getReturnedDescriptors()))
        .append(" archived descriptors provided\n");
      sb.append("    ").append(FormattingUtils.formatBytes(
          this.archiveDescriptorQueue.getReturnedBytes())).append(" of ")
        .append("archived descriptors provided\n");
    }
    return sb.toString();
  }
}