Fixed issue #2814: "Git Check for modifications" and Commit dialog runs batch files...
[TortoiseGit.git] / src / TortoisePlink / sshshare.c
blob258483fa32125c5ff305556fb14bce6c00b035ba
1 /*
2 * Support for SSH connection sharing, i.e. permitting one PuTTY to
3 * open its own channels over the SSH session being run by another.
4 */
6 /*
7 * Discussion and technical documentation
8 * ======================================
10 * The basic strategy for PuTTY's implementation of SSH connection
11 * sharing is to have a single 'upstream' PuTTY process, which manages
12 * the real SSH connection and all the cryptography, and then zero or
13 * more 'downstream' PuTTYs, which never talk to the real host but
14 * only talk to the upstream through local IPC (Unix-domain sockets or
15 * Windows named pipes).
17 * The downstreams communicate with the upstream using a protocol
18 * derived from SSH itself, which I'll document in detail below. In
19 * brief, though: the downstream->upstream protocol uses a trivial
20 * binary packet protocol (just length/type/data) to encapsulate
21 * unencrypted SSH messages, and downstreams talk to the upstream more
22 * or less as if it was an SSH server itself. (So downstreams can
23 * themselves open multiple SSH channels, for example, by sending
24 * multiple SSH2_MSG_CHANNEL_OPENs; they can send CHANNEL_REQUESTs of
25 * their choice within each channel, and they handle their own
26 * WINDOW_ADJUST messages.)
28 * The upstream would ideally handle these downstreams by just putting
29 * their messages into the queue for proper SSH-2 encapsulation and
30 * encryption and sending them straight on to the server. However,
31 * that's not quite feasible as written, because client-side channel
32 * IDs could easily conflict (between multiple downstreams, or between
33 * a downstream and the upstream). To protect against that, the
34 * upstream rewrites the client-side channel IDs in messages it passes
35 * on to the server, so that it's performing what you might describe
36 * as 'channel-number NAT'. Then the upstream remembers which of its
37 * own channel IDs are channels it's managing itself, and which are
38 * placeholders associated with a particular downstream, so that when
39 * replies come in from the server they can be sent on to the relevant
40 * downstream (after un-NATting the channel number, of course).
42 * Global requests from downstreams are only accepted if the upstream
43 * knows what to do about them; currently the only such requests are
44 * the ones having to do with remote-to-local port forwarding (in
45 * which, again, the upstream remembers that some of the forwardings
46 * it's asked the server to set up were on behalf of particular
47 * downstreams, and sends the incoming CHANNEL_OPENs to those
48 * downstreams when connections come in).
50 * Other fiddly pieces of this mechanism are X forwarding and
51 * (OpenSSH-style) agent forwarding. Both of these have a fundamental
52 * problem arising from the protocol design: that the CHANNEL_OPEN
53 * from the server introducing a forwarded connection does not carry
54 * any indication of which session channel gave rise to it; so if
55 * session channels from multiple downstreams enable those forwarding
56 * methods, it's hard for the upstream to know which downstream to
57 * send the resulting connections back to.
59 * For X forwarding, we can work around this in a really painful way
60 * by using the fake X11 authorisation data sent to the server as part
61 * of the forwarding setup: upstream ensures that every X forwarding
62 * request carries distinguishable fake auth data, and then when X
63 * connections come in it waits to see the auth data in the X11 setup
64 * message before it decides which downstream to pass the connection
65 * on to.
67 * For agent forwarding, that workaround is unavailable. As a result,
68 * this system (and, as far as I can think of, any other system too)
69 * has the fundamental constraint that it can only forward one SSH
70 * agent - it can't forward two agents to different session channels.
71 * So downstreams can request agent forwarding if they like, but if
72 * they do, they'll get whatever SSH agent is known to the upstream
73 * (if any) forwarded to their sessions.
75 * Downstream-to-upstream protocol
76 * -------------------------------
78 * Here I document in detail the protocol spoken between PuTTY
79 * downstreams and upstreams over local IPC. The IPC mechanism can
80 * vary between host platforms, but the protocol is the same.
82 * The protocol commences with a version exchange which is exactly
83 * like the SSH-2 one, in that each side sends a single line of text
84 * of the form
86 * <protocol>-<version>-<softwareversion> [comments] \r\n
88 * The only difference is that in real SSH-2, <protocol> is the string
89 * "SSH", whereas in this protocol the string is
90 * "SSHCONNECTION@putty.projects.tartarus.org".
92 * (The SSH RFCs allow many protocol-level identifier namespaces to be
93 * extended by implementors without central standardisation as long as
94 * they suffix "@" and a domain name they control to their new ids.
95 * RFC 4253 does not define this particular name to be changeable at
96 * all, but I like to think this is obviously how it would have done
97 * so if the working group had foreseen the need :-)
99 * Thereafter, all data exchanged consists of a sequence of binary
100 * packets concatenated end-to-end, each of which is of the form
102 * uint32 length of packet, N
103 * byte[N] N bytes of packet data
105 * and, since these are SSH-2 messages, the first data byte is taken
106 * to be the packet type code.
108 * These messages are interpreted as those of an SSH connection, after
109 * userauth completes, and without any repeat key exchange.
110 * Specifically, any message from the SSH Connection Protocol is
111 * permitted, and also SSH_MSG_IGNORE, SSH_MSG_DEBUG,
112 * SSH_MSG_DISCONNECT and SSH_MSG_UNIMPLEMENTED from the SSH Transport
113 * Protocol.
115 * This protocol imposes a few additional requirements, over and above
116 * those of the standard SSH Connection Protocol:
118 * Message sizes are not permitted to exceed 0x4010 (16400) bytes,
119 * including their length header.
121 * When the server (i.e. really the PuTTY upstream) sends
122 * SSH_MSG_CHANNEL_OPEN with channel type "x11", and the client
123 * (downstream) responds with SSH_MSG_CHANNEL_OPEN_CONFIRMATION, that
124 * confirmation message MUST include an initial window size of at
125 * least 256. (Rationale: this is a bit of a fudge which makes it
126 * easier, by eliminating the possibility of nasty edge cases, for an
127 * upstream to arrange not to pass the CHANNEL_OPEN on to downstream
128 * until after it's seen the X11 auth data to decide which downstream
129 * it needs to go to.)
132 #include <stdio.h>
133 #include <stdlib.h>
134 #include <assert.h>
135 #include <limits.h>
137 #include "putty.h"
138 #include "tree234.h"
139 #include "ssh.h"
141 struct ssh_sharing_state {
142 const struct plug_function_table *fn;
143 /* the above variable absolutely *must* be the first in this structure */
145 char *sockname; /* the socket name, kept for cleanup */
146 Socket listensock; /* the master listening Socket */
147 tree234 *connections; /* holds ssh_sharing_connstates */
148 unsigned nextid; /* preferred id for next connstate */
149 Ssh ssh; /* instance of the ssh backend */
150 char *server_verstring; /* server version string after "SSH-" */
153 struct share_globreq;
155 struct ssh_sharing_connstate {
156 const struct plug_function_table *fn;
157 /* the above variable absolutely *must* be the first in this structure */
159 unsigned id; /* used to identify this downstream in log messages */
161 Socket sock; /* the Socket for this connection */
162 struct ssh_sharing_state *parent;
164 int crLine; /* coroutine state for share_receive */
166 int sent_verstring, got_verstring, curr_packetlen;
168 unsigned char recvbuf[0x4010];
169 int recvlen;
172 * Assorted state we have to remember about this downstream, so
173 * that we can clean it up appropriately when the downstream goes
174 * away.
177 /* Channels which don't have a downstream id, i.e. we've passed a
178 * CHANNEL_OPEN down from the server but not had an
179 * OPEN_CONFIRMATION or OPEN_FAILURE back. If downstream goes
180 * away, we respond to all of these with OPEN_FAILURE. */
181 tree234 *halfchannels; /* stores 'struct share_halfchannel' */
183 /* Channels which do have a downstream id. We need to index these
184 * by both server id and upstream id, so we can find a channel
185 * when handling either an upward or a downward message referring
186 * to it. */
187 tree234 *channels_by_us; /* stores 'struct share_channel' */
188 tree234 *channels_by_server; /* stores 'struct share_channel' */
190 /* Another class of channel which doesn't have a downstream id.
191 * The difference between these and halfchannels is that xchannels
192 * do have an *upstream* id, because upstream has already accepted
193 * the channel request from the server. This arises in the case of
194 * X forwarding, where we have to accept the request and read the
195 * X authorisation data before we know whether the channel needs
196 * to be forwarded to a downstream. */
197 tree234 *xchannels_by_us; /* stores 'struct share_xchannel' */
198 tree234 *xchannels_by_server; /* stores 'struct share_xchannel' */
200 /* Remote port forwarding requests in force. */
201 tree234 *forwardings; /* stores 'struct share_forwarding' */
203 /* Global requests we've sent on to the server, pending replies. */
204 struct share_globreq *globreq_head, *globreq_tail;
207 struct share_halfchannel {
208 unsigned server_id;
211 /* States of a share_channel. */
212 enum {
213 OPEN,
214 SENT_CLOSE,
215 RCVD_CLOSE,
216 /* Downstream has sent CHANNEL_OPEN but server hasn't replied yet.
217 * If downstream goes away when a channel is in this state, we
218 * must wait for the server's response before starting to send
219 * CLOSE. Channels in this state are also not held in
220 * channels_by_server, because their server_id field is
221 * meaningless. */
222 UNACKNOWLEDGED
225 struct share_channel {
226 unsigned downstream_id, upstream_id, server_id;
227 int downstream_maxpkt;
228 int state;
230 * Some channels (specifically, channels on which downstream has
231 * sent "x11-req") have the additional function of storing a set
232 * of downstream X authorisation data and a handle to an upstream
233 * fake set.
235 struct X11FakeAuth *x11_auth_upstream;
236 int x11_auth_proto;
237 char *x11_auth_data;
238 int x11_auth_datalen;
239 int x11_one_shot;
242 struct share_forwarding {
243 char *host;
244 int port;
245 int active; /* has the server sent REQUEST_SUCCESS? */
248 struct share_xchannel_message {
249 struct share_xchannel_message *next;
250 int type;
251 unsigned char *data;
252 int datalen;
255 struct share_xchannel {
256 unsigned upstream_id, server_id;
259 * xchannels come in two flavours: live and dead. Live ones are
260 * waiting for an OPEN_CONFIRMATION or OPEN_FAILURE from
261 * downstream; dead ones have had an OPEN_FAILURE, so they only
262 * exist as a means of letting us conveniently respond to further
263 * channel messages from the server until such time as the server
264 * sends us CHANNEL_CLOSE.
266 int live;
269 * When we receive OPEN_CONFIRMATION, we will need to send a
270 * WINDOW_ADJUST to the server to synchronise the windows. For
271 * this purpose we need to know what window we have so far offered
272 * the server. We record this as exactly the value in the
273 * OPEN_CONFIRMATION that upstream sent us, adjusted by the amount
274 * by which the two X greetings differed in length.
276 int window;
279 * Linked list of SSH messages from the server relating to this
280 * channel, which we queue up until downstream sends us an
281 * OPEN_CONFIRMATION and we can belatedly send them all on.
283 struct share_xchannel_message *msghead, *msgtail;
286 enum {
287 GLOBREQ_TCPIP_FORWARD,
288 GLOBREQ_CANCEL_TCPIP_FORWARD
291 struct share_globreq {
292 struct share_globreq *next;
293 int type;
294 int want_reply;
295 struct share_forwarding *fwd;
298 static int share_connstate_cmp(void *av, void *bv)
300 const struct ssh_sharing_connstate *a =
301 (const struct ssh_sharing_connstate *)av;
302 const struct ssh_sharing_connstate *b =
303 (const struct ssh_sharing_connstate *)bv;
305 if (a->id < b->id)
306 return -1;
307 else if (a->id > b->id)
308 return +1;
309 else
310 return 0;
313 static unsigned share_find_unused_id
314 (struct ssh_sharing_state *sharestate, unsigned first)
316 int low_orig, low, mid, high, high_orig;
317 struct ssh_sharing_connstate *cs;
318 unsigned ret;
321 * Find the lowest unused downstream ID greater or equal to
322 * 'first'.
324 * Begin by seeing if 'first' itself is available. If it is, we'll
325 * just return it; if it's already in the tree, we'll find the
326 * tree index where it appears and use that for the next stage.
329 struct ssh_sharing_connstate dummy;
330 dummy.id = first;
331 cs = findrelpos234(sharestate->connections, &dummy, NULL,
332 REL234_GE, &low_orig);
333 if (!cs)
334 return first;
338 * Now binary-search using the counted B-tree, to find the largest
339 * ID which is in a contiguous sequence from the beginning of that
340 * range.
342 low = low_orig;
343 high = high_orig = count234(sharestate->connections);
344 while (high - low > 1) {
345 mid = (high + low) / 2;
346 cs = index234(sharestate->connections, mid);
347 if (cs->id == first + (mid - low_orig))
348 low = mid; /* this one is still in the sequence */
349 else
350 high = mid; /* this one is past the end */
354 * Now low is the tree index of the largest ID in the initial
355 * sequence. So the return value is one more than low's id, and we
356 * know low's id is given by the formula in the binary search loop
357 * above.
359 * (If an SSH connection went on for _enormously_ long, we might
360 * reach a point where all ids from 'first' to UINT_MAX were in
361 * use. In that situation the formula below would wrap round by
362 * one and return zero, which is conveniently the right way to
363 * signal 'no id available' from this function.)
365 ret = first + (low - low_orig) + 1;
367 struct ssh_sharing_connstate dummy;
368 dummy.id = ret;
369 assert(NULL == find234(sharestate->connections, &dummy, NULL));
371 return ret;
374 static int share_halfchannel_cmp(void *av, void *bv)
376 const struct share_halfchannel *a = (const struct share_halfchannel *)av;
377 const struct share_halfchannel *b = (const struct share_halfchannel *)bv;
379 if (a->server_id < b->server_id)
380 return -1;
381 else if (a->server_id > b->server_id)
382 return +1;
383 else
384 return 0;
387 static int share_channel_us_cmp(void *av, void *bv)
389 const struct share_channel *a = (const struct share_channel *)av;
390 const struct share_channel *b = (const struct share_channel *)bv;
392 if (a->upstream_id < b->upstream_id)
393 return -1;
394 else if (a->upstream_id > b->upstream_id)
395 return +1;
396 else
397 return 0;
400 static int share_channel_server_cmp(void *av, void *bv)
402 const struct share_channel *a = (const struct share_channel *)av;
403 const struct share_channel *b = (const struct share_channel *)bv;
405 if (a->server_id < b->server_id)
406 return -1;
407 else if (a->server_id > b->server_id)
408 return +1;
409 else
410 return 0;
413 static int share_xchannel_us_cmp(void *av, void *bv)
415 const struct share_xchannel *a = (const struct share_xchannel *)av;
416 const struct share_xchannel *b = (const struct share_xchannel *)bv;
418 if (a->upstream_id < b->upstream_id)
419 return -1;
420 else if (a->upstream_id > b->upstream_id)
421 return +1;
422 else
423 return 0;
426 static int share_xchannel_server_cmp(void *av, void *bv)
428 const struct share_xchannel *a = (const struct share_xchannel *)av;
429 const struct share_xchannel *b = (const struct share_xchannel *)bv;
431 if (a->server_id < b->server_id)
432 return -1;
433 else if (a->server_id > b->server_id)
434 return +1;
435 else
436 return 0;
439 static int share_forwarding_cmp(void *av, void *bv)
441 const struct share_forwarding *a = (const struct share_forwarding *)av;
442 const struct share_forwarding *b = (const struct share_forwarding *)bv;
443 int i;
445 if ((i = strcmp(a->host, b->host)) != 0)
446 return i;
447 else if (a->port < b->port)
448 return -1;
449 else if (a->port > b->port)
450 return +1;
451 else
452 return 0;
455 static void share_xchannel_free(struct share_xchannel *xc)
457 while (xc->msghead) {
458 struct share_xchannel_message *tmp = xc->msghead;
459 xc->msghead = tmp->next;
460 sfree(tmp);
462 sfree(xc);
465 static void share_connstate_free(struct ssh_sharing_connstate *cs)
467 struct share_halfchannel *hc;
468 struct share_xchannel *xc;
469 struct share_channel *chan;
470 struct share_forwarding *fwd;
472 while ((hc = (struct share_halfchannel *)
473 delpos234(cs->halfchannels, 0)) != NULL)
474 sfree(hc);
475 freetree234(cs->halfchannels);
477 /* All channels live in 'channels_by_us' but only some in
478 * 'channels_by_server', so we use the former to find the list of
479 * ones to free */
480 freetree234(cs->channels_by_server);
481 while ((chan = (struct share_channel *)
482 delpos234(cs->channels_by_us, 0)) != NULL)
483 sfree(chan);
484 freetree234(cs->channels_by_us);
486 /* But every xchannel is in both trees, so it doesn't matter which
487 * we use to free them. */
488 while ((xc = (struct share_xchannel *)
489 delpos234(cs->xchannels_by_us, 0)) != NULL)
490 share_xchannel_free(xc);
491 freetree234(cs->xchannels_by_us);
492 freetree234(cs->xchannels_by_server);
494 while ((fwd = (struct share_forwarding *)
495 delpos234(cs->forwardings, 0)) != NULL)
496 sfree(fwd);
497 freetree234(cs->forwardings);
499 while (cs->globreq_head) {
500 struct share_globreq *globreq = cs->globreq_head;
501 cs->globreq_head = cs->globreq_head->next;
502 sfree(globreq);
505 if (cs->sock)
506 sk_close(cs->sock);
508 sfree(cs);
511 void sharestate_free(void *v)
513 struct ssh_sharing_state *sharestate = (struct ssh_sharing_state *)v;
514 struct ssh_sharing_connstate *cs;
516 platform_ssh_share_cleanup(sharestate->sockname);
518 while ((cs = (struct ssh_sharing_connstate *)
519 delpos234(sharestate->connections, 0)) != NULL) {
520 share_connstate_free(cs);
522 freetree234(sharestate->connections);
523 if (sharestate->listensock) {
524 sk_close(sharestate->listensock);
525 sharestate->listensock = NULL;
527 sfree(sharestate->server_verstring);
528 sfree(sharestate->sockname);
529 sfree(sharestate);
532 static struct share_halfchannel *share_add_halfchannel
533 (struct ssh_sharing_connstate *cs, unsigned server_id)
535 struct share_halfchannel *hc = snew(struct share_halfchannel);
536 hc->server_id = server_id;
537 if (add234(cs->halfchannels, hc) != hc) {
538 /* Duplicate?! */
539 sfree(hc);
540 return NULL;
541 } else {
542 return hc;
546 static struct share_halfchannel *share_find_halfchannel
547 (struct ssh_sharing_connstate *cs, unsigned server_id)
549 struct share_halfchannel dummyhc;
550 dummyhc.server_id = server_id;
551 return find234(cs->halfchannels, &dummyhc, NULL);
554 static void share_remove_halfchannel(struct ssh_sharing_connstate *cs,
555 struct share_halfchannel *hc)
557 del234(cs->halfchannels, hc);
558 sfree(hc);
561 static struct share_channel *share_add_channel
562 (struct ssh_sharing_connstate *cs, unsigned downstream_id,
563 unsigned upstream_id, unsigned server_id, int state, int maxpkt)
565 struct share_channel *chan = snew(struct share_channel);
566 chan->downstream_id = downstream_id;
567 chan->upstream_id = upstream_id;
568 chan->server_id = server_id;
569 chan->state = state;
570 chan->downstream_maxpkt = maxpkt;
571 chan->x11_auth_upstream = NULL;
572 chan->x11_auth_data = NULL;
573 chan->x11_auth_proto = -1;
574 chan->x11_auth_datalen = 0;
575 chan->x11_one_shot = 0;
576 if (add234(cs->channels_by_us, chan) != chan) {
577 sfree(chan);
578 return NULL;
580 if (chan->state != UNACKNOWLEDGED) {
581 if (add234(cs->channels_by_server, chan) != chan) {
582 del234(cs->channels_by_us, chan);
583 sfree(chan);
584 return NULL;
587 return chan;
590 static void share_channel_set_server_id(struct ssh_sharing_connstate *cs,
591 struct share_channel *chan,
592 unsigned server_id, int newstate)
594 chan->server_id = server_id;
595 chan->state = newstate;
596 assert(newstate != UNACKNOWLEDGED);
597 add234(cs->channels_by_server, chan);
600 static struct share_channel *share_find_channel_by_upstream
601 (struct ssh_sharing_connstate *cs, unsigned upstream_id)
603 struct share_channel dummychan;
604 dummychan.upstream_id = upstream_id;
605 return find234(cs->channels_by_us, &dummychan, NULL);
608 static struct share_channel *share_find_channel_by_server
609 (struct ssh_sharing_connstate *cs, unsigned server_id)
611 struct share_channel dummychan;
612 dummychan.server_id = server_id;
613 return find234(cs->channels_by_server, &dummychan, NULL);
616 static void share_remove_channel(struct ssh_sharing_connstate *cs,
617 struct share_channel *chan)
619 del234(cs->channels_by_us, chan);
620 del234(cs->channels_by_server, chan);
621 if (chan->x11_auth_upstream)
622 ssh_sharing_remove_x11_display(cs->parent->ssh,
623 chan->x11_auth_upstream);
624 sfree(chan->x11_auth_data);
625 sfree(chan);
628 static struct share_xchannel *share_add_xchannel
629 (struct ssh_sharing_connstate *cs,
630 unsigned upstream_id, unsigned server_id)
632 struct share_xchannel *xc = snew(struct share_xchannel);
633 xc->upstream_id = upstream_id;
634 xc->server_id = server_id;
635 xc->live = TRUE;
636 xc->msghead = xc->msgtail = NULL;
637 if (add234(cs->xchannels_by_us, xc) != xc) {
638 sfree(xc);
639 return NULL;
641 if (add234(cs->xchannels_by_server, xc) != xc) {
642 del234(cs->xchannels_by_us, xc);
643 sfree(xc);
644 return NULL;
646 return xc;
649 static struct share_xchannel *share_find_xchannel_by_upstream
650 (struct ssh_sharing_connstate *cs, unsigned upstream_id)
652 struct share_xchannel dummyxc;
653 dummyxc.upstream_id = upstream_id;
654 return find234(cs->xchannels_by_us, &dummyxc, NULL);
657 static struct share_xchannel *share_find_xchannel_by_server
658 (struct ssh_sharing_connstate *cs, unsigned server_id)
660 struct share_xchannel dummyxc;
661 dummyxc.server_id = server_id;
662 return find234(cs->xchannels_by_server, &dummyxc, NULL);
665 static void share_remove_xchannel(struct ssh_sharing_connstate *cs,
666 struct share_xchannel *xc)
668 del234(cs->xchannels_by_us, xc);
669 del234(cs->xchannels_by_server, xc);
670 share_xchannel_free(xc);
673 static struct share_forwarding *share_add_forwarding
674 (struct ssh_sharing_connstate *cs,
675 const char *host, int port)
677 struct share_forwarding *fwd = snew(struct share_forwarding);
678 fwd->host = dupstr(host);
679 fwd->port = port;
680 fwd->active = FALSE;
681 if (add234(cs->forwardings, fwd) != fwd) {
682 /* Duplicate?! */
683 sfree(fwd);
684 return NULL;
686 return fwd;
689 static struct share_forwarding *share_find_forwarding
690 (struct ssh_sharing_connstate *cs, const char *host, int port)
692 struct share_forwarding dummyfwd, *ret;
693 dummyfwd.host = dupstr(host);
694 dummyfwd.port = port;
695 ret = find234(cs->forwardings, &dummyfwd, NULL);
696 sfree(dummyfwd.host);
697 return ret;
700 static void share_remove_forwarding(struct ssh_sharing_connstate *cs,
701 struct share_forwarding *fwd)
703 del234(cs->forwardings, fwd);
704 sfree(fwd);
707 static void send_packet_to_downstream(struct ssh_sharing_connstate *cs,
708 int type, const void *pkt, int pktlen,
709 struct share_channel *chan)
711 if (!cs->sock) /* throw away all packets destined for a dead downstream */
712 return;
714 if (type == SSH2_MSG_CHANNEL_DATA) {
716 * Special case which we take care of at a low level, so as to
717 * be sure to apply it in all cases. On rare occasions we
718 * might find that we have a channel for which the
719 * downstream's maximum packet size exceeds the max packet
720 * size we presented to the server on its behalf. (This can
721 * occur in X11 forwarding, where we have to send _our_
722 * CHANNEL_OPEN_CONFIRMATION before we discover which if any
723 * downstream the channel is destined for, so if that
724 * downstream turns out to present a smaller max packet size
725 * then we're in this situation.)
727 * If that happens, we just chop up the packet into pieces and
728 * send them as separate CHANNEL_DATA packets.
730 const char *upkt = (const char *)pkt;
731 char header[13]; /* 4 length + 1 type + 4 channel id + 4 string len */
733 int len = toint(GET_32BIT(upkt + 4));
734 upkt += 8; /* skip channel id + length field */
736 if (len < 0 || len > pktlen - 8)
737 len = pktlen - 8;
739 do {
740 int this_len = (len > chan->downstream_maxpkt ?
741 chan->downstream_maxpkt : len);
742 PUT_32BIT(header, this_len + 9);
743 header[4] = type;
744 PUT_32BIT(header + 5, chan->downstream_id);
745 PUT_32BIT(header + 9, this_len);
746 sk_write(cs->sock, header, 13);
747 sk_write(cs->sock, upkt, this_len);
748 len -= this_len;
749 upkt += this_len;
750 } while (len > 0);
751 } else {
753 * Just do the obvious thing.
755 char header[9];
757 PUT_32BIT(header, pktlen + 1);
758 header[4] = type;
759 sk_write(cs->sock, header, 5);
760 sk_write(cs->sock, pkt, pktlen);
764 static void share_try_cleanup(struct ssh_sharing_connstate *cs)
766 int i;
767 struct share_halfchannel *hc;
768 struct share_channel *chan;
769 struct share_forwarding *fwd;
772 * Any half-open channels, i.e. those for which we'd received
773 * CHANNEL_OPEN from the server but not passed back a response
774 * from downstream, should be responded to with OPEN_FAILURE.
776 while ((hc = (struct share_halfchannel *)
777 index234(cs->halfchannels, 0)) != NULL) {
778 static const char reason[] = "PuTTY downstream no longer available";
779 static const char lang[] = "en";
780 unsigned char packet[256];
781 int pos = 0;
783 PUT_32BIT(packet + pos, hc->server_id); pos += 4;
784 PUT_32BIT(packet + pos, SSH2_OPEN_CONNECT_FAILED); pos += 4;
785 PUT_32BIT(packet + pos, strlen(reason)); pos += 4;
786 memcpy(packet + pos, reason, strlen(reason)); pos += strlen(reason);
787 PUT_32BIT(packet + pos, strlen(lang)); pos += 4;
788 memcpy(packet + pos, lang, strlen(lang)); pos += strlen(lang);
789 ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
790 SSH2_MSG_CHANNEL_OPEN_FAILURE,
791 packet, pos, "cleanup after"
792 " downstream went away");
794 share_remove_halfchannel(cs, hc);
798 * Any actually open channels should have a CHANNEL_CLOSE sent for
799 * them, unless we've already done so. We won't be able to
800 * actually clean them up until CHANNEL_CLOSE comes back from the
801 * server, though (unless the server happens to have sent a CLOSE
802 * already).
804 * Another annoying exception is UNACKNOWLEDGED channels, i.e.
805 * we've _sent_ a CHANNEL_OPEN to the server but not received an
806 * OPEN_CONFIRMATION or OPEN_FAILURE. We must wait for a reply
807 * before closing the channel, because until we see that reply we
808 * won't have the server's channel id to put in the close message.
810 for (i = 0; (chan = (struct share_channel *)
811 index234(cs->channels_by_us, i)) != NULL; i++) {
812 unsigned char packet[256];
813 int pos = 0;
815 if (chan->state != SENT_CLOSE && chan->state != UNACKNOWLEDGED) {
816 PUT_32BIT(packet + pos, chan->server_id); pos += 4;
817 ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
818 SSH2_MSG_CHANNEL_CLOSE,
819 packet, pos, "cleanup after"
820 " downstream went away");
821 if (chan->state != RCVD_CLOSE) {
822 chan->state = SENT_CLOSE;
823 } else {
824 /* In this case, we _can_ clear up the channel now. */
825 ssh_delete_sharing_channel(cs->parent->ssh, chan->upstream_id);
826 share_remove_channel(cs, chan);
827 i--; /* don't accidentally skip one as a result */
833 * Any remote port forwardings we're managing on behalf of this
834 * downstream should be cancelled. Again, we must defer those for
835 * which we haven't yet seen REQUEST_SUCCESS/FAILURE.
837 * We take a fire-and-forget approach during cleanup, not
838 * bothering to set want_reply.
840 for (i = 0; (fwd = (struct share_forwarding *)
841 index234(cs->forwardings, i)) != NULL; i++) {
842 if (fwd->active) {
843 static const char request[] = "cancel-tcpip-forward";
844 char *packet = snewn(256 + strlen(fwd->host), char);
845 int pos = 0;
847 PUT_32BIT(packet + pos, strlen(request)); pos += 4;
848 memcpy(packet + pos, request, strlen(request));
849 pos += strlen(request);
851 packet[pos++] = 0; /* !want_reply */
853 PUT_32BIT(packet + pos, strlen(fwd->host)); pos += 4;
854 memcpy(packet + pos, fwd->host, strlen(fwd->host));
855 pos += strlen(fwd->host);
857 PUT_32BIT(packet + pos, fwd->port); pos += 4;
859 ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
860 SSH2_MSG_GLOBAL_REQUEST,
861 packet, pos, "cleanup after"
862 " downstream went away");
863 sfree(packet);
865 share_remove_forwarding(cs, fwd);
866 i--; /* don't accidentally skip one as a result */
870 if (count234(cs->halfchannels) == 0 &&
871 count234(cs->channels_by_us) == 0 &&
872 count234(cs->forwardings) == 0) {
874 * Now we're _really_ done, so we can get rid of cs completely.
876 del234(cs->parent->connections, cs);
877 ssh_sharing_downstream_disconnected(cs->parent->ssh, cs->id);
878 share_connstate_free(cs);
882 static void share_begin_cleanup(struct ssh_sharing_connstate *cs)
885 sk_close(cs->sock);
886 cs->sock = NULL;
888 share_try_cleanup(cs);
891 static void share_disconnect(struct ssh_sharing_connstate *cs,
892 const char *message)
894 static const char lang[] = "en";
895 int msglen = strlen(message);
896 char *packet = snewn(msglen + 256, char);
897 int pos = 0;
899 PUT_32BIT(packet + pos, SSH2_DISCONNECT_PROTOCOL_ERROR); pos += 4;
901 PUT_32BIT(packet + pos, msglen); pos += 4;
902 memcpy(packet + pos, message, msglen);
903 pos += msglen;
905 PUT_32BIT(packet + pos, strlen(lang)); pos += 4;
906 memcpy(packet + pos, lang, strlen(lang)); pos += strlen(lang);
908 send_packet_to_downstream(cs, SSH2_MSG_DISCONNECT, packet, pos, NULL);
910 share_begin_cleanup(cs);
913 static int share_closing(Plug plug, const char *error_msg, int error_code,
914 int calling_back)
916 struct ssh_sharing_connstate *cs = (struct ssh_sharing_connstate *)plug;
917 if (error_msg)
918 ssh_sharing_logf(cs->parent->ssh, cs->id, "%s", error_msg);
919 share_begin_cleanup(cs);
920 return 1;
923 static int getstring_inner(const void *vdata, int datalen,
924 char **out, int *outlen)
926 const unsigned char *data = (const unsigned char *)vdata;
927 int len;
929 if (datalen < 4)
930 return FALSE;
932 len = toint(GET_32BIT(data));
933 if (len < 0 || len > datalen - 4)
934 return FALSE;
936 if (outlen)
937 *outlen = len + 4; /* total size including length field */
938 if (out)
939 *out = dupprintf("%.*s", len, (char *)data + 4);
940 return TRUE;
943 static char *getstring(const void *data, int datalen)
945 char *ret;
946 if (getstring_inner(data, datalen, &ret, NULL))
947 return ret;
948 else
949 return NULL;
952 static int getstring_size(const void *data, int datalen)
954 int ret;
955 if (getstring_inner(data, datalen, NULL, &ret))
956 return ret;
957 else
958 return -1;
962 * Append a message to the end of an xchannel's queue, with the length
963 * and type code filled in and the data block allocated but
964 * uninitialised.
966 struct share_xchannel_message *share_xchannel_add_message
967 (struct share_xchannel *xc, int type, int len)
969 unsigned char *block;
970 struct share_xchannel_message *msg;
973 * Be a little tricksy here by allocating a single memory block
974 * containing both the 'struct share_xchannel_message' and the
975 * actual data. Simplifies freeing it later.
977 block = smalloc(sizeof(struct share_xchannel_message) + len);
978 msg = (struct share_xchannel_message *)block;
979 msg->data = block + sizeof(struct share_xchannel_message);
980 msg->datalen = len;
981 msg->type = type;
984 * Queue it in the xchannel.
986 if (xc->msgtail)
987 xc->msgtail->next = msg;
988 else
989 xc->msghead = msg;
990 msg->next = NULL;
991 xc->msgtail = msg;
993 return msg;
996 void share_dead_xchannel_respond(struct ssh_sharing_connstate *cs,
997 struct share_xchannel *xc)
1000 * Handle queued incoming messages from the server destined for an
1001 * xchannel which is dead (i.e. downstream sent OPEN_FAILURE).
1003 int delete = FALSE;
1004 while (xc->msghead) {
1005 struct share_xchannel_message *msg = xc->msghead;
1006 xc->msghead = msg->next;
1008 if (msg->type == SSH2_MSG_CHANNEL_REQUEST && msg->datalen > 4) {
1010 * A CHANNEL_REQUEST is responded to by sending
1011 * CHANNEL_FAILURE, if it has want_reply set.
1013 int wantreplypos = getstring_size(msg->data, msg->datalen);
1014 if (wantreplypos > 0 && wantreplypos < msg->datalen &&
1015 msg->data[wantreplypos] != 0) {
1016 unsigned char id[4];
1017 PUT_32BIT(id, xc->server_id);
1018 ssh_send_packet_from_downstream
1019 (cs->parent->ssh, cs->id, SSH2_MSG_CHANNEL_FAILURE, id, 4,
1020 "downstream refused X channel open");
1022 } else if (msg->type == SSH2_MSG_CHANNEL_CLOSE) {
1024 * On CHANNEL_CLOSE we can discard the channel completely.
1026 delete = TRUE;
1029 sfree(msg);
1031 xc->msgtail = NULL;
1032 if (delete) {
1033 ssh_delete_sharing_channel(cs->parent->ssh, xc->upstream_id);
1034 share_remove_xchannel(cs, xc);
1038 void share_xchannel_confirmation(struct ssh_sharing_connstate *cs,
1039 struct share_xchannel *xc,
1040 struct share_channel *chan,
1041 unsigned downstream_window)
1043 unsigned char window_adjust[8];
1046 * Send all the queued messages downstream.
1048 while (xc->msghead) {
1049 struct share_xchannel_message *msg = xc->msghead;
1050 xc->msghead = msg->next;
1052 if (msg->datalen >= 4)
1053 PUT_32BIT(msg->data, chan->downstream_id);
1054 send_packet_to_downstream(cs, msg->type,
1055 msg->data, msg->datalen, chan);
1057 sfree(msg);
1061 * Send a WINDOW_ADJUST back upstream, to synchronise the window
1062 * size downstream thinks it's presented with the one we've
1063 * actually presented.
1065 PUT_32BIT(window_adjust, xc->server_id);
1066 PUT_32BIT(window_adjust + 4, downstream_window - xc->window);
1067 ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
1068 SSH2_MSG_CHANNEL_WINDOW_ADJUST,
1069 window_adjust, 8, "window adjustment after"
1070 " downstream accepted X channel");
1073 void share_xchannel_failure(struct ssh_sharing_connstate *cs,
1074 struct share_xchannel *xc)
1077 * If downstream refuses to open our X channel at all for some
1078 * reason, we must respond by sending an emergency CLOSE upstream.
1080 unsigned char id[4];
1081 PUT_32BIT(id, xc->server_id);
1082 ssh_send_packet_from_downstream
1083 (cs->parent->ssh, cs->id, SSH2_MSG_CHANNEL_CLOSE, id, 4,
1084 "downstream refused X channel open");
1087 * Now mark the xchannel as dead, and respond to anything sent on
1088 * it until we see CLOSE for it in turn.
1090 xc->live = FALSE;
1091 share_dead_xchannel_respond(cs, xc);
1094 void share_setup_x11_channel(void *csv, void *chanv,
1095 unsigned upstream_id, unsigned server_id,
1096 unsigned server_currwin, unsigned server_maxpkt,
1097 unsigned client_adjusted_window,
1098 const char *peer_addr, int peer_port, int endian,
1099 int protomajor, int protominor,
1100 const void *initial_data, int initial_len)
1102 struct ssh_sharing_connstate *cs = (struct ssh_sharing_connstate *)csv;
1103 struct share_channel *chan = (struct share_channel *)chanv;
1104 struct share_xchannel *xc;
1105 struct share_xchannel_message *msg;
1106 void *greeting;
1107 int greeting_len;
1108 unsigned char *pkt;
1109 int pktlen;
1112 * Create an xchannel containing data we've already received from
1113 * the X client, and preload it with a CHANNEL_DATA message
1114 * containing our own made-up authorisation greeting and any
1115 * additional data sent from the server so far.
1117 xc = share_add_xchannel(cs, upstream_id, server_id);
1118 greeting = x11_make_greeting(endian, protomajor, protominor,
1119 chan->x11_auth_proto,
1120 chan->x11_auth_data, chan->x11_auth_datalen,
1121 peer_addr, peer_port, &greeting_len);
1122 msg = share_xchannel_add_message(xc, SSH2_MSG_CHANNEL_DATA,
1123 8 + greeting_len + initial_len);
1124 /* leave the channel id field unfilled - we don't know the
1125 * downstream id yet, of course */
1126 PUT_32BIT(msg->data + 4, greeting_len + initial_len);
1127 memcpy(msg->data + 8, greeting, greeting_len);
1128 memcpy(msg->data + 8 + greeting_len, initial_data, initial_len);
1129 sfree(greeting);
1131 xc->window = client_adjusted_window + greeting_len;
1134 * Send on a CHANNEL_OPEN to downstream.
1136 pktlen = 27 + strlen(peer_addr);
1137 pkt = snewn(pktlen, unsigned char);
1138 PUT_32BIT(pkt, 3); /* strlen("x11") */
1139 memcpy(pkt+4, "x11", 3);
1140 PUT_32BIT(pkt+7, server_id);
1141 PUT_32BIT(pkt+11, server_currwin);
1142 PUT_32BIT(pkt+15, server_maxpkt);
1143 PUT_32BIT(pkt+19, strlen(peer_addr));
1144 memcpy(pkt+23, peer_addr, strlen(peer_addr));
1145 PUT_32BIT(pkt+23+strlen(peer_addr), peer_port);
1146 send_packet_to_downstream(cs, SSH2_MSG_CHANNEL_OPEN, pkt, pktlen, NULL);
1147 sfree(pkt);
1150 * If this was a once-only X forwarding, clean it up now.
1152 if (chan->x11_one_shot) {
1153 ssh_sharing_remove_x11_display(cs->parent->ssh,
1154 chan->x11_auth_upstream);
1155 chan->x11_auth_upstream = NULL;
1156 sfree(chan->x11_auth_data);
1157 chan->x11_auth_proto = -1;
1158 chan->x11_auth_datalen = 0;
1159 chan->x11_one_shot = 0;
1163 void share_got_pkt_from_server(void *csv, int type,
1164 unsigned char *pkt, int pktlen)
1166 struct ssh_sharing_connstate *cs = (struct ssh_sharing_connstate *)csv;
1167 struct share_globreq *globreq;
1168 int id_pos;
1169 unsigned upstream_id, server_id;
1170 struct share_channel *chan;
1171 struct share_xchannel *xc;
1173 switch (type) {
1174 case SSH2_MSG_REQUEST_SUCCESS:
1175 case SSH2_MSG_REQUEST_FAILURE:
1176 globreq = cs->globreq_head;
1177 if (globreq->type == GLOBREQ_TCPIP_FORWARD) {
1178 if (type == SSH2_MSG_REQUEST_FAILURE) {
1179 share_remove_forwarding(cs, globreq->fwd);
1180 } else {
1181 globreq->fwd->active = TRUE;
1183 } else if (globreq->type == GLOBREQ_CANCEL_TCPIP_FORWARD) {
1184 if (type == SSH2_MSG_REQUEST_SUCCESS) {
1185 share_remove_forwarding(cs, globreq->fwd);
1188 if (globreq->want_reply) {
1189 send_packet_to_downstream(cs, type, pkt, pktlen, NULL);
1191 cs->globreq_head = globreq->next;
1192 sfree(globreq);
1193 if (cs->globreq_head == NULL)
1194 cs->globreq_tail = NULL;
1196 if (!cs->sock) {
1197 /* Retry cleaning up this connection, in case that reply
1198 * was the last thing we were waiting for. */
1199 share_try_cleanup(cs);
1202 break;
1204 case SSH2_MSG_CHANNEL_OPEN:
1205 id_pos = getstring_size(pkt, pktlen);
1206 assert(id_pos >= 0);
1207 server_id = GET_32BIT(pkt + id_pos);
1208 share_add_halfchannel(cs, server_id);
1210 send_packet_to_downstream(cs, type, pkt, pktlen, NULL);
1211 break;
1213 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
1214 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
1215 case SSH2_MSG_CHANNEL_CLOSE:
1216 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1217 case SSH2_MSG_CHANNEL_DATA:
1218 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1219 case SSH2_MSG_CHANNEL_EOF:
1220 case SSH2_MSG_CHANNEL_REQUEST:
1221 case SSH2_MSG_CHANNEL_SUCCESS:
1222 case SSH2_MSG_CHANNEL_FAILURE:
1224 * All these messages have the recipient channel id as the
1225 * first uint32 field in the packet. Substitute the downstream
1226 * channel id for our one and pass the packet downstream.
1228 assert(pktlen >= 4);
1229 upstream_id = GET_32BIT(pkt);
1230 if ((chan = share_find_channel_by_upstream(cs, upstream_id)) != NULL) {
1232 * The normal case: this id refers to an open channel.
1234 PUT_32BIT(pkt, chan->downstream_id);
1235 send_packet_to_downstream(cs, type, pkt, pktlen, chan);
1238 * Update the channel state, for messages that need it.
1240 if (type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
1241 if (chan->state == UNACKNOWLEDGED && pktlen >= 8) {
1242 share_channel_set_server_id(cs, chan, GET_32BIT(pkt+4),
1243 OPEN);
1244 if (!cs->sock) {
1245 /* Retry cleaning up this connection, so that we
1246 * can send an immediate CLOSE on this channel for
1247 * which we now know the server id. */
1248 share_try_cleanup(cs);
1251 } else if (type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
1252 ssh_delete_sharing_channel(cs->parent->ssh, chan->upstream_id);
1253 share_remove_channel(cs, chan);
1254 } else if (type == SSH2_MSG_CHANNEL_CLOSE) {
1255 if (chan->state == SENT_CLOSE) {
1256 ssh_delete_sharing_channel(cs->parent->ssh,
1257 chan->upstream_id);
1258 share_remove_channel(cs, chan);
1259 if (!cs->sock) {
1260 /* Retry cleaning up this connection, in case this
1261 * channel closure was the last thing we were
1262 * waiting for. */
1263 share_try_cleanup(cs);
1265 } else {
1266 chan->state = RCVD_CLOSE;
1269 } else if ((xc = share_find_xchannel_by_upstream(cs, upstream_id))
1270 != NULL) {
1272 * The unusual case: this id refers to an xchannel. Add it
1273 * to the xchannel's queue.
1275 struct share_xchannel_message *msg;
1277 msg = share_xchannel_add_message(xc, type, pktlen);
1278 memcpy(msg->data, pkt, pktlen);
1280 /* If the xchannel is dead, then also respond to it (which
1281 * may involve deleting the channel). */
1282 if (!xc->live)
1283 share_dead_xchannel_respond(cs, xc);
1285 break;
1287 default:
1288 assert(!"This packet type should never have come from ssh.c");
1289 break;
1293 static void share_got_pkt_from_downstream(struct ssh_sharing_connstate *cs,
1294 int type,
1295 unsigned char *pkt, int pktlen)
1297 char *request_name;
1298 struct share_forwarding *fwd;
1299 int id_pos;
1300 unsigned old_id, new_id, server_id;
1301 struct share_globreq *globreq;
1302 struct share_channel *chan;
1303 struct share_halfchannel *hc;
1304 struct share_xchannel *xc;
1305 char *err = NULL;
1307 switch (type) {
1308 case SSH2_MSG_DISCONNECT:
1310 * This message stops here: if downstream is disconnecting
1311 * from us, that doesn't mean we want to disconnect from the
1312 * SSH server. Close the downstream connection and start
1313 * cleanup.
1315 share_begin_cleanup(cs);
1316 break;
1318 case SSH2_MSG_GLOBAL_REQUEST:
1320 * The only global requests we understand are "tcpip-forward"
1321 * and "cancel-tcpip-forward". Since those require us to
1322 * maintain state, we must assume that other global requests
1323 * will probably require that too, and so we don't forward on
1324 * any request we don't understand.
1326 request_name = getstring(pkt, pktlen);
1327 if (request_name == NULL) {
1328 err = dupprintf("Truncated GLOBAL_REQUEST packet");
1329 goto confused;
1332 if (!strcmp(request_name, "tcpip-forward")) {
1333 int wantreplypos, orig_wantreply, port, ret;
1334 char *host;
1336 sfree(request_name);
1339 * Pick the packet apart to find the want_reply field and
1340 * the host/port we're going to ask to listen on.
1342 wantreplypos = getstring_size(pkt, pktlen);
1343 if (wantreplypos < 0 || wantreplypos >= pktlen) {
1344 err = dupprintf("Truncated GLOBAL_REQUEST packet");
1345 goto confused;
1347 orig_wantreply = pkt[wantreplypos];
1348 port = getstring_size(pkt + (wantreplypos + 1),
1349 pktlen - (wantreplypos + 1));
1350 port += (wantreplypos + 1);
1351 if (port < 0 || port > pktlen - 4) {
1352 err = dupprintf("Truncated GLOBAL_REQUEST packet");
1353 goto confused;
1355 host = getstring(pkt + (wantreplypos + 1),
1356 pktlen - (wantreplypos + 1));
1357 assert(host != NULL);
1358 port = GET_32BIT(pkt + port);
1361 * See if we can allocate space in ssh.c's tree of remote
1362 * port forwardings. If we can't, it's because another
1363 * client sharing this connection has already allocated
1364 * the identical port forwarding, so we take it on
1365 * ourselves to manufacture a failure packet and send it
1366 * back to downstream.
1368 ret = ssh_alloc_sharing_rportfwd(cs->parent->ssh, host, port, cs);
1369 if (!ret) {
1370 if (orig_wantreply) {
1371 send_packet_to_downstream(cs, SSH2_MSG_REQUEST_FAILURE,
1372 "", 0, NULL);
1374 } else {
1376 * We've managed to make space for this forwarding
1377 * locally. Pass the request on to the SSH server, but
1378 * set want_reply even if it wasn't originally set, so
1379 * that we know whether this forwarding needs to be
1380 * cleaned up if downstream goes away.
1382 int old_wantreply = pkt[wantreplypos];
1383 pkt[wantreplypos] = 1;
1384 ssh_send_packet_from_downstream
1385 (cs->parent->ssh, cs->id, type, pkt, pktlen,
1386 old_wantreply ? NULL : "upstream added want_reply flag");
1387 fwd = share_add_forwarding(cs, host, port);
1388 ssh_sharing_queue_global_request(cs->parent->ssh, cs);
1390 if (fwd) {
1391 globreq = snew(struct share_globreq);
1392 globreq->next = NULL;
1393 if (cs->globreq_tail)
1394 cs->globreq_tail->next = globreq;
1395 else
1396 cs->globreq_head = globreq;
1397 globreq->fwd = fwd;
1398 globreq->want_reply = orig_wantreply;
1399 globreq->type = GLOBREQ_TCPIP_FORWARD;
1403 sfree(host);
1404 } else if (!strcmp(request_name, "cancel-tcpip-forward")) {
1405 int wantreplypos, orig_wantreply, port;
1406 char *host;
1407 struct share_forwarding *fwd;
1409 sfree(request_name);
1412 * Pick the packet apart to find the want_reply field and
1413 * the host/port we're going to ask to listen on.
1415 wantreplypos = getstring_size(pkt, pktlen);
1416 if (wantreplypos < 0 || wantreplypos >= pktlen) {
1417 err = dupprintf("Truncated GLOBAL_REQUEST packet");
1418 goto confused;
1420 orig_wantreply = pkt[wantreplypos];
1421 port = getstring_size(pkt + (wantreplypos + 1),
1422 pktlen - (wantreplypos + 1));
1423 port += (wantreplypos + 1);
1424 if (port < 0 || port > pktlen - 4) {
1425 err = dupprintf("Truncated GLOBAL_REQUEST packet");
1426 goto confused;
1428 host = getstring(pkt + (wantreplypos + 1),
1429 pktlen - (wantreplypos + 1));
1430 assert(host != NULL);
1431 port = GET_32BIT(pkt + port);
1434 * Look up the existing forwarding with these details.
1436 fwd = share_find_forwarding(cs, host, port);
1437 if (!fwd) {
1438 if (orig_wantreply) {
1439 send_packet_to_downstream(cs, SSH2_MSG_REQUEST_FAILURE,
1440 "", 0, NULL);
1442 } else {
1444 * Pass the cancel request on to the SSH server, but
1445 * set want_reply even if it wasn't originally set, so
1446 * that _we_ know whether the forwarding has been
1447 * deleted even if downstream doesn't want to know.
1449 int old_wantreply = pkt[wantreplypos];
1450 pkt[wantreplypos] = 1;
1451 ssh_send_packet_from_downstream
1452 (cs->parent->ssh, cs->id, type, pkt, pktlen,
1453 old_wantreply ? NULL : "upstream added want_reply flag");
1454 ssh_sharing_queue_global_request(cs->parent->ssh, cs);
1457 sfree(host);
1458 } else {
1460 * Request we don't understand. Manufacture a failure
1461 * message if an answer was required.
1463 int wantreplypos;
1465 sfree(request_name);
1467 wantreplypos = getstring_size(pkt, pktlen);
1468 if (wantreplypos < 0 || wantreplypos >= pktlen) {
1469 err = dupprintf("Truncated GLOBAL_REQUEST packet");
1470 goto confused;
1472 if (pkt[wantreplypos])
1473 send_packet_to_downstream(cs, SSH2_MSG_REQUEST_FAILURE,
1474 "", 0, NULL);
1476 break;
1478 case SSH2_MSG_CHANNEL_OPEN:
1479 /* Sender channel id comes after the channel type string */
1480 id_pos = getstring_size(pkt, pktlen);
1481 if (id_pos < 0 || id_pos > pktlen - 12) {
1482 err = dupprintf("Truncated CHANNEL_OPEN packet");
1483 goto confused;
1486 old_id = GET_32BIT(pkt + id_pos);
1487 new_id = ssh_alloc_sharing_channel(cs->parent->ssh, cs);
1488 share_add_channel(cs, old_id, new_id, 0, UNACKNOWLEDGED,
1489 GET_32BIT(pkt + id_pos + 8));
1490 PUT_32BIT(pkt + id_pos, new_id);
1491 ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
1492 type, pkt, pktlen, NULL);
1493 break;
1495 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
1496 if (pktlen < 16) {
1497 err = dupprintf("Truncated CHANNEL_OPEN_CONFIRMATION packet");
1498 goto confused;
1501 id_pos = 4; /* sender channel id is 2nd uint32 field in packet */
1502 old_id = GET_32BIT(pkt + id_pos);
1504 server_id = GET_32BIT(pkt);
1505 /* This server id may refer to either a halfchannel or an xchannel. */
1506 hc = NULL, xc = NULL; /* placate optimiser */
1507 if ((hc = share_find_halfchannel(cs, server_id)) != NULL) {
1508 new_id = ssh_alloc_sharing_channel(cs->parent->ssh, cs);
1509 } else if ((xc = share_find_xchannel_by_server(cs, server_id))
1510 != NULL) {
1511 new_id = xc->upstream_id;
1512 } else {
1513 err = dupprintf("CHANNEL_OPEN_CONFIRMATION packet cited unknown channel %u", (unsigned)server_id);
1514 goto confused;
1517 PUT_32BIT(pkt + id_pos, new_id);
1519 chan = share_add_channel(cs, old_id, new_id, server_id, OPEN,
1520 GET_32BIT(pkt + 12));
1522 if (hc) {
1523 ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
1524 type, pkt, pktlen, NULL);
1525 share_remove_halfchannel(cs, hc);
1526 } else if (xc) {
1527 unsigned downstream_window = GET_32BIT(pkt + 8);
1528 if (downstream_window < 256) {
1529 err = dupprintf("Initial window size for x11 channel must be at least 256 (got %u)", downstream_window);
1530 goto confused;
1532 share_xchannel_confirmation(cs, xc, chan, downstream_window);
1533 share_remove_xchannel(cs, xc);
1536 break;
1538 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
1539 if (pktlen < 4) {
1540 err = dupprintf("Truncated CHANNEL_OPEN_FAILURE packet");
1541 goto confused;
1544 server_id = GET_32BIT(pkt);
1545 /* This server id may refer to either a halfchannel or an xchannel. */
1546 if ((hc = share_find_halfchannel(cs, server_id)) != NULL) {
1547 ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
1548 type, pkt, pktlen, NULL);
1549 share_remove_halfchannel(cs, hc);
1550 } else if ((xc = share_find_xchannel_by_server(cs, server_id))
1551 != NULL) {
1552 share_xchannel_failure(cs, xc);
1553 } else {
1554 err = dupprintf("CHANNEL_OPEN_FAILURE packet cited unknown channel %u", (unsigned)server_id);
1555 goto confused;
1558 break;
1560 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1561 case SSH2_MSG_CHANNEL_DATA:
1562 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1563 case SSH2_MSG_CHANNEL_EOF:
1564 case SSH2_MSG_CHANNEL_CLOSE:
1565 case SSH2_MSG_CHANNEL_REQUEST:
1566 case SSH2_MSG_CHANNEL_SUCCESS:
1567 case SSH2_MSG_CHANNEL_FAILURE:
1568 case SSH2_MSG_IGNORE:
1569 case SSH2_MSG_DEBUG:
1570 if (type == SSH2_MSG_CHANNEL_REQUEST &&
1571 (request_name = getstring(pkt + 4, pktlen - 4)) != NULL) {
1573 * Agent forwarding requests from downstream are treated
1574 * specially. Because OpenSSHD doesn't let us enable agent
1575 * forwarding independently per session channel, and in
1576 * particular because the OpenSSH-defined agent forwarding
1577 * protocol does not mark agent-channel requests with the
1578 * id of the session channel they originate from, the only
1579 * way we can implement agent forwarding in a
1580 * connection-shared PuTTY is to forward the _upstream_
1581 * agent. Hence, we unilaterally deny agent forwarding
1582 * requests from downstreams if we aren't prepared to
1583 * forward an agent ourselves.
1585 * (If we are, then we dutifully pass agent forwarding
1586 * requests upstream. OpenSSHD has the curious behaviour
1587 * that all but the first such request will be rejected,
1588 * but all session channels opened after the first request
1589 * get agent forwarding enabled whether they ask for it or
1590 * not; but that's not our concern, since other SSH
1591 * servers supporting the same piece of protocol might in
1592 * principle at least manage to enable agent forwarding on
1593 * precisely the channels that requested it, even if the
1594 * subsequent CHANNEL_OPENs still can't be associated with
1595 * a parent session channel.)
1597 if (!strcmp(request_name, "auth-agent-req@openssh.com") &&
1598 !ssh_agent_forwarding_permitted(cs->parent->ssh)) {
1599 unsigned server_id = GET_32BIT(pkt);
1600 unsigned char recipient_id[4];
1602 sfree(request_name);
1604 chan = share_find_channel_by_server(cs, server_id);
1605 if (chan) {
1606 PUT_32BIT(recipient_id, chan->downstream_id);
1607 send_packet_to_downstream(cs, SSH2_MSG_CHANNEL_FAILURE,
1608 recipient_id, 4, NULL);
1609 } else {
1610 char *buf = dupprintf("Agent forwarding request for "
1611 "unrecognised channel %u", server_id);
1612 share_disconnect(cs, buf);
1613 sfree(buf);
1614 return;
1616 break;
1620 * Another thing we treat specially is X11 forwarding
1621 * requests. For these, we have to make up another set of
1622 * X11 auth data, and enter it into our SSH connection's
1623 * list of possible X11 authorisation credentials so that
1624 * when we see an X11 channel open request we can know
1625 * whether it's one to handle locally or one to pass on to
1626 * a downstream, and if the latter, which one.
1628 if (!strcmp(request_name, "x11-req")) {
1629 unsigned server_id = GET_32BIT(pkt);
1630 int want_reply, single_connection, screen;
1631 char *auth_proto_str, *auth_data;
1632 int auth_proto, protolen, datalen;
1633 int pos;
1635 sfree(request_name);
1637 chan = share_find_channel_by_server(cs, server_id);
1638 if (!chan) {
1639 char *buf = dupprintf("X11 forwarding request for "
1640 "unrecognised channel %u", server_id);
1641 share_disconnect(cs, buf);
1642 sfree(buf);
1643 return;
1647 * Pick apart the whole message to find the downstream
1648 * auth details.
1650 /* we have already seen: 4 bytes channel id, 4+7 request name */
1651 if (pktlen < 17) {
1652 err = dupprintf("Truncated CHANNEL_REQUEST(\"x11\") packet");
1653 goto confused;
1655 want_reply = pkt[15] != 0;
1656 single_connection = pkt[16] != 0;
1657 auth_proto_str = getstring(pkt+17, pktlen-17);
1658 auth_proto = x11_identify_auth_proto(auth_proto_str);
1659 sfree(auth_proto_str);
1660 pos = 17 + getstring_size(pkt+17, pktlen-17);
1661 auth_data = getstring(pkt+pos, pktlen-pos);
1662 pos += getstring_size(pkt+pos, pktlen-pos);
1664 if (pktlen < pos+4) {
1665 err = dupprintf("Truncated CHANNEL_REQUEST(\"x11\") packet");
1666 sfree(auth_data);
1667 goto confused;
1669 screen = GET_32BIT(pkt+pos);
1671 if (auth_proto < 0) {
1672 /* Reject due to not understanding downstream's
1673 * requested authorisation method. */
1674 unsigned char recipient_id[4];
1675 PUT_32BIT(recipient_id, chan->downstream_id);
1676 send_packet_to_downstream(cs, SSH2_MSG_CHANNEL_FAILURE,
1677 recipient_id, 4, NULL);
1678 sfree(auth_data);
1679 break;
1682 chan->x11_auth_proto = auth_proto;
1683 chan->x11_auth_data = x11_dehexify(auth_data,
1684 &chan->x11_auth_datalen);
1685 sfree(auth_data);
1686 chan->x11_auth_upstream =
1687 ssh_sharing_add_x11_display(cs->parent->ssh, auth_proto,
1688 cs, chan);
1689 chan->x11_one_shot = single_connection;
1692 * Now construct a replacement X forwarding request,
1693 * containing our own auth data, and send that to the
1694 * server.
1696 protolen = strlen(chan->x11_auth_upstream->protoname);
1697 datalen = strlen(chan->x11_auth_upstream->datastring);
1698 pktlen = 29+protolen+datalen;
1699 pkt = snewn(pktlen, unsigned char);
1700 PUT_32BIT(pkt, server_id);
1701 PUT_32BIT(pkt+4, 7); /* strlen("x11-req") */
1702 memcpy(pkt+8, "x11-req", 7);
1703 pkt[15] = want_reply;
1704 pkt[16] = single_connection;
1705 PUT_32BIT(pkt+17, protolen);
1706 memcpy(pkt+21, chan->x11_auth_upstream->protoname, protolen);
1707 PUT_32BIT(pkt+21+protolen, datalen);
1708 memcpy(pkt+25+protolen, chan->x11_auth_upstream->datastring,
1709 datalen);
1710 PUT_32BIT(pkt+25+protolen+datalen, screen);
1711 ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
1712 SSH2_MSG_CHANNEL_REQUEST,
1713 pkt, pktlen, NULL);
1714 sfree(pkt);
1716 break;
1719 sfree(request_name);
1722 ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
1723 type, pkt, pktlen, NULL);
1724 if (type == SSH2_MSG_CHANNEL_CLOSE && pktlen >= 4) {
1725 server_id = GET_32BIT(pkt);
1726 chan = share_find_channel_by_server(cs, server_id);
1727 if (chan) {
1728 if (chan->state == RCVD_CLOSE) {
1729 ssh_delete_sharing_channel(cs->parent->ssh,
1730 chan->upstream_id);
1731 share_remove_channel(cs, chan);
1732 } else {
1733 chan->state = SENT_CLOSE;
1737 break;
1739 default:
1740 err = dupprintf("Unexpected packet type %d\n", type);
1741 goto confused;
1744 * Any other packet type is unexpected. In particular, we
1745 * never pass GLOBAL_REQUESTs downstream, so we never expect
1746 * to see SSH2_MSG_REQUEST_{SUCCESS,FAILURE}.
1748 confused:
1749 assert(err != NULL);
1750 share_disconnect(cs, err);
1751 sfree(err);
1752 break;
1757 * Coroutine macros similar to, but simplified from, those in ssh.c.
1759 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
1760 #define crFinish(z) } *crLine = 0; return (z); }
1761 #define crGetChar(c) do \
1763 while (len == 0) { \
1764 *crLine =__LINE__; return 1; case __LINE__:; \
1766 len--; \
1767 (c) = (unsigned char)*data++; \
1768 } while (0)
1770 static int share_receive(Plug plug, int urgent, char *data, int len)
1772 struct ssh_sharing_connstate *cs = (struct ssh_sharing_connstate *)plug;
1773 static const char expected_verstring_prefix[] =
1774 "SSHCONNECTION@putty.projects.tartarus.org-2.0-";
1775 unsigned char c;
1777 crBegin(cs->crLine);
1780 * First read the version string from downstream.
1782 cs->recvlen = 0;
1783 while (1) {
1784 crGetChar(c);
1785 if (c == '\012')
1786 break;
1787 if (cs->recvlen >= sizeof(cs->recvbuf)) {
1788 char *buf = dupprintf("Version string far too long\n");
1789 share_disconnect(cs, buf);
1790 sfree(buf);
1791 goto dead;
1793 cs->recvbuf[cs->recvlen++] = c;
1797 * Now parse the version string to make sure it's at least vaguely
1798 * sensible, and log it.
1800 if (cs->recvlen < sizeof(expected_verstring_prefix)-1 ||
1801 memcmp(cs->recvbuf, expected_verstring_prefix,
1802 sizeof(expected_verstring_prefix) - 1)) {
1803 char *buf = dupprintf("Version string did not have expected prefix\n");
1804 share_disconnect(cs, buf);
1805 sfree(buf);
1806 goto dead;
1808 if (cs->recvlen > 0 && cs->recvbuf[cs->recvlen-1] == '\015')
1809 cs->recvlen--; /* trim off \r before \n */
1810 ssh_sharing_logf(cs->parent->ssh, cs->id,
1811 "Downstream version string: %.*s",
1812 cs->recvlen, cs->recvbuf);
1815 * Loop round reading packets.
1817 while (1) {
1818 cs->recvlen = 0;
1819 while (cs->recvlen < 4) {
1820 crGetChar(c);
1821 cs->recvbuf[cs->recvlen++] = c;
1823 cs->curr_packetlen = toint(GET_32BIT(cs->recvbuf) + 4);
1824 if (cs->curr_packetlen < 5 ||
1825 cs->curr_packetlen > sizeof(cs->recvbuf)) {
1826 char *buf = dupprintf("Bad packet length %u\n",
1827 (unsigned)cs->curr_packetlen);
1828 share_disconnect(cs, buf);
1829 sfree(buf);
1830 goto dead;
1832 while (cs->recvlen < cs->curr_packetlen) {
1833 crGetChar(c);
1834 cs->recvbuf[cs->recvlen++] = c;
1837 share_got_pkt_from_downstream(cs, cs->recvbuf[4],
1838 cs->recvbuf + 5, cs->recvlen - 5);
1841 dead:;
1842 crFinish(1);
1845 static void share_sent(Plug plug, int bufsize)
1847 /* struct ssh_sharing_connstate *cs = (struct ssh_sharing_connstate *)plug; */
1850 * We do nothing here, because we expect that there won't be a
1851 * need to throttle and unthrottle the connection to a downstream.
1852 * It should automatically throttle itself: if the SSH server
1853 * sends huge amounts of data on all channels then it'll run out
1854 * of window until our downstream sends it back some
1855 * WINDOW_ADJUSTs.
1859 static int share_listen_closing(Plug plug, const char *error_msg,
1860 int error_code, int calling_back)
1862 struct ssh_sharing_state *sharestate = (struct ssh_sharing_state *)plug;
1863 if (error_msg)
1864 ssh_sharing_logf(sharestate->ssh, 0,
1865 "listening socket: %s", error_msg);
1866 sk_close(sharestate->listensock);
1867 sharestate->listensock = NULL;
1868 return 1;
1871 static void share_send_verstring(struct ssh_sharing_connstate *cs)
1873 char *fullstring = dupcat("SSHCONNECTION@putty.projects.tartarus.org-2.0-",
1874 cs->parent->server_verstring, "\015\012", NULL);
1875 sk_write(cs->sock, fullstring, strlen(fullstring));
1876 sfree(fullstring);
1878 cs->sent_verstring = TRUE;
1881 int share_ndownstreams(void *state)
1883 struct ssh_sharing_state *sharestate = (struct ssh_sharing_state *)state;
1884 return count234(sharestate->connections);
1887 void share_activate(void *state, const char *server_verstring)
1890 * Indication from ssh.c that we are now ready to begin serving
1891 * any downstreams that have already connected to us.
1893 struct ssh_sharing_state *sharestate = (struct ssh_sharing_state *)state;
1894 struct ssh_sharing_connstate *cs;
1895 int i;
1898 * Trim the server's version string down to just the software
1899 * version component, removing "SSH-2.0-" or whatever at the
1900 * front.
1902 for (i = 0; i < 2; i++) {
1903 server_verstring += strcspn(server_verstring, "-");
1904 if (*server_verstring)
1905 server_verstring++;
1908 sharestate->server_verstring = dupstr(server_verstring);
1910 for (i = 0; (cs = (struct ssh_sharing_connstate *)
1911 index234(sharestate->connections, i)) != NULL; i++) {
1912 assert(!cs->sent_verstring);
1913 share_send_verstring(cs);
1917 static int share_listen_accepting(Plug plug,
1918 accept_fn_t constructor, accept_ctx_t ctx)
1920 static const struct plug_function_table connection_fn_table = {
1921 NULL, /* no log function, because that's for outgoing connections */
1922 share_closing,
1923 share_receive,
1924 share_sent,
1925 NULL /* no accepting function, because we've already done it */
1927 struct ssh_sharing_state *sharestate = (struct ssh_sharing_state *)plug;
1928 struct ssh_sharing_connstate *cs;
1929 const char *err;
1930 char *peerinfo;
1933 * A new downstream has connected to us.
1935 cs = snew(struct ssh_sharing_connstate);
1936 cs->fn = &connection_fn_table;
1937 cs->parent = sharestate;
1939 if ((cs->id = share_find_unused_id(sharestate, sharestate->nextid)) == 0 &&
1940 (cs->id = share_find_unused_id(sharestate, 1)) == 0) {
1941 sfree(cs);
1942 return 1;
1944 sharestate->nextid = cs->id + 1;
1945 if (sharestate->nextid == 0)
1946 sharestate->nextid++; /* only happens in VERY long-running upstreams */
1948 cs->sock = constructor(ctx, (Plug) cs);
1949 if ((err = sk_socket_error(cs->sock)) != NULL) {
1950 sfree(cs);
1951 return err != NULL;
1954 sk_set_frozen(cs->sock, 0);
1956 add234(cs->parent->connections, cs);
1958 cs->sent_verstring = FALSE;
1959 if (sharestate->server_verstring)
1960 share_send_verstring(cs);
1962 cs->got_verstring = FALSE;
1963 cs->recvlen = 0;
1964 cs->crLine = 0;
1965 cs->halfchannels = newtree234(share_halfchannel_cmp);
1966 cs->channels_by_us = newtree234(share_channel_us_cmp);
1967 cs->channels_by_server = newtree234(share_channel_server_cmp);
1968 cs->xchannels_by_us = newtree234(share_xchannel_us_cmp);
1969 cs->xchannels_by_server = newtree234(share_xchannel_server_cmp);
1970 cs->forwardings = newtree234(share_forwarding_cmp);
1971 cs->globreq_head = cs->globreq_tail = NULL;
1973 peerinfo = sk_peer_info(cs->sock);
1974 ssh_sharing_downstream_connected(sharestate->ssh, cs->id, peerinfo);
1975 sfree(peerinfo);
1977 return 0;
1980 /* Per-application overrides for what roles we can take (e.g. pscp
1981 * will never be an upstream) */
1982 extern const int share_can_be_downstream;
1983 extern const int share_can_be_upstream;
1986 * Init function for connection sharing. We either open a listening
1987 * socket and become an upstream, or connect to an existing one and
1988 * become a downstream, or do neither. We are responsible for deciding
1989 * which of these to do (including checking the Conf to see if
1990 * connection sharing is even enabled in the first place). If we
1991 * become a downstream, we return the Socket with which we connected
1992 * to the upstream; otherwise (whether or not we have established an
1993 * upstream) we return NULL.
1995 Socket ssh_connection_sharing_init(const char *host, int port,
1996 Conf *conf, Ssh ssh, void **state)
1998 static const struct plug_function_table listen_fn_table = {
1999 NULL, /* no log function, because that's for outgoing connections */
2000 share_listen_closing,
2001 NULL, /* no receive function on a listening socket */
2002 NULL, /* no sent function on a listening socket */
2003 share_listen_accepting
2006 int result, can_upstream, can_downstream;
2007 char *logtext, *ds_err, *us_err;
2008 char *sockname;
2009 Socket sock;
2010 struct ssh_sharing_state *sharestate;
2012 if (!conf_get_int(conf, CONF_ssh_connection_sharing))
2013 return NULL; /* do not share anything */
2014 can_upstream = share_can_be_upstream &&
2015 conf_get_int(conf, CONF_ssh_connection_sharing_upstream);
2016 can_downstream = share_can_be_downstream &&
2017 conf_get_int(conf, CONF_ssh_connection_sharing_downstream);
2018 if (!can_upstream && !can_downstream)
2019 return NULL;
2022 * Decide on the string used to identify the connection point
2023 * between upstream and downstream (be it a Windows named pipe or
2024 * a Unix-domain socket or whatever else).
2026 * I wondered about making this a SHA hash of all sorts of pieces
2027 * of the PuTTY configuration - essentially everything PuTTY uses
2028 * to know where and how to make a connection, including all the
2029 * proxy details (or rather, all the _relevant_ ones - only
2030 * including settings that other settings didn't prevent from
2031 * having any effect), plus the username. However, I think it's
2032 * better to keep it really simple: the connection point
2033 * identifier is derived from the hostname and port used to index
2034 * the host-key cache (not necessarily where we _physically_
2035 * connected to, in cases involving proxies or CONF_loghost), plus
2036 * the username if one is specified.
2039 char *username = get_remote_username(conf);
2041 if (port == 22) {
2042 if (username)
2043 sockname = dupprintf("%s@%s", username, host);
2044 else
2045 sockname = dupprintf("%s", host);
2046 } else {
2047 if (username)
2048 sockname = dupprintf("%s@%s:%d", username, host, port);
2049 else
2050 sockname = dupprintf("%s:%d", host, port);
2053 sfree(username);
2056 * The platform-specific code may transform this further in
2057 * order to conform to local namespace conventions (e.g. not
2058 * using slashes in filenames), but that's its job and not
2059 * ours.
2064 * Create a data structure for the listening plug if we turn out
2065 * to be an upstream.
2067 sharestate = snew(struct ssh_sharing_state);
2068 sharestate->fn = &listen_fn_table;
2069 sharestate->listensock = NULL;
2072 * Now hand off to a per-platform routine that either connects to
2073 * an existing upstream (using 'ssh' as the plug), establishes our
2074 * own upstream (using 'sharestate' as the plug), or forks off a
2075 * separate upstream and then connects to that. It will return a
2076 * code telling us which kind of socket it put in 'sock'.
2078 sock = NULL;
2079 logtext = ds_err = us_err = NULL;
2080 result = platform_ssh_share(sockname, conf, (Plug)ssh,
2081 (Plug)sharestate, &sock, &logtext, &ds_err,
2082 &us_err, can_upstream, can_downstream);
2083 ssh_connshare_log(ssh, result, logtext, ds_err, us_err);
2084 sfree(logtext);
2085 sfree(ds_err);
2086 sfree(us_err);
2087 switch (result) {
2088 case SHARE_NONE:
2090 * We aren't sharing our connection at all (e.g. something
2091 * went wrong setting the socket up). Free the upstream
2092 * structure and return NULL.
2094 assert(sock == NULL);
2095 *state = NULL;
2096 sfree(sharestate);
2097 sfree(sockname);
2098 return NULL;
2100 case SHARE_DOWNSTREAM:
2102 * We are downstream, so free sharestate which it turns out we
2103 * don't need after all, and return the downstream socket as a
2104 * replacement for an ordinary SSH connection.
2106 *state = NULL;
2107 sfree(sharestate);
2108 sfree(sockname);
2109 return sock;
2111 case SHARE_UPSTREAM:
2113 * We are upstream. Set up sharestate properly and pass a copy
2114 * to the caller; return NULL, to tell ssh.c that it has to
2115 * make an ordinary connection after all.
2117 *state = sharestate;
2118 sharestate->listensock = sock;
2119 sharestate->connections = newtree234(share_connstate_cmp);
2120 sharestate->ssh = ssh;
2121 sharestate->server_verstring = NULL;
2122 sharestate->sockname = sockname;
2123 sharestate->nextid = 1;
2124 return NULL;
2127 return NULL;