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