network.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. SocketPeerInfo *(*peer_info) (Socket *s);
  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, 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. #ifdef MPEXT
  212. int timeout,
  213. int sndbuf,
  214. const char *srcaddr
  215. #endif
  216. );
  217. Socket *sk_newlistener(const char *srcaddr, int port, Plug *plug,
  218. bool local_host_only, int address_family);
  219. static inline Plug *sk_plug(Socket *s, Plug *p)
  220. { return s->vt->plug(s, p); }
  221. static inline void sk_close(Socket *s)
  222. { s->vt->close(s); }
  223. static inline size_t sk_write(Socket *s, const void *data, size_t len)
  224. { return s->vt->write(s, data, len); }
  225. static inline size_t sk_write_oob(Socket *s, const void *data, size_t len)
  226. { return s->vt->write_oob(s, data, len); }
  227. static inline void sk_write_eof(Socket *s)
  228. { s->vt->write_eof(s); }
  229. #pragma option push -w-bei // WINSCP
  230. static inline void plug_log(
  231. Plug *p, int type, SockAddr *addr, int port, const char *msg, int code)
  232. { p->vt->log(p, type, addr, port, msg, code); }
  233. #pragma option pop // WINSCP
  234. static inline void plug_closing(Plug *p, PlugCloseType type, const char *msg)
  235. { p->vt->closing(p, type, msg); }
  236. static inline void plug_closing_normal(Plug *p)
  237. { p->vt->closing(p, PLUGCLOSE_NORMAL, NULL); }
  238. static inline void plug_closing_error(Plug *p, const char *msg)
  239. { p->vt->closing(p, PLUGCLOSE_ERROR, msg); }
  240. static inline void plug_closing_user_abort(Plug *p)
  241. { p->vt->closing(p, PLUGCLOSE_USER_ABORT, "User aborted connection setup"); }
  242. static inline void plug_receive(Plug *p, int urg, const char *data, size_t len)
  243. { p->vt->receive(p, urg, data, len); }
  244. static inline void plug_sent (Plug *p, size_t bufsize)
  245. { p->vt->sent(p, bufsize); }
  246. static inline int plug_accepting(Plug *p, accept_fn_t cons, accept_ctx_t ctx)
  247. { return p->vt->accepting(p, cons, ctx); }
  248. /*
  249. * Special error values are returned from sk_namelookup and sk_new
  250. * if there's a problem. These functions extract an error message,
  251. * or return NULL if there's no problem.
  252. */
  253. const char *sk_addr_error(SockAddr *addr);
  254. static inline const char *sk_socket_error(Socket *s)
  255. { return s->vt->socket_error(s); }
  256. /*
  257. * Set the `frozen' flag on a socket. A frozen socket is one in
  258. * which all READABLE notifications are ignored, so that data is
  259. * not accepted from the peer until the socket is unfrozen. This
  260. * exists for two purposes:
  261. *
  262. * - Port forwarding: when a local listening port receives a
  263. * connection, we do not want to receive data from the new
  264. * socket until we have somewhere to send it. Hence, we freeze
  265. * the socket until its associated SSH channel is ready; then we
  266. * unfreeze it and pending data is delivered.
  267. *
  268. * - Socket buffering: if an SSH channel (or the whole connection)
  269. * backs up or presents a zero window, we must freeze the
  270. * associated local socket in order to avoid unbounded buffer
  271. * growth.
  272. */
  273. static inline void sk_set_frozen(Socket *s, bool is_frozen)
  274. { s->vt->set_frozen(s, is_frozen); }
  275. /*
  276. * Return a structure giving some information about the other end of
  277. * the socket. May be NULL, if nothing is available at all. If it is
  278. * not NULL, then it is dynamically allocated, and should be freed by
  279. * a call to sk_free_peer_info(). See below for the definition.
  280. */
  281. static inline SocketPeerInfo *sk_peer_info(Socket *s)
  282. { return s->vt->peer_info(s); }
  283. /*
  284. * The structure returned from sk_peer_info, and a function to free
  285. * one (in utils).
  286. */
  287. struct SocketPeerInfo {
  288. int addressfamily;
  289. /*
  290. * Text form of the IPv4 or IPv6 address of the other end of the
  291. * socket, if available, in the standard text representation.
  292. */
  293. const char *addr_text;
  294. /*
  295. * Binary form of the same address. Filled in if and only if
  296. * addr_text is not NULL. You can tell which branch of the union
  297. * is used by examining 'addressfamily'.
  298. */
  299. union {
  300. unsigned char ipv6[16];
  301. unsigned char ipv4[4];
  302. } addr_bin;
  303. /*
  304. * Remote port number, or -1 if not available.
  305. */
  306. int port;
  307. /*
  308. * Free-form text suitable for putting in log messages. For IP
  309. * sockets, repeats the address and port information from above.
  310. * But it can be completely different, e.g. for Unix-domain
  311. * sockets it gives information about the uid, gid and pid of the
  312. * connecting process.
  313. */
  314. const char *log_text;
  315. };
  316. void sk_free_peer_info(SocketPeerInfo *pi);
  317. /*
  318. * Simple wrapper on getservbyname(), needed by portfwd.c. Returns the
  319. * port number, in host byte order (suitable for printf and so on).
  320. * Returns 0 on failure. Any platform not supporting getservbyname
  321. * can just return 0 - this function is not required to handle
  322. * numeric port specifications.
  323. */
  324. int net_service_lookup(const char *service);
  325. /*
  326. * Look up the local hostname; return value needs freeing.
  327. * May return NULL.
  328. */
  329. char *get_hostname(void);
  330. /*
  331. * Trivial socket implementation which just stores an error. Found in
  332. * errsock.c.
  333. *
  334. * The consume_string variant takes an already-formatted dynamically
  335. * allocated string, and takes over ownership of that string.
  336. */
  337. Socket *new_error_socket_fmt(Plug *plug, const char *fmt, ...)
  338. PRINTF_LIKE(2, 3);
  339. Socket *new_error_socket_consume_string(Plug *plug, char *errmsg);
  340. /*
  341. * Trivial plug that does absolutely nothing. Found in nullplug.c.
  342. */
  343. extern Plug *const nullplug;
  344. /*
  345. * Some trivial no-op plug functions, also in nullplug.c; exposed here
  346. * so that other Plug implementations can use them too.
  347. *
  348. * In particular, nullplug_log is useful to Plugs that don't need to
  349. * worry about logging.
  350. */
  351. void nullplug_log(Plug *plug, PlugLogType type, SockAddr *addr,
  352. int port, const char *err_msg, int err_code);
  353. void nullplug_closing(Plug *plug, PlugCloseType type, const char *error_msg);
  354. void nullplug_receive(Plug *plug, int urgent, const char *data, size_t len);
  355. void nullplug_sent(Plug *plug, size_t bufsize);
  356. /* ----------------------------------------------------------------------
  357. * Functions defined outside the network code, which have to be
  358. * declared in this header file rather than the main putty.h because
  359. * they use types defined here.
  360. */
  361. void backend_socket_log(Seat *seat, LogContext *logctx,
  362. PlugLogType type, SockAddr *addr, int port,
  363. const char *error_msg, int error_code, Conf *conf,
  364. bool session_started);
  365. typedef struct ProxyStderrBuf {
  366. char buf[8192];
  367. size_t size;
  368. const char *prefix; /* must be statically allocated */
  369. } ProxyStderrBuf;
  370. void psb_init(ProxyStderrBuf *psb);
  371. void psb_set_prefix(ProxyStderrBuf *psb, const char *prefix);
  372. void log_proxy_stderr(
  373. Plug *plug, ProxyStderrBuf *psb, const void *vdata, size_t len);
  374. /* ----------------------------------------------------------------------
  375. * The DeferredSocketOpener trait. This is a thing that some Socket
  376. * implementations may choose to own if they need to delay actually
  377. * setting up the underlying connection. For example, sockets used in
  378. * local-proxy handling (Unix FdSocket / Windows HandleSocket) might
  379. * need to do this if they have to prompt the user interactively for
  380. * parts of the command they'll run.
  381. *
  382. * Mostly, a DeferredSocketOpener implementation will keep to itself,
  383. * arrange its own callbacks in order to do whatever setup it needs,
  384. * and when it's ready, call back to its parent Socket via some
  385. * implementation-specific API of its own. So the shared API here
  386. * requires almost nothing: the only thing we need is a free function,
  387. * so that if the owner of a Socket of this kind needs to close it
  388. * before the deferred connection process is finished, the Socket can
  389. * also clean up the DeferredSocketOpener dangling off it.
  390. */
  391. struct DeferredSocketOpener {
  392. const DeferredSocketOpenerVtable *vt;
  393. };
  394. struct DeferredSocketOpenerVtable {
  395. void (*free)(DeferredSocketOpener *);
  396. };
  397. static inline void deferred_socket_opener_free(DeferredSocketOpener *dso)
  398. { dso->vt->free(dso); }
  399. DeferredSocketOpener *null_deferred_socket_opener(void);
  400. #endif