1 /*
2  * Network proxy abstraction in PuTTY
3  *
4  * A proxy layer, if necessary, wedges itself between the network
5  * code and the higher level backend.
6  */
7 
8 #include <assert.h>
9 #include <ctype.h>
10 #include <string.h>
11 
12 #include "putty.h"
13 #include "network.h"
14 #include "proxy.h"
15 
16 #define do_proxy_dns(conf) \
17     (conf_get_int(conf, CONF_proxy_dns) == FORCE_ON || \
18          (conf_get_int(conf, CONF_proxy_dns) == AUTO && \
19               conf_get_int(conf, CONF_proxy_type) != PROXY_SOCKS4))
20 
21 /*
22  * Call this when proxy negotiation is complete, so that this
23  * socket can begin working normally.
24  */
proxy_activate(ProxySocket * p)25 void proxy_activate (ProxySocket *p)
26 {
27     size_t output_before, output_after;
28 
29     p->state = PROXY_STATE_ACTIVE;
30 
31     /* we want to ignore new receive events until we have sent
32      * all of our buffered receive data.
33      */
34     sk_set_frozen(p->sub_socket, true);
35 
36     /* how many bytes of output have we buffered? */
37     output_before = bufchain_size(&p->pending_oob_output_data) +
38         bufchain_size(&p->pending_output_data);
39     /* and keep track of how many bytes do not get sent. */
40     output_after = 0;
41 
42     /* send buffered OOB writes */
43     while (bufchain_size(&p->pending_oob_output_data) > 0) {
44         ptrlen data = bufchain_prefix(&p->pending_oob_output_data);
45         output_after += sk_write_oob(p->sub_socket, data.ptr, data.len);
46         bufchain_consume(&p->pending_oob_output_data, data.len);
47     }
48 
49     /* send buffered normal writes */
50     while (bufchain_size(&p->pending_output_data) > 0) {
51         ptrlen data = bufchain_prefix(&p->pending_output_data);
52         output_after += sk_write(p->sub_socket, data.ptr, data.len);
53         bufchain_consume(&p->pending_output_data, data.len);
54     }
55 
56     /* if we managed to send any data, let the higher levels know. */
57     if (output_after < output_before)
58         plug_sent(p->plug, output_after);
59 
60     /* if we have a pending EOF to send, send it */
61     if (p->pending_eof) sk_write_eof(p->sub_socket);
62 
63     /* if the backend wanted the socket unfrozen, try to unfreeze.
64      * our set_frozen handler will flush buffered receive data before
65      * unfreezing the actual underlying socket.
66      */
67     if (!p->freeze)
68         sk_set_frozen(&p->sock, false);
69 }
70 
71 /* basic proxy socket functions */
72 
sk_proxy_plug(Socket * s,Plug * p)73 static Plug *sk_proxy_plug (Socket *s, Plug *p)
74 {
75     ProxySocket *ps = container_of(s, ProxySocket, sock);
76     Plug *ret = ps->plug;
77     if (p)
78         ps->plug = p;
79     return ret;
80 }
81 
sk_proxy_close(Socket * s)82 static void sk_proxy_close (Socket *s)
83 {
84     ProxySocket *ps = container_of(s, ProxySocket, sock);
85 
86     sk_close(ps->sub_socket);
87     sk_addr_free(ps->remote_addr);
88     sfree(ps);
89 }
90 
sk_proxy_write(Socket * s,const void * data,size_t len)91 static size_t sk_proxy_write (Socket *s, const void *data, size_t len)
92 {
93     ProxySocket *ps = container_of(s, ProxySocket, sock);
94 
95     if (ps->state != PROXY_STATE_ACTIVE) {
96         bufchain_add(&ps->pending_output_data, data, len);
97         return bufchain_size(&ps->pending_output_data);
98     }
99     return sk_write(ps->sub_socket, data, len);
100 }
101 
sk_proxy_write_oob(Socket * s,const void * data,size_t len)102 static size_t sk_proxy_write_oob (Socket *s, const void *data, size_t len)
103 {
104     ProxySocket *ps = container_of(s, ProxySocket, sock);
105 
106     if (ps->state != PROXY_STATE_ACTIVE) {
107         bufchain_clear(&ps->pending_output_data);
108         bufchain_clear(&ps->pending_oob_output_data);
109         bufchain_add(&ps->pending_oob_output_data, data, len);
110         return len;
111     }
112     return sk_write_oob(ps->sub_socket, data, len);
113 }
114 
sk_proxy_write_eof(Socket * s)115 static void sk_proxy_write_eof (Socket *s)
116 {
117     ProxySocket *ps = container_of(s, ProxySocket, sock);
118 
119     if (ps->state != PROXY_STATE_ACTIVE) {
120         ps->pending_eof = true;
121         return;
122     }
123     sk_write_eof(ps->sub_socket);
124 }
125 
sk_proxy_set_frozen(Socket * s,bool is_frozen)126 static void sk_proxy_set_frozen (Socket *s, bool is_frozen)
127 {
128     ProxySocket *ps = container_of(s, ProxySocket, sock);
129 
130     if (ps->state != PROXY_STATE_ACTIVE) {
131         ps->freeze = is_frozen;
132         return;
133     }
134 
135     /* handle any remaining buffered recv data first */
136     if (bufchain_size(&ps->pending_input_data) > 0) {
137         ps->freeze = is_frozen;
138 
139         /* loop while we still have buffered data, and while we are
140          * unfrozen. the plug_receive call in the loop could result
141          * in a call back into this function refreezing the socket,
142          * so we have to check each time.
143          */
144         while (!ps->freeze && bufchain_size(&ps->pending_input_data) > 0) {
145             char databuf[512];
146             ptrlen data = bufchain_prefix(&ps->pending_input_data);
147             if (data.len > lenof(databuf))
148                 data.len = lenof(databuf);
149             memcpy(databuf, data.ptr, data.len);
150             bufchain_consume(&ps->pending_input_data, data.len);
151             plug_receive(ps->plug, 0, databuf, data.len);
152         }
153 
154         /* if we're still frozen, we'll have to wait for another
155          * call from the backend to finish unbuffering the data.
156          */
157         if (ps->freeze) return;
158     }
159 
160     sk_set_frozen(ps->sub_socket, is_frozen);
161 }
162 
sk_proxy_socket_error(Socket * s)163 static const char * sk_proxy_socket_error (Socket *s)
164 {
165     ProxySocket *ps = container_of(s, ProxySocket, sock);
166     if (ps->error != NULL || ps->sub_socket == NULL) {
167         return ps->error;
168     }
169     return sk_socket_error(ps->sub_socket);
170 }
171 
172 /* basic proxy plug functions */
173 
plug_proxy_log(Plug * plug,PlugLogType type,SockAddr * addr,int port,const char * error_msg,int error_code)174 static void plug_proxy_log(Plug *plug, PlugLogType type, SockAddr *addr,
175                            int port, const char *error_msg, int error_code)
176 {
177     ProxySocket *ps = container_of(plug, ProxySocket, plugimpl);
178 
179     plug_log(ps->plug, type, addr, port, error_msg, error_code);
180 }
181 
plug_proxy_closing(Plug * p,const char * error_msg,int error_code,bool calling_back)182 static void plug_proxy_closing (Plug *p, const char *error_msg,
183                                 int error_code, bool calling_back)
184 {
185     ProxySocket *ps = container_of(p, ProxySocket, plugimpl);
186 
187     if (ps->state != PROXY_STATE_ACTIVE) {
188         ps->closing_error_msg = error_msg;
189         ps->closing_error_code = error_code;
190         ps->closing_calling_back = calling_back;
191         ps->negotiate(ps, PROXY_CHANGE_CLOSING);
192     } else {
193         plug_closing(ps->plug, error_msg, error_code, calling_back);
194     }
195 }
196 
plug_proxy_receive(Plug * p,int urgent,const char * data,size_t len)197 static void plug_proxy_receive(
198     Plug *p, int urgent, const char *data, size_t len)
199 {
200     ProxySocket *ps = container_of(p, ProxySocket, plugimpl);
201 
202     if (ps->state != PROXY_STATE_ACTIVE) {
203         /* we will lose the urgentness of this data, but since most,
204          * if not all, of this data will be consumed by the negotiation
205          * process, hopefully it won't affect the protocol above us
206          */
207         bufchain_add(&ps->pending_input_data, data, len);
208         ps->receive_urgent = (urgent != 0);
209         ps->receive_data = data;
210         ps->receive_len = len;
211         ps->negotiate(ps, PROXY_CHANGE_RECEIVE);
212     } else {
213         plug_receive(ps->plug, urgent, data, len);
214     }
215 }
216 
plug_proxy_sent(Plug * p,size_t bufsize)217 static void plug_proxy_sent (Plug *p, size_t bufsize)
218 {
219     ProxySocket *ps = container_of(p, ProxySocket, plugimpl);
220 
221     if (ps->state != PROXY_STATE_ACTIVE) {
222         ps->negotiate(ps, PROXY_CHANGE_SENT);
223         return;
224     }
225     plug_sent(ps->plug, bufsize);
226 }
227 
plug_proxy_accepting(Plug * p,accept_fn_t constructor,accept_ctx_t ctx)228 static int plug_proxy_accepting(Plug *p,
229                                 accept_fn_t constructor, accept_ctx_t ctx)
230 {
231     ProxySocket *ps = container_of(p, ProxySocket, plugimpl);
232 
233     if (ps->state != PROXY_STATE_ACTIVE) {
234         ps->accepting_constructor = constructor;
235         ps->accepting_ctx = ctx;
236         return ps->negotiate(ps, PROXY_CHANGE_ACCEPTING);
237     }
238     return plug_accepting(ps->plug, constructor, ctx);
239 }
240 
241 /*
242  * This function can accept a NULL pointer as `addr', in which case
243  * it will only check the host name.
244  */
proxy_for_destination(SockAddr * addr,const char * hostname,int port,Conf * conf)245 static bool proxy_for_destination(SockAddr *addr, const char *hostname,
246                                   int port, Conf *conf)
247 {
248     int s = 0, e = 0;
249     char hostip[64];
250     int hostip_len, hostname_len;
251     const char *exclude_list;
252 
253     /*
254      * Special local connections such as Unix-domain sockets
255      * unconditionally cannot be proxied, even in proxy-localhost
256      * mode. There just isn't any way to ask any known proxy type for
257      * them.
258      */
259     if (addr && sk_address_is_special_local(addr))
260         return false;                  /* do not proxy */
261 
262     /*
263      * Check the host name and IP against the hard-coded
264      * representations of `localhost'.
265      */
266     if (!conf_get_bool(conf, CONF_even_proxy_localhost) &&
267         (sk_hostname_is_local(hostname) ||
268          (addr && sk_address_is_local(addr))))
269         return false;                  /* do not proxy */
270 
271     /* we want a string representation of the IP address for comparisons */
272     if (addr) {
273         sk_getaddr(addr, hostip, 64);
274         hostip_len = strlen(hostip);
275     } else
276         hostip_len = 0;                /* placate gcc; shouldn't be required */
277 
278     hostname_len = strlen(hostname);
279 
280     exclude_list = conf_get_str(conf, CONF_proxy_exclude_list);
281 
282     /* now parse the exclude list, and see if either our IP
283      * or hostname matches anything in it.
284      */
285 
286     while (exclude_list[s]) {
287         while (exclude_list[s] &&
288                (isspace((unsigned char)exclude_list[s]) ||
289                 exclude_list[s] == ',')) s++;
290 
291         if (!exclude_list[s]) break;
292 
293         e = s;
294 
295         while (exclude_list[e] &&
296                (isalnum((unsigned char)exclude_list[e]) ||
297                 exclude_list[e] == '-' ||
298                 exclude_list[e] == '.' ||
299                 exclude_list[e] == '*')) e++;
300 
301         if (exclude_list[s] == '*') {
302             /* wildcard at beginning of entry */
303 
304             if ((addr && strnicmp(hostip + hostip_len - (e - s - 1),
305                                   exclude_list + s + 1, e - s - 1) == 0) ||
306                 strnicmp(hostname + hostname_len - (e - s - 1),
307                          exclude_list + s + 1, e - s - 1) == 0) {
308                 /* IP/hostname range excluded. do not use proxy. */
309                 return false;
310             }
311         } else if (exclude_list[e-1] == '*') {
312             /* wildcard at end of entry */
313 
314             if ((addr && strnicmp(hostip, exclude_list + s, e - s - 1) == 0) ||
315                 strnicmp(hostname, exclude_list + s, e - s - 1) == 0) {
316                 /* IP/hostname range excluded. do not use proxy. */
317                 return false;
318             }
319         } else {
320             /* no wildcard at either end, so let's try an absolute
321              * match (ie. a specific IP)
322              */
323 
324             if (addr && strnicmp(hostip, exclude_list + s, e - s) == 0)
325                 return false; /* IP/hostname excluded. do not use proxy. */
326             if (strnicmp(hostname, exclude_list + s, e - s) == 0)
327                 return false; /* IP/hostname excluded. do not use proxy. */
328         }
329 
330         s = e;
331 
332         /* Make sure we really have reached the next comma or end-of-string */
333         while (exclude_list[s] &&
334                !isspace((unsigned char)exclude_list[s]) &&
335                exclude_list[s] != ',') s++;
336     }
337 
338     /* no matches in the exclude list, so use the proxy */
339     return true;
340 }
341 
dns_log_msg(const char * host,int addressfamily,const char * reason)342 static char *dns_log_msg(const char *host, int addressfamily,
343                          const char *reason)
344 {
345     return dupprintf("Looking up host \"%s\"%s for %s", host,
346                      (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
347                       addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" :
348                       ""), reason);
349 }
350 
name_lookup(const char * host,int port,char ** canonicalname,Conf * conf,int addressfamily,LogContext * logctx,const char * reason)351 SockAddr *name_lookup(const char *host, int port, char **canonicalname,
352                      Conf *conf, int addressfamily, LogContext *logctx,
353                      const char *reason)
354 {
355     if (conf_get_int(conf, CONF_proxy_type) != PROXY_NONE &&
356         do_proxy_dns(conf) &&
357         proxy_for_destination(NULL, host, port, conf)) {
358 
359         if (logctx)
360             logeventf(logctx, "Leaving host lookup to proxy of \"%s\""
361                       " (for %s)", host, reason);
362 
363         *canonicalname = dupstr(host);
364         return sk_nonamelookup(host);
365     } else {
366         if (logctx)
367             logevent_and_free(
368                 logctx, dns_log_msg(host, addressfamily, reason));
369 
370         return sk_namelookup(host, canonicalname, addressfamily);
371     }
372 }
373 
374 static const SocketVtable ProxySocket_sockvt = {
375     .plug = sk_proxy_plug,
376     .close = sk_proxy_close,
377     .write = sk_proxy_write,
378     .write_oob = sk_proxy_write_oob,
379     .write_eof = sk_proxy_write_eof,
380     .set_frozen = sk_proxy_set_frozen,
381     .socket_error = sk_proxy_socket_error,
382     .peer_info = NULL,
383 };
384 
385 static const PlugVtable ProxySocket_plugvt = {
386     .log = plug_proxy_log,
387     .closing = plug_proxy_closing,
388     .receive = plug_proxy_receive,
389     .sent = plug_proxy_sent,
390     .accepting = plug_proxy_accepting
391 };
392 
new_connection(SockAddr * addr,const char * hostname,int port,bool privport,bool oobinline,bool nodelay,bool keepalive,Plug * plug,Conf * conf)393 Socket *new_connection(SockAddr *addr, const char *hostname,
394                        int port, bool privport,
395                        bool oobinline, bool nodelay, bool keepalive,
396                        Plug *plug, Conf *conf)
397 {
398     if (conf_get_int(conf, CONF_proxy_type) != PROXY_NONE &&
399         proxy_for_destination(addr, hostname, port, conf))
400     {
401         ProxySocket *ret;
402         SockAddr *proxy_addr;
403         char *proxy_canonical_name;
404         const char *proxy_type;
405         Socket *sret;
406         int type;
407 
408         if ((sret = platform_new_connection(addr, hostname, port, privport,
409                                             oobinline, nodelay, keepalive,
410                                             plug, conf)) != NULL)
411             return sret;
412 
413         ret = snew(ProxySocket);
414         ret->sock.vt = &ProxySocket_sockvt;
415         ret->plugimpl.vt = &ProxySocket_plugvt;
416         ret->conf = conf_copy(conf);
417         ret->plug = plug;
418         ret->remote_addr = addr;       /* will need to be freed on close */
419         ret->remote_port = port;
420 
421         ret->error = NULL;
422         ret->pending_eof = false;
423         ret->freeze = false;
424 
425         bufchain_init(&ret->pending_input_data);
426         bufchain_init(&ret->pending_output_data);
427         bufchain_init(&ret->pending_oob_output_data);
428 
429         ret->sub_socket = NULL;
430         ret->state = PROXY_STATE_NEW;
431         ret->negotiate = NULL;
432 
433         type = conf_get_int(conf, CONF_proxy_type);
434         if (type == PROXY_HTTP) {
435             ret->negotiate = proxy_http_negotiate;
436             proxy_type = "HTTP";
437         } else if (type == PROXY_SOCKS4) {
438             ret->negotiate = proxy_socks4_negotiate;
439             proxy_type = "SOCKS 4";
440         } else if (type == PROXY_SOCKS5) {
441             ret->negotiate = proxy_socks5_negotiate;
442             proxy_type = "SOCKS 5";
443         } else if (type == PROXY_TELNET) {
444             ret->negotiate = proxy_telnet_negotiate;
445             proxy_type = "Telnet";
446         } else {
447             ret->error = "Proxy error: Unknown proxy method";
448             return &ret->sock;
449         }
450 
451         {
452             char *logmsg = dupprintf("Will use %s proxy at %s:%d to connect"
453                                       " to %s:%d", proxy_type,
454                                       conf_get_str(conf, CONF_proxy_host),
455                                       conf_get_int(conf, CONF_proxy_port),
456                                       hostname, port);
457             plug_log(plug, PLUGLOG_PROXY_MSG, NULL, 0, logmsg, 0);
458             sfree(logmsg);
459         }
460 
461         {
462             char *logmsg = dns_log_msg(conf_get_str(conf, CONF_proxy_host),
463                                        conf_get_int(conf, CONF_addressfamily),
464                                        "proxy");
465             plug_log(plug, PLUGLOG_PROXY_MSG, NULL, 0, logmsg, 0);
466             sfree(logmsg);
467         }
468 
469         /* look-up proxy */
470         proxy_addr = sk_namelookup(conf_get_str(conf, CONF_proxy_host),
471                                    &proxy_canonical_name,
472                                    conf_get_int(conf, CONF_addressfamily));
473         if (sk_addr_error(proxy_addr) != NULL) {
474             ret->error = "Proxy error: Unable to resolve proxy host name";
475             sk_addr_free(proxy_addr);
476             return &ret->sock;
477         }
478         sfree(proxy_canonical_name);
479 
480         {
481             char addrbuf[256], *logmsg;
482             sk_getaddr(proxy_addr, addrbuf, lenof(addrbuf));
483             logmsg = dupprintf("Connecting to %s proxy at %s port %d",
484                                proxy_type, addrbuf,
485                                conf_get_int(conf, CONF_proxy_port));
486             plug_log(plug, PLUGLOG_PROXY_MSG, NULL, 0, logmsg, 0);
487             sfree(logmsg);
488         }
489 
490         /* create the actual socket we will be using,
491          * connected to our proxy server and port.
492          */
493         ret->sub_socket = sk_new(proxy_addr,
494                                  conf_get_int(conf, CONF_proxy_port),
495                                  privport, oobinline,
496                                  nodelay, keepalive, &ret->plugimpl);
497         if (sk_socket_error(ret->sub_socket) != NULL)
498             return &ret->sock;
499 
500         /* start the proxy negotiation process... */
501         sk_set_frozen(ret->sub_socket, false);
502         ret->negotiate(ret, PROXY_CHANGE_NEW);
503 
504         return &ret->sock;
505     }
506 
507     /* no proxy, so just return the direct socket */
508     return sk_new(addr, port, privport, oobinline, nodelay, keepalive, plug);
509 }
510 
new_listener(const char * srcaddr,int port,Plug * plug,bool local_host_only,Conf * conf,int addressfamily)511 Socket *new_listener(const char *srcaddr, int port, Plug *plug,
512                      bool local_host_only, Conf *conf, int addressfamily)
513 {
514     /* TODO: SOCKS (and potentially others) support inbound
515      * TODO: connections via the proxy. support them.
516      */
517 
518     return sk_newlistener(srcaddr, port, plug, local_host_only, addressfamily);
519 }
520 
521 /* ----------------------------------------------------------------------
522  * HTTP CONNECT proxy type.
523  */
524 
get_line_end(char * data,size_t len,size_t * out)525 static bool get_line_end(char *data, size_t len, size_t *out)
526 {
527     size_t off = 0;
528 
529     while (off < len)
530     {
531         if (data[off] == '\n') {
532             /* we have a newline */
533             off++;
534 
535             /* is that the only thing on this line? */
536             if (off <= 2) {
537                 *out = off;
538                 return true;
539             }
540 
541             /* if not, then there is the possibility that this header
542              * continues onto the next line, if it starts with a space
543              * or a tab.
544              */
545 
546             if (off + 1 < len && data[off+1] != ' ' && data[off+1] != '\t') {
547                 *out = off;
548                 return true;
549             }
550 
551             /* the line does continue, so we have to keep going
552              * until we see an the header's "real" end of line.
553              */
554             off++;
555         }
556 
557         off++;
558     }
559 
560     return false;
561 }
562 
proxy_http_negotiate(ProxySocket * p,int change)563 int proxy_http_negotiate (ProxySocket *p, int change)
564 {
565     if (p->state == PROXY_STATE_NEW) {
566         /* we are just beginning the proxy negotiate process,
567          * so we'll send off the initial bits of the request.
568          * for this proxy method, it's just a simple HTTP
569          * request
570          */
571         char *buf, dest[512];
572         char *username, *password;
573 
574         sk_getaddr(p->remote_addr, dest, lenof(dest));
575 
576         buf = dupprintf("CONNECT %s:%i HTTP/1.1\r\nHost: %s:%i\r\n",
577                         dest, p->remote_port, dest, p->remote_port);
578         sk_write(p->sub_socket, buf, strlen(buf));
579         sfree(buf);
580 
581         username = conf_get_str(p->conf, CONF_proxy_username);
582         password = conf_get_str(p->conf, CONF_proxy_password);
583         if (username[0] || password[0]) {
584             char *buf, *buf2;
585             int i, j, len;
586             buf = dupprintf("%s:%s", username, password);
587             len = strlen(buf);
588             buf2 = snewn(len * 4 / 3 + 100, char);
589             sprintf(buf2, "Proxy-Authorization: Basic ");
590             for (i = 0, j = strlen(buf2); i < len; i += 3, j += 4)
591                 base64_encode_atom((unsigned char *)(buf+i),
592                                    (len-i > 3 ? 3 : len-i), buf2+j);
593             strcpy(buf2+j, "\r\n");
594             sk_write(p->sub_socket, buf2, strlen(buf2));
595             sfree(buf);
596             sfree(buf2);
597         }
598 
599         sk_write(p->sub_socket, "\r\n", 2);
600 
601         p->state = 1;
602         return 0;
603     }
604 
605     if (change == PROXY_CHANGE_CLOSING) {
606         /* if our proxy negotiation process involves closing and opening
607          * new sockets, then we would want to intercept this closing
608          * callback when we were expecting it. if we aren't anticipating
609          * a socket close, then some error must have occurred. we'll
610          * just pass those errors up to the backend.
611          */
612         plug_closing(p->plug, p->closing_error_msg, p->closing_error_code,
613                      p->closing_calling_back);
614         return 0; /* ignored */
615     }
616 
617     if (change == PROXY_CHANGE_SENT) {
618         /* some (or all) of what we wrote to the proxy was sent.
619          * we don't do anything new, however, until we receive the
620          * proxy's response. we might want to set a timer so we can
621          * timeout the proxy negotiation after a while...
622          */
623         return 0;
624     }
625 
626     if (change == PROXY_CHANGE_ACCEPTING) {
627         /* we should _never_ see this, as we are using our socket to
628          * connect to a proxy, not accepting inbound connections.
629          * what should we do? close the socket with an appropriate
630          * error message?
631          */
632         return plug_accepting(p->plug,
633                               p->accepting_constructor, p->accepting_ctx);
634     }
635 
636     if (change == PROXY_CHANGE_RECEIVE) {
637         /* we have received data from the underlying socket, which
638          * we'll need to parse, process, and respond to appropriately.
639          */
640 
641         char *data, *datap;
642         size_t len, eol;
643 
644         if (p->state == 1) {
645 
646             int min_ver, maj_ver, status;
647 
648             /* get the status line */
649             len = bufchain_size(&p->pending_input_data);
650             assert(len > 0);           /* or we wouldn't be here */
651             data = snewn(len+1, char);
652             bufchain_fetch(&p->pending_input_data, data, len);
653             /*
654              * We must NUL-terminate this data, because Windows
655              * sscanf appears to require a NUL at the end of the
656              * string because it strlens it _first_. Sigh.
657              */
658             data[len] = '\0';
659 
660             if (!get_line_end(data, len, &eol)) {
661                 sfree(data);
662                 return 1;
663             }
664 
665             status = -1;
666             /* We can't rely on whether the %n incremented the sscanf return */
667             if (sscanf((char *)data, "HTTP/%i.%i %n",
668                        &maj_ver, &min_ver, &status) < 2 || status == -1) {
669                 plug_closing(p->plug, "Proxy error: HTTP response was absent",
670                              PROXY_ERROR_GENERAL, 0);
671                 sfree(data);
672                 return 1;
673             }
674 
675             /* remove the status line from the input buffer. */
676             bufchain_consume(&p->pending_input_data, eol);
677             if (data[status] != '2') {
678                 /* error */
679                 char *buf;
680                 data[eol] = '\0';
681                 while (eol > status &&
682                        (data[eol-1] == '\r' || data[eol-1] == '\n'))
683                     data[--eol] = '\0';
684                 buf = dupprintf("Proxy error: %s", data+status);
685                 plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
686                 sfree(buf);
687                 sfree(data);
688                 return 1;
689             }
690 
691             sfree(data);
692 
693             p->state = 2;
694         }
695 
696         if (p->state == 2) {
697 
698             /* get headers. we're done when we get a
699              * header of length 2, (ie. just "\r\n")
700              */
701 
702             len = bufchain_size(&p->pending_input_data);
703             assert(len > 0);           /* or we wouldn't be here */
704             data = snewn(len, char);
705             datap = data;
706             bufchain_fetch(&p->pending_input_data, data, len);
707 
708             if (!get_line_end(datap, len, &eol)) {
709                 sfree(data);
710                 return 1;
711             }
712             while (eol > 2) {
713                 bufchain_consume(&p->pending_input_data, eol);
714                 datap += eol;
715                 len   -= eol;
716                 if (!get_line_end(datap, len, &eol))
717                     eol = 0;           /* terminate the loop */
718             }
719 
720             if (eol == 2) {
721                 /* we're done */
722                 bufchain_consume(&p->pending_input_data, 2);
723                 proxy_activate(p);
724                 /* proxy activate will have dealt with
725                  * whatever is left of the buffer */
726                 sfree(data);
727                 return 1;
728             }
729 
730             sfree(data);
731             return 1;
732         }
733     }
734 
735     plug_closing(p->plug, "Proxy error: unexpected proxy error",
736                  PROXY_ERROR_UNEXPECTED, 0);
737     return 1;
738 }
739 
740 /* ----------------------------------------------------------------------
741  * SOCKS proxy type.
742  */
743 
744 /* SOCKS version 4 */
proxy_socks4_negotiate(ProxySocket * p,int change)745 int proxy_socks4_negotiate (ProxySocket *p, int change)
746 {
747     if (p->state == PROXY_CHANGE_NEW) {
748 
749         /* request format:
750          *  version number (1 byte) = 4
751          *  command code (1 byte)
752          *    1 = CONNECT
753          *    2 = BIND
754          *  dest. port (2 bytes) [network order]
755          *  dest. address (4 bytes)
756          *  user ID (variable length, null terminated string)
757          */
758 
759         strbuf *command = strbuf_new();
760         char hostname[512];
761         bool write_hostname = false;
762 
763         put_byte(command, 4);          /* SOCKS version 4 */
764         put_byte(command, 1);          /* CONNECT command */
765         put_uint16(command, p->remote_port);
766 
767         switch (sk_addrtype(p->remote_addr)) {
768           case ADDRTYPE_IPV4: {
769             char addr[4];
770             sk_addrcopy(p->remote_addr, addr);
771             put_data(command, addr, 4);
772             break;
773           }
774           case ADDRTYPE_NAME:
775             sk_getaddr(p->remote_addr, hostname, lenof(hostname));
776             put_uint32(command, 1);
777             write_hostname = true;
778             break;
779           case ADDRTYPE_IPV6:
780             p->error = "Proxy error: SOCKS version 4 does not support IPv6";
781             strbuf_free(command);
782             return 1;
783         }
784 
785         put_asciz(command, conf_get_str(p->conf, CONF_proxy_username));
786         if (write_hostname)
787             put_asciz(command, hostname);
788         sk_write(p->sub_socket, command->s, command->len);
789         strbuf_free(command);
790 
791         p->state = 1;
792         return 0;
793     }
794 
795     if (change == PROXY_CHANGE_CLOSING) {
796         /* if our proxy negotiation process involves closing and opening
797          * new sockets, then we would want to intercept this closing
798          * callback when we were expecting it. if we aren't anticipating
799          * a socket close, then some error must have occurred. we'll
800          * just pass those errors up to the backend.
801          */
802         plug_closing(p->plug, p->closing_error_msg, p->closing_error_code,
803                      p->closing_calling_back);
804         return 0; /* ignored */
805     }
806 
807     if (change == PROXY_CHANGE_SENT) {
808         /* some (or all) of what we wrote to the proxy was sent.
809          * we don't do anything new, however, until we receive the
810          * proxy's response. we might want to set a timer so we can
811          * timeout the proxy negotiation after a while...
812          */
813         return 0;
814     }
815 
816     if (change == PROXY_CHANGE_ACCEPTING) {
817         /* we should _never_ see this, as we are using our socket to
818          * connect to a proxy, not accepting inbound connections.
819          * what should we do? close the socket with an appropriate
820          * error message?
821          */
822         return plug_accepting(p->plug,
823                               p->accepting_constructor, p->accepting_ctx);
824     }
825 
826     if (change == PROXY_CHANGE_RECEIVE) {
827         /* we have received data from the underlying socket, which
828          * we'll need to parse, process, and respond to appropriately.
829          */
830 
831         if (p->state == 1) {
832             /* response format:
833              *  version number (1 byte) = 4
834              *  reply code (1 byte)
835              *    90 = request granted
836              *    91 = request rejected or failed
837              *    92 = request rejected due to lack of IDENTD on client
838              *    93 = request rejected due to difference in user ID
839              *         (what we sent vs. what IDENTD said)
840              *  dest. port (2 bytes)
841              *  dest. address (4 bytes)
842              */
843 
844             char data[8];
845 
846             if (bufchain_size(&p->pending_input_data) < 8)
847                 return 1;              /* not got anything yet */
848 
849             /* get the response */
850             bufchain_fetch(&p->pending_input_data, data, 8);
851 
852             if (data[0] != 0) {
853                 plug_closing(p->plug, "Proxy error: SOCKS proxy responded with "
854                                       "unexpected reply code version",
855                              PROXY_ERROR_GENERAL, 0);
856                 return 1;
857             }
858 
859             if (data[1] != 90) {
860 
861                 switch (data[1]) {
862                   case 92:
863                     plug_closing(p->plug, "Proxy error: SOCKS server wanted IDENTD on client",
864                                  PROXY_ERROR_GENERAL, 0);
865                     break;
866                   case 93:
867                     plug_closing(p->plug, "Proxy error: Username and IDENTD on client don't agree",
868                                  PROXY_ERROR_GENERAL, 0);
869                     break;
870                   case 91:
871                   default:
872                     plug_closing(p->plug, "Proxy error: Error while communicating with proxy",
873                                  PROXY_ERROR_GENERAL, 0);
874                     break;
875                 }
876 
877                 return 1;
878             }
879             bufchain_consume(&p->pending_input_data, 8);
880 
881             /* we're done */
882             proxy_activate(p);
883             /* proxy activate will have dealt with
884              * whatever is left of the buffer */
885             return 1;
886         }
887     }
888 
889     plug_closing(p->plug, "Proxy error: unexpected proxy error",
890                  PROXY_ERROR_UNEXPECTED, 0);
891     return 1;
892 }
893 
894 /* SOCKS version 5 */
proxy_socks5_negotiate(ProxySocket * p,int change)895 int proxy_socks5_negotiate (ProxySocket *p, int change)
896 {
897     if (p->state == PROXY_CHANGE_NEW) {
898 
899         /* initial command:
900          *  version number (1 byte) = 5
901          *  number of available authentication methods (1 byte)
902          *  available authentication methods (1 byte * previous value)
903          *    authentication methods:
904          *     0x00 = no authentication
905          *     0x01 = GSSAPI
906          *     0x02 = username/password
907          *     0x03 = CHAP
908          */
909 
910         strbuf *command;
911         char *username, *password;
912         int method_count_offset, methods_start;
913 
914         command = strbuf_new();
915         put_byte(command, 5);          /* SOCKS version 5 */
916         username = conf_get_str(p->conf, CONF_proxy_username);
917         password = conf_get_str(p->conf, CONF_proxy_password);
918 
919         method_count_offset = command->len;
920         put_byte(command, 0);
921         methods_start = command->len;
922 
923         put_byte(command, 0x00);       /* no authentication */
924 
925         if (username[0] || password[0]) {
926             proxy_socks5_offerencryptedauth(BinarySink_UPCAST(command));
927             put_byte(command, 0x02);    /* username/password */
928         }
929 
930         command->u[method_count_offset] = command->len - methods_start;
931 
932         sk_write(p->sub_socket, command->s, command->len);
933         strbuf_free(command);
934 
935         p->state = 1;
936         return 0;
937     }
938 
939     if (change == PROXY_CHANGE_CLOSING) {
940         /* if our proxy negotiation process involves closing and opening
941          * new sockets, then we would want to intercept this closing
942          * callback when we were expecting it. if we aren't anticipating
943          * a socket close, then some error must have occurred. we'll
944          * just pass those errors up to the backend.
945          */
946         plug_closing(p->plug, p->closing_error_msg, p->closing_error_code,
947                      p->closing_calling_back);
948         return 0; /* ignored */
949     }
950 
951     if (change == PROXY_CHANGE_SENT) {
952         /* some (or all) of what we wrote to the proxy was sent.
953          * we don't do anything new, however, until we receive the
954          * proxy's response. we might want to set a timer so we can
955          * timeout the proxy negotiation after a while...
956          */
957         return 0;
958     }
959 
960     if (change == PROXY_CHANGE_ACCEPTING) {
961         /* we should _never_ see this, as we are using our socket to
962          * connect to a proxy, not accepting inbound connections.
963          * what should we do? close the socket with an appropriate
964          * error message?
965          */
966         return plug_accepting(p->plug,
967                               p->accepting_constructor, p->accepting_ctx);
968     }
969 
970     if (change == PROXY_CHANGE_RECEIVE) {
971         /* we have received data from the underlying socket, which
972          * we'll need to parse, process, and respond to appropriately.
973          */
974 
975         if (p->state == 1) {
976 
977             /* initial response:
978              *  version number (1 byte) = 5
979              *  authentication method (1 byte)
980              *    authentication methods:
981              *     0x00 = no authentication
982              *     0x01 = GSSAPI
983              *     0x02 = username/password
984              *     0x03 = CHAP
985              *     0xff = no acceptable methods
986              */
987             char data[2];
988 
989             if (bufchain_size(&p->pending_input_data) < 2)
990                 return 1;              /* not got anything yet */
991 
992             /* get the response */
993             bufchain_fetch(&p->pending_input_data, data, 2);
994 
995             if (data[0] != 5) {
996                 plug_closing(p->plug, "Proxy error: SOCKS proxy returned unexpected version",
997                              PROXY_ERROR_GENERAL, 0);
998                 return 1;
999             }
1000 
1001             if (data[1] == 0x00) p->state = 2; /* no authentication needed */
1002             else if (data[1] == 0x01) p->state = 4; /* GSSAPI authentication */
1003             else if (data[1] == 0x02) p->state = 5; /* username/password authentication */
1004             else if (data[1] == 0x03) p->state = 6; /* CHAP authentication */
1005             else {
1006                 plug_closing(p->plug, "Proxy error: SOCKS proxy did not accept our authentication",
1007                              PROXY_ERROR_GENERAL, 0);
1008                 return 1;
1009             }
1010             bufchain_consume(&p->pending_input_data, 2);
1011         }
1012 
1013         if (p->state == 7) {
1014 
1015             /* password authentication reply format:
1016              *  version number (1 bytes) = 1
1017              *  reply code (1 byte)
1018              *    0 = succeeded
1019              *    >0 = failed
1020              */
1021             char data[2];
1022 
1023             if (bufchain_size(&p->pending_input_data) < 2)
1024                 return 1;              /* not got anything yet */
1025 
1026             /* get the response */
1027             bufchain_fetch(&p->pending_input_data, data, 2);
1028 
1029             if (data[0] != 1) {
1030                 plug_closing(p->plug, "Proxy error: SOCKS password "
1031                              "subnegotiation contained wrong version number",
1032                              PROXY_ERROR_GENERAL, 0);
1033                 return 1;
1034             }
1035 
1036             if (data[1] != 0) {
1037 
1038                 plug_closing(p->plug, "Proxy error: SOCKS proxy refused"
1039                              " password authentication",
1040                              PROXY_ERROR_GENERAL, 0);
1041                 return 1;
1042             }
1043 
1044             bufchain_consume(&p->pending_input_data, 2);
1045             p->state = 2;              /* now proceed as authenticated */
1046         }
1047 
1048         if (p->state == 8) {
1049             int ret;
1050             ret = proxy_socks5_handlechap(p);
1051             if (ret) return ret;
1052         }
1053 
1054         if (p->state == 2) {
1055 
1056             /* request format:
1057              *  version number (1 byte) = 5
1058              *  command code (1 byte)
1059              *    1 = CONNECT
1060              *    2 = BIND
1061              *    3 = UDP ASSOCIATE
1062              *  reserved (1 byte) = 0x00
1063              *  address type (1 byte)
1064              *    1 = IPv4
1065              *    3 = domainname (first byte has length, no terminating null)
1066              *    4 = IPv6
1067              *  dest. address (variable)
1068              *  dest. port (2 bytes) [network order]
1069              */
1070 
1071             strbuf *command = strbuf_new();
1072             put_byte(command, 5);      /* SOCKS version 5 */
1073             put_byte(command, 1);      /* CONNECT command */
1074             put_byte(command, 0x00);   /* reserved byte */
1075 
1076             switch (sk_addrtype(p->remote_addr)) {
1077               case ADDRTYPE_IPV4:
1078                 put_byte(command, 1);  /* IPv4 */
1079                 sk_addrcopy(p->remote_addr, strbuf_append(command, 4));
1080                 break;
1081               case ADDRTYPE_IPV6:
1082                 put_byte(command, 4);  /* IPv6 */
1083                 sk_addrcopy(p->remote_addr, strbuf_append(command, 16));
1084                 break;
1085               case ADDRTYPE_NAME: {
1086                 char hostname[512];
1087                 put_byte(command, 3);  /* domain name */
1088                 sk_getaddr(p->remote_addr, hostname, lenof(hostname));
1089                 if (!put_pstring(command, hostname)) {
1090                   p->error = "Proxy error: SOCKS 5 cannot "
1091                       "support host names longer than 255 chars";
1092                   strbuf_free(command);
1093                   return 1;
1094                 }
1095                 break;
1096               }
1097             }
1098 
1099             put_uint16(command, p->remote_port);
1100 
1101             sk_write(p->sub_socket, command->s, command->len);
1102 
1103             strbuf_free(command);
1104 
1105             p->state = 3;
1106             return 1;
1107         }
1108 
1109         if (p->state == 3) {
1110 
1111             /* reply format:
1112              *  version number (1 bytes) = 5
1113              *  reply code (1 byte)
1114              *    0 = succeeded
1115              *    1 = general SOCKS server failure
1116              *    2 = connection not allowed by ruleset
1117              *    3 = network unreachable
1118              *    4 = host unreachable
1119              *    5 = connection refused
1120              *    6 = TTL expired
1121              *    7 = command not supported
1122              *    8 = address type not supported
1123              * reserved (1 byte) = x00
1124              * address type (1 byte)
1125              *    1 = IPv4
1126              *    3 = domainname (first byte has length, no terminating null)
1127              *    4 = IPv6
1128              * server bound address (variable)
1129              * server bound port (2 bytes) [network order]
1130              */
1131             char data[5];
1132             int len;
1133 
1134             /* First 5 bytes of packet are enough to tell its length. */
1135             if (bufchain_size(&p->pending_input_data) < 5)
1136                 return 1;              /* not got anything yet */
1137 
1138             /* get the response */
1139             bufchain_fetch(&p->pending_input_data, data, 5);
1140 
1141             if (data[0] != 5) {
1142                 plug_closing(p->plug, "Proxy error: SOCKS proxy returned wrong version number",
1143                              PROXY_ERROR_GENERAL, 0);
1144                 return 1;
1145             }
1146 
1147             if (data[1] != 0) {
1148                 char buf[256];
1149 
1150                 strcpy(buf, "Proxy error: ");
1151 
1152                 switch (data[1]) {
1153                   case 1: strcat(buf, "General SOCKS server failure"); break;
1154                   case 2: strcat(buf, "Connection not allowed by ruleset"); break;
1155                   case 3: strcat(buf, "Network unreachable"); break;
1156                   case 4: strcat(buf, "Host unreachable"); break;
1157                   case 5: strcat(buf, "Connection refused"); break;
1158                   case 6: strcat(buf, "TTL expired"); break;
1159                   case 7: strcat(buf, "Command not supported"); break;
1160                   case 8: strcat(buf, "Address type not supported"); break;
1161                   default: sprintf(buf+strlen(buf),
1162                                    "Unrecognised SOCKS error code %d",
1163                                    data[1]);
1164                     break;
1165                 }
1166                 plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
1167 
1168                 return 1;
1169             }
1170 
1171             /*
1172              * Eat the rest of the reply packet.
1173              */
1174             len = 6;                   /* first 4 bytes, last 2 */
1175             switch (data[3]) {
1176               case 1: len += 4; break; /* IPv4 address */
1177               case 4: len += 16; break;/* IPv6 address */
1178               case 3: len += 1+(unsigned char)data[4]; break; /* domain name */
1179               default:
1180                 plug_closing(p->plug, "Proxy error: SOCKS proxy returned "
1181                              "unrecognised address format",
1182                              PROXY_ERROR_GENERAL, 0);
1183                 return 1;
1184             }
1185             if (bufchain_size(&p->pending_input_data) < len)
1186                 return 1;              /* not got whole reply yet */
1187             bufchain_consume(&p->pending_input_data, len);
1188 
1189             /* we're done */
1190             proxy_activate(p);
1191             return 1;
1192         }
1193 
1194         if (p->state == 4) {
1195             /* TODO: Handle GSSAPI authentication */
1196             plug_closing(p->plug, "Proxy error: We don't support GSSAPI authentication",
1197                          PROXY_ERROR_GENERAL, 0);
1198             return 1;
1199         }
1200 
1201         if (p->state == 5) {
1202             const char *username = conf_get_str(p->conf, CONF_proxy_username);
1203             const char *password = conf_get_str(p->conf, CONF_proxy_password);
1204             if (username[0] || password[0]) {
1205                 strbuf *auth = strbuf_new_nm();
1206                 put_byte(auth, 1); /* version number of subnegotiation */
1207                 if (!put_pstring(auth, username)) {
1208                     p->error = "Proxy error: SOCKS 5 authentication cannot "
1209                         "support usernames longer than 255 chars";
1210                     strbuf_free(auth);
1211                     return 1;
1212                 }
1213                 if (!put_pstring(auth, password)) {
1214                     p->error = "Proxy error: SOCKS 5 authentication cannot "
1215                         "support passwords longer than 255 chars";
1216                     strbuf_free(auth);
1217                     return 1;
1218                 }
1219                 sk_write(p->sub_socket, auth->s, auth->len);
1220                 strbuf_free(auth);
1221                 p->state = 7;
1222             } else
1223                 plug_closing(p->plug, "Proxy error: Server chose "
1224                              "username/password authentication but we "
1225                              "didn't offer it!",
1226                          PROXY_ERROR_GENERAL, 0);
1227             return 1;
1228         }
1229 
1230         if (p->state == 6) {
1231             int ret;
1232             ret = proxy_socks5_selectchap(p);
1233             if (ret) return ret;
1234         }
1235 
1236     }
1237 
1238     plug_closing(p->plug, "Proxy error: Unexpected proxy error",
1239                  PROXY_ERROR_UNEXPECTED, 0);
1240     return 1;
1241 }
1242 
1243 /* ----------------------------------------------------------------------
1244  * `Telnet' proxy type.
1245  *
1246  * (This is for ad-hoc proxies where you connect to the proxy's
1247  * telnet port and send a command such as `connect host port'. The
1248  * command is configurable, since this proxy type is typically not
1249  * standardised or at all well-defined.)
1250  */
1251 
format_telnet_command(SockAddr * addr,int port,Conf * conf)1252 char *format_telnet_command(SockAddr *addr, int port, Conf *conf)
1253 {
1254     char *fmt = conf_get_str(conf, CONF_proxy_telnet_command);
1255     int so = 0, eo = 0;
1256     strbuf *buf = strbuf_new();
1257 
1258     /* we need to escape \\, \%, \r, \n, \t, \x??, \0???,
1259      * %%, %host, %port, %user, and %pass
1260      */
1261 
1262     while (fmt[eo] != 0) {
1263 
1264         /* scan forward until we hit end-of-line,
1265          * or an escape character (\ or %) */
1266         while (fmt[eo] != 0 && fmt[eo] != '%' && fmt[eo] != '\\')
1267             eo++;
1268 
1269         /* if we hit eol, break out of our escaping loop */
1270         if (fmt[eo] == 0) break;
1271 
1272         /* if there was any unescaped text before the escape
1273          * character, send that now */
1274         if (eo != so)
1275             put_data(buf, fmt + so, eo - so);
1276 
1277         so = eo++;
1278 
1279         /* if the escape character was the last character of
1280          * the line, we'll just stop and send it. */
1281         if (fmt[eo] == 0) break;
1282 
1283         if (fmt[so] == '\\') {
1284 
1285             /* we recognize \\, \%, \r, \n, \t, \x??.
1286              * anything else, we just send unescaped (including the \).
1287              */
1288 
1289             switch (fmt[eo]) {
1290 
1291               case '\\':
1292                 put_byte(buf, '\\');
1293                 eo++;
1294                 break;
1295 
1296               case '%':
1297                 put_byte(buf, '%');
1298                 eo++;
1299                 break;
1300 
1301               case 'r':
1302                 put_byte(buf, '\r');
1303                 eo++;
1304                 break;
1305 
1306               case 'n':
1307                 put_byte(buf, '\n');
1308                 eo++;
1309                 break;
1310 
1311               case 't':
1312                 put_byte(buf, '\t');
1313                 eo++;
1314                 break;
1315 
1316               case 'x':
1317               case 'X': {
1318                 /* escaped hexadecimal value (ie. \xff) */
1319                 unsigned char v = 0;
1320                 int i = 0;
1321 
1322                 for (;;) {
1323                   eo++;
1324                   if (fmt[eo] >= '0' && fmt[eo] <= '9')
1325                       v += fmt[eo] - '0';
1326                   else if (fmt[eo] >= 'a' && fmt[eo] <= 'f')
1327                       v += fmt[eo] - 'a' + 10;
1328                   else if (fmt[eo] >= 'A' && fmt[eo] <= 'F')
1329                       v += fmt[eo] - 'A' + 10;
1330                   else {
1331                     /* non hex character, so we abort and just
1332                      * send the whole thing unescaped (including \x)
1333                      */
1334                     put_byte(buf, '\\');
1335                     eo = so + 1;
1336                     break;
1337                   }
1338 
1339                   /* we only extract two hex characters */
1340                   if (i == 1) {
1341                     put_byte(buf, v);
1342                     eo++;
1343                     break;
1344                   }
1345 
1346                   i++;
1347                   v <<= 4;
1348                 }
1349                 break;
1350               }
1351 
1352               default:
1353                 put_data(buf, fmt + so, 2);
1354                 eo++;
1355                 break;
1356             }
1357         } else {
1358 
1359             /* % escape. we recognize %%, %host, %port, %user, %pass.
1360              * %proxyhost, %proxyport. Anything else we just send
1361              * unescaped (including the %).
1362              */
1363 
1364             if (fmt[eo] == '%') {
1365                 put_byte(buf, '%');
1366                 eo++;
1367             }
1368             else if (strnicmp(fmt + eo, "host", 4) == 0) {
1369                 char dest[512];
1370                 sk_getaddr(addr, dest, lenof(dest));
1371                 put_data(buf, dest, strlen(dest));
1372                 eo += 4;
1373             }
1374             else if (strnicmp(fmt + eo, "port", 4) == 0) {
1375                 strbuf_catf(buf, "%d", port);
1376                 eo += 4;
1377             }
1378             else if (strnicmp(fmt + eo, "user", 4) == 0) {
1379                 const char *username = conf_get_str(conf, CONF_proxy_username);
1380                 put_data(buf, username, strlen(username));
1381                 eo += 4;
1382             }
1383             else if (strnicmp(fmt + eo, "pass", 4) == 0) {
1384                 const char *password = conf_get_str(conf, CONF_proxy_password);
1385                 put_data(buf, password, strlen(password));
1386                 eo += 4;
1387             }
1388             else if (strnicmp(fmt + eo, "proxyhost", 9) == 0) {
1389                 const char *host = conf_get_str(conf, CONF_proxy_host);
1390                 put_data(buf, host, strlen(host));
1391                 eo += 9;
1392             }
1393             else if (strnicmp(fmt + eo, "proxyport", 9) == 0) {
1394                 int port = conf_get_int(conf, CONF_proxy_port);
1395                 strbuf_catf(buf, "%d", port);
1396                 eo += 9;
1397             }
1398             else {
1399                 /* we don't escape this, so send the % now, and
1400                  * don't advance eo, so that we'll consider the
1401                  * text immediately following the % as unescaped.
1402                  */
1403                 put_byte(buf, '%');
1404             }
1405         }
1406 
1407         /* resume scanning for additional escapes after this one. */
1408         so = eo;
1409     }
1410 
1411     /* if there is any unescaped text at the end of the line, send it */
1412     if (eo != so) {
1413         put_data(buf, fmt + so, eo - so);
1414     }
1415 
1416     return strbuf_to_str(buf);
1417 }
1418 
proxy_telnet_negotiate(ProxySocket * p,int change)1419 int proxy_telnet_negotiate (ProxySocket *p, int change)
1420 {
1421     if (p->state == PROXY_CHANGE_NEW) {
1422         char *formatted_cmd;
1423 
1424         formatted_cmd = format_telnet_command(p->remote_addr, p->remote_port,
1425                                               p->conf);
1426 
1427         {
1428             /*
1429              * Re-escape control chars in the command, for logging.
1430              */
1431             char *reescaped = snewn(4*strlen(formatted_cmd) + 1, char);
1432             const char *in;
1433             char *out;
1434             char *logmsg;
1435 
1436             for (in = formatted_cmd, out = reescaped; *in; in++) {
1437                 if (*in == '\n') {
1438                     *out++ = '\\'; *out++ = 'n';
1439                 } else if (*in == '\r') {
1440                     *out++ = '\\'; *out++ = 'r';
1441                 } else if (*in == '\t') {
1442                     *out++ = '\\'; *out++ = 't';
1443                 } else if (*in == '\\') {
1444                     *out++ = '\\'; *out++ = '\\';
1445                 } else if ((unsigned)(((unsigned char)*in) - 0x20) <
1446                            (0x7F-0x20)) {
1447                     *out++ = *in;
1448                 } else {
1449                     out += sprintf(out, "\\x%02X", (unsigned)*in & 0xFF);
1450                 }
1451             }
1452             *out = '\0';
1453 
1454             logmsg = dupprintf("Sending Telnet proxy command: %s", reescaped);
1455             plug_log(p->plug, PLUGLOG_PROXY_MSG, NULL, 0, logmsg, 0);
1456             sfree(logmsg);
1457             sfree(reescaped);
1458         }
1459 
1460         sk_write(p->sub_socket, formatted_cmd, strlen(formatted_cmd));
1461         sfree(formatted_cmd);
1462 
1463         p->state = 1;
1464         return 0;
1465     }
1466 
1467     if (change == PROXY_CHANGE_CLOSING) {
1468         /* if our proxy negotiation process involves closing and opening
1469          * new sockets, then we would want to intercept this closing
1470          * callback when we were expecting it. if we aren't anticipating
1471          * a socket close, then some error must have occurred. we'll
1472          * just pass those errors up to the backend.
1473          */
1474         plug_closing(p->plug, p->closing_error_msg, p->closing_error_code,
1475                      p->closing_calling_back);
1476         return 0; /* ignored */
1477     }
1478 
1479     if (change == PROXY_CHANGE_SENT) {
1480         /* some (or all) of what we wrote to the proxy was sent.
1481          * we don't do anything new, however, until we receive the
1482          * proxy's response. we might want to set a timer so we can
1483          * timeout the proxy negotiation after a while...
1484          */
1485         return 0;
1486     }
1487 
1488     if (change == PROXY_CHANGE_ACCEPTING) {
1489         /* we should _never_ see this, as we are using our socket to
1490          * connect to a proxy, not accepting inbound connections.
1491          * what should we do? close the socket with an appropriate
1492          * error message?
1493          */
1494         return plug_accepting(p->plug,
1495                               p->accepting_constructor, p->accepting_ctx);
1496     }
1497 
1498     if (change == PROXY_CHANGE_RECEIVE) {
1499         /* we have received data from the underlying socket, which
1500          * we'll need to parse, process, and respond to appropriately.
1501          */
1502 
1503         /* we're done */
1504         proxy_activate(p);
1505         /* proxy activate will have dealt with
1506          * whatever is left of the buffer */
1507         return 1;
1508     }
1509 
1510     plug_closing(p->plug, "Proxy error: Unexpected proxy error",
1511                  PROXY_ERROR_UNEXPECTED, 0);
1512     return 1;
1513 }
1514