network.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. /*
  2. * Networking abstraction in PuTTY.
  3. *
  4. * The way this works is: a back end can choose to open any number
  5. * of sockets - including zero, which might be necessary in some.
  6. * It can register a bunch of callbacks (most notably for when
  7. * data is received) for each socket, and it can call the networking
  8. * abstraction to send data without having to worry about blocking.
  9. * The stuff behind the abstraction takes care of selects and
  10. * nonblocking writes and all that sort of painful gubbins.
  11. */
  12. #ifndef PUTTY_NETWORK_H
  13. #define PUTTY_NETWORK_H
  14. #include "defs.h"
  15. typedef struct SocketVtable SocketVtable;
  16. typedef struct PlugVtable PlugVtable;
  17. struct Socket {
  18. const struct SocketVtable *vt;
  19. };
  20. struct SocketVtable {
  21. Plug *(*plug) (Socket *s, Plug *p);
  22. /* use a different plug (return the old one) */
  23. /* if p is NULL, it doesn't change the plug */
  24. /* but it does return the one it's using */
  25. void (*close) (Socket *s);
  26. size_t (*write) (Socket *s, const void *data, size_t len);
  27. size_t (*write_oob) (Socket *s, const void *data, size_t len);
  28. void (*write_eof) (Socket *s);
  29. void (*set_frozen) (Socket *s, bool is_frozen);
  30. /* ignored by tcp, but vital for ssl */
  31. const char *(*socket_error) (Socket *s);
  32. SocketEndpointInfo *(*endpoint_info) (Socket *s, bool peer);
  33. };
  34. typedef union { void *p; int i; } accept_ctx_t;
  35. typedef Socket *(*accept_fn_t)(accept_ctx_t ctx, Plug *plug);
  36. struct Plug {
  37. const struct PlugVtable *vt;
  38. };
  39. typedef enum PlugLogType {
  40. PLUGLOG_CONNECT_TRYING,
  41. PLUGLOG_CONNECT_FAILED,
  42. PLUGLOG_CONNECT_SUCCESS,
  43. PLUGLOG_PROXY_MSG,
  44. } PlugLogType;
  45. typedef enum PlugCloseType {
  46. PLUGCLOSE_NORMAL,
  47. PLUGCLOSE_ERROR,
  48. PLUGCLOSE_BROKEN_PIPE,
  49. PLUGCLOSE_USER_ABORT,
  50. } PlugCloseType;
  51. struct PlugVtable {
  52. /*
  53. * Passes the client progress reports on the process of setting
  54. * up the connection.
  55. *
  56. * - PLUGLOG_CONNECT_TRYING means we are about to try to connect
  57. * to address `addr' (error_msg and error_code are ignored)
  58. *
  59. * - PLUGLOG_CONNECT_FAILED means we have failed to connect to
  60. * address `addr' (error_msg and error_code are supplied). This
  61. * is not a fatal error - we may well have other candidate
  62. * addresses to fall back to. When it _is_ fatal, the closing()
  63. * function will be called.
  64. *
  65. * - PLUGLOG_CONNECT_SUCCESS means we have succeeded in making a
  66. * connection. `addr' gives the address we connected to, if
  67. * available. (But sometimes, in cases of complicated proxy
  68. * setups, it might not be available, so receivers of this log
  69. * event should be prepared to deal with addr==NULL.)
  70. *
  71. * - PLUGLOG_PROXY_MSG means that error_msg contains a line of
  72. * logging information from whatever the connection is being
  73. * proxied through. This will typically be a wodge of
  74. * standard-error output from a local proxy command, so the
  75. * receiver should probably prefix it to indicate this.
  76. *
  77. * Note that sometimes log messages may be sent even to Socket
  78. * types that don't involve making an outgoing connection, e.g.
  79. * because the same core implementation (such as Windows handle
  80. * sockets) is shared between listening and connecting sockets. So
  81. * all Plugs must implement this method, even if only to ignore
  82. * the logged events.
  83. */
  84. void (*log)(Plug *p, Socket *s, PlugLogType type, SockAddr *addr, int port,
  85. const char *error_msg, int error_code);
  86. /*
  87. * Notifies the Plug that the socket is closing, and something
  88. * about why.
  89. *
  90. * - PLUGCLOSE_NORMAL means an ordinary non-error closure. In
  91. * this case, error_msg should be ignored (and hopefully
  92. * callers will have passed NULL).
  93. *
  94. * - PLUGCLOSE_ERROR indicates that an OS error occurred, and
  95. * 'error_msg' contains a string describing it, for use in
  96. * diagnostics. (Ownership of the string is not transferred.)
  97. * This error class covers anything other than the special
  98. * case below:
  99. *
  100. * - PLUGCLOSE_BROKEN_PIPE behaves like PLUGCLOSE_ERROR (in
  101. * particular, there's still an error message provided), but
  102. * distinguishes the particular error condition signalled by
  103. * EPIPE / ERROR_BROKEN_PIPE, which ssh/sharing.c needs to
  104. * recognise and handle specially in one situation.
  105. *
  106. * - PLUGCLOSE_USER_ABORT means that the close has happened as a
  107. * result of some kind of deliberate user action (e.g. hitting
  108. * ^C at a password prompt presented by a proxy socket setup
  109. * phase). This can be used to suppress interactive error
  110. * messages sent to the user (such as dialog boxes), on the
  111. * grounds that the user already knows. However, 'error_msg'
  112. * will still contain some appropriate text, so that
  113. * non-interactive error reporting (e.g. event logs) can still
  114. * record why the connection terminated.
  115. */
  116. void (*closing)(Plug *p, PlugCloseType type, const char *error_msg);
  117. /*
  118. * Provides incoming socket data to the Plug. Three cases:
  119. *
  120. * - urgent==0. `data' points to `len' bytes of perfectly
  121. * ordinary data.
  122. *
  123. * - urgent==1. `data' points to `len' bytes of data,
  124. * which were read from before an Urgent pointer.
  125. *
  126. * - urgent==2. `data' points to `len' bytes of data,
  127. * the first of which was the one at the Urgent mark.
  128. */
  129. void (*receive) (Plug *p, int urgent, const char *data, size_t len);
  130. /*
  131. * Called when the pending send backlog on a socket is cleared or
  132. * partially cleared. The new backlog size is passed in the
  133. * `bufsize' parameter.
  134. */
  135. void (*sent) (Plug *p, size_t bufsize);
  136. /*
  137. * Only called on listener-type sockets, and is passed a
  138. * constructor function+context that will create a fresh Socket
  139. * describing the connection. It returns nonzero if it doesn't
  140. * want the connection for some reason, or 0 on success.
  141. */
  142. int (*accepting)(Plug *p, accept_fn_t constructor, accept_ctx_t ctx);
  143. };
  144. /* Proxy indirection layer.
  145. *
  146. * Calling new_connection transfers ownership of 'addr': the proxy
  147. * layer is now responsible for freeing it, and the caller shouldn't
  148. * assume it exists any more.
  149. *
  150. * If calling this from a backend with a Seat, you can also give it a
  151. * pointer to the backend's Interactor trait. In that situation, it
  152. * might replace the backend's seat with a temporary seat of its own,
  153. * and give the real Seat to an Interactor somewhere in the proxy
  154. * system so that it can ask for passwords (and, in the case of SSH
  155. * proxying, other prompts like host key checks). If that happens,
  156. * then the resulting 'temp seat' is the backend's property, and it
  157. * will have to remember to free it when cleaning up, or after
  158. * flushing it back into the real seat when the network connection
  159. * attempt completes.
  160. *
  161. * You can free your TempSeat and resume using the real Seat when one
  162. * of two things happens: either your Plug's closing() method is
  163. * called (indicating failure to connect), or its log() method is
  164. * called with PLUGLOG_CONNECT_SUCCESS. In the latter case, you'll
  165. * probably want to flush the TempSeat's contents into the real Seat,
  166. * of course.
  167. */
  168. Socket *new_connection(SockAddr *addr, const char *hostname,
  169. int port, bool privport,
  170. bool oobinline, bool nodelay, bool keepalive,
  171. Plug *plug, Conf *conf, Interactor *interactor);
  172. Socket *new_listener(const char *srcaddr, int port, Plug *plug,
  173. bool local_host_only, Conf *conf, int addressfamily);
  174. SockAddr *name_lookup(const char *host, int port, char **canonicalname,
  175. Conf *conf, int addressfamily, LogContext *logctx,
  176. const char *lookup_reason_for_logging);
  177. /* platform-dependent callback from new_connection() */
  178. /* (same caveat about addr as new_connection()) */
  179. Socket *platform_new_connection(SockAddr *addr, const char *hostname,
  180. int port, bool privport,
  181. bool oobinline, bool nodelay, bool keepalive,
  182. Plug *plug, Conf *conf, Interactor *itr);
  183. /* callback for SSH jump-host proxying */
  184. Socket *sshproxy_new_connection(SockAddr *addr, const char *hostname,
  185. int port, bool privport,
  186. bool oobinline, bool nodelay, bool keepalive,
  187. Plug *plug, Conf *conf, Interactor *itr);
  188. /* socket functions */
  189. void sk_init(void); /* called once at program startup */
  190. void sk_cleanup(void); /* called just before program exit */
  191. SockAddr *sk_namelookup(const char *host, char **canonicalname, int address_family);
  192. SockAddr *sk_nonamelookup(const char *host);
  193. void sk_getaddr(SockAddr *addr, char *buf, int buflen);
  194. bool sk_addr_needs_port(SockAddr *addr);
  195. bool sk_hostname_is_local(const char *name);
  196. bool sk_address_is_local(SockAddr *addr);
  197. bool sk_address_is_special_local(SockAddr *addr);
  198. int sk_addrtype(SockAddr *addr);
  199. void sk_addrcopy(SockAddr *addr, char *buf);
  200. void sk_addr_free(SockAddr *addr);
  201. /* sk_addr_dup generates another SockAddr which contains the same data
  202. * as the original one and can be freed independently. May not actually
  203. * physically _duplicate_ it: incrementing a reference count so that
  204. * one more free is required before it disappears is an acceptable
  205. * implementation. */
  206. SockAddr *sk_addr_dup(SockAddr *addr);
  207. /* NB, control of 'addr' is passed via sk_new, which takes responsibility
  208. * for freeing it, as for new_connection() */
  209. Socket *sk_new(SockAddr *addr, int port, bool privport, bool oobinline,
  210. bool nodelay, bool keepalive, Plug *p);
  211. Socket *sk_newlistener(const char *srcaddr, int port, Plug *plug,
  212. bool local_host_only, int address_family);
  213. static inline Plug *sk_plug(Socket *s, Plug *p)
  214. { return s->vt->plug(s, p); }
  215. static inline void sk_close(Socket *s)
  216. { s->vt->close(s); }
  217. static inline size_t sk_write(Socket *s, const void *data, size_t len)
  218. { return s->vt->write(s, data, len); }
  219. static inline size_t sk_write_oob(Socket *s, const void *data, size_t len)
  220. { return s->vt->write_oob(s, data, len); }
  221. static inline void sk_write_eof(Socket *s)
  222. { s->vt->write_eof(s); }
  223. static inline void plug_log(
  224. Plug *p, Socket *s, int type, SockAddr *addr, int port,
  225. const char *msg, int code)
  226. { p->vt->log(p, s, type, addr, port, msg, code); }
  227. static inline void plug_closing(Plug *p, PlugCloseType type, const char *msg)
  228. { p->vt->closing(p, type, msg); }
  229. static inline void plug_closing_normal(Plug *p)
  230. { p->vt->closing(p, PLUGCLOSE_NORMAL, NULL); }
  231. static inline void plug_closing_error(Plug *p, const char *msg)
  232. { p->vt->closing(p, PLUGCLOSE_ERROR, msg); }
  233. static inline void plug_closing_user_abort(Plug *p)
  234. { p->vt->closing(p, PLUGCLOSE_USER_ABORT, "User aborted connection setup"); }
  235. static inline void plug_receive(Plug *p, int urg, const char *data, size_t len)
  236. { p->vt->receive(p, urg, data, len); }
  237. static inline void plug_sent (Plug *p, size_t bufsize)
  238. { p->vt->sent(p, bufsize); }
  239. static inline int plug_accepting(Plug *p, accept_fn_t cons, accept_ctx_t ctx)
  240. { return p->vt->accepting(p, cons, ctx); }
  241. /*
  242. * Special error values are returned from sk_namelookup and sk_new
  243. * if there's a problem. These functions extract an error message,
  244. * or return NULL if there's no problem.
  245. */
  246. const char *sk_addr_error(SockAddr *addr);
  247. static inline const char *sk_socket_error(Socket *s)
  248. { return s->vt->socket_error(s); }
  249. /*
  250. * Set the `frozen' flag on a socket. A frozen socket is one in
  251. * which all READABLE notifications are ignored, so that data is
  252. * not accepted from the peer until the socket is unfrozen. This
  253. * exists for two purposes:
  254. *
  255. * - Port forwarding: when a local listening port receives a
  256. * connection, we do not want to receive data from the new
  257. * socket until we have somewhere to send it. Hence, we freeze
  258. * the socket until its associated SSH channel is ready; then we
  259. * unfreeze it and pending data is delivered.
  260. *
  261. * - Socket buffering: if an SSH channel (or the whole connection)
  262. * backs up or presents a zero window, we must freeze the
  263. * associated local socket in order to avoid unbounded buffer
  264. * growth.
  265. */
  266. static inline void sk_set_frozen(Socket *s, bool is_frozen)
  267. { s->vt->set_frozen(s, is_frozen); }
  268. /*
  269. * Return a structure giving some information about one end of
  270. * the socket. May be NULL, if nothing is available at all. If it is
  271. * not NULL, then it is dynamically allocated, and should be freed by
  272. * a call to sk_free_endpoint_info(). See below for the definition.
  273. */
  274. static inline SocketEndpointInfo *sk_endpoint_info(Socket *s, bool peer)
  275. { return s->vt->endpoint_info(s, peer); }
  276. static inline SocketEndpointInfo *sk_peer_info(Socket *s)
  277. { return sk_endpoint_info(s, true); }
  278. /*
  279. * The structure returned from sk_endpoint_info, and a function to free
  280. * one (in utils).
  281. */
  282. struct SocketEndpointInfo {
  283. int addressfamily;
  284. /*
  285. * Text form of the IPv4 or IPv6 address of the specified end of the
  286. * socket, if available, in the standard text representation.
  287. */
  288. const char *addr_text;
  289. /*
  290. * Binary form of the same address. Filled in if and only if
  291. * addr_text is not NULL. You can tell which branch of the union
  292. * is used by examining 'addressfamily'.
  293. */
  294. union {
  295. unsigned char ipv6[16];
  296. unsigned char ipv4[4];
  297. } addr_bin;
  298. /*
  299. * Remote port number, or -1 if not available.
  300. */
  301. int port;
  302. /*
  303. * Free-form text suitable for putting in log messages. For IP
  304. * sockets, repeats the address and port information from above.
  305. * But it can be completely different, e.g. for Unix-domain
  306. * sockets it gives information about the uid, gid and pid of the
  307. * connecting process.
  308. */
  309. const char *log_text;
  310. };
  311. void sk_free_endpoint_info(SocketEndpointInfo *ei);
  312. /*
  313. * Simple wrapper on getservbyname(), needed by portfwd.c. Returns the
  314. * port number, in host byte order (suitable for printf and so on).
  315. * Returns 0 on failure. Any platform not supporting getservbyname
  316. * can just return 0 - this function is not required to handle
  317. * numeric port specifications.
  318. */
  319. int net_service_lookup(const char *service);
  320. /*
  321. * Look up the local hostname; return value needs freeing.
  322. * May return NULL.
  323. */
  324. char *get_hostname(void);
  325. /*
  326. * Trivial socket implementation which just stores an error. Found in
  327. * errsock.c.
  328. *
  329. * The consume_string variant takes an already-formatted dynamically
  330. * allocated string, and takes over ownership of that string.
  331. */
  332. Socket *new_error_socket_fmt(Plug *plug, const char *fmt, ...)
  333. PRINTF_LIKE(2, 3);
  334. Socket *new_error_socket_consume_string(Plug *plug, char *errmsg);
  335. /*
  336. * Trivial plug that does absolutely nothing. Found in nullplug.c.
  337. */
  338. extern Plug *const nullplug;
  339. /*
  340. * Some trivial no-op plug functions, also in nullplug.c; exposed here
  341. * so that other Plug implementations can use them too.
  342. *
  343. * In particular, nullplug_log is useful to Plugs that don't need to
  344. * worry about logging.
  345. */
  346. void nullplug_log(Plug *plug, Socket *s, PlugLogType type, SockAddr *addr,
  347. int port, const char *err_msg, int err_code);
  348. void nullplug_closing(Plug *plug, PlugCloseType type, const char *error_msg);
  349. void nullplug_receive(Plug *plug, int urgent, const char *data, size_t len);
  350. void nullplug_sent(Plug *plug, size_t bufsize);
  351. /*
  352. * Similar no-op socket function.
  353. */
  354. SocketEndpointInfo *nullsock_endpoint_info(Socket *s, bool peer);
  355. /* ----------------------------------------------------------------------
  356. * Functions defined outside the network code, which have to be
  357. * declared in this header file rather than the main putty.h because
  358. * they use types defined here.
  359. */
  360. void backend_socket_log(Seat *seat, LogContext *logctx, Socket *sock,
  361. PlugLogType type, SockAddr *addr, int port,
  362. const char *error_msg, int error_code, Conf *conf,
  363. bool session_started);
  364. typedef struct ProxyStderrBuf {
  365. char buf[8192];
  366. size_t size;
  367. const char *prefix; /* must be statically allocated */
  368. } ProxyStderrBuf;
  369. void psb_init(ProxyStderrBuf *psb);
  370. void psb_set_prefix(ProxyStderrBuf *psb, const char *prefix);
  371. void log_proxy_stderr(Plug *plug, Socket *sock, ProxyStderrBuf *psb,
  372. const void *vdata, size_t len);
  373. /* ----------------------------------------------------------------------
  374. * The DeferredSocketOpener trait. This is a thing that some Socket
  375. * implementations may choose to own if they need to delay actually
  376. * setting up the underlying connection. For example, sockets used in
  377. * local-proxy handling (Unix FdSocket / Windows HandleSocket) might
  378. * need to do this if they have to prompt the user interactively for
  379. * parts of the command they'll run.
  380. *
  381. * Mostly, a DeferredSocketOpener implementation will keep to itself,
  382. * arrange its own callbacks in order to do whatever setup it needs,
  383. * and when it's ready, call back to its parent Socket via some
  384. * implementation-specific API of its own. So the shared API here
  385. * requires almost nothing: the only thing we need is a free function,
  386. * so that if the owner of a Socket of this kind needs to close it
  387. * before the deferred connection process is finished, the Socket can
  388. * also clean up the DeferredSocketOpener dangling off it.
  389. */
  390. struct DeferredSocketOpener {
  391. const DeferredSocketOpenerVtable *vt;
  392. };
  393. struct DeferredSocketOpenerVtable {
  394. void (*free)(DeferredSocketOpener *);
  395. };
  396. static inline void deferred_socket_opener_free(DeferredSocketOpener *dso)
  397. { dso->vt->free(dso); }
  398. DeferredSocketOpener *null_deferred_socket_opener(void);
  399. #endif