tor-resolve.c 9.78 KB
Newer Older
Nick Mathewson's avatar
Nick Mathewson committed
1
/* Copyright 2004-2005 Roger Dingledine, Nick Mathewson */
2
3
4
5
6
/* See LICENSE for licensing information */
/* $Id$ */

#include "orconfig.h"

7
#include "../common/compat.h"
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
#include "../common/util.h"
#include "../common/log.h"

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <assert.h>

#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h> /* Must be included before sys/stat.h for Ultrix */
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif

#ifdef MS_WINDOWS
34
#if defined(_MSC_VER) && (_MSC_VER <= 1300)
35
36
37
38
39
40
41
#include <winsock.h>
#else
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
#endif

42
#define RESPONSE_LEN_4 8
43
#define log_sock_error(act, _s)                                         \
44
45
  STMT_BEGIN log_fn(LOG_ERR, LD_NET, "Error while %s: %s", act,         \
              tor_socket_strerror(tor_socket_errno(_s))); STMT_END
46

47
48
static void usage(void) ATTR_NORETURN;

Roger Dingledine's avatar
Roger Dingledine committed
49
50
51
/** Set *<b>out</b> to a newly allocated SOCKS4a resolve request with
 * <b>username</b> and <b>hostname</b> as provided.  Return the number
 * of bytes in the request. */
52
static int
53
54
55
56
57
build_socks_resolve_request(char **out,
                            const char *username,
                            const char *hostname,
                            int reverse,
                            int version)
58
{
59
  size_t len = 0;
60
61
62
63
  tor_assert(out);
  tor_assert(username);
  tor_assert(hostname);

64
65
66
67
68
69
70
  if (version == 4) {
    len = 8 + strlen(username) + 1 + strlen(hostname) + 1;
    *out = tor_malloc(len);
    (*out)[0] = 4;      /* SOCKS version 4 */
    (*out)[1] = '\xF0'; /* Command: resolve. */
    set_uint16((*out)+2, htons(0)); /* port: 0. */
    set_uint32((*out)+4, htonl(0x00000001u)); /* addr: 0.0.0.1 */
71
72
    memcpy((*out)+8, username, strlen(username)+1);
    memcpy((*out)+8+strlen(username)+1, hostname, strlen(hostname)+1);
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
  } else if (version == 5) {
    int is_ip_address;
    struct in_addr in;
    size_t addrlen;
    is_ip_address = tor_inet_aton(hostname, &in);
    if (!is_ip_address && reverse) {
      log_err(LD_GENERAL, "Tried to do a reverse lookup on a non-IP!");
      return -1;
    }
    addrlen = is_ip_address ? 4 : 1 + strlen(hostname);
    len = 6 + addrlen;
    *out = tor_malloc(len);
    (*out)[0] = 5; /* SOCKS version 5 */
    (*out)[1] = reverse ? '\xF1' : '\xF0'; /* RESOLVE_PTR or RESOLVE */
    (*out)[2] = 0; /* reserved. */
    (*out)[3] = is_ip_address ? 1 : 3;
    if (is_ip_address) {
90
      set_uint32((*out)+4, in.s_addr);
91
92
93
94
95
96
97
98
    } else {
      (*out)[4] = (char)(uint8_t)(addrlen - 1);
      memcpy((*out)+5, hostname, addrlen - 1);
    }
    set_uint16((*out)+4+addrlen, 0); /* port */
  } else {
    tor_assert(0);
  }
99
100
101
102

  return len;
}

Roger Dingledine's avatar
Roger Dingledine committed
103
104
105
/** Given a <b>len</b>-byte SOCKS4a response in <b>response</b>, set
 * *<b>addr_out</b> to the address it contains (in host order).
 * Return 0 on success, -1 on error.
106
 */
107
static int
108
parse_socks4a_resolve_response(const char *response, size_t len,
109
                               uint32_t *addr_out)
110
111
112
113
114
{
  uint8_t status;
  tor_assert(response);
  tor_assert(addr_out);

115
  if (len < RESPONSE_LEN_4) {
116
    log_warn(LD_PROTOCOL,"Truncated socks response.");
117
    return -1;
118
119
  }
  if (((uint8_t)response[0])!=0) { /* version: 0 */
120
    log_warn(LD_PROTOCOL,"Nonzero version in socks response: bad format.");
121
    return -1;
122
  }
123
  status = (uint8_t)response[1];
124
  if (get_uint16(response+2)!=0) { /* port: 0 */
125
    log_warn(LD_PROTOCOL,"Nonzero port in socks response: bad format.");
126
    return -1;
127
  }
128
  if (status != 90) {
129
    log_warn(LD_NET,"Got status response '%d': socks request failed.", status);
130
    return -1;
131
  }
132
133
134
135
136

  *addr_out = ntohl(get_uint32(response+4));
  return 0;
}

137
138
/** Send a resolve request for <b>hostname</b> to the Tor listening on
 * <b>sockshost</b>:<b>socksport</b>.  Store the resulting IPv4
Roger Dingledine's avatar
Roger Dingledine committed
139
 * address (in host order) into *<b>result_addr</b>.
140
 */
141
static int
142
do_resolve(const char *hostname, uint32_t sockshost, uint16_t socksport,
143
144
           int reverse, int version,
           uint32_t *result_addr, char **result_hostname)
145
146
147
{
  int s;
  struct sockaddr_in socksaddr;
148
149
  char *req = NULL;
  int len = 0;
150
151
152

  tor_assert(hostname);
  tor_assert(result_addr);
153
154
155
156
  tor_assert(version == 4 || version == 5);

  *result_addr = 0;
  *result_hostname = NULL;
157

158
  s = tor_open_socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
159
160
161
162
163
164
165
166
167
168
169
170
171
172
  if (s<0) {
    log_sock_error("creating_socket", -1);
    return -1;
  }

  memset(&socksaddr, 0, sizeof(socksaddr));
  socksaddr.sin_family = AF_INET;
  socksaddr.sin_port = htons(socksport);
  socksaddr.sin_addr.s_addr = htonl(sockshost);
  if (connect(s, (struct sockaddr*)&socksaddr, sizeof(socksaddr))) {
    log_sock_error("connecting to SOCKS host", s);
    return -1;
  }

173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
  if (version == 5) {
    char method_buf[2];
    if (write_all(s, "\x05\x01\x00", 3, 1) != 3) {
      log_err(LD_NET, "Error sending SOCKS5 method list.");
      return -1;
    }
    if (read_all(s, method_buf, 2, 1) != 2) {
      log_err(LD_NET, "Error reading SOCKS5 methods.");
      return -1;
    }
    if (method_buf[0] != '\x05') {
      log_err(LD_NET, "Unrecognized socks version: %u",
              (unsigned)method_buf[0]);
      return -1;
    }
    if (method_buf[1] != '\x00') {
      log_err(LD_NET, "Unrecognized socks authentication method: %u",
              (unsigned)method_buf[1]);
      return -1;
    }
  }

  if ((len = build_socks_resolve_request(&req, "", hostname, reverse,
                                         version))<0) {
197
    log_err(LD_BUG,"Error generating SOCKS request");
198
199
    return -1;
  }
200
201
202
203
  if (write_all(s, req, len, 1) != len) {
    log_sock_error("sending SOCKS request", s);
    tor_free(req);
    return -1;
204
205
206
  }
  tor_free(req);

207
208
209
210
  if (version == 4) {
    char reply_buf[RESPONSE_LEN_4];
    if (read_all(s, reply_buf, RESPONSE_LEN_4, 1) != RESPONSE_LEN_4) {
      log_err(LD_NET, "Error reading SOCKS4 response.");
211
212
      return -1;
    }
213
214
    if (parse_socks4a_resolve_response(reply_buf, RESPONSE_LEN_4,
                                       result_addr)<0){
215
216
      return -1;
    }
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
  } else {
    char reply_buf[4];
    if (read_all(s, reply_buf, 4, 1) != 4) {
      log_err(LD_NET, "Error reading SOCKS5 response.");
      return -1;
    }
    if (reply_buf[0] != 5) {
      log_err(LD_NET, "Bad SOCKS5 reply version.");
      return -1;
    }
    if (reply_buf[1] != 0) {
      log_warn(LD_NET,"Got status response '%u': SOCKS5 request failed.",
               (unsigned)reply_buf[1]);
      return -1;
    }
    if (reply_buf[3] == 1) {
      /* IPv4 address */
      if (read_all(s, reply_buf, 4, 1) != 4) {
        log_err(LD_NET, "Error reading address in socks5 response.");
        return -1;
      }
      *result_addr = ntohl(get_uint32(reply_buf));
    } else if (reply_buf[3] == 3) {
240
      size_t result_len;
241
242
243
244
      if (read_all(s, reply_buf, 1, 1) != 1) {
        log_err(LD_NET, "Error reading address_length in socks5 response.");
        return -1;
      }
245
246
247
      result_len = *(uint8_t*)(reply_buf);
      *result_hostname = tor_malloc(result_len+1);
      if (read_all(s, *result_hostname, result_len, 1) != (int) result_len) {
248
249
250
        log_err(LD_NET, "Error reading hostname in socks5 response.");
        return -1;
      }
251
      (*result_hostname)[result_len] = '\0';
252
    }
253
254
255
256
257
  }

  return 0;
}

258
/** Print a usage message and exit. */
259
static void
260
usage(void)
261
{
262
263
  puts("Syntax: tor-resolve [-4] [-v] [-x] [-F] "
       "hostname [sockshost:socksport]");
264
265
266
  exit(1);
}

267
/** Entry point to tor-resolve */
268
269
270
271
272
int
main(int argc, char **argv)
{
  uint32_t sockshost;
  uint16_t socksport;
273
  int isSocks4 = 0, isVerbose = 0, isReverse = 0, force = 0;
274
275
276
  char **arg;
  int n_args;
  struct in_addr a;
277
278
  uint32_t result = 0;
  char *result_hostname = NULL;
279
  char buf[INET_NTOA_BUF_LEN];
280
281
282
283

  arg = &argv[1];
  n_args = argc-1;

Roger Dingledine's avatar
Roger Dingledine committed
284
  if (!n_args)
285
286
    usage();

287
288
289
290
  if (!strcmp(arg[0],"--version")) {
    printf("Tor version %s.\n",VERSION);
    return 0;
  }
291
292
293
294
295
296
297
298
299
  while (n_args && *arg[0] == '-') {
    if (!strcmp("-v", arg[0]))
      isVerbose = 1;
    else if (!strcmp("-4", arg[0]))
      isSocks4 = 1;
    else if (!strcmp("-5", arg[0]))
      isSocks4 = 0;
    else if (!strcmp("-x", arg[0]))
      isReverse = 1;
300
301
    else if (!strcmp("-F", arg[0]))
      force = 1;
302
303
304
305
306
307
308
    else {
      fprintf(stderr, "Unrecognized flag '%s'\n", arg[0]);
      usage();
    }
    ++arg;
    --n_args;
  }
309

310
311
312
313
314
315
  if (isSocks4 && isReverse) {
    fprintf(stderr, "Reverse lookups not supported with SOCKS4a\n");
    usage();
  }

  if (isVerbose) {
316
317
318
319
320
    add_stream_log(LOG_DEBUG, LOG_ERR, "<stderr>", stderr);
  } else {
    add_stream_log(LOG_WARN, LOG_ERR, "<stderr>", stderr);
  }
  if (n_args == 1) {
321
    log_debug(LD_CONFIG, "defaulting to localhost:9050");
322
323
324
    sockshost = 0x7f000001u; /* localhost */
    socksport = 9050; /* 9050 */
  } else if (n_args == 2) {
325
    if (parse_addr_port(LOG_WARN, arg[1], NULL, &sockshost, &socksport)<0) {
326
327
328
329
      fprintf(stderr, "Couldn't parse/resolve address %s", arg[1]);
      return 1;
    }
    if (socksport == 0) {
330
      log_debug(LD_CONFIG, "defaulting to port 9050");
331
332
333
334
335
336
      socksport = 9050;
    }
  } else {
    usage();
  }

337
  if (!strcasecmpend(arg[0], ".onion") && !force) {
338
339
340
341
    fprintf(stderr,
       "%s is a hidden service; those don't have IP addresses.\n\n"
       "To connect to a hidden service, you need to send the hostname\n"
       "to Tor; we suggest an application that uses SOCKS 4a.\n", arg[0]);
342
343
344
    return 1;
  }

345
  if (network_init()<0) {
346
    log_err(LD_BUG,"Error initializing network; exiting.");
347
    return 1;
348
349
  }

350
351
352
  if (do_resolve(arg[0], sockshost, socksport, isReverse,
                 isSocks4 ? 4 : 5, &result,
                 &result_hostname))
353
354
    return 1;

355
356
357
358
359
360
361
  if (result_hostname) {
    printf("%s\n", result_hostname);
  } else {
    a.s_addr = htonl(result);
    tor_inet_ntoa(&a, buf, sizeof(buf));
    printf("%s\n", buf);
  }
362
363
  return 0;
}
Roger Dingledine's avatar
Roger Dingledine committed
364