]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - sshshare.c
Avoid logging pre-verstring EPIPE from sharing downstreams.
[PuTTY.git] / sshshare.c
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  */
5
6 /*
7  * Discussion and technical documentation
8  * ======================================
9  *
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).
16  *
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.)
27  *
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).
41  *
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).
49  *
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.
58  *
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.
66  *
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.
74  *
75  * Downstream-to-upstream protocol
76  * -------------------------------
77  *
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.
81  *
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
85  *
86  *   <protocol>-<version>-<softwareversion> [comments] \r\n
87  *
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".
91  *
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 :-)
98  *
99  * Thereafter, all data exchanged consists of a sequence of binary
100  * packets concatenated end-to-end, each of which is of the form
101  *
102  *     uint32     length of packet, N
103  *     byte[N]    N bytes of packet data
104  *
105  * and, since these are SSH-2 messages, the first data byte is taken
106  * to be the packet type code.
107  *
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.
114  *
115  * This protocol imposes a few additional requirements, over and above
116  * those of the standard SSH Connection Protocol:
117  *
118  * Message sizes are not permitted to exceed 0x4010 (16400) bytes,
119  * including their length header.
120  *
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.)
130  */
131
132 #include <stdio.h>
133 #include <stdlib.h>
134 #include <assert.h>
135 #include <limits.h>
136 #include <errno.h>
137
138 #include "putty.h"
139 #include "tree234.h"
140 #include "ssh.h"
141
142 struct ssh_sharing_state {
143     const struct plug_function_table *fn;
144     /* the above variable absolutely *must* be the first in this structure */
145
146     char *sockname;                  /* the socket name, kept for cleanup */
147     Socket listensock;               /* the master listening Socket */
148     tree234 *connections;            /* holds ssh_sharing_connstates */
149     unsigned nextid;                 /* preferred id for next connstate */
150     Ssh ssh;                         /* instance of the ssh backend */
151     char *server_verstring;          /* server version string after "SSH-" */
152 };
153
154 struct share_globreq;
155
156 struct ssh_sharing_connstate {
157     const struct plug_function_table *fn;
158     /* the above variable absolutely *must* be the first in this structure */
159
160     unsigned id;    /* used to identify this downstream in log messages */
161
162     Socket sock;                     /* the Socket for this connection */
163     struct ssh_sharing_state *parent;
164
165     int crLine;                        /* coroutine state for share_receive */
166
167     int sent_verstring, got_verstring, curr_packetlen;
168
169     unsigned char recvbuf[0x4010];
170     int recvlen;
171
172     /*
173      * Assorted state we have to remember about this downstream, so
174      * that we can clean it up appropriately when the downstream goes
175      * away.
176      */
177
178     /* Channels which don't have a downstream id, i.e. we've passed a
179      * CHANNEL_OPEN down from the server but not had an
180      * OPEN_CONFIRMATION or OPEN_FAILURE back. If downstream goes
181      * away, we respond to all of these with OPEN_FAILURE. */
182     tree234 *halfchannels;         /* stores 'struct share_halfchannel' */
183
184     /* Channels which do have a downstream id. We need to index these
185      * by both server id and upstream id, so we can find a channel
186      * when handling either an upward or a downward message referring
187      * to it. */
188     tree234 *channels_by_us;       /* stores 'struct share_channel' */
189     tree234 *channels_by_server;   /* stores 'struct share_channel' */
190
191     /* Another class of channel which doesn't have a downstream id.
192      * The difference between these and halfchannels is that xchannels
193      * do have an *upstream* id, because upstream has already accepted
194      * the channel request from the server. This arises in the case of
195      * X forwarding, where we have to accept the request and read the
196      * X authorisation data before we know whether the channel needs
197      * to be forwarded to a downstream. */
198     tree234 *xchannels_by_us;     /* stores 'struct share_xchannel' */
199     tree234 *xchannels_by_server; /* stores 'struct share_xchannel' */
200
201     /* Remote port forwarding requests in force. */
202     tree234 *forwardings;          /* stores 'struct share_forwarding' */
203
204     /* Global requests we've sent on to the server, pending replies. */
205     struct share_globreq *globreq_head, *globreq_tail;
206 };
207
208 struct share_halfchannel {
209     unsigned server_id;
210 };
211
212 /* States of a share_channel. */
213 enum {
214     OPEN,
215     SENT_CLOSE,
216     RCVD_CLOSE,
217     /* Downstream has sent CHANNEL_OPEN but server hasn't replied yet.
218      * If downstream goes away when a channel is in this state, we
219      * must wait for the server's response before starting to send
220      * CLOSE. Channels in this state are also not held in
221      * channels_by_server, because their server_id field is
222      * meaningless. */
223     UNACKNOWLEDGED
224 };
225
226 struct share_channel {
227     unsigned downstream_id, upstream_id, server_id;
228     int downstream_maxpkt;
229     int state;
230     /*
231      * Some channels (specifically, channels on which downstream has
232      * sent "x11-req") have the additional function of storing a set
233      * of downstream X authorisation data and a handle to an upstream
234      * fake set.
235      */
236     struct X11FakeAuth *x11_auth_upstream;
237     int x11_auth_proto;
238     char *x11_auth_data;
239     int x11_auth_datalen;
240     int x11_one_shot;
241 };
242
243 struct share_forwarding {
244     char *host;
245     int port;
246     int active;             /* has the server sent REQUEST_SUCCESS? */
247 };
248
249 struct share_xchannel_message {
250     struct share_xchannel_message *next;
251     int type;
252     unsigned char *data;
253     int datalen;
254 };
255
256 struct share_xchannel {
257     unsigned upstream_id, server_id;
258
259     /*
260      * xchannels come in two flavours: live and dead. Live ones are
261      * waiting for an OPEN_CONFIRMATION or OPEN_FAILURE from
262      * downstream; dead ones have had an OPEN_FAILURE, so they only
263      * exist as a means of letting us conveniently respond to further
264      * channel messages from the server until such time as the server
265      * sends us CHANNEL_CLOSE.
266      */
267     int live;
268
269     /*
270      * When we receive OPEN_CONFIRMATION, we will need to send a
271      * WINDOW_ADJUST to the server to synchronise the windows. For
272      * this purpose we need to know what window we have so far offered
273      * the server. We record this as exactly the value in the
274      * OPEN_CONFIRMATION that upstream sent us, adjusted by the amount
275      * by which the two X greetings differed in length.
276      */
277     int window;
278
279     /*
280      * Linked list of SSH messages from the server relating to this
281      * channel, which we queue up until downstream sends us an
282      * OPEN_CONFIRMATION and we can belatedly send them all on.
283      */
284     struct share_xchannel_message *msghead, *msgtail;
285 };
286
287 enum {
288     GLOBREQ_TCPIP_FORWARD,
289     GLOBREQ_CANCEL_TCPIP_FORWARD
290 };
291
292 struct share_globreq {
293     struct share_globreq *next;
294     int type;
295     int want_reply;
296     struct share_forwarding *fwd;
297 };
298
299 static int share_connstate_cmp(void *av, void *bv)
300 {
301     const struct ssh_sharing_connstate *a =
302         (const struct ssh_sharing_connstate *)av;
303     const struct ssh_sharing_connstate *b =
304         (const struct ssh_sharing_connstate *)bv;
305
306     if (a->id < b->id)
307         return -1;
308     else if (a->id > b->id)
309         return +1;
310     else
311         return 0;
312 }
313
314 static unsigned share_find_unused_id
315 (struct ssh_sharing_state *sharestate, unsigned first)
316 {
317     int low_orig, low, mid, high, high_orig;
318     struct ssh_sharing_connstate *cs;
319     unsigned ret;
320
321     /*
322      * Find the lowest unused downstream ID greater or equal to
323      * 'first'.
324      *
325      * Begin by seeing if 'first' itself is available. If it is, we'll
326      * just return it; if it's already in the tree, we'll find the
327      * tree index where it appears and use that for the next stage.
328      */
329     {
330         struct ssh_sharing_connstate dummy;
331         dummy.id = first;
332         cs = findrelpos234(sharestate->connections, &dummy, NULL,
333                            REL234_GE, &low_orig);
334         if (!cs)
335             return first;
336     }
337
338     /*
339      * Now binary-search using the counted B-tree, to find the largest
340      * ID which is in a contiguous sequence from the beginning of that
341      * range.
342      */
343     low = low_orig;
344     high = high_orig = count234(sharestate->connections);
345     while (high - low > 1) {
346         mid = (high + low) / 2;
347         cs = index234(sharestate->connections, mid);
348         if (cs->id == first + (mid - low_orig))
349             low = mid;                 /* this one is still in the sequence */
350         else
351             high = mid;                /* this one is past the end */
352     }
353
354     /*
355      * Now low is the tree index of the largest ID in the initial
356      * sequence. So the return value is one more than low's id, and we
357      * know low's id is given by the formula in the binary search loop
358      * above.
359      *
360      * (If an SSH connection went on for _enormously_ long, we might
361      * reach a point where all ids from 'first' to UINT_MAX were in
362      * use. In that situation the formula below would wrap round by
363      * one and return zero, which is conveniently the right way to
364      * signal 'no id available' from this function.)
365      */
366     ret = first + (low - low_orig) + 1;
367     {
368         struct ssh_sharing_connstate dummy;
369         dummy.id = ret;
370         assert(NULL == find234(sharestate->connections, &dummy, NULL));
371     }
372     return ret;
373 }
374
375 static int share_halfchannel_cmp(void *av, void *bv)
376 {
377     const struct share_halfchannel *a = (const struct share_halfchannel *)av;
378     const struct share_halfchannel *b = (const struct share_halfchannel *)bv;
379
380     if (a->server_id < b->server_id)
381         return -1;
382     else if (a->server_id > b->server_id)
383         return +1;
384     else
385         return 0;
386 }
387
388 static int share_channel_us_cmp(void *av, void *bv)
389 {
390     const struct share_channel *a = (const struct share_channel *)av;
391     const struct share_channel *b = (const struct share_channel *)bv;
392
393     if (a->upstream_id < b->upstream_id)
394         return -1;
395     else if (a->upstream_id > b->upstream_id)
396         return +1;
397     else
398         return 0;
399 }
400
401 static int share_channel_server_cmp(void *av, void *bv)
402 {
403     const struct share_channel *a = (const struct share_channel *)av;
404     const struct share_channel *b = (const struct share_channel *)bv;
405
406     if (a->server_id < b->server_id)
407         return -1;
408     else if (a->server_id > b->server_id)
409         return +1;
410     else
411         return 0;
412 }
413
414 static int share_xchannel_us_cmp(void *av, void *bv)
415 {
416     const struct share_xchannel *a = (const struct share_xchannel *)av;
417     const struct share_xchannel *b = (const struct share_xchannel *)bv;
418
419     if (a->upstream_id < b->upstream_id)
420         return -1;
421     else if (a->upstream_id > b->upstream_id)
422         return +1;
423     else
424         return 0;
425 }
426
427 static int share_xchannel_server_cmp(void *av, void *bv)
428 {
429     const struct share_xchannel *a = (const struct share_xchannel *)av;
430     const struct share_xchannel *b = (const struct share_xchannel *)bv;
431
432     if (a->server_id < b->server_id)
433         return -1;
434     else if (a->server_id > b->server_id)
435         return +1;
436     else
437         return 0;
438 }
439
440 static int share_forwarding_cmp(void *av, void *bv)
441 {
442     const struct share_forwarding *a = (const struct share_forwarding *)av;
443     const struct share_forwarding *b = (const struct share_forwarding *)bv;
444     int i;
445
446     if ((i = strcmp(a->host, b->host)) != 0)
447         return i;
448     else if (a->port < b->port)
449         return -1;
450     else if (a->port > b->port)
451         return +1;
452     else
453         return 0;
454 }
455
456 static void share_xchannel_free(struct share_xchannel *xc)
457 {
458     while (xc->msghead) {
459         struct share_xchannel_message *tmp = xc->msghead;
460         xc->msghead = tmp->next;
461         sfree(tmp);
462     }
463     sfree(xc);
464 }
465
466 static void share_connstate_free(struct ssh_sharing_connstate *cs)
467 {
468     struct share_halfchannel *hc;
469     struct share_xchannel *xc;
470     struct share_channel *chan;
471     struct share_forwarding *fwd;
472
473     while ((hc = (struct share_halfchannel *)
474             delpos234(cs->halfchannels, 0)) != NULL)
475         sfree(hc);
476     freetree234(cs->halfchannels);
477
478     /* All channels live in 'channels_by_us' but only some in
479      * 'channels_by_server', so we use the former to find the list of
480      * ones to free */
481     freetree234(cs->channels_by_server);
482     while ((chan = (struct share_channel *)
483             delpos234(cs->channels_by_us, 0)) != NULL)
484         sfree(chan);
485     freetree234(cs->channels_by_us);
486
487     /* But every xchannel is in both trees, so it doesn't matter which
488      * we use to free them. */
489     while ((xc = (struct share_xchannel *)
490             delpos234(cs->xchannels_by_us, 0)) != NULL)
491         share_xchannel_free(xc);
492     freetree234(cs->xchannels_by_us);
493     freetree234(cs->xchannels_by_server);
494
495     while ((fwd = (struct share_forwarding *)
496             delpos234(cs->forwardings, 0)) != NULL)
497         sfree(fwd);
498     freetree234(cs->forwardings);
499
500     while (cs->globreq_head) {
501         struct share_globreq *globreq = cs->globreq_head;
502         cs->globreq_head = cs->globreq_head->next;
503         sfree(globreq);
504     }
505
506     if (cs->sock)
507         sk_close(cs->sock);
508
509     sfree(cs);
510 }
511
512 void sharestate_free(void *v)
513 {
514     struct ssh_sharing_state *sharestate = (struct ssh_sharing_state *)v;
515     struct ssh_sharing_connstate *cs;
516
517     platform_ssh_share_cleanup(sharestate->sockname);
518
519     while ((cs = (struct ssh_sharing_connstate *)
520             delpos234(sharestate->connections, 0)) != NULL) {
521         share_connstate_free(cs);
522     }
523     freetree234(sharestate->connections);
524     if (sharestate->listensock) {
525         sk_close(sharestate->listensock);
526         sharestate->listensock = NULL;
527     }
528     sfree(sharestate->server_verstring);
529     sfree(sharestate->sockname);
530     sfree(sharestate);
531 }
532
533 static struct share_halfchannel *share_add_halfchannel
534     (struct ssh_sharing_connstate *cs, unsigned server_id)
535 {
536     struct share_halfchannel *hc = snew(struct share_halfchannel);
537     hc->server_id = server_id;
538     if (add234(cs->halfchannels, hc) != hc) {
539         /* Duplicate?! */
540         sfree(hc);
541         return NULL;
542     } else {
543         return hc;
544     }
545 }
546
547 static struct share_halfchannel *share_find_halfchannel
548     (struct ssh_sharing_connstate *cs, unsigned server_id)
549 {
550     struct share_halfchannel dummyhc;
551     dummyhc.server_id = server_id;
552     return find234(cs->halfchannels, &dummyhc, NULL);
553 }
554
555 static void share_remove_halfchannel(struct ssh_sharing_connstate *cs,
556                                      struct share_halfchannel *hc)
557 {
558     del234(cs->halfchannels, hc);
559     sfree(hc);
560 }
561
562 static struct share_channel *share_add_channel
563     (struct ssh_sharing_connstate *cs, unsigned downstream_id,
564      unsigned upstream_id, unsigned server_id, int state, int maxpkt)
565 {
566     struct share_channel *chan = snew(struct share_channel);
567     chan->downstream_id = downstream_id;
568     chan->upstream_id = upstream_id;
569     chan->server_id = server_id;
570     chan->state = state;
571     chan->downstream_maxpkt = maxpkt;
572     chan->x11_auth_upstream = NULL;
573     chan->x11_auth_data = NULL;
574     chan->x11_auth_proto = -1;
575     chan->x11_auth_datalen = 0;
576     chan->x11_one_shot = 0;
577     if (add234(cs->channels_by_us, chan) != chan) {
578         sfree(chan);
579         return NULL;
580     }
581     if (chan->state != UNACKNOWLEDGED) {
582         if (add234(cs->channels_by_server, chan) != chan) {
583             del234(cs->channels_by_us, chan);
584             sfree(chan);            
585             return NULL;
586         }
587     }
588     return chan;
589 }
590
591 static void share_channel_set_server_id(struct ssh_sharing_connstate *cs,
592                                         struct share_channel *chan,
593                                         unsigned server_id, int newstate)
594 {
595     chan->server_id = server_id;
596     chan->state = newstate;
597     assert(newstate != UNACKNOWLEDGED);
598     add234(cs->channels_by_server, chan);
599 }
600
601 static struct share_channel *share_find_channel_by_upstream
602     (struct ssh_sharing_connstate *cs, unsigned upstream_id)
603 {
604     struct share_channel dummychan;
605     dummychan.upstream_id = upstream_id;
606     return find234(cs->channels_by_us, &dummychan, NULL);
607 }
608
609 static struct share_channel *share_find_channel_by_server
610     (struct ssh_sharing_connstate *cs, unsigned server_id)
611 {
612     struct share_channel dummychan;
613     dummychan.server_id = server_id;
614     return find234(cs->channels_by_server, &dummychan, NULL);
615 }
616
617 static void share_remove_channel(struct ssh_sharing_connstate *cs,
618                                  struct share_channel *chan)
619 {
620     del234(cs->channels_by_us, chan);
621     del234(cs->channels_by_server, chan);
622     if (chan->x11_auth_upstream)
623         ssh_sharing_remove_x11_display(cs->parent->ssh,
624                                        chan->x11_auth_upstream);
625     sfree(chan->x11_auth_data);
626     sfree(chan);
627 }
628
629 static struct share_xchannel *share_add_xchannel
630     (struct ssh_sharing_connstate *cs,
631      unsigned upstream_id, unsigned server_id)
632 {
633     struct share_xchannel *xc = snew(struct share_xchannel);
634     xc->upstream_id = upstream_id;
635     xc->server_id = server_id;
636     xc->live = TRUE;
637     xc->msghead = xc->msgtail = NULL;
638     if (add234(cs->xchannels_by_us, xc) != xc) {
639         sfree(xc);
640         return NULL;
641     }
642     if (add234(cs->xchannels_by_server, xc) != xc) {
643         del234(cs->xchannels_by_us, xc);
644         sfree(xc);
645         return NULL;
646     }
647     return xc;
648 }
649
650 static struct share_xchannel *share_find_xchannel_by_upstream
651     (struct ssh_sharing_connstate *cs, unsigned upstream_id)
652 {
653     struct share_xchannel dummyxc;
654     dummyxc.upstream_id = upstream_id;
655     return find234(cs->xchannels_by_us, &dummyxc, NULL);
656 }
657
658 static struct share_xchannel *share_find_xchannel_by_server
659     (struct ssh_sharing_connstate *cs, unsigned server_id)
660 {
661     struct share_xchannel dummyxc;
662     dummyxc.server_id = server_id;
663     return find234(cs->xchannels_by_server, &dummyxc, NULL);
664 }
665
666 static void share_remove_xchannel(struct ssh_sharing_connstate *cs,
667                                  struct share_xchannel *xc)
668 {
669     del234(cs->xchannels_by_us, xc);
670     del234(cs->xchannels_by_server, xc);
671     share_xchannel_free(xc);
672 }
673
674 static struct share_forwarding *share_add_forwarding
675     (struct ssh_sharing_connstate *cs,
676      const char *host, int port)
677 {
678     struct share_forwarding *fwd = snew(struct share_forwarding);
679     fwd->host = dupstr(host);
680     fwd->port = port;
681     fwd->active = FALSE;
682     if (add234(cs->forwardings, fwd) != fwd) {
683         /* Duplicate?! */
684         sfree(fwd);
685         return NULL;
686     }
687     return fwd;
688 }
689
690 static struct share_forwarding *share_find_forwarding
691     (struct ssh_sharing_connstate *cs, const char *host, int port)
692 {
693     struct share_forwarding dummyfwd, *ret;
694     dummyfwd.host = dupstr(host);
695     dummyfwd.port = port;
696     ret = find234(cs->forwardings, &dummyfwd, NULL);
697     sfree(dummyfwd.host);
698     return ret;
699 }
700
701 static void share_remove_forwarding(struct ssh_sharing_connstate *cs,
702                                     struct share_forwarding *fwd)
703 {
704     del234(cs->forwardings, fwd);
705     sfree(fwd);
706 }
707
708 static void send_packet_to_downstream(struct ssh_sharing_connstate *cs,
709                                       int type, const void *pkt, int pktlen,
710                                       struct share_channel *chan)
711 {
712     if (!cs->sock) /* throw away all packets destined for a dead downstream */
713         return;
714
715     if (type == SSH2_MSG_CHANNEL_DATA) {
716         /*
717          * Special case which we take care of at a low level, so as to
718          * be sure to apply it in all cases. On rare occasions we
719          * might find that we have a channel for which the
720          * downstream's maximum packet size exceeds the max packet
721          * size we presented to the server on its behalf. (This can
722          * occur in X11 forwarding, where we have to send _our_
723          * CHANNEL_OPEN_CONFIRMATION before we discover which if any
724          * downstream the channel is destined for, so if that
725          * downstream turns out to present a smaller max packet size
726          * then we're in this situation.)
727          *
728          * If that happens, we just chop up the packet into pieces and
729          * send them as separate CHANNEL_DATA packets.
730          */
731         const char *upkt = (const char *)pkt;
732         char header[13]; /* 4 length + 1 type + 4 channel id + 4 string len */
733
734         int len = toint(GET_32BIT(upkt + 4));
735         upkt += 8;                /* skip channel id + length field */
736
737         if (len < 0 || len > pktlen - 8)
738             len = pktlen - 8;
739
740         do {
741             int this_len = (len > chan->downstream_maxpkt ?
742                             chan->downstream_maxpkt : len);
743             PUT_32BIT(header, this_len + 9);
744             header[4] = type;
745             PUT_32BIT(header + 5, chan->downstream_id);
746             PUT_32BIT(header + 9, this_len);
747             sk_write(cs->sock, header, 13);
748             sk_write(cs->sock, upkt, this_len);
749             len -= this_len;
750             upkt += this_len;
751         } while (len > 0);
752     } else {
753         /*
754          * Just do the obvious thing.
755          */
756         char header[9];
757
758         PUT_32BIT(header, pktlen + 1);
759         header[4] = type;
760         sk_write(cs->sock, header, 5);
761         sk_write(cs->sock, pkt, pktlen);
762     }
763 }
764
765 static void share_try_cleanup(struct ssh_sharing_connstate *cs)
766 {
767     int i;
768     struct share_halfchannel *hc;
769     struct share_channel *chan;
770     struct share_forwarding *fwd;
771
772     /*
773      * Any half-open channels, i.e. those for which we'd received
774      * CHANNEL_OPEN from the server but not passed back a response
775      * from downstream, should be responded to with OPEN_FAILURE.
776      */
777     while ((hc = (struct share_halfchannel *)
778             index234(cs->halfchannels, 0)) != NULL) {
779         static const char reason[] = "PuTTY downstream no longer available";
780         static const char lang[] = "en";
781         unsigned char packet[256];
782         int pos = 0;
783
784         PUT_32BIT(packet + pos, hc->server_id); pos += 4;
785         PUT_32BIT(packet + pos, SSH2_OPEN_CONNECT_FAILED); pos += 4;
786         PUT_32BIT(packet + pos, strlen(reason)); pos += 4;
787         memcpy(packet + pos, reason, strlen(reason)); pos += strlen(reason);
788         PUT_32BIT(packet + pos, strlen(lang)); pos += 4;
789         memcpy(packet + pos, lang, strlen(lang)); pos += strlen(lang);
790         ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
791                                         SSH2_MSG_CHANNEL_OPEN_FAILURE,
792                                         packet, pos, "cleanup after"
793                                         " downstream went away");
794
795         share_remove_halfchannel(cs, hc);
796     }
797
798     /*
799      * Any actually open channels should have a CHANNEL_CLOSE sent for
800      * them, unless we've already done so. We won't be able to
801      * actually clean them up until CHANNEL_CLOSE comes back from the
802      * server, though (unless the server happens to have sent a CLOSE
803      * already).
804      *
805      * Another annoying exception is UNACKNOWLEDGED channels, i.e.
806      * we've _sent_ a CHANNEL_OPEN to the server but not received an
807      * OPEN_CONFIRMATION or OPEN_FAILURE. We must wait for a reply
808      * before closing the channel, because until we see that reply we
809      * won't have the server's channel id to put in the close message.
810      */
811     for (i = 0; (chan = (struct share_channel *)
812                  index234(cs->channels_by_us, i)) != NULL; i++) {
813         unsigned char packet[256];
814         int pos = 0;
815
816         if (chan->state != SENT_CLOSE && chan->state != UNACKNOWLEDGED) {
817             PUT_32BIT(packet + pos, chan->server_id); pos += 4;
818             ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
819                                             SSH2_MSG_CHANNEL_CLOSE,
820                                             packet, pos, "cleanup after"
821                                             " downstream went away");
822             if (chan->state != RCVD_CLOSE) {
823                 chan->state = SENT_CLOSE;
824             } else {
825                 /* In this case, we _can_ clear up the channel now. */
826                 ssh_delete_sharing_channel(cs->parent->ssh, chan->upstream_id);
827                 share_remove_channel(cs, chan);
828                 i--;    /* don't accidentally skip one as a result */
829             }
830         }
831     }
832
833     /*
834      * Any remote port forwardings we're managing on behalf of this
835      * downstream should be cancelled. Again, we must defer those for
836      * which we haven't yet seen REQUEST_SUCCESS/FAILURE.
837      *
838      * We take a fire-and-forget approach during cleanup, not
839      * bothering to set want_reply.
840      */
841     for (i = 0; (fwd = (struct share_forwarding *)
842                  index234(cs->forwardings, i)) != NULL; i++) {
843         if (fwd->active) {
844             static const char request[] = "cancel-tcpip-forward";
845             char *packet = snewn(256 + strlen(fwd->host), char);
846             int pos = 0;
847
848             PUT_32BIT(packet + pos, strlen(request)); pos += 4;
849             memcpy(packet + pos, request, strlen(request));
850             pos += strlen(request);
851
852             packet[pos++] = 0;         /* !want_reply */
853
854             PUT_32BIT(packet + pos, strlen(fwd->host)); pos += 4;
855             memcpy(packet + pos, fwd->host, strlen(fwd->host));
856             pos += strlen(fwd->host);
857
858             PUT_32BIT(packet + pos, fwd->port); pos += 4;
859
860             ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
861                                             SSH2_MSG_GLOBAL_REQUEST,
862                                             packet, pos, "cleanup after"
863                                             " downstream went away");
864             sfree(packet);
865
866             share_remove_forwarding(cs, fwd);
867             i--;    /* don't accidentally skip one as a result */
868         }
869     }
870
871     if (count234(cs->halfchannels) == 0 &&
872         count234(cs->channels_by_us) == 0 &&
873         count234(cs->forwardings) == 0) {
874         /*
875          * Now we're _really_ done, so we can get rid of cs completely.
876          */
877         del234(cs->parent->connections, cs);
878         ssh_sharing_downstream_disconnected(cs->parent->ssh, cs->id);
879         share_connstate_free(cs);
880     }
881 }
882
883 static void share_begin_cleanup(struct ssh_sharing_connstate *cs)
884 {
885
886     sk_close(cs->sock);
887     cs->sock = NULL;
888
889     share_try_cleanup(cs);
890 }
891
892 static void share_disconnect(struct ssh_sharing_connstate *cs,
893                              const char *message)
894 {
895     static const char lang[] = "en";
896     int msglen = strlen(message);
897     char *packet = snewn(msglen + 256, char);
898     int pos = 0;
899
900     PUT_32BIT(packet + pos, SSH2_DISCONNECT_PROTOCOL_ERROR); pos += 4;
901
902     PUT_32BIT(packet + pos, msglen); pos += 4;
903     memcpy(packet + pos, message, msglen);
904     pos += msglen;
905
906     PUT_32BIT(packet + pos, strlen(lang)); pos += 4;
907     memcpy(packet + pos, lang, strlen(lang)); pos += strlen(lang);
908
909     send_packet_to_downstream(cs, SSH2_MSG_DISCONNECT, packet, pos, NULL);
910
911     share_begin_cleanup(cs);
912 }
913
914 static int share_closing(Plug plug, const char *error_msg, int error_code,
915                          int calling_back)
916 {
917     struct ssh_sharing_connstate *cs = (struct ssh_sharing_connstate *)plug;
918
919     if (error_msg) {
920 #ifdef BROKEN_PIPE_ERROR_CODE
921         /*
922          * Most of the time, we log what went wrong when a downstream
923          * disappears with a socket error. One exception, though, is
924          * receiving EPIPE when we haven't received a protocol version
925          * string from the downstream, because that can happen as a result
926          * of plink -shareexists (opening the connection and instantly
927          * closing it again without bothering to read our version string).
928          * So that one case is not treated as a log-worthy error.
929          */
930         printf("%d %d\n", error_code, cs->got_verstring);
931         if (error_code == BROKEN_PIPE_ERROR_CODE && !cs->got_verstring)
932             /* do nothing */;
933         else
934 #endif
935             ssh_sharing_logf(cs->parent->ssh, cs->id,
936                              "Socket error: %s", error_msg);
937     }
938     share_begin_cleanup(cs);
939     return 1;
940 }
941
942 static int getstring_inner(const void *vdata, int datalen,
943                            char **out, int *outlen)
944 {
945     const unsigned char *data = (const unsigned char *)vdata;
946     int len;
947
948     if (datalen < 4)
949         return FALSE;
950
951     len = toint(GET_32BIT(data));
952     if (len < 0 || len > datalen - 4)
953         return FALSE;
954
955     if (outlen)
956         *outlen = len + 4;         /* total size including length field */
957     if (out)
958         *out = dupprintf("%.*s", len, (char *)data + 4);
959     return TRUE;
960 }
961
962 static char *getstring(const void *data, int datalen)
963 {
964     char *ret;
965     if (getstring_inner(data, datalen, &ret, NULL))
966         return ret;
967     else
968         return NULL;
969 }
970
971 static int getstring_size(const void *data, int datalen)
972 {
973     int ret;
974     if (getstring_inner(data, datalen, NULL, &ret))
975         return ret;
976     else
977         return -1;
978 }
979
980 /*
981  * Append a message to the end of an xchannel's queue, with the length
982  * and type code filled in and the data block allocated but
983  * uninitialised.
984  */
985 struct share_xchannel_message *share_xchannel_add_message
986 (struct share_xchannel *xc, int type, int len)
987 {
988     unsigned char *block;
989     struct share_xchannel_message *msg;
990
991     /*
992      * Be a little tricksy here by allocating a single memory block
993      * containing both the 'struct share_xchannel_message' and the
994      * actual data. Simplifies freeing it later.
995      */
996     block = smalloc(sizeof(struct share_xchannel_message) + len);
997     msg = (struct share_xchannel_message *)block;
998     msg->data = block + sizeof(struct share_xchannel_message);
999     msg->datalen = len;
1000     msg->type = type;
1001
1002     /*
1003      * Queue it in the xchannel.
1004      */
1005     if (xc->msgtail)
1006         xc->msgtail->next = msg;
1007     else
1008         xc->msghead = msg;
1009     msg->next = NULL;
1010     xc->msgtail = msg;
1011
1012     return msg;
1013 }
1014
1015 void share_dead_xchannel_respond(struct ssh_sharing_connstate *cs,
1016                                  struct share_xchannel *xc)
1017 {
1018     /*
1019      * Handle queued incoming messages from the server destined for an
1020      * xchannel which is dead (i.e. downstream sent OPEN_FAILURE).
1021      */
1022     int delete = FALSE;
1023     while (xc->msghead) {
1024         struct share_xchannel_message *msg = xc->msghead;
1025         xc->msghead = msg->next;
1026
1027         if (msg->type == SSH2_MSG_CHANNEL_REQUEST && msg->datalen > 4) {
1028             /*
1029              * A CHANNEL_REQUEST is responded to by sending
1030              * CHANNEL_FAILURE, if it has want_reply set.
1031              */
1032             int wantreplypos = getstring_size(msg->data, msg->datalen);
1033             if (wantreplypos > 0 && wantreplypos < msg->datalen &&
1034                 msg->data[wantreplypos] != 0) {
1035                 unsigned char id[4];
1036                 PUT_32BIT(id, xc->server_id);
1037                 ssh_send_packet_from_downstream
1038                     (cs->parent->ssh, cs->id, SSH2_MSG_CHANNEL_FAILURE, id, 4,
1039                      "downstream refused X channel open");
1040             }
1041         } else if (msg->type == SSH2_MSG_CHANNEL_CLOSE) {
1042             /*
1043              * On CHANNEL_CLOSE we can discard the channel completely.
1044              */
1045             delete = TRUE;
1046         }
1047
1048         sfree(msg);
1049     }
1050     xc->msgtail = NULL;
1051     if (delete) {
1052         ssh_delete_sharing_channel(cs->parent->ssh, xc->upstream_id);
1053         share_remove_xchannel(cs, xc);
1054     }
1055 }
1056
1057 void share_xchannel_confirmation(struct ssh_sharing_connstate *cs,
1058                                  struct share_xchannel *xc,
1059                                  struct share_channel *chan,
1060                                  unsigned downstream_window)
1061 {
1062     unsigned char window_adjust[8];
1063
1064     /*
1065      * Send all the queued messages downstream.
1066      */
1067     while (xc->msghead) {
1068         struct share_xchannel_message *msg = xc->msghead;
1069         xc->msghead = msg->next;
1070
1071         if (msg->datalen >= 4)
1072             PUT_32BIT(msg->data, chan->downstream_id);
1073         send_packet_to_downstream(cs, msg->type,
1074                                   msg->data, msg->datalen, chan);
1075
1076         sfree(msg);
1077     }
1078
1079     /*
1080      * Send a WINDOW_ADJUST back upstream, to synchronise the window
1081      * size downstream thinks it's presented with the one we've
1082      * actually presented.
1083      */
1084     PUT_32BIT(window_adjust, xc->server_id);
1085     PUT_32BIT(window_adjust + 4, downstream_window - xc->window);
1086     ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
1087                                     SSH2_MSG_CHANNEL_WINDOW_ADJUST,
1088                                     window_adjust, 8, "window adjustment after"
1089                                     " downstream accepted X channel");
1090 }
1091
1092 void share_xchannel_failure(struct ssh_sharing_connstate *cs,
1093                             struct share_xchannel *xc)
1094 {
1095     /*
1096      * If downstream refuses to open our X channel at all for some
1097      * reason, we must respond by sending an emergency CLOSE upstream.
1098      */
1099     unsigned char id[4];
1100     PUT_32BIT(id, xc->server_id);
1101     ssh_send_packet_from_downstream
1102         (cs->parent->ssh, cs->id, SSH2_MSG_CHANNEL_CLOSE, id, 4,
1103          "downstream refused X channel open");
1104
1105     /*
1106      * Now mark the xchannel as dead, and respond to anything sent on
1107      * it until we see CLOSE for it in turn.
1108      */
1109     xc->live = FALSE;
1110     share_dead_xchannel_respond(cs, xc);
1111 }
1112
1113 void share_setup_x11_channel(void *csv, void *chanv,
1114                              unsigned upstream_id, unsigned server_id,
1115                              unsigned server_currwin, unsigned server_maxpkt,
1116                              unsigned client_adjusted_window,
1117                              const char *peer_addr, int peer_port, int endian,
1118                              int protomajor, int protominor,
1119                              const void *initial_data, int initial_len)
1120 {
1121     struct ssh_sharing_connstate *cs = (struct ssh_sharing_connstate *)csv;
1122     struct share_channel *chan = (struct share_channel *)chanv;
1123     struct share_xchannel *xc;
1124     struct share_xchannel_message *msg;
1125     void *greeting;
1126     int greeting_len;
1127     unsigned char *pkt;
1128     int pktlen;
1129
1130     /*
1131      * Create an xchannel containing data we've already received from
1132      * the X client, and preload it with a CHANNEL_DATA message
1133      * containing our own made-up authorisation greeting and any
1134      * additional data sent from the server so far.
1135      */
1136     xc = share_add_xchannel(cs, upstream_id, server_id);
1137     greeting = x11_make_greeting(endian, protomajor, protominor,
1138                                  chan->x11_auth_proto,
1139                                  chan->x11_auth_data, chan->x11_auth_datalen,
1140                                  peer_addr, peer_port, &greeting_len);
1141     msg = share_xchannel_add_message(xc, SSH2_MSG_CHANNEL_DATA,
1142                                      8 + greeting_len + initial_len);
1143     /* leave the channel id field unfilled - we don't know the
1144      * downstream id yet, of course */
1145     PUT_32BIT(msg->data + 4, greeting_len + initial_len);
1146     memcpy(msg->data + 8, greeting, greeting_len);
1147     memcpy(msg->data + 8 + greeting_len, initial_data, initial_len);
1148     sfree(greeting);
1149
1150     xc->window = client_adjusted_window + greeting_len;
1151
1152     /*
1153      * Send on a CHANNEL_OPEN to downstream.
1154      */
1155     pktlen = 27 + strlen(peer_addr);
1156     pkt = snewn(pktlen, unsigned char);
1157     PUT_32BIT(pkt, 3);                 /* strlen("x11") */
1158     memcpy(pkt+4, "x11", 3);
1159     PUT_32BIT(pkt+7, server_id);
1160     PUT_32BIT(pkt+11, server_currwin);
1161     PUT_32BIT(pkt+15, server_maxpkt);
1162     PUT_32BIT(pkt+19, strlen(peer_addr));
1163     memcpy(pkt+23, peer_addr, strlen(peer_addr));
1164     PUT_32BIT(pkt+23+strlen(peer_addr), peer_port);
1165     send_packet_to_downstream(cs, SSH2_MSG_CHANNEL_OPEN, pkt, pktlen, NULL);
1166     sfree(pkt);
1167
1168     /*
1169      * If this was a once-only X forwarding, clean it up now.
1170      */
1171     if (chan->x11_one_shot) {
1172         ssh_sharing_remove_x11_display(cs->parent->ssh,
1173                                        chan->x11_auth_upstream);
1174         chan->x11_auth_upstream = NULL;
1175         sfree(chan->x11_auth_data);
1176         chan->x11_auth_proto = -1;
1177         chan->x11_auth_datalen = 0;
1178         chan->x11_one_shot = 0;
1179     }
1180 }
1181
1182 void share_got_pkt_from_server(void *csv, int type,
1183                                unsigned char *pkt, int pktlen)
1184 {
1185     struct ssh_sharing_connstate *cs = (struct ssh_sharing_connstate *)csv;
1186     struct share_globreq *globreq;
1187     int id_pos;
1188     unsigned upstream_id, server_id;
1189     struct share_channel *chan;
1190     struct share_xchannel *xc;
1191
1192     switch (type) {
1193       case SSH2_MSG_REQUEST_SUCCESS:
1194       case SSH2_MSG_REQUEST_FAILURE:
1195         globreq = cs->globreq_head;
1196         if (globreq->type == GLOBREQ_TCPIP_FORWARD) {
1197             if (type == SSH2_MSG_REQUEST_FAILURE) {
1198                 share_remove_forwarding(cs, globreq->fwd);
1199             } else {
1200                 globreq->fwd->active = TRUE;
1201             }
1202         } else if (globreq->type == GLOBREQ_CANCEL_TCPIP_FORWARD) {
1203             if (type == SSH2_MSG_REQUEST_SUCCESS) {
1204                 share_remove_forwarding(cs, globreq->fwd);
1205             }
1206         }
1207         if (globreq->want_reply) {
1208             send_packet_to_downstream(cs, type, pkt, pktlen, NULL);
1209         }
1210         cs->globreq_head = globreq->next;
1211         sfree(globreq);
1212         if (cs->globreq_head == NULL)
1213             cs->globreq_tail = NULL;
1214
1215         if (!cs->sock) {
1216             /* Retry cleaning up this connection, in case that reply
1217              * was the last thing we were waiting for. */
1218             share_try_cleanup(cs);
1219         }
1220
1221         break;
1222
1223       case SSH2_MSG_CHANNEL_OPEN:
1224         id_pos = getstring_size(pkt, pktlen);
1225         assert(id_pos >= 0);
1226         server_id = GET_32BIT(pkt + id_pos);
1227         share_add_halfchannel(cs, server_id);
1228
1229         send_packet_to_downstream(cs, type, pkt, pktlen, NULL);
1230         break;
1231
1232       case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
1233       case SSH2_MSG_CHANNEL_OPEN_FAILURE:
1234       case SSH2_MSG_CHANNEL_CLOSE:
1235       case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1236       case SSH2_MSG_CHANNEL_DATA:
1237       case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1238       case SSH2_MSG_CHANNEL_EOF:
1239       case SSH2_MSG_CHANNEL_REQUEST:
1240       case SSH2_MSG_CHANNEL_SUCCESS:
1241       case SSH2_MSG_CHANNEL_FAILURE:
1242         /*
1243          * All these messages have the recipient channel id as the
1244          * first uint32 field in the packet. Substitute the downstream
1245          * channel id for our one and pass the packet downstream.
1246          */
1247         assert(pktlen >= 4);
1248         upstream_id = GET_32BIT(pkt);
1249         if ((chan = share_find_channel_by_upstream(cs, upstream_id)) != NULL) {
1250             /*
1251              * The normal case: this id refers to an open channel.
1252              */
1253             PUT_32BIT(pkt, chan->downstream_id);
1254             send_packet_to_downstream(cs, type, pkt, pktlen, chan);
1255
1256             /*
1257              * Update the channel state, for messages that need it.
1258              */
1259             if (type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
1260                 if (chan->state == UNACKNOWLEDGED && pktlen >= 8) {
1261                     share_channel_set_server_id(cs, chan, GET_32BIT(pkt+4),
1262                                                 OPEN);
1263                     if (!cs->sock) {
1264                         /* Retry cleaning up this connection, so that we
1265                          * can send an immediate CLOSE on this channel for
1266                          * which we now know the server id. */
1267                         share_try_cleanup(cs);
1268                     }
1269                 }
1270             } else if (type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
1271                 ssh_delete_sharing_channel(cs->parent->ssh, chan->upstream_id);
1272                 share_remove_channel(cs, chan);
1273             } else if (type == SSH2_MSG_CHANNEL_CLOSE) {
1274                 if (chan->state == SENT_CLOSE) {
1275                     ssh_delete_sharing_channel(cs->parent->ssh,
1276                                                chan->upstream_id);
1277                     share_remove_channel(cs, chan);
1278                     if (!cs->sock) {
1279                         /* Retry cleaning up this connection, in case this
1280                          * channel closure was the last thing we were
1281                          * waiting for. */
1282                         share_try_cleanup(cs);
1283                     }
1284                 } else {
1285                     chan->state = RCVD_CLOSE;
1286                 }
1287             }
1288         } else if ((xc = share_find_xchannel_by_upstream(cs, upstream_id))
1289                    != NULL) {
1290             /*
1291              * The unusual case: this id refers to an xchannel. Add it
1292              * to the xchannel's queue.
1293              */
1294             struct share_xchannel_message *msg;
1295
1296             msg = share_xchannel_add_message(xc, type, pktlen);
1297             memcpy(msg->data, pkt, pktlen);
1298
1299             /* If the xchannel is dead, then also respond to it (which
1300              * may involve deleting the channel). */
1301             if (!xc->live)
1302                 share_dead_xchannel_respond(cs, xc);
1303         }
1304         break;
1305
1306       default:
1307         assert(!"This packet type should never have come from ssh.c");
1308         break;
1309     }
1310 }
1311
1312 static void share_got_pkt_from_downstream(struct ssh_sharing_connstate *cs,
1313                                           int type,
1314                                           unsigned char *pkt, int pktlen)
1315 {
1316     char *request_name;
1317     struct share_forwarding *fwd;
1318     int id_pos;
1319     unsigned old_id, new_id, server_id;
1320     struct share_globreq *globreq;
1321     struct share_channel *chan;
1322     struct share_halfchannel *hc;
1323     struct share_xchannel *xc;
1324     char *err = NULL;
1325
1326     switch (type) {
1327       case SSH2_MSG_DISCONNECT:
1328         /*
1329          * This message stops here: if downstream is disconnecting
1330          * from us, that doesn't mean we want to disconnect from the
1331          * SSH server. Close the downstream connection and start
1332          * cleanup.
1333          */
1334         share_begin_cleanup(cs);
1335         break;
1336
1337       case SSH2_MSG_GLOBAL_REQUEST:
1338         /*
1339          * The only global requests we understand are "tcpip-forward"
1340          * and "cancel-tcpip-forward". Since those require us to
1341          * maintain state, we must assume that other global requests
1342          * will probably require that too, and so we don't forward on
1343          * any request we don't understand.
1344          */
1345         request_name = getstring(pkt, pktlen);
1346         if (request_name == NULL) {
1347             err = dupprintf("Truncated GLOBAL_REQUEST packet");
1348             goto confused;
1349         }
1350
1351         if (!strcmp(request_name, "tcpip-forward")) {
1352             int wantreplypos, orig_wantreply, port, ret;
1353             char *host;
1354
1355             sfree(request_name);
1356
1357             /*
1358              * Pick the packet apart to find the want_reply field and
1359              * the host/port we're going to ask to listen on.
1360              */
1361             wantreplypos = getstring_size(pkt, pktlen);
1362             if (wantreplypos < 0 || wantreplypos >= pktlen) {
1363                 err = dupprintf("Truncated GLOBAL_REQUEST packet");
1364                 goto confused;
1365             }
1366             orig_wantreply = pkt[wantreplypos];
1367             port = getstring_size(pkt + (wantreplypos + 1),
1368                                   pktlen - (wantreplypos + 1));
1369             port += (wantreplypos + 1);
1370             if (port < 0 || port > pktlen - 4) {
1371                 err = dupprintf("Truncated GLOBAL_REQUEST packet");
1372                 goto confused;
1373             }
1374             host = getstring(pkt + (wantreplypos + 1),
1375                              pktlen - (wantreplypos + 1));
1376             assert(host != NULL);
1377             port = GET_32BIT(pkt + port);
1378
1379             /*
1380              * See if we can allocate space in ssh.c's tree of remote
1381              * port forwardings. If we can't, it's because another
1382              * client sharing this connection has already allocated
1383              * the identical port forwarding, so we take it on
1384              * ourselves to manufacture a failure packet and send it
1385              * back to downstream.
1386              */
1387             ret = ssh_alloc_sharing_rportfwd(cs->parent->ssh, host, port, cs);
1388             if (!ret) {
1389                 if (orig_wantreply) {
1390                     send_packet_to_downstream(cs, SSH2_MSG_REQUEST_FAILURE,
1391                                               "", 0, NULL);
1392                 }
1393             } else {
1394                 /*
1395                  * We've managed to make space for this forwarding
1396                  * locally. Pass the request on to the SSH server, but
1397                  * set want_reply even if it wasn't originally set, so
1398                  * that we know whether this forwarding needs to be
1399                  * cleaned up if downstream goes away.
1400                  */
1401                 int old_wantreply = pkt[wantreplypos];
1402                 pkt[wantreplypos] = 1;
1403                 ssh_send_packet_from_downstream
1404                     (cs->parent->ssh, cs->id, type, pkt, pktlen,
1405                      old_wantreply ? NULL : "upstream added want_reply flag");
1406                 fwd = share_add_forwarding(cs, host, port);
1407                 ssh_sharing_queue_global_request(cs->parent->ssh, cs);
1408
1409                 if (fwd) {
1410                     globreq = snew(struct share_globreq);
1411                     globreq->next = NULL;
1412                     if (cs->globreq_tail)
1413                         cs->globreq_tail->next = globreq;
1414                     else
1415                         cs->globreq_head = globreq;
1416                     globreq->fwd = fwd;
1417                     globreq->want_reply = orig_wantreply;
1418                     globreq->type = GLOBREQ_TCPIP_FORWARD;
1419                 }
1420             }
1421
1422             sfree(host);
1423         } else if (!strcmp(request_name, "cancel-tcpip-forward")) {
1424             int wantreplypos, orig_wantreply, port;
1425             char *host;
1426             struct share_forwarding *fwd;
1427
1428             sfree(request_name);
1429
1430             /*
1431              * Pick the packet apart to find the want_reply field and
1432              * the host/port we're going to ask to listen on.
1433              */
1434             wantreplypos = getstring_size(pkt, pktlen);
1435             if (wantreplypos < 0 || wantreplypos >= pktlen) {
1436                 err = dupprintf("Truncated GLOBAL_REQUEST packet");
1437                 goto confused;
1438             }
1439             orig_wantreply = pkt[wantreplypos];
1440             port = getstring_size(pkt + (wantreplypos + 1),
1441                                   pktlen - (wantreplypos + 1));
1442             port += (wantreplypos + 1);
1443             if (port < 0 || port > pktlen - 4) {
1444                 err = dupprintf("Truncated GLOBAL_REQUEST packet");
1445                 goto confused;
1446             }
1447             host = getstring(pkt + (wantreplypos + 1),
1448                              pktlen - (wantreplypos + 1));
1449             assert(host != NULL);
1450             port = GET_32BIT(pkt + port);
1451
1452             /*
1453              * Look up the existing forwarding with these details.
1454              */
1455             fwd = share_find_forwarding(cs, host, port);
1456             if (!fwd) {
1457                 if (orig_wantreply) {
1458                     send_packet_to_downstream(cs, SSH2_MSG_REQUEST_FAILURE,
1459                                               "", 0, NULL);
1460                 }
1461             } else {
1462                 /*
1463                  * Pass the cancel request on to the SSH server, but
1464                  * set want_reply even if it wasn't originally set, so
1465                  * that _we_ know whether the forwarding has been
1466                  * deleted even if downstream doesn't want to know.
1467                  */
1468                 int old_wantreply = pkt[wantreplypos];
1469                 pkt[wantreplypos] = 1;
1470                 ssh_send_packet_from_downstream
1471                     (cs->parent->ssh, cs->id, type, pkt, pktlen,
1472                      old_wantreply ? NULL : "upstream added want_reply flag");
1473                 ssh_sharing_queue_global_request(cs->parent->ssh, cs);
1474             }
1475
1476             sfree(host);
1477         } else {
1478             /*
1479              * Request we don't understand. Manufacture a failure
1480              * message if an answer was required.
1481              */
1482             int wantreplypos;
1483
1484             sfree(request_name);
1485
1486             wantreplypos = getstring_size(pkt, pktlen);
1487             if (wantreplypos < 0 || wantreplypos >= pktlen) {
1488                 err = dupprintf("Truncated GLOBAL_REQUEST packet");
1489                 goto confused;
1490             }
1491             if (pkt[wantreplypos])
1492                 send_packet_to_downstream(cs, SSH2_MSG_REQUEST_FAILURE,
1493                                           "", 0, NULL);
1494         }
1495         break;
1496
1497       case SSH2_MSG_CHANNEL_OPEN:
1498         /* Sender channel id comes after the channel type string */
1499         id_pos = getstring_size(pkt, pktlen);
1500         if (id_pos < 0 || id_pos > pktlen - 12) {
1501             err = dupprintf("Truncated CHANNEL_OPEN packet");
1502             goto confused;
1503         }
1504
1505         old_id = GET_32BIT(pkt + id_pos);
1506         new_id = ssh_alloc_sharing_channel(cs->parent->ssh, cs);
1507         share_add_channel(cs, old_id, new_id, 0, UNACKNOWLEDGED,
1508                           GET_32BIT(pkt + id_pos + 8));
1509         PUT_32BIT(pkt + id_pos, new_id);
1510         ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
1511                                         type, pkt, pktlen, NULL);
1512         break;
1513
1514       case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
1515         if (pktlen < 16) {
1516             err = dupprintf("Truncated CHANNEL_OPEN_CONFIRMATION packet");
1517             goto confused;
1518         }
1519
1520         id_pos = 4;  /* sender channel id is 2nd uint32 field in packet */
1521         old_id = GET_32BIT(pkt + id_pos);
1522
1523         server_id = GET_32BIT(pkt);
1524         /* This server id may refer to either a halfchannel or an xchannel. */
1525         hc = NULL, xc = NULL;          /* placate optimiser */
1526         if ((hc = share_find_halfchannel(cs, server_id)) != NULL) {
1527             new_id = ssh_alloc_sharing_channel(cs->parent->ssh, cs);
1528         } else if ((xc = share_find_xchannel_by_server(cs, server_id))
1529                    != NULL) {
1530             new_id = xc->upstream_id;
1531         } else {
1532             err = dupprintf("CHANNEL_OPEN_CONFIRMATION packet cited unknown channel %u", (unsigned)server_id);
1533             goto confused;
1534         }
1535             
1536         PUT_32BIT(pkt + id_pos, new_id);
1537
1538         chan = share_add_channel(cs, old_id, new_id, server_id, OPEN,
1539                                  GET_32BIT(pkt + 12));
1540
1541         if (hc) {
1542             ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
1543                                             type, pkt, pktlen, NULL);
1544             share_remove_halfchannel(cs, hc);
1545         } else if (xc) {
1546             unsigned downstream_window = GET_32BIT(pkt + 8);
1547             if (downstream_window < 256) {
1548                 err = dupprintf("Initial window size for x11 channel must be at least 256 (got %u)", downstream_window);
1549                 goto confused;
1550             }
1551             share_xchannel_confirmation(cs, xc, chan, downstream_window);
1552             share_remove_xchannel(cs, xc);
1553         }
1554
1555         break;
1556
1557       case SSH2_MSG_CHANNEL_OPEN_FAILURE:
1558         if (pktlen < 4) {
1559             err = dupprintf("Truncated CHANNEL_OPEN_FAILURE packet");
1560             goto confused;
1561         }
1562
1563         server_id = GET_32BIT(pkt);
1564         /* This server id may refer to either a halfchannel or an xchannel. */
1565         if ((hc = share_find_halfchannel(cs, server_id)) != NULL) {
1566             ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
1567                                             type, pkt, pktlen, NULL);
1568             share_remove_halfchannel(cs, hc);
1569         } else if ((xc = share_find_xchannel_by_server(cs, server_id))
1570                    != NULL) {
1571             share_xchannel_failure(cs, xc);
1572         } else {
1573             err = dupprintf("CHANNEL_OPEN_FAILURE packet cited unknown channel %u", (unsigned)server_id);
1574             goto confused;
1575         }
1576
1577         break;
1578
1579       case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1580       case SSH2_MSG_CHANNEL_DATA:
1581       case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1582       case SSH2_MSG_CHANNEL_EOF:
1583       case SSH2_MSG_CHANNEL_CLOSE:
1584       case SSH2_MSG_CHANNEL_REQUEST:
1585       case SSH2_MSG_CHANNEL_SUCCESS:
1586       case SSH2_MSG_CHANNEL_FAILURE:
1587       case SSH2_MSG_IGNORE:
1588       case SSH2_MSG_DEBUG:
1589         if (type == SSH2_MSG_CHANNEL_REQUEST &&
1590             (request_name = getstring(pkt + 4, pktlen - 4)) != NULL) {
1591             /*
1592              * Agent forwarding requests from downstream are treated
1593              * specially. Because OpenSSHD doesn't let us enable agent
1594              * forwarding independently per session channel, and in
1595              * particular because the OpenSSH-defined agent forwarding
1596              * protocol does not mark agent-channel requests with the
1597              * id of the session channel they originate from, the only
1598              * way we can implement agent forwarding in a
1599              * connection-shared PuTTY is to forward the _upstream_
1600              * agent. Hence, we unilaterally deny agent forwarding
1601              * requests from downstreams if we aren't prepared to
1602              * forward an agent ourselves.
1603              *
1604              * (If we are, then we dutifully pass agent forwarding
1605              * requests upstream. OpenSSHD has the curious behaviour
1606              * that all but the first such request will be rejected,
1607              * but all session channels opened after the first request
1608              * get agent forwarding enabled whether they ask for it or
1609              * not; but that's not our concern, since other SSH
1610              * servers supporting the same piece of protocol might in
1611              * principle at least manage to enable agent forwarding on
1612              * precisely the channels that requested it, even if the
1613              * subsequent CHANNEL_OPENs still can't be associated with
1614              * a parent session channel.)
1615              */
1616             if (!strcmp(request_name, "auth-agent-req@openssh.com") &&
1617                 !ssh_agent_forwarding_permitted(cs->parent->ssh)) {
1618                 unsigned server_id = GET_32BIT(pkt);
1619                 unsigned char recipient_id[4];
1620
1621                 sfree(request_name);
1622
1623                 chan = share_find_channel_by_server(cs, server_id);
1624                 if (chan) {
1625                     PUT_32BIT(recipient_id, chan->downstream_id);
1626                     send_packet_to_downstream(cs, SSH2_MSG_CHANNEL_FAILURE,
1627                                               recipient_id, 4, NULL);
1628                 } else {
1629                     char *buf = dupprintf("Agent forwarding request for "
1630                                           "unrecognised channel %u", server_id);
1631                     share_disconnect(cs, buf);
1632                     sfree(buf);
1633                     return;
1634                 }
1635                 break;
1636             }
1637
1638             /*
1639              * Another thing we treat specially is X11 forwarding
1640              * requests. For these, we have to make up another set of
1641              * X11 auth data, and enter it into our SSH connection's
1642              * list of possible X11 authorisation credentials so that
1643              * when we see an X11 channel open request we can know
1644              * whether it's one to handle locally or one to pass on to
1645              * a downstream, and if the latter, which one.
1646              */
1647             if (!strcmp(request_name, "x11-req")) {
1648                 unsigned server_id = GET_32BIT(pkt);
1649                 int want_reply, single_connection, screen;
1650                 char *auth_proto_str, *auth_data;
1651                 int auth_proto, protolen, datalen;
1652                 int pos;
1653
1654                 sfree(request_name);
1655
1656                 chan = share_find_channel_by_server(cs, server_id);
1657                 if (!chan) {
1658                     char *buf = dupprintf("X11 forwarding request for "
1659                                           "unrecognised channel %u", server_id);
1660                     share_disconnect(cs, buf);
1661                     sfree(buf);
1662                     return;
1663                 }
1664
1665                 /*
1666                  * Pick apart the whole message to find the downstream
1667                  * auth details.
1668                  */
1669                 /* we have already seen: 4 bytes channel id, 4+7 request name */
1670                 if (pktlen < 17) {
1671                     err = dupprintf("Truncated CHANNEL_REQUEST(\"x11\") packet");
1672                     goto confused;
1673                 }
1674                 want_reply = pkt[15] != 0;
1675                 single_connection = pkt[16] != 0;
1676                 auth_proto_str = getstring(pkt+17, pktlen-17);
1677                 auth_proto = x11_identify_auth_proto(auth_proto_str);
1678                 sfree(auth_proto_str);
1679                 pos = 17 + getstring_size(pkt+17, pktlen-17);
1680                 auth_data = getstring(pkt+pos, pktlen-pos);
1681                 pos += getstring_size(pkt+pos, pktlen-pos);
1682
1683                 if (pktlen < pos+4) {
1684                     err = dupprintf("Truncated CHANNEL_REQUEST(\"x11\") packet");
1685                     sfree(auth_data);
1686                     goto confused;
1687                 }
1688                 screen = GET_32BIT(pkt+pos);
1689
1690                 if (auth_proto < 0) {
1691                     /* Reject due to not understanding downstream's
1692                      * requested authorisation method. */
1693                     unsigned char recipient_id[4];
1694                     PUT_32BIT(recipient_id, chan->downstream_id);
1695                     send_packet_to_downstream(cs, SSH2_MSG_CHANNEL_FAILURE,
1696                                               recipient_id, 4, NULL);
1697                     sfree(auth_data);
1698                     break;
1699                 }
1700
1701                 chan->x11_auth_proto = auth_proto;
1702                 chan->x11_auth_data = x11_dehexify(auth_data,
1703                                                    &chan->x11_auth_datalen);
1704                 sfree(auth_data);
1705                 chan->x11_auth_upstream =
1706                     ssh_sharing_add_x11_display(cs->parent->ssh, auth_proto,
1707                                                 cs, chan);
1708                 chan->x11_one_shot = single_connection;
1709
1710                 /*
1711                  * Now construct a replacement X forwarding request,
1712                  * containing our own auth data, and send that to the
1713                  * server.
1714                  */
1715                 protolen = strlen(chan->x11_auth_upstream->protoname);
1716                 datalen = strlen(chan->x11_auth_upstream->datastring);
1717                 pktlen = 29+protolen+datalen;
1718                 pkt = snewn(pktlen, unsigned char);
1719                 PUT_32BIT(pkt, server_id);
1720                 PUT_32BIT(pkt+4, 7);   /* strlen("x11-req") */
1721                 memcpy(pkt+8, "x11-req", 7);
1722                 pkt[15] = want_reply;
1723                 pkt[16] = single_connection;
1724                 PUT_32BIT(pkt+17, protolen);
1725                 memcpy(pkt+21, chan->x11_auth_upstream->protoname, protolen);
1726                 PUT_32BIT(pkt+21+protolen, datalen);
1727                 memcpy(pkt+25+protolen, chan->x11_auth_upstream->datastring,
1728                        datalen);
1729                 PUT_32BIT(pkt+25+protolen+datalen, screen);
1730                 ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
1731                                                 SSH2_MSG_CHANNEL_REQUEST,
1732                                                 pkt, pktlen, NULL);
1733                 sfree(pkt);
1734
1735                 break;
1736             }
1737
1738             sfree(request_name);
1739         }
1740
1741         ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
1742                                         type, pkt, pktlen, NULL);
1743         if (type == SSH2_MSG_CHANNEL_CLOSE && pktlen >= 4) {
1744             server_id = GET_32BIT(pkt);
1745             chan = share_find_channel_by_server(cs, server_id);
1746             if (chan) {
1747                 if (chan->state == RCVD_CLOSE) {
1748                     ssh_delete_sharing_channel(cs->parent->ssh,
1749                                                chan->upstream_id);
1750                     share_remove_channel(cs, chan);
1751                 } else {
1752                     chan->state = SENT_CLOSE;
1753                 }
1754             }
1755         }
1756         break;
1757
1758       default:
1759         err = dupprintf("Unexpected packet type %d\n", type);
1760         goto confused;
1761
1762         /*
1763          * Any other packet type is unexpected. In particular, we
1764          * never pass GLOBAL_REQUESTs downstream, so we never expect
1765          * to see SSH2_MSG_REQUEST_{SUCCESS,FAILURE}.
1766          */
1767       confused:
1768         assert(err != NULL);
1769         share_disconnect(cs, err);
1770         sfree(err);
1771         break;
1772     }
1773 }
1774
1775 /*
1776  * Coroutine macros similar to, but simplified from, those in ssh.c.
1777  */
1778 #define crBegin(v)      { int *crLine = &v; switch(v) { case 0:;
1779 #define crFinish(z)     } *crLine = 0; return (z); }
1780 #define crGetChar(c) do                                         \
1781     {                                                           \
1782         while (len == 0) {                                      \
1783             *crLine =__LINE__; return 1; case __LINE__:;        \
1784         }                                                       \
1785         len--;                                                  \
1786         (c) = (unsigned char)*data++;                           \
1787     } while (0)
1788
1789 static int share_receive(Plug plug, int urgent, char *data, int len)
1790 {
1791     struct ssh_sharing_connstate *cs = (struct ssh_sharing_connstate *)plug;
1792     static const char expected_verstring_prefix[] =
1793         "SSHCONNECTION@putty.projects.tartarus.org-2.0-";
1794     unsigned char c;
1795
1796     crBegin(cs->crLine);
1797
1798     /*
1799      * First read the version string from downstream.
1800      */
1801     cs->recvlen = 0;
1802     while (1) {
1803         crGetChar(c);
1804         if (c == '\012')
1805             break;
1806         if (cs->recvlen >= sizeof(cs->recvbuf)) {
1807             char *buf = dupprintf("Version string far too long\n");
1808             share_disconnect(cs, buf);
1809             sfree(buf);
1810             goto dead;
1811         }
1812         cs->recvbuf[cs->recvlen++] = c;
1813     }
1814
1815     /*
1816      * Now parse the version string to make sure it's at least vaguely
1817      * sensible, and log it.
1818      */
1819     if (cs->recvlen < sizeof(expected_verstring_prefix)-1 ||
1820         memcmp(cs->recvbuf, expected_verstring_prefix,
1821                sizeof(expected_verstring_prefix) - 1)) {
1822         char *buf = dupprintf("Version string did not have expected prefix\n");
1823         share_disconnect(cs, buf);
1824         sfree(buf);
1825         goto dead;
1826     }
1827     if (cs->recvlen > 0 && cs->recvbuf[cs->recvlen-1] == '\015')
1828         cs->recvlen--;                 /* trim off \r before \n */
1829     ssh_sharing_logf(cs->parent->ssh, cs->id,
1830                      "Downstream version string: %.*s",
1831                      cs->recvlen, cs->recvbuf);
1832     cs->got_verstring = TRUE;
1833
1834     /*
1835      * Loop round reading packets.
1836      */
1837     while (1) {
1838         cs->recvlen = 0;
1839         while (cs->recvlen < 4) {
1840             crGetChar(c);
1841             cs->recvbuf[cs->recvlen++] = c;
1842         }
1843         cs->curr_packetlen = toint(GET_32BIT(cs->recvbuf) + 4);
1844         if (cs->curr_packetlen < 5 ||
1845             cs->curr_packetlen > sizeof(cs->recvbuf)) {
1846             char *buf = dupprintf("Bad packet length %u\n",
1847                                   (unsigned)cs->curr_packetlen);
1848             share_disconnect(cs, buf);
1849             sfree(buf);
1850             goto dead;
1851         }
1852         while (cs->recvlen < cs->curr_packetlen) {
1853             crGetChar(c);
1854             cs->recvbuf[cs->recvlen++] = c;
1855         }
1856
1857         share_got_pkt_from_downstream(cs, cs->recvbuf[4],
1858                                       cs->recvbuf + 5, cs->recvlen - 5);
1859     }
1860
1861   dead:;
1862     crFinish(1);
1863 }
1864
1865 static void share_sent(Plug plug, int bufsize)
1866 {
1867     /* struct ssh_sharing_connstate *cs = (struct ssh_sharing_connstate *)plug; */
1868
1869     /*
1870      * We do nothing here, because we expect that there won't be a
1871      * need to throttle and unthrottle the connection to a downstream.
1872      * It should automatically throttle itself: if the SSH server
1873      * sends huge amounts of data on all channels then it'll run out
1874      * of window until our downstream sends it back some
1875      * WINDOW_ADJUSTs.
1876      */
1877 }
1878
1879 static int share_listen_closing(Plug plug, const char *error_msg,
1880                                 int error_code, int calling_back)
1881 {
1882     struct ssh_sharing_state *sharestate = (struct ssh_sharing_state *)plug;
1883     if (error_msg)
1884         ssh_sharing_logf(sharestate->ssh, 0,
1885                          "listening socket: %s", error_msg);
1886     sk_close(sharestate->listensock);
1887     sharestate->listensock = NULL;
1888     return 1;
1889 }
1890
1891 static void share_send_verstring(struct ssh_sharing_connstate *cs)
1892 {
1893     char *fullstring = dupcat("SSHCONNECTION@putty.projects.tartarus.org-2.0-",
1894                               cs->parent->server_verstring, "\015\012", NULL);
1895     sk_write(cs->sock, fullstring, strlen(fullstring));
1896     sfree(fullstring);
1897
1898     cs->sent_verstring = TRUE;
1899 }
1900
1901 int share_ndownstreams(void *state)
1902 {
1903     struct ssh_sharing_state *sharestate = (struct ssh_sharing_state *)state;
1904     return count234(sharestate->connections);
1905 }
1906
1907 void share_activate(void *state, const char *server_verstring)
1908 {
1909     /*
1910      * Indication from ssh.c that we are now ready to begin serving
1911      * any downstreams that have already connected to us.
1912      */
1913     struct ssh_sharing_state *sharestate = (struct ssh_sharing_state *)state;
1914     struct ssh_sharing_connstate *cs;
1915     int i;
1916
1917     /*
1918      * Trim the server's version string down to just the software
1919      * version component, removing "SSH-2.0-" or whatever at the
1920      * front.
1921      */
1922     for (i = 0; i < 2; i++) {
1923         server_verstring += strcspn(server_verstring, "-");
1924         if (*server_verstring)
1925             server_verstring++;
1926     }
1927
1928     sharestate->server_verstring = dupstr(server_verstring);
1929
1930     for (i = 0; (cs = (struct ssh_sharing_connstate *)
1931                  index234(sharestate->connections, i)) != NULL; i++) {
1932         assert(!cs->sent_verstring);
1933         share_send_verstring(cs);
1934     }
1935 }
1936
1937 static int share_listen_accepting(Plug plug,
1938                                   accept_fn_t constructor, accept_ctx_t ctx)
1939 {
1940     static const struct plug_function_table connection_fn_table = {
1941         NULL, /* no log function, because that's for outgoing connections */
1942         share_closing,
1943         share_receive,
1944         share_sent,
1945         NULL /* no accepting function, because we've already done it */
1946     };
1947     struct ssh_sharing_state *sharestate = (struct ssh_sharing_state *)plug;
1948     struct ssh_sharing_connstate *cs;
1949     const char *err;
1950     char *peerinfo;
1951
1952     /*
1953      * A new downstream has connected to us.
1954      */
1955     cs = snew(struct ssh_sharing_connstate);
1956     cs->fn = &connection_fn_table;
1957     cs->parent = sharestate;
1958
1959     if ((cs->id = share_find_unused_id(sharestate, sharestate->nextid)) == 0 &&
1960         (cs->id = share_find_unused_id(sharestate, 1)) == 0) {
1961         sfree(cs);
1962         return 1;
1963     }
1964     sharestate->nextid = cs->id + 1;
1965     if (sharestate->nextid == 0)
1966         sharestate->nextid++; /* only happens in VERY long-running upstreams */
1967
1968     cs->sock = constructor(ctx, (Plug) cs);
1969     if ((err = sk_socket_error(cs->sock)) != NULL) {
1970         sfree(cs);
1971         return err != NULL;
1972     }
1973
1974     sk_set_frozen(cs->sock, 0);
1975
1976     add234(cs->parent->connections, cs);
1977
1978     cs->sent_verstring = FALSE;
1979     if (sharestate->server_verstring)
1980         share_send_verstring(cs);
1981
1982     cs->got_verstring = FALSE;
1983     cs->recvlen = 0;
1984     cs->crLine = 0;
1985     cs->halfchannels = newtree234(share_halfchannel_cmp);
1986     cs->channels_by_us = newtree234(share_channel_us_cmp);
1987     cs->channels_by_server = newtree234(share_channel_server_cmp);
1988     cs->xchannels_by_us = newtree234(share_xchannel_us_cmp);
1989     cs->xchannels_by_server = newtree234(share_xchannel_server_cmp);
1990     cs->forwardings = newtree234(share_forwarding_cmp);
1991     cs->globreq_head = cs->globreq_tail = NULL;
1992
1993     peerinfo = sk_peer_info(cs->sock);
1994     ssh_sharing_downstream_connected(sharestate->ssh, cs->id, peerinfo);
1995     sfree(peerinfo);
1996
1997     return 0;
1998 }
1999
2000 /* Per-application overrides for what roles we can take (e.g. pscp
2001  * will never be an upstream) */
2002 extern const int share_can_be_downstream;
2003 extern const int share_can_be_upstream;
2004
2005 /*
2006  * Decide on the string used to identify the connection point between
2007  * upstream and downstream (be it a Windows named pipe or a
2008  * Unix-domain socket or whatever else).
2009  *
2010  * I wondered about making this a SHA hash of all sorts of pieces of
2011  * the PuTTY configuration - essentially everything PuTTY uses to know
2012  * where and how to make a connection, including all the proxy details
2013  * (or rather, all the _relevant_ ones - only including settings that
2014  * other settings didn't prevent from having any effect), plus the
2015  * username. However, I think it's better to keep it really simple:
2016  * the connection point identifier is derived from the hostname and
2017  * port used to index the host-key cache (not necessarily where we
2018  * _physically_ connected to, in cases involving proxies or
2019  * CONF_loghost), plus the username if one is specified.
2020  *
2021  * The per-platform code will quite likely hash or obfuscate this name
2022  * in turn, for privacy from other users; failing that, it might
2023  * transform it to avoid dangerous filename characters and so on. But
2024  * that doesn't matter to us: for us, the point is that two session
2025  * configurations which return the same string from this function will
2026  * be treated as potentially shareable with each other.
2027  */
2028 char *ssh_share_sockname(const char *host, int port, Conf *conf)
2029 {
2030     char *username = get_remote_username(conf);
2031     char *sockname;
2032
2033     if (port == 22) {
2034         if (username)
2035             sockname = dupprintf("%s@%s", username, host);
2036         else
2037             sockname = dupprintf("%s", host);
2038     } else {
2039         if (username)
2040             sockname = dupprintf("%s@%s:%d", username, host, port);
2041         else
2042             sockname = dupprintf("%s:%d", host, port);
2043     }
2044
2045     sfree(username);
2046     return sockname;
2047 }
2048
2049 static void nullplug_socket_log(Plug plug, int type, SockAddr addr, int port,
2050                                 const char *error_msg, int error_code) {}
2051 static int nullplug_closing(Plug plug, const char *error_msg, int error_code,
2052                             int calling_back) { return 0; }
2053 static int nullplug_receive(Plug plug, int urgent, char *data,
2054                             int len) { return 0; }
2055 static void nullplug_sent(Plug plug, int bufsize) {}
2056
2057 int ssh_share_test_for_upstream(const char *host, int port, Conf *conf)
2058 {
2059     static const struct plug_function_table fn_table = {
2060         nullplug_socket_log,
2061         nullplug_closing,
2062         nullplug_receive,
2063         nullplug_sent,
2064         NULL
2065     };
2066     struct nullplug {
2067         const struct plug_function_table *fn;
2068     } np;
2069
2070     char *sockname, *logtext, *ds_err, *us_err;
2071     int result;
2072     Socket sock;
2073
2074     np.fn = &fn_table;
2075
2076     sockname = ssh_share_sockname(host, port, conf);
2077
2078     sock = NULL;
2079     logtext = ds_err = us_err = NULL;
2080     result = platform_ssh_share(sockname, conf, (Plug)&np, (Plug)NULL, &sock,
2081                                 &logtext, &ds_err, &us_err, FALSE, TRUE);
2082
2083     sfree(logtext);
2084     sfree(ds_err);
2085     sfree(us_err);
2086     sfree(sockname);
2087
2088     if (result == SHARE_NONE) {
2089         assert(sock == NULL);
2090         return FALSE;
2091     } else {
2092         assert(result == SHARE_DOWNSTREAM);
2093         sk_close(sock);
2094         return TRUE;
2095     }
2096 }
2097
2098 /*
2099  * Init function for connection sharing. We either open a listening
2100  * socket and become an upstream, or connect to an existing one and
2101  * become a downstream, or do neither. We are responsible for deciding
2102  * which of these to do (including checking the Conf to see if
2103  * connection sharing is even enabled in the first place). If we
2104  * become a downstream, we return the Socket with which we connected
2105  * to the upstream; otherwise (whether or not we have established an
2106  * upstream) we return NULL.
2107  */
2108 Socket ssh_connection_sharing_init(const char *host, int port,
2109                                    Conf *conf, Ssh ssh, void **state)
2110 {
2111     static const struct plug_function_table listen_fn_table = {
2112         NULL, /* no log function, because that's for outgoing connections */
2113         share_listen_closing,
2114         NULL, /* no receive function on a listening socket */
2115         NULL, /* no sent function on a listening socket */
2116         share_listen_accepting
2117     };
2118
2119     int result, can_upstream, can_downstream;
2120     char *logtext, *ds_err, *us_err;
2121     char *sockname;
2122     Socket sock;
2123     struct ssh_sharing_state *sharestate;
2124
2125     if (!conf_get_int(conf, CONF_ssh_connection_sharing))
2126         return NULL;                   /* do not share anything */
2127     can_upstream = share_can_be_upstream &&
2128         conf_get_int(conf, CONF_ssh_connection_sharing_upstream);
2129     can_downstream = share_can_be_downstream &&
2130         conf_get_int(conf, CONF_ssh_connection_sharing_downstream);
2131     if (!can_upstream && !can_downstream)
2132         return NULL;
2133
2134     sockname = ssh_share_sockname(host, port, conf);
2135
2136     /*
2137      * Create a data structure for the listening plug if we turn out
2138      * to be an upstream.
2139      */
2140     sharestate = snew(struct ssh_sharing_state);
2141     sharestate->fn = &listen_fn_table;
2142     sharestate->listensock = NULL;
2143
2144     /*
2145      * Now hand off to a per-platform routine that either connects to
2146      * an existing upstream (using 'ssh' as the plug), establishes our
2147      * own upstream (using 'sharestate' as the plug), or forks off a
2148      * separate upstream and then connects to that. It will return a
2149      * code telling us which kind of socket it put in 'sock'.
2150      */
2151     sock = NULL;
2152     logtext = ds_err = us_err = NULL;
2153     result = platform_ssh_share(sockname, conf, (Plug)ssh,
2154                                 (Plug)sharestate, &sock, &logtext, &ds_err,
2155                                 &us_err, can_upstream, can_downstream);
2156     ssh_connshare_log(ssh, result, logtext, ds_err, us_err);
2157     sfree(logtext);
2158     sfree(ds_err);
2159     sfree(us_err);
2160     switch (result) {
2161       case SHARE_NONE:
2162         /*
2163          * We aren't sharing our connection at all (e.g. something
2164          * went wrong setting the socket up). Free the upstream
2165          * structure and return NULL.
2166          */
2167         assert(sock == NULL);
2168         *state = NULL;
2169         sfree(sharestate);
2170         sfree(sockname);
2171         return NULL;
2172
2173       case SHARE_DOWNSTREAM:
2174         /*
2175          * We are downstream, so free sharestate which it turns out we
2176          * don't need after all, and return the downstream socket as a
2177          * replacement for an ordinary SSH connection.
2178          */
2179         *state = NULL;
2180         sfree(sharestate);
2181         sfree(sockname);
2182         return sock;
2183
2184       case SHARE_UPSTREAM:
2185         /*
2186          * We are upstream. Set up sharestate properly and pass a copy
2187          * to the caller; return NULL, to tell ssh.c that it has to
2188          * make an ordinary connection after all.
2189          */
2190         *state = sharestate;
2191         sharestate->listensock = sock;
2192         sharestate->connections = newtree234(share_connstate_cmp);
2193         sharestate->ssh = ssh;
2194         sharestate->server_verstring = NULL;
2195         sharestate->sockname = sockname;
2196         sharestate->nextid = 1;
2197         return NULL;
2198     }
2199
2200     return NULL;
2201 }