summaryrefslogtreecommitdiff
path: root/src/ot_udp.c
blob: 2918c2556f253fc0538d8d88750abdaeb67ef259 (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
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
/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
   It is considered beerware. Prost. Skol. Cheers or whatever. */

/* System */
#include <arpa/inet.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

/* Opentracker */
#include "ot_ip.h"
#include "ot_random.h"
#include "ot_rijndael.h"
#include "ot_socket.h"
#include "ot_worker.h"
#include "ot_stats.h"
#include "ot_udp.h"
#include "trackerlogic.h"

/* BEP 15: "Up to about 74 torrents can be scraped at once" */
#define OT_MAX_SCRAPE_UDP 74

static uint32_t g_rijndael_round_key[44] = {0};
static volatile uint32_t g_key_of_the_hour[2] = {0};
static volatile ot_time  g_hour_of_the_key;


static void     udp_generate_rijndael_round_key(void) {
  uint32_t key[16];
  random_bytes(key, sizeof(key));
  rijndaelKeySetupEnc128(g_rijndael_round_key, (uint8_t *)key);

  g_key_of_the_hour[0] = random_uint32();
  g_hour_of_the_key = time_now_minutes();
}

/* Generate current and previous connection id for ip */
static void udp_make_connectionid(uint32_t connid[2], const ot_ip6 remoteip, int age) {
  uint32_t plain[4], crypt[4];
  int      i;
  uint32_t current_key_of_the_hour;

  if (time_since_minutes(g_hour_of_the_key) >= 60) {
    uint32_t old_key_of_the_hour = g_key_of_the_hour[0];
    uint32_t new_key_of_the_hour = random_uint32();
    /* If in the meantime another thread has performed
       key rotation, do not overwrite their results */
    if (time_since_minutes(g_hour_of_the_key) >= 60) {
      /* Upgrade en bloc */
      g_hour_of_the_key    = time_now_minutes();
      g_key_of_the_hour[0] = new_key_of_the_hour;
      g_key_of_the_hour[1] = old_key_of_the_hour;
    }
  }

  memcpy(plain, remoteip, sizeof(plain));
  current_key_of_the_hour = g_key_of_the_hour[age];
  for (i = 0; i < 4; ++i)
    plain[i] ^= current_key_of_the_hour;
  rijndaelEncrypt128(g_rijndael_round_key, (uint8_t *)plain, (uint8_t *)crypt);
  connid[0] = crypt[0] ^ crypt[1];
  connid[1] = crypt[2] ^ crypt[3];
}

/* BEP 15 packet layouts, as byte offsets into the datagram */
enum {
  /* Every request starts alike */
  UDP_REQUEST_CONNECTION_ID_OFFSET  = 0,
  UDP_REQUEST_ACTION_OFFSET         = 8,
  UDP_REQUEST_TRANSACTION_ID_OFFSET = 12,
  UDP_REQUEST_HEADER_SIZE           = 16,

  UDP_ANNOUNCE_INFO_HASH_OFFSET     = 16,
  UDP_ANNOUNCE_LEFT_OFFSET          = 64, /* 64 bit */
  UDP_ANNOUNCE_EVENT_OFFSET         = 80,
  UDP_ANNOUNCE_NUM_WANT_OFFSET      = 92,
  UDP_ANNOUNCE_PORT_OFFSET          = 96, /* 16 bit */
  UDP_ANNOUNCE_SIZE                 = 98,

  UDP_SCRAPE_INFO_HASH_OFFSET       = 16,

  /* And so does every reply */
  UDP_REPLY_ACTION_OFFSET           = 0,
  UDP_REPLY_TRANSACTION_ID_OFFSET   = 4,
  UDP_REPLY_HEADER_SIZE             = 8
};

enum { UDP_ACTION_CONNECT = 0, UDP_ACTION_ANNOUNCE = 1, UDP_ACTION_SCRAPE = 2, UDP_ACTION_ERROR = 3 };
enum { UDP_EVENT_COMPLETED = 1, UDP_EVENT_STOPPED = 3 };

/* What a client puts where the connection id goes, when it asks for one */
static const uint8_t g_udp_protocol_id[8] = {0x00, 0x00, 0x04, 0x17, 0x27, 0x10, 0x19, 0x80};

static uint32_t udp_read32(const char *packet, size_t offset) {
  uint32_t value;
  memcpy(&value, packet + offset, sizeof(value));
  return ntohl(value);
}

/* Returns where the rest of the reply goes */
static char *udp_reply_header(char *reply, uint32_t action, const char *request) {
  action = htonl(action);
  memcpy(reply + UDP_REPLY_ACTION_OFFSET, &action, sizeof(action));
  memcpy(reply + UDP_REPLY_TRANSACTION_ID_OFFSET, request + UDP_REQUEST_TRANSACTION_ID_OFFSET, sizeof(uint32_t));
  return reply + UDP_REPLY_HEADER_SIZE;
}

static void udp_send_error(int64_t serversocket, struct ot_workstruct *ws, const char *message, const ot_ip6 remoteip, uint16_t remoteport) {
  size_t size  = strlen(message) + 1;
  char  *reply = udp_reply_header(ws->outbuf, UDP_ACTION_ERROR, ws->inbuf);

  memcpy(reply, message, size);
  ws->reply_size = UDP_REPLY_HEADER_SIZE + size;
  socket_send(serversocket, ws->outbuf, ws->reply_size, remoteip, remoteport);
}

/* UDP implementation according to http://xbtt.sourceforge.net/udp_tracker_protocol.html */
int handle_udp6(int64_t serversocket, struct ot_workstruct *ws) {
  ot_ip6      remoteip;
  const char *request = ws->inbuf;
  char       *reply;
  uint32_t    left, event, numwant;
  uint32_t    connid[2];
  uint32_t    action;
  uint16_t    port, remoteport;
  size_t      byte_count, scrape_count, max_peers, i;
  ot_hash    *hashes;

  ssize_t     result = socket_recv(serversocket, ws->inbuf, G_INBUF_SIZE, remoteip, &remoteport);
  if (result <= 0)
    return 0;
  byte_count = (size_t)result;

  stats_issue_event(ws, EVENT_ACCEPT, FLAG_UDP, (uintptr_t)remoteip);
  stats_issue_event(ws, EVENT_READ, FLAG_UDP, byte_count);

  /* Minimum udp tracker packet size, also catches error */
  if (byte_count < UDP_REQUEST_HEADER_SIZE)
    return 1;

  /* Get action to take. Ignore error messages and broken packets */
  action = udp_read32(request, UDP_REQUEST_ACTION_OFFSET);
  if (action > UDP_ACTION_SCRAPE)
    return 1;

  /* Generate the connection id we give out and expect to and from
     the requesting ip address, this prevents udp spoofing */
  udp_make_connectionid(connid, remoteip, 0);

  /* Initialise hash pointer */
  ws->hash    = NULL;
  ws->peer_id = NULL;

  /* If action is not connect, then we expect the derived
     connection id in first 64 bit */
  if (action != UDP_ACTION_CONNECT && memcmp(request + UDP_REQUEST_CONNECTION_ID_OFFSET, connid, sizeof(connid))) {
    /* If connection id does not match, try the one that was
       valid in the previous hour. Only if this also does not
       match, return an error packet */
    udp_make_connectionid(connid, remoteip, 1);
    if (memcmp(request + UDP_REQUEST_CONNECTION_ID_OFFSET, connid, sizeof(connid))) {
      udp_send_error(serversocket, ws, "Connection ID missmatch.", remoteip, remoteport);
      stats_issue_event(ws, EVENT_CONNID_MISSMATCH, FLAG_UDP, ws->reply_size);
      return 1;
    }
  }

  switch (action) {
  case UDP_ACTION_CONNECT:
    if (memcmp(request + UDP_REQUEST_CONNECTION_ID_OFFSET, g_udp_protocol_id, sizeof(g_udp_protocol_id)))
      return 1;

    reply  = udp_reply_header(ws->outbuf, UDP_ACTION_CONNECT, request);
    memcpy(reply, connid, sizeof(connid));
    reply += sizeof(connid);

    socket_send(serversocket, ws->outbuf, reply - ws->outbuf, remoteip, remoteport);
    stats_issue_event(ws, EVENT_CONNECT, FLAG_UDP, reply - ws->outbuf);
    break;

  case UDP_ACTION_ANNOUNCE:
    if (byte_count < UDP_ANNOUNCE_SIZE)
      return 1;

    /* We do only want to know, if it is zero */
    left     = udp_read32(request, UDP_ANNOUNCE_LEFT_OFFSET) | udp_read32(request, UDP_ANNOUNCE_LEFT_OFFSET + sizeof(uint32_t));
    event    = udp_read32(request, UDP_ANNOUNCE_EVENT_OFFSET);
    numwant  = udp_read32(request, UDP_ANNOUNCE_NUM_WANT_OFFSET);
    ws->hash = (ot_hash *)(ws->inbuf + UDP_ANNOUNCE_INFO_HASH_OFFSET);

    /* The peer keeps its port the way it came over the wire */
    memcpy(&port, request + UDP_ANNOUNCE_PORT_OFFSET, sizeof(port));

    OT_SETIP(ws->peer, remoteip);
    OT_SETPORT(ws->peer, &port);
    OT_PEERFLAG(ws->peer) = 0;

    if (event == UDP_EVENT_COMPLETED)
      OT_PEERFLAG(ws->peer) |= PEER_FLAG_COMPLETED;
    if (event == UDP_EVENT_STOPPED)
      OT_PEERFLAG(ws->peer) |= PEER_FLAG_STOPPED;
    if (!left)
      OT_PEERFLAG(ws->peer) |= PEER_FLAG_SEEDING;

    reply = udp_reply_header(ws->outbuf, UDP_ACTION_ANNOUNCE, request);

    if (OT_PEERFLAG(ws->peer) & PEER_FLAG_STOPPED) { /* Peer is gone. */
      /* This one writes the whole reply, and leaves the header alone */
      ws->reply      = ws->outbuf;
      ws->reply_size = remove_peer_from_torrent(FLAG_UDP, ws);
    } else {
      /* List of peers should fit in a single UDP packet */
      max_peers = ip_is_v4mapped(remoteip) ? OT_MAX_PEERS_UDP4 : OT_MAX_PEERS_UDP6;
      if (numwant > max_peers)
        numwant = max_peers;

      ws->reply      = reply;
      ws->reply_size = add_peer_to_torrent_and_return_peers(FLAG_UDP, ws, numwant);

      /* The announce path answers a refusal itself, so nothing is left here
         but a tracker that could not get the memory to track the torrent */
      if (!ws->reply_size) {
        udp_send_error(serversocket, ws, "Tracker is out of resources, try again later.", remoteip, remoteport);
        return 1;
      }
      ws->reply_size += UDP_REPLY_HEADER_SIZE;
    }

    socket_send(serversocket, ws->outbuf, ws->reply_size, remoteip, remoteport);
    stats_issue_event(ws, EVENT_ANNOUNCE, FLAG_UDP, ws->reply_size);
    break;

  case UDP_ACTION_SCRAPE:
    scrape_count = (byte_count - UDP_SCRAPE_INFO_HASH_OFFSET) / sizeof(ot_hash);
    if (scrape_count > OT_MAX_SCRAPE_UDP)
      scrape_count = OT_MAX_SCRAPE_UDP;

    hashes = (ot_hash *)(ws->inbuf + UDP_SCRAPE_INFO_HASH_OFFSET);
    reply  = udp_reply_header(ws->outbuf, UDP_ACTION_SCRAPE, request);
    for (i = 0; i < scrape_count; ++i)
      reply += return_udp_scrape_for_torrent(hashes[i], reply);

    socket_send(serversocket, ws->outbuf, reply - ws->outbuf, remoteip, remoteport);
    stats_issue_event(ws, EVENT_SCRAPE, FLAG_UDP, scrape_count);
    break;
  }
  return 1;
}

static void udp_run(struct ot_worker *me) {
  while (g_opentracker_running)
    handle_udp6(me->sock, &me->ws);
}

void udp_init(void) {
  if (!g_rijndael_round_key[0])
    udp_generate_rijndael_round_key();
}

void udp_worker_install(int64_t sock) {
#ifdef _DEBUG
  fprintf(stderr, "Installing a worker on udp socket %ld\n", (unsigned long)sock);
#endif
  socket_set_blocking((int)sock, 1);

  if (worker_start(udp_run, sock) == -1)
    fprintf(stderr, "Warning: could not install a udp worker, this socket stays with the workers already running.\n");
}