You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tcp.c 30KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  1. #include <string.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <assert.h>
  5. #include <errno.h>
  6. #include <byteswap.h>
  7. #include <ipxe/timer.h>
  8. #include <ipxe/iobuf.h>
  9. #include <ipxe/malloc.h>
  10. #include <ipxe/retry.h>
  11. #include <ipxe/refcnt.h>
  12. #include <ipxe/xfer.h>
  13. #include <ipxe/open.h>
  14. #include <ipxe/uri.h>
  15. #include <ipxe/tcpip.h>
  16. #include <ipxe/tcp.h>
  17. /** @file
  18. *
  19. * TCP protocol
  20. *
  21. */
  22. FILE_LICENCE ( GPL2_OR_LATER );
  23. /** A TCP connection */
  24. struct tcp_connection {
  25. /** Reference counter */
  26. struct refcnt refcnt;
  27. /** List of TCP connections */
  28. struct list_head list;
  29. /** Flags */
  30. unsigned int flags;
  31. /** Data transfer interface */
  32. struct interface xfer;
  33. /** Remote socket address */
  34. struct sockaddr_tcpip peer;
  35. /** Local port */
  36. unsigned int local_port;
  37. /** Current TCP state */
  38. unsigned int tcp_state;
  39. /** Previous TCP state
  40. *
  41. * Maintained only for debug messages
  42. */
  43. unsigned int prev_tcp_state;
  44. /** Current sequence number
  45. *
  46. * Equivalent to SND.UNA in RFC 793 terminology.
  47. */
  48. uint32_t snd_seq;
  49. /** Unacknowledged sequence count
  50. *
  51. * Equivalent to (SND.NXT-SND.UNA) in RFC 793 terminology.
  52. */
  53. uint32_t snd_sent;
  54. /** Send window
  55. *
  56. * Equivalent to SND.WND in RFC 793 terminology
  57. */
  58. uint32_t snd_win;
  59. /** Current acknowledgement number
  60. *
  61. * Equivalent to RCV.NXT in RFC 793 terminology.
  62. */
  63. uint32_t rcv_ack;
  64. /** Receive window
  65. *
  66. * Equivalent to RCV.WND in RFC 793 terminology.
  67. */
  68. uint32_t rcv_win;
  69. /** Most recent received timestamp
  70. *
  71. * Equivalent to TS.Recent in RFC 1323 terminology.
  72. */
  73. uint32_t ts_recent;
  74. /** Transmit queue */
  75. struct list_head queue;
  76. /** Retransmission timer */
  77. struct retry_timer timer;
  78. /** Shutdown (TIME_WAIT) timer */
  79. struct retry_timer wait;
  80. };
  81. /** TCP flags */
  82. enum tcp_flags {
  83. /** TCP data transfer interface has been closed */
  84. TCP_XFER_CLOSED = 0x0001,
  85. /** TCP timestamps are enabled */
  86. TCP_TS_ENABLED = 0x0002,
  87. /** TCP acknowledgement is pending */
  88. TCP_ACK_PENDING = 0x0004,
  89. };
  90. /**
  91. * List of registered TCP connections
  92. */
  93. static LIST_HEAD ( tcp_conns );
  94. /* Forward declarations */
  95. static struct interface_descriptor tcp_xfer_desc;
  96. static void tcp_expired ( struct retry_timer *timer, int over );
  97. static void tcp_wait_expired ( struct retry_timer *timer, int over );
  98. static int tcp_rx_ack ( struct tcp_connection *tcp, uint32_t ack,
  99. uint32_t win );
  100. /**
  101. * Name TCP state
  102. *
  103. * @v state TCP state
  104. * @ret name Name of TCP state
  105. */
  106. static inline __attribute__ (( always_inline )) const char *
  107. tcp_state ( int state ) {
  108. switch ( state ) {
  109. case TCP_CLOSED: return "CLOSED";
  110. case TCP_LISTEN: return "LISTEN";
  111. case TCP_SYN_SENT: return "SYN_SENT";
  112. case TCP_SYN_RCVD: return "SYN_RCVD";
  113. case TCP_ESTABLISHED: return "ESTABLISHED";
  114. case TCP_FIN_WAIT_1: return "FIN_WAIT_1";
  115. case TCP_FIN_WAIT_2: return "FIN_WAIT_2";
  116. case TCP_CLOSING_OR_LAST_ACK: return "CLOSING/LAST_ACK";
  117. case TCP_TIME_WAIT: return "TIME_WAIT";
  118. case TCP_CLOSE_WAIT: return "CLOSE_WAIT";
  119. default: return "INVALID";
  120. }
  121. }
  122. /**
  123. * Dump TCP state transition
  124. *
  125. * @v tcp TCP connection
  126. */
  127. static inline __attribute__ (( always_inline )) void
  128. tcp_dump_state ( struct tcp_connection *tcp ) {
  129. if ( tcp->tcp_state != tcp->prev_tcp_state ) {
  130. DBGC ( tcp, "TCP %p transitioned from %s to %s\n", tcp,
  131. tcp_state ( tcp->prev_tcp_state ),
  132. tcp_state ( tcp->tcp_state ) );
  133. }
  134. tcp->prev_tcp_state = tcp->tcp_state;
  135. }
  136. /**
  137. * Dump TCP flags
  138. *
  139. * @v flags TCP flags
  140. */
  141. static inline __attribute__ (( always_inline )) void
  142. tcp_dump_flags ( struct tcp_connection *tcp, unsigned int flags ) {
  143. if ( flags & TCP_RST )
  144. DBGC2 ( tcp, " RST" );
  145. if ( flags & TCP_SYN )
  146. DBGC2 ( tcp, " SYN" );
  147. if ( flags & TCP_PSH )
  148. DBGC2 ( tcp, " PSH" );
  149. if ( flags & TCP_FIN )
  150. DBGC2 ( tcp, " FIN" );
  151. if ( flags & TCP_ACK )
  152. DBGC2 ( tcp, " ACK" );
  153. }
  154. /***************************************************************************
  155. *
  156. * Open and close
  157. *
  158. ***************************************************************************
  159. */
  160. /**
  161. * Bind TCP connection to local port
  162. *
  163. * @v tcp TCP connection
  164. * @v port Local port number
  165. * @ret rc Return status code
  166. *
  167. * If the port is 0, the connection is assigned an available port
  168. * between 1024 and 65535.
  169. */
  170. static int tcp_bind ( struct tcp_connection *tcp, unsigned int port ) {
  171. struct tcp_connection *existing;
  172. uint16_t try_port;
  173. unsigned int i;
  174. /* If no port is specified, find an available port */
  175. if ( ! port ) {
  176. try_port = random();
  177. for ( i = 0 ; i < 65536 ; i++ ) {
  178. try_port++;
  179. if ( try_port < 1024 )
  180. continue;
  181. if ( tcp_bind ( tcp, try_port ) == 0 )
  182. return 0;
  183. }
  184. DBGC ( tcp, "TCP %p could not bind: no free ports\n", tcp );
  185. return -EADDRINUSE;
  186. }
  187. /* Attempt bind to local port */
  188. list_for_each_entry ( existing, &tcp_conns, list ) {
  189. if ( existing->local_port == port ) {
  190. DBGC ( tcp, "TCP %p could not bind: port %d in use\n",
  191. tcp, port );
  192. return -EADDRINUSE;
  193. }
  194. }
  195. tcp->local_port = port;
  196. DBGC ( tcp, "TCP %p bound to port %d\n", tcp, port );
  197. return 0;
  198. }
  199. /**
  200. * Open a TCP connection
  201. *
  202. * @v xfer Data transfer interface
  203. * @v peer Peer socket address
  204. * @v local Local socket address, or NULL
  205. * @ret rc Return status code
  206. */
  207. static int tcp_open ( struct interface *xfer, struct sockaddr *peer,
  208. struct sockaddr *local ) {
  209. struct sockaddr_tcpip *st_peer = ( struct sockaddr_tcpip * ) peer;
  210. struct sockaddr_tcpip *st_local = ( struct sockaddr_tcpip * ) local;
  211. struct tcp_connection *tcp;
  212. unsigned int bind_port;
  213. int rc;
  214. /* Allocate and initialise structure */
  215. tcp = zalloc ( sizeof ( *tcp ) );
  216. if ( ! tcp )
  217. return -ENOMEM;
  218. DBGC ( tcp, "TCP %p allocated\n", tcp );
  219. ref_init ( &tcp->refcnt, NULL );
  220. intf_init ( &tcp->xfer, &tcp_xfer_desc, &tcp->refcnt );
  221. timer_init ( &tcp->timer, tcp_expired );
  222. timer_init ( &tcp->wait, tcp_wait_expired );
  223. tcp->prev_tcp_state = TCP_CLOSED;
  224. tcp->tcp_state = TCP_STATE_SENT ( TCP_SYN );
  225. tcp_dump_state ( tcp );
  226. tcp->snd_seq = random();
  227. INIT_LIST_HEAD ( &tcp->queue );
  228. memcpy ( &tcp->peer, st_peer, sizeof ( tcp->peer ) );
  229. /* Bind to local port */
  230. bind_port = ( st_local ? ntohs ( st_local->st_port ) : 0 );
  231. if ( ( rc = tcp_bind ( tcp, bind_port ) ) != 0 )
  232. goto err;
  233. /* Start timer to initiate SYN */
  234. start_timer_nodelay ( &tcp->timer );
  235. /* Attach parent interface, transfer reference to connection
  236. * list and return
  237. */
  238. intf_plug_plug ( &tcp->xfer, xfer );
  239. list_add ( &tcp->list, &tcp_conns );
  240. return 0;
  241. err:
  242. ref_put ( &tcp->refcnt );
  243. return rc;
  244. }
  245. /**
  246. * Close TCP connection
  247. *
  248. * @v tcp TCP connection
  249. * @v rc Reason for close
  250. *
  251. * Closes the data transfer interface. If the TCP state machine is in
  252. * a suitable state, the connection will be deleted.
  253. */
  254. static void tcp_close ( struct tcp_connection *tcp, int rc ) {
  255. struct io_buffer *iobuf;
  256. struct io_buffer *tmp;
  257. /* Close data transfer interface */
  258. intf_shutdown ( &tcp->xfer, rc );
  259. tcp->flags |= TCP_XFER_CLOSED;
  260. /* If we are in CLOSED, or have otherwise not yet received a
  261. * SYN (i.e. we are in LISTEN or SYN_SENT), just delete the
  262. * connection.
  263. */
  264. if ( ! ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) ) {
  265. /* Transition to CLOSED for the sake of debugging messages */
  266. tcp->tcp_state = TCP_CLOSED;
  267. tcp_dump_state ( tcp );
  268. /* Free any unsent I/O buffers */
  269. list_for_each_entry_safe ( iobuf, tmp, &tcp->queue, list ) {
  270. list_del ( &iobuf->list );
  271. free_iob ( iobuf );
  272. }
  273. /* Remove from list and drop reference */
  274. stop_timer ( &tcp->timer );
  275. list_del ( &tcp->list );
  276. ref_put ( &tcp->refcnt );
  277. DBGC ( tcp, "TCP %p connection deleted\n", tcp );
  278. return;
  279. }
  280. /* If we have not had our SYN acknowledged (i.e. we are in
  281. * SYN_RCVD), pretend that it has been acknowledged so that we
  282. * can send a FIN without breaking things.
  283. */
  284. if ( ! ( tcp->tcp_state & TCP_STATE_ACKED ( TCP_SYN ) ) )
  285. tcp_rx_ack ( tcp, ( tcp->snd_seq + 1 ), 0 );
  286. /* If we have no data remaining to send, start sending FIN */
  287. if ( list_empty ( &tcp->queue ) ) {
  288. tcp->tcp_state |= TCP_STATE_SENT ( TCP_FIN );
  289. tcp_dump_state ( tcp );
  290. }
  291. }
  292. /***************************************************************************
  293. *
  294. * Transmit data path
  295. *
  296. ***************************************************************************
  297. */
  298. /**
  299. * Calculate transmission window
  300. *
  301. * @v tcp TCP connection
  302. * @ret len Maximum length that can be sent in a single packet
  303. */
  304. static size_t tcp_xmit_win ( struct tcp_connection *tcp ) {
  305. size_t len;
  306. /* Not ready if we're not in a suitable connection state */
  307. if ( ! TCP_CAN_SEND_DATA ( tcp->tcp_state ) )
  308. return 0;
  309. /* Length is the minimum of the receiver's window and the path MTU */
  310. len = tcp->snd_win;
  311. if ( len > TCP_PATH_MTU )
  312. len = TCP_PATH_MTU;
  313. return len;
  314. }
  315. /**
  316. * Process TCP transmit queue
  317. *
  318. * @v tcp TCP connection
  319. * @v max_len Maximum length to process
  320. * @v dest I/O buffer to fill with data, or NULL
  321. * @v remove Remove data from queue
  322. * @ret len Length of data processed
  323. *
  324. * This processes at most @c max_len bytes from the TCP connection's
  325. * transmit queue. Data will be copied into the @c dest I/O buffer
  326. * (if provided) and, if @c remove is true, removed from the transmit
  327. * queue.
  328. */
  329. static size_t tcp_process_queue ( struct tcp_connection *tcp, size_t max_len,
  330. struct io_buffer *dest, int remove ) {
  331. struct io_buffer *iobuf;
  332. struct io_buffer *tmp;
  333. size_t frag_len;
  334. size_t len = 0;
  335. list_for_each_entry_safe ( iobuf, tmp, &tcp->queue, list ) {
  336. frag_len = iob_len ( iobuf );
  337. if ( frag_len > max_len )
  338. frag_len = max_len;
  339. if ( dest ) {
  340. memcpy ( iob_put ( dest, frag_len ), iobuf->data,
  341. frag_len );
  342. }
  343. if ( remove ) {
  344. iob_pull ( iobuf, frag_len );
  345. if ( ! iob_len ( iobuf ) ) {
  346. list_del ( &iobuf->list );
  347. free_iob ( iobuf );
  348. }
  349. }
  350. len += frag_len;
  351. max_len -= frag_len;
  352. }
  353. return len;
  354. }
  355. /**
  356. * Transmit any outstanding data
  357. *
  358. * @v tcp TCP connection
  359. *
  360. * Transmits any outstanding data on the connection.
  361. *
  362. * Note that even if an error is returned, the retransmission timer
  363. * will have been started if necessary, and so the stack will
  364. * eventually attempt to retransmit the failed packet.
  365. */
  366. static int tcp_xmit ( struct tcp_connection *tcp ) {
  367. struct io_buffer *iobuf;
  368. struct tcp_header *tcphdr;
  369. struct tcp_mss_option *mssopt;
  370. struct tcp_timestamp_padded_option *tsopt;
  371. void *payload;
  372. unsigned int flags;
  373. size_t len = 0;
  374. uint32_t seq_len;
  375. uint32_t app_win;
  376. uint32_t max_rcv_win;
  377. int rc;
  378. /* If retransmission timer is already running, do nothing */
  379. if ( timer_running ( &tcp->timer ) )
  380. return 0;
  381. /* Calculate both the actual (payload) and sequence space
  382. * lengths that we wish to transmit.
  383. */
  384. if ( TCP_CAN_SEND_DATA ( tcp->tcp_state ) ) {
  385. len = tcp_process_queue ( tcp, tcp_xmit_win ( tcp ),
  386. NULL, 0 );
  387. }
  388. seq_len = len;
  389. flags = TCP_FLAGS_SENDING ( tcp->tcp_state );
  390. if ( flags & ( TCP_SYN | TCP_FIN ) ) {
  391. /* SYN or FIN consume one byte, and we can never send both */
  392. assert ( ! ( ( flags & TCP_SYN ) && ( flags & TCP_FIN ) ) );
  393. seq_len++;
  394. }
  395. tcp->snd_sent = seq_len;
  396. /* If we have nothing to transmit, stop now */
  397. if ( ( seq_len == 0 ) && ! ( tcp->flags & TCP_ACK_PENDING ) )
  398. return 0;
  399. /* If we are transmitting anything that requires
  400. * acknowledgement (i.e. consumes sequence space), start the
  401. * retransmission timer. Do this before attempting to
  402. * allocate the I/O buffer, in case allocation itself fails.
  403. */
  404. if ( seq_len )
  405. start_timer ( &tcp->timer );
  406. /* Allocate I/O buffer */
  407. iobuf = alloc_iob ( len + MAX_HDR_LEN );
  408. if ( ! iobuf ) {
  409. DBGC ( tcp, "TCP %p could not allocate iobuf for %08x..%08x "
  410. "%08x\n", tcp, tcp->snd_seq, ( tcp->snd_seq + seq_len ),
  411. tcp->rcv_ack );
  412. return -ENOMEM;
  413. }
  414. iob_reserve ( iobuf, MAX_HDR_LEN );
  415. /* Fill data payload from transmit queue */
  416. tcp_process_queue ( tcp, len, iobuf, 0 );
  417. /* Expand receive window if possible */
  418. max_rcv_win = ( ( freemem * 3 ) / 4 );
  419. if ( max_rcv_win > TCP_MAX_WINDOW_SIZE )
  420. max_rcv_win = TCP_MAX_WINDOW_SIZE;
  421. app_win = xfer_window ( &tcp->xfer );
  422. if ( max_rcv_win > app_win )
  423. max_rcv_win = app_win;
  424. max_rcv_win &= ~0x03; /* Keep everything dword-aligned */
  425. if ( tcp->rcv_win < max_rcv_win )
  426. tcp->rcv_win = max_rcv_win;
  427. /* Fill up the TCP header */
  428. payload = iobuf->data;
  429. if ( flags & TCP_SYN ) {
  430. mssopt = iob_push ( iobuf, sizeof ( *mssopt ) );
  431. mssopt->kind = TCP_OPTION_MSS;
  432. mssopt->length = sizeof ( *mssopt );
  433. mssopt->mss = htons ( TCP_MSS );
  434. }
  435. if ( ( flags & TCP_SYN ) || ( tcp->flags & TCP_TS_ENABLED ) ) {
  436. tsopt = iob_push ( iobuf, sizeof ( *tsopt ) );
  437. memset ( tsopt->nop, TCP_OPTION_NOP, sizeof ( tsopt->nop ) );
  438. tsopt->tsopt.kind = TCP_OPTION_TS;
  439. tsopt->tsopt.length = sizeof ( tsopt->tsopt );
  440. tsopt->tsopt.tsval = htonl ( currticks() );
  441. tsopt->tsopt.tsecr = htonl ( tcp->ts_recent );
  442. }
  443. if ( ! ( flags & TCP_SYN ) )
  444. flags |= TCP_PSH;
  445. tcphdr = iob_push ( iobuf, sizeof ( *tcphdr ) );
  446. memset ( tcphdr, 0, sizeof ( *tcphdr ) );
  447. tcphdr->src = htons ( tcp->local_port );
  448. tcphdr->dest = tcp->peer.st_port;
  449. tcphdr->seq = htonl ( tcp->snd_seq );
  450. tcphdr->ack = htonl ( tcp->rcv_ack );
  451. tcphdr->hlen = ( ( payload - iobuf->data ) << 2 );
  452. tcphdr->flags = flags;
  453. tcphdr->win = htons ( tcp->rcv_win );
  454. tcphdr->csum = tcpip_chksum ( iobuf->data, iob_len ( iobuf ) );
  455. /* Dump header */
  456. DBGC2 ( tcp, "TCP %p TX %d->%d %08x..%08x %08x %4zd",
  457. tcp, ntohs ( tcphdr->src ), ntohs ( tcphdr->dest ),
  458. ntohl ( tcphdr->seq ), ( ntohl ( tcphdr->seq ) + seq_len ),
  459. ntohl ( tcphdr->ack ), len );
  460. tcp_dump_flags ( tcp, tcphdr->flags );
  461. DBGC2 ( tcp, "\n" );
  462. /* Transmit packet */
  463. if ( ( rc = tcpip_tx ( iobuf, &tcp_protocol, NULL, &tcp->peer, NULL,
  464. &tcphdr->csum ) ) != 0 ) {
  465. DBGC ( tcp, "TCP %p could not transmit %08x..%08x %08x: %s\n",
  466. tcp, tcp->snd_seq, ( tcp->snd_seq + tcp->snd_sent ),
  467. tcp->rcv_ack, strerror ( rc ) );
  468. return rc;
  469. }
  470. /* Clear ACK-pending flag */
  471. tcp->flags &= ~TCP_ACK_PENDING;
  472. return 0;
  473. }
  474. /**
  475. * Retransmission timer expired
  476. *
  477. * @v timer Retransmission timer
  478. * @v over Failure indicator
  479. */
  480. static void tcp_expired ( struct retry_timer *timer, int over ) {
  481. struct tcp_connection *tcp =
  482. container_of ( timer, struct tcp_connection, timer );
  483. DBGC ( tcp, "TCP %p timer %s in %s for %08x..%08x %08x\n", tcp,
  484. ( over ? "expired" : "fired" ), tcp_state ( tcp->tcp_state ),
  485. tcp->snd_seq, ( tcp->snd_seq + tcp->snd_sent ), tcp->rcv_ack );
  486. assert ( ( tcp->tcp_state == TCP_SYN_SENT ) ||
  487. ( tcp->tcp_state == TCP_SYN_RCVD ) ||
  488. ( tcp->tcp_state == TCP_ESTABLISHED ) ||
  489. ( tcp->tcp_state == TCP_FIN_WAIT_1 ) ||
  490. ( tcp->tcp_state == TCP_CLOSE_WAIT ) ||
  491. ( tcp->tcp_state == TCP_CLOSING_OR_LAST_ACK ) );
  492. if ( over ) {
  493. /* If we have finally timed out and given up,
  494. * terminate the connection
  495. */
  496. tcp->tcp_state = TCP_CLOSED;
  497. tcp_dump_state ( tcp );
  498. tcp_close ( tcp, -ETIMEDOUT );
  499. } else {
  500. /* Otherwise, retransmit the packet */
  501. tcp_xmit ( tcp );
  502. }
  503. }
  504. /**
  505. * Shutdown timer expired
  506. *
  507. * @v timer Shutdown timer
  508. * @v over Failure indicator
  509. */
  510. static void tcp_wait_expired ( struct retry_timer *timer, int over __unused ) {
  511. struct tcp_connection *tcp =
  512. container_of ( timer, struct tcp_connection, wait );
  513. assert ( tcp->tcp_state == TCP_TIME_WAIT );
  514. DBGC ( tcp, "TCP %p wait complete in %s for %08x..%08x %08x\n", tcp,
  515. tcp_state ( tcp->tcp_state ), tcp->snd_seq,
  516. ( tcp->snd_seq + tcp->snd_sent ), tcp->rcv_ack );
  517. tcp->tcp_state = TCP_CLOSED;
  518. tcp_dump_state ( tcp );
  519. tcp_close ( tcp, 0 );
  520. }
  521. /**
  522. * Send RST response to incoming packet
  523. *
  524. * @v in_tcphdr TCP header of incoming packet
  525. * @ret rc Return status code
  526. */
  527. static int tcp_xmit_reset ( struct tcp_connection *tcp,
  528. struct sockaddr_tcpip *st_dest,
  529. struct tcp_header *in_tcphdr ) {
  530. struct io_buffer *iobuf;
  531. struct tcp_header *tcphdr;
  532. int rc;
  533. /* Allocate space for dataless TX buffer */
  534. iobuf = alloc_iob ( MAX_HDR_LEN );
  535. if ( ! iobuf ) {
  536. DBGC ( tcp, "TCP %p could not allocate iobuf for RST "
  537. "%08x..%08x %08x\n", tcp, ntohl ( in_tcphdr->ack ),
  538. ntohl ( in_tcphdr->ack ), ntohl ( in_tcphdr->seq ) );
  539. return -ENOMEM;
  540. }
  541. iob_reserve ( iobuf, MAX_HDR_LEN );
  542. /* Construct RST response */
  543. tcphdr = iob_push ( iobuf, sizeof ( *tcphdr ) );
  544. memset ( tcphdr, 0, sizeof ( *tcphdr ) );
  545. tcphdr->src = in_tcphdr->dest;
  546. tcphdr->dest = in_tcphdr->src;
  547. tcphdr->seq = in_tcphdr->ack;
  548. tcphdr->ack = in_tcphdr->seq;
  549. tcphdr->hlen = ( ( sizeof ( *tcphdr ) / 4 ) << 4 );
  550. tcphdr->flags = ( TCP_RST | TCP_ACK );
  551. tcphdr->win = htons ( TCP_MAX_WINDOW_SIZE );
  552. tcphdr->csum = tcpip_chksum ( iobuf->data, iob_len ( iobuf ) );
  553. /* Dump header */
  554. DBGC2 ( tcp, "TCP %p TX %d->%d %08x..%08x %08x %4d",
  555. tcp, ntohs ( tcphdr->src ), ntohs ( tcphdr->dest ),
  556. ntohl ( tcphdr->seq ), ( ntohl ( tcphdr->seq ) ),
  557. ntohl ( tcphdr->ack ), 0 );
  558. tcp_dump_flags ( tcp, tcphdr->flags );
  559. DBGC2 ( tcp, "\n" );
  560. /* Transmit packet */
  561. if ( ( rc = tcpip_tx ( iobuf, &tcp_protocol, NULL, st_dest,
  562. NULL, &tcphdr->csum ) ) != 0 ) {
  563. DBGC ( tcp, "TCP %p could not transmit RST %08x..%08x %08x: "
  564. "%s\n", tcp, ntohl ( in_tcphdr->ack ),
  565. ntohl ( in_tcphdr->ack ), ntohl ( in_tcphdr->seq ),
  566. strerror ( rc ) );
  567. return rc;
  568. }
  569. return 0;
  570. }
  571. /***************************************************************************
  572. *
  573. * Receive data path
  574. *
  575. ***************************************************************************
  576. */
  577. /**
  578. * Identify TCP connection by local port number
  579. *
  580. * @v local_port Local port
  581. * @ret tcp TCP connection, or NULL
  582. */
  583. static struct tcp_connection * tcp_demux ( unsigned int local_port ) {
  584. struct tcp_connection *tcp;
  585. list_for_each_entry ( tcp, &tcp_conns, list ) {
  586. if ( tcp->local_port == local_port )
  587. return tcp;
  588. }
  589. return NULL;
  590. }
  591. /**
  592. * Parse TCP received options
  593. *
  594. * @v tcp TCP connection
  595. * @v data Raw options data
  596. * @v len Raw options length
  597. * @v options Options structure to fill in
  598. */
  599. static void tcp_rx_opts ( struct tcp_connection *tcp, const void *data,
  600. size_t len, struct tcp_options *options ) {
  601. const void *end = ( data + len );
  602. const struct tcp_option *option;
  603. unsigned int kind;
  604. memset ( options, 0, sizeof ( *options ) );
  605. while ( data < end ) {
  606. option = data;
  607. kind = option->kind;
  608. if ( kind == TCP_OPTION_END )
  609. return;
  610. if ( kind == TCP_OPTION_NOP ) {
  611. data++;
  612. continue;
  613. }
  614. switch ( kind ) {
  615. case TCP_OPTION_MSS:
  616. options->mssopt = data;
  617. break;
  618. case TCP_OPTION_TS:
  619. options->tsopt = data;
  620. break;
  621. default:
  622. DBGC ( tcp, "TCP %p received unknown option %d\n",
  623. tcp, kind );
  624. break;
  625. }
  626. data += option->length;
  627. }
  628. }
  629. /**
  630. * Consume received sequence space
  631. *
  632. * @v tcp TCP connection
  633. * @v seq_len Sequence space length to consume
  634. */
  635. static void tcp_rx_seq ( struct tcp_connection *tcp, uint32_t seq_len ) {
  636. tcp->rcv_ack += seq_len;
  637. if ( tcp->rcv_win > seq_len ) {
  638. tcp->rcv_win -= seq_len;
  639. } else {
  640. tcp->rcv_win = 0;
  641. }
  642. tcp->flags |= TCP_ACK_PENDING;
  643. }
  644. /**
  645. * Handle TCP received SYN
  646. *
  647. * @v tcp TCP connection
  648. * @v seq SEQ value (in host-endian order)
  649. * @v options TCP options
  650. * @ret rc Return status code
  651. */
  652. static int tcp_rx_syn ( struct tcp_connection *tcp, uint32_t seq,
  653. struct tcp_options *options ) {
  654. /* Synchronise sequence numbers on first SYN */
  655. if ( ! ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) ) {
  656. tcp->rcv_ack = seq;
  657. if ( options->tsopt )
  658. tcp->flags |= TCP_TS_ENABLED;
  659. }
  660. /* Ignore duplicate SYN */
  661. if ( ( tcp->rcv_ack - seq ) > 0 )
  662. return 0;
  663. /* Acknowledge SYN */
  664. tcp_rx_seq ( tcp, 1 );
  665. /* Mark SYN as received and start sending ACKs with each packet */
  666. tcp->tcp_state |= ( TCP_STATE_SENT ( TCP_ACK ) |
  667. TCP_STATE_RCVD ( TCP_SYN ) );
  668. return 0;
  669. }
  670. /**
  671. * Handle TCP received ACK
  672. *
  673. * @v tcp TCP connection
  674. * @v ack ACK value (in host-endian order)
  675. * @v win WIN value (in host-endian order)
  676. * @ret rc Return status code
  677. */
  678. static int tcp_rx_ack ( struct tcp_connection *tcp, uint32_t ack,
  679. uint32_t win ) {
  680. uint32_t ack_len = ( ack - tcp->snd_seq );
  681. size_t len;
  682. unsigned int acked_flags;
  683. /* Check for out-of-range or old duplicate ACKs */
  684. if ( ack_len > tcp->snd_sent ) {
  685. DBGC ( tcp, "TCP %p received ACK for %08x..%08x, "
  686. "sent only %08x..%08x\n", tcp, tcp->snd_seq,
  687. ( tcp->snd_seq + ack_len ), tcp->snd_seq,
  688. ( tcp->snd_seq + tcp->snd_sent ) );
  689. if ( TCP_HAS_BEEN_ESTABLISHED ( tcp->tcp_state ) ) {
  690. /* Just ignore what might be old duplicate ACKs */
  691. return 0;
  692. } else {
  693. /* Send RST if an out-of-range ACK is received
  694. * on a not-yet-established connection, as per
  695. * RFC 793.
  696. */
  697. return -EINVAL;
  698. }
  699. }
  700. /* Ignore ACKs that don't actually acknowledge any new data.
  701. * (In particular, do not stop the retransmission timer; this
  702. * avoids creating a sorceror's apprentice syndrome when a
  703. * duplicate ACK is received and we still have data in our
  704. * transmit queue.)
  705. */
  706. if ( ack_len == 0 )
  707. return 0;
  708. /* Stop the retransmission timer */
  709. stop_timer ( &tcp->timer );
  710. /* Determine acknowledged flags and data length */
  711. len = ack_len;
  712. acked_flags = ( TCP_FLAGS_SENDING ( tcp->tcp_state ) &
  713. ( TCP_SYN | TCP_FIN ) );
  714. if ( acked_flags )
  715. len--;
  716. /* Update SEQ and sent counters, and window size */
  717. tcp->snd_seq = ack;
  718. tcp->snd_sent = 0;
  719. tcp->snd_win = win;
  720. /* Remove any acknowledged data from transmit queue */
  721. tcp_process_queue ( tcp, len, NULL, 1 );
  722. /* Mark SYN/FIN as acknowledged if applicable. */
  723. if ( acked_flags )
  724. tcp->tcp_state |= TCP_STATE_ACKED ( acked_flags );
  725. /* Start sending FIN if we've had all possible data ACKed */
  726. if ( list_empty ( &tcp->queue ) && ( tcp->flags & TCP_XFER_CLOSED ) )
  727. tcp->tcp_state |= TCP_STATE_SENT ( TCP_FIN );
  728. return 0;
  729. }
  730. /**
  731. * Handle TCP received data
  732. *
  733. * @v tcp TCP connection
  734. * @v seq SEQ value (in host-endian order)
  735. * @v iobuf I/O buffer
  736. * @ret rc Return status code
  737. *
  738. * This function takes ownership of the I/O buffer.
  739. */
  740. static int tcp_rx_data ( struct tcp_connection *tcp, uint32_t seq,
  741. struct io_buffer *iobuf ) {
  742. uint32_t already_rcvd;
  743. uint32_t len;
  744. int rc;
  745. /* Ignore duplicate or out-of-order data */
  746. already_rcvd = ( tcp->rcv_ack - seq );
  747. len = iob_len ( iobuf );
  748. if ( already_rcvd >= len ) {
  749. free_iob ( iobuf );
  750. return 0;
  751. }
  752. iob_pull ( iobuf, already_rcvd );
  753. len -= already_rcvd;
  754. /* Acknowledge new data */
  755. tcp_rx_seq ( tcp, len );
  756. /* Deliver data to application */
  757. if ( ( rc = xfer_deliver_iob ( &tcp->xfer, iobuf ) ) != 0 ) {
  758. DBGC ( tcp, "TCP %p could not deliver %08x..%08x: %s\n",
  759. tcp, seq, ( seq + len ), strerror ( rc ) );
  760. return rc;
  761. }
  762. return 0;
  763. }
  764. /**
  765. * Handle TCP received FIN
  766. *
  767. * @v tcp TCP connection
  768. * @v seq SEQ value (in host-endian order)
  769. * @ret rc Return status code
  770. */
  771. static int tcp_rx_fin ( struct tcp_connection *tcp, uint32_t seq ) {
  772. /* Ignore duplicate or out-of-order FIN */
  773. if ( ( tcp->rcv_ack - seq ) > 0 )
  774. return 0;
  775. /* Acknowledge FIN */
  776. tcp_rx_seq ( tcp, 1 );
  777. /* Mark FIN as received */
  778. tcp->tcp_state |= TCP_STATE_RCVD ( TCP_FIN );
  779. /* Close connection */
  780. tcp_close ( tcp, 0 );
  781. return 0;
  782. }
  783. /**
  784. * Handle TCP received RST
  785. *
  786. * @v tcp TCP connection
  787. * @v seq SEQ value (in host-endian order)
  788. * @ret rc Return status code
  789. */
  790. static int tcp_rx_rst ( struct tcp_connection *tcp, uint32_t seq ) {
  791. /* Accept RST only if it falls within the window. If we have
  792. * not yet received a SYN, then we have no window to test
  793. * against, so fall back to checking that our SYN has been
  794. * ACKed.
  795. */
  796. if ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) {
  797. if ( ( seq - tcp->rcv_ack ) >= tcp->rcv_win )
  798. return 0;
  799. } else {
  800. if ( ! ( tcp->tcp_state & TCP_STATE_ACKED ( TCP_SYN ) ) )
  801. return 0;
  802. }
  803. /* Abort connection */
  804. tcp->tcp_state = TCP_CLOSED;
  805. tcp_dump_state ( tcp );
  806. tcp_close ( tcp, -ECONNRESET );
  807. DBGC ( tcp, "TCP %p connection reset by peer\n", tcp );
  808. return -ECONNRESET;
  809. }
  810. /**
  811. * Process received packet
  812. *
  813. * @v iobuf I/O buffer
  814. * @v st_src Partially-filled source address
  815. * @v st_dest Partially-filled destination address
  816. * @v pshdr_csum Pseudo-header checksum
  817. * @ret rc Return status code
  818. */
  819. static int tcp_rx ( struct io_buffer *iobuf,
  820. struct sockaddr_tcpip *st_src,
  821. struct sockaddr_tcpip *st_dest __unused,
  822. uint16_t pshdr_csum ) {
  823. struct tcp_header *tcphdr = iobuf->data;
  824. struct tcp_connection *tcp;
  825. struct tcp_options options;
  826. size_t hlen;
  827. uint16_t csum;
  828. uint32_t seq;
  829. uint32_t ack;
  830. uint32_t win;
  831. uint32_t ts_recent;
  832. unsigned int flags;
  833. size_t len;
  834. int rc;
  835. /* Sanity check packet */
  836. if ( iob_len ( iobuf ) < sizeof ( *tcphdr ) ) {
  837. DBG ( "TCP packet too short at %zd bytes (min %zd bytes)\n",
  838. iob_len ( iobuf ), sizeof ( *tcphdr ) );
  839. rc = -EINVAL;
  840. goto discard;
  841. }
  842. hlen = ( ( tcphdr->hlen & TCP_MASK_HLEN ) / 16 ) * 4;
  843. if ( hlen < sizeof ( *tcphdr ) ) {
  844. DBG ( "TCP header too short at %zd bytes (min %zd bytes)\n",
  845. hlen, sizeof ( *tcphdr ) );
  846. rc = -EINVAL;
  847. goto discard;
  848. }
  849. if ( hlen > iob_len ( iobuf ) ) {
  850. DBG ( "TCP header too long at %zd bytes (max %zd bytes)\n",
  851. hlen, iob_len ( iobuf ) );
  852. rc = -EINVAL;
  853. goto discard;
  854. }
  855. csum = tcpip_continue_chksum ( pshdr_csum, iobuf->data,
  856. iob_len ( iobuf ) );
  857. if ( csum != 0 ) {
  858. DBG ( "TCP checksum incorrect (is %04x including checksum "
  859. "field, should be 0000)\n", csum );
  860. rc = -EINVAL;
  861. goto discard;
  862. }
  863. /* Parse parameters from header and strip header */
  864. tcp = tcp_demux ( ntohs ( tcphdr->dest ) );
  865. seq = ntohl ( tcphdr->seq );
  866. ack = ntohl ( tcphdr->ack );
  867. win = ntohs ( tcphdr->win );
  868. flags = tcphdr->flags;
  869. tcp_rx_opts ( tcp, ( ( ( void * ) tcphdr ) + sizeof ( *tcphdr ) ),
  870. ( hlen - sizeof ( *tcphdr ) ), &options );
  871. ts_recent = ( options.tsopt ?
  872. ntohl ( options.tsopt->tsval ) : tcp->ts_recent );
  873. iob_pull ( iobuf, hlen );
  874. len = iob_len ( iobuf );
  875. /* Dump header */
  876. DBGC2 ( tcp, "TCP %p RX %d<-%d %08x %08x..%08zx %4zd",
  877. tcp, ntohs ( tcphdr->dest ), ntohs ( tcphdr->src ),
  878. ntohl ( tcphdr->ack ), ntohl ( tcphdr->seq ),
  879. ( ntohl ( tcphdr->seq ) + len +
  880. ( ( tcphdr->flags & ( TCP_SYN | TCP_FIN ) ) ? 1 : 0 )), len);
  881. tcp_dump_flags ( tcp, tcphdr->flags );
  882. DBGC2 ( tcp, "\n" );
  883. /* If no connection was found, send RST */
  884. if ( ! tcp ) {
  885. tcp_xmit_reset ( tcp, st_src, tcphdr );
  886. rc = -ENOTCONN;
  887. goto discard;
  888. }
  889. /* Handle ACK, if present */
  890. if ( flags & TCP_ACK ) {
  891. if ( ( rc = tcp_rx_ack ( tcp, ack, win ) ) != 0 ) {
  892. tcp_xmit_reset ( tcp, st_src, tcphdr );
  893. goto discard;
  894. }
  895. }
  896. /* Force an ACK if this packet is out of order */
  897. if ( ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) &&
  898. ( seq != tcp->rcv_ack ) ) {
  899. tcp->flags |= TCP_ACK_PENDING;
  900. }
  901. /* Handle SYN, if present */
  902. if ( flags & TCP_SYN ) {
  903. tcp_rx_syn ( tcp, seq, &options );
  904. seq++;
  905. }
  906. /* Handle RST, if present */
  907. if ( flags & TCP_RST ) {
  908. if ( ( rc = tcp_rx_rst ( tcp, seq ) ) != 0 )
  909. goto discard;
  910. }
  911. /* Handle new data, if any */
  912. tcp_rx_data ( tcp, seq, iob_disown ( iobuf ) );
  913. seq += len;
  914. /* Handle FIN, if present */
  915. if ( flags & TCP_FIN ) {
  916. tcp_rx_fin ( tcp, seq );
  917. seq++;
  918. }
  919. /* Update timestamp, if applicable */
  920. if ( seq == tcp->rcv_ack )
  921. tcp->ts_recent = ts_recent;
  922. /* Dump out any state change as a result of the received packet */
  923. tcp_dump_state ( tcp );
  924. /* Send out any pending data */
  925. tcp_xmit ( tcp );
  926. /* If this packet was the last we expect to receive, set up
  927. * timer to expire and cause the connection to be freed.
  928. */
  929. if ( TCP_CLOSED_GRACEFULLY ( tcp->tcp_state ) ) {
  930. stop_timer ( &tcp->wait );
  931. start_timer_fixed ( &tcp->wait, ( 2 * TCP_MSL ) );
  932. }
  933. return 0;
  934. discard:
  935. /* Free received packet */
  936. free_iob ( iobuf );
  937. return rc;
  938. }
  939. /** TCP protocol */
  940. struct tcpip_protocol tcp_protocol __tcpip_protocol = {
  941. .name = "TCP",
  942. .rx = tcp_rx,
  943. .tcpip_proto = IP_TCP,
  944. };
  945. /***************************************************************************
  946. *
  947. * Data transfer interface
  948. *
  949. ***************************************************************************
  950. */
  951. /**
  952. * Close interface
  953. *
  954. * @v tcp TCP connection
  955. * @v rc Reason for close
  956. */
  957. static void tcp_xfer_close ( struct tcp_connection *tcp, int rc ) {
  958. /* Close data transfer interface */
  959. tcp_close ( tcp, rc );
  960. /* Transmit FIN, if possible */
  961. tcp_xmit ( tcp );
  962. }
  963. /**
  964. * Check flow control window
  965. *
  966. * @v tcp TCP connection
  967. * @ret len Length of window
  968. */
  969. static size_t tcp_xfer_window ( struct tcp_connection *tcp ) {
  970. /* Not ready if data queue is non-empty. This imposes a limit
  971. * of only one unACKed packet in the TX queue at any time; we
  972. * do this to conserve memory usage.
  973. */
  974. if ( ! list_empty ( &tcp->queue ) )
  975. return 0;
  976. /* Return TCP window length */
  977. return tcp_xmit_win ( tcp );
  978. }
  979. /**
  980. * Deliver datagram as I/O buffer
  981. *
  982. * @v tcp TCP connection
  983. * @v iobuf Datagram I/O buffer
  984. * @v meta Data transfer metadata
  985. * @ret rc Return status code
  986. */
  987. static int tcp_xfer_deliver ( struct tcp_connection *tcp,
  988. struct io_buffer *iobuf,
  989. struct xfer_metadata *meta __unused ) {
  990. /* Enqueue packet */
  991. list_add_tail ( &iobuf->list, &tcp->queue );
  992. /* Transmit data, if possible */
  993. tcp_xmit ( tcp );
  994. return 0;
  995. }
  996. /** TCP data transfer interface operations */
  997. static struct interface_operation tcp_xfer_operations[] = {
  998. INTF_OP ( xfer_deliver, struct tcp_connection *, tcp_xfer_deliver ),
  999. INTF_OP ( xfer_window, struct tcp_connection *, tcp_xfer_window ),
  1000. INTF_OP ( intf_close, struct tcp_connection *, tcp_xfer_close ),
  1001. };
  1002. /** TCP data transfer interface descriptor */
  1003. static struct interface_descriptor tcp_xfer_desc =
  1004. INTF_DESC ( struct tcp_connection, xfer, tcp_xfer_operations );
  1005. /***************************************************************************
  1006. *
  1007. * Openers
  1008. *
  1009. ***************************************************************************
  1010. */
  1011. /** TCP socket opener */
  1012. struct socket_opener tcp_socket_opener __socket_opener = {
  1013. .semantics = TCP_SOCK_STREAM,
  1014. .family = AF_INET,
  1015. .open = tcp_open,
  1016. };
  1017. /** Linkage hack */
  1018. int tcp_sock_stream = TCP_SOCK_STREAM;
  1019. /**
  1020. * Open TCP URI
  1021. *
  1022. * @v xfer Data transfer interface
  1023. * @v uri URI
  1024. * @ret rc Return status code
  1025. */
  1026. static int tcp_open_uri ( struct interface *xfer, struct uri *uri ) {
  1027. struct sockaddr_tcpip peer;
  1028. /* Sanity check */
  1029. if ( ! uri->host )
  1030. return -EINVAL;
  1031. memset ( &peer, 0, sizeof ( peer ) );
  1032. peer.st_port = htons ( uri_port ( uri, 0 ) );
  1033. return xfer_open_named_socket ( xfer, SOCK_STREAM,
  1034. ( struct sockaddr * ) &peer,
  1035. uri->host, NULL );
  1036. }
  1037. /** TCP URI opener */
  1038. struct uri_opener tcp_uri_opener __uri_opener = {
  1039. .scheme = "tcp",
  1040. .open = tcp_open_uri,
  1041. };