1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. #include <string.h>
  2. #include <stdlib.h>
  3. #include <assert.h>
  4. #include <byteswap.h>
  5. #include <latch.h>
  6. #include <errno.h>
  7. #include <gpxe/process.h>
  8. #include <gpxe/init.h>
  9. #include <gpxe/netdevice.h>
  10. #include <gpxe/pkbuff.h>
  11. #include <gpxe/ip.h>
  12. #include <gpxe/tcp.h>
  13. #include <gpxe/tcpip.h>
  14. #include <gpxe/retry.h>
  15. #include "uip/uip.h"
  16. /** @file
  17. *
  18. * TCP protocol
  19. *
  20. * The gPXE TCP stack is currently implemented on top of the uIP
  21. * protocol stack. This file provides wrappers around uIP so that
  22. * higher-level protocol implementations do not need to talk directly
  23. * to uIP (which has a somewhat baroque API).
  24. *
  25. * Basic operation is to create a #tcp_connection structure, call
  26. * tcp_connect() and then call run_tcpip() in a loop until the
  27. * operation has completed. The TCP stack will call the various
  28. * methods defined in the #tcp_operations structure in order to send
  29. * and receive data.
  30. *
  31. * See hello.c for a trivial example of a TCP protocol using this
  32. * API.
  33. *
  34. */
  35. #if USE_UIP
  36. /**
  37. * TCP transmit buffer
  38. *
  39. * When a tcp_operations::senddata() method is called, it is
  40. * guaranteed to be able to use this buffer as temporary space for
  41. * constructing the data to be sent. For example, code such as
  42. *
  43. * @code
  44. *
  45. * static void my_senddata ( struct tcp_connection *conn, void *buf,
  46. * size_t len ) {
  47. * len = snprintf ( buf, len, "FETCH %s\r\n", filename );
  48. * tcp_send ( conn, buf + already_sent, len - already_sent );
  49. * }
  50. *
  51. * @endcode
  52. *
  53. * is allowed, and is probably the best way to deal with
  54. * variably-sized data.
  55. *
  56. * Note that you cannot use this simple mechanism if you want to be
  57. * able to construct single data blocks of more than #len bytes.
  58. */
  59. static void *tcp_buffer = uip_buf + ( 40 + UIP_LLH_LEN );
  60. /** Size of #tcp_buffer */
  61. static size_t tcp_buflen = UIP_BUFSIZE - ( 40 + UIP_LLH_LEN );
  62. /**
  63. * Open a TCP connection
  64. *
  65. * @v conn TCP connection
  66. *
  67. * This sets up a new TCP connection to the remote host specified in
  68. * tcp_connection::sin.
  69. */
  70. void tcp_connect ( struct tcp_connection *conn ) {
  71. struct uip_conn *uip_conn;
  72. u16_t ipaddr[2];
  73. assert ( conn->sin.sin_addr.s_addr != 0 );
  74. assert ( conn->sin.sin_port != 0 );
  75. assert ( conn->tcp_op != NULL );
  76. assert ( sizeof ( uip_conn->appstate ) == sizeof ( conn ) );
  77. * ( ( uint32_t * ) ipaddr ) = conn->sin.sin_addr.s_addr;
  78. uip_conn = uip_connect ( ipaddr, conn->sin.sin_port );
  79. #warning "Use linked lists so that uip_connect() cannot fail"
  80. assert ( uip_conn != NULL );
  81. *( ( void ** ) uip_conn->appstate ) = conn;
  82. }
  83. /**
  84. * Send data via a TCP connection
  85. *
  86. * @v conn TCP connection
  87. * @v data Data to send
  88. * @v len Length of data
  89. *
  90. * Data will be automatically limited to the current TCP window size.
  91. *
  92. * If retransmission is required, the connection's
  93. * tcp_operations::senddata() method will be called again in order to
  94. * regenerate the data.
  95. */
  96. void tcp_send ( struct tcp_connection *conn __unused,
  97. const void *data, size_t len ) {
  98. assert ( conn = *( ( void ** ) uip_conn->appstate ) );
  99. if ( len > tcp_buflen )
  100. len = tcp_buflen;
  101. memmove ( tcp_buffer, data, len );
  102. uip_send ( tcp_buffer, len );
  103. }
  104. /**
  105. * Close a TCP connection
  106. *
  107. * @v conn TCP connection
  108. */
  109. void tcp_close ( struct tcp_connection *conn __unused ) {
  110. assert ( conn = *( ( void ** ) uip_conn->appstate ) );
  111. uip_close();
  112. }
  113. /**
  114. * uIP TCP application call interface
  115. *
  116. * This is the entry point of gPXE from the point of view of the uIP
  117. * protocol stack. This function calls the appropriate methods from
  118. * the connection's @tcp_operations table in order to process received
  119. * data, transmit new data etc.
  120. */
  121. void uip_tcp_appcall ( void ) {
  122. struct tcp_connection *conn = *( ( void ** ) uip_conn->appstate );
  123. struct tcp_operations *op = conn->tcp_op;
  124. if ( op->closed ) {
  125. if ( uip_aborted() )
  126. op->closed ( conn, -ECONNABORTED );
  127. if ( uip_timedout() )
  128. op->closed ( conn, -ETIMEDOUT );
  129. if ( uip_closed() )
  130. op->closed ( conn, 0 );
  131. }
  132. if ( uip_connected() && op->connected )
  133. op->connected ( conn );
  134. if ( uip_acked() && op->acked )
  135. op->acked ( conn, uip_conn->len );
  136. if ( uip_newdata() && op->newdata )
  137. op->newdata ( conn, ( void * ) uip_appdata, uip_len );
  138. if ( ( uip_rexmit() || uip_newdata() || uip_acked() ||
  139. uip_connected() || uip_poll() ) && op->senddata )
  140. op->senddata ( conn, tcp_buffer, tcp_buflen );
  141. }
  142. /* Present here to allow everything to link. Will go into separate
  143. * udp.c file
  144. */
  145. void uip_udp_appcall ( void ) {
  146. }
  147. /**
  148. * Perform periodic processing of all TCP connections
  149. *
  150. * This allows TCP connections to retransmit data if necessary.
  151. */
  152. static void tcp_periodic ( void ) {
  153. struct pk_buff *pkb;
  154. int i;
  155. for ( i = 0 ; i < UIP_CONNS ; i++ ) {
  156. uip_periodic ( i );
  157. if ( uip_len > 0 ) {
  158. pkb = alloc_pkb ( uip_len + MAX_LL_HEADER_LEN);
  159. if ( ! pkb )
  160. continue;
  161. pkb_reserve ( pkb, MAX_LL_HEADER_LEN );
  162. pkb_put ( pkb, uip_len );
  163. memcpy ( pkb->data, uip_buf, uip_len );
  164. ipv4_uip_tx ( pkb );
  165. }
  166. }
  167. }
  168. /**
  169. * Kick a connection into life
  170. *
  171. * @v conn TCP connection
  172. *
  173. * Call this function when you have new data to send and are not
  174. * already being called as part of TCP processing.
  175. */
  176. void tcp_kick ( struct tcp_connection *conn __unused ) {
  177. /* Just kick all the connections; this will work for now */
  178. tcp_periodic();
  179. }
  180. /**
  181. * Single-step the TCP stack
  182. *
  183. * @v process TCP process
  184. *
  185. * This calls tcp_periodic() at regular intervals.
  186. */
  187. static void tcp_step ( struct process *process ) {
  188. static unsigned long timeout = 0;
  189. if ( currticks() > timeout ) {
  190. timeout = currticks() + ( TICKS_PER_SEC / 10 );
  191. tcp_periodic ();
  192. }
  193. schedule ( process );
  194. }
  195. /** TCP stack process */
  196. static struct process tcp_process = {
  197. .step = tcp_step,
  198. };
  199. /** Initialise the TCP stack */
  200. static void init_tcp ( void ) {
  201. schedule ( &tcp_process );
  202. }
  203. INIT_FN ( INIT_PROCESS, init_tcp, NULL, NULL );
  204. #else
  205. /**
  206. * List of registered TCP connections
  207. */
  208. static LIST_HEAD ( tcp_conns );
  209. /**
  210. * List of TCP states
  211. */
  212. static const char *tcp_states[] = {
  213. "CLOSED",
  214. "LISTEN",
  215. "SYN_SENT",
  216. "SYN_RCVD",
  217. "ESTABLISHED",
  218. "FIN_WAIT_1",
  219. "FIN_WAIT_2",
  220. "CLOSING",
  221. "TIME_WAIT",
  222. "CLOSE_WAIT",
  223. "LAST_ACK",
  224. "INVALID" };
  225. /**
  226. * TCP state transition function
  227. *
  228. * @v conn TCP connection
  229. * @v nxt_state Next TCP state
  230. */
  231. void tcp_set_flags ( struct tcp_connection *conn ) {
  232. /* Set the TCP flags */
  233. switch ( conn->tcp_state ) {
  234. case TCP_CLOSED:
  235. if ( conn->tcp_lstate == TCP_SYN_RCVD ) {
  236. conn->tcp_flags |= TCP_RST;
  237. }
  238. break;
  239. case TCP_LISTEN:
  240. break;
  241. case TCP_SYN_SENT:
  242. if ( conn->tcp_lstate == TCP_LISTEN ||
  243. conn->tcp_lstate == TCP_CLOSED ) {
  244. conn->tcp_flags |= TCP_SYN;
  245. }
  246. break;
  247. case TCP_SYN_RCVD:
  248. if ( conn->tcp_lstate == TCP_LISTEN ||
  249. conn->tcp_lstate == TCP_SYN_SENT ) {
  250. conn->tcp_flags |= ( TCP_SYN | TCP_ACK );
  251. }
  252. break;
  253. case TCP_ESTABLISHED:
  254. if ( conn->tcp_lstate == TCP_SYN_SENT ) {
  255. conn->tcp_flags |= TCP_ACK;
  256. }
  257. break;
  258. case TCP_FIN_WAIT_1:
  259. if ( conn->tcp_lstate == TCP_SYN_RCVD ||
  260. conn->tcp_lstate == TCP_ESTABLISHED ) {
  261. conn->tcp_flags |= TCP_FIN;
  262. }
  263. break;
  264. case TCP_FIN_WAIT_2:
  265. break;
  266. case TCP_CLOSING:
  267. if ( conn->tcp_lstate == TCP_FIN_WAIT_1 ) {
  268. conn->tcp_flags |= TCP_ACK;
  269. }
  270. break;
  271. case TCP_TIME_WAIT:
  272. if ( conn->tcp_lstate == TCP_FIN_WAIT_1 ||
  273. conn->tcp_lstate == TCP_FIN_WAIT_2 ) {
  274. conn->tcp_flags |= TCP_ACK;
  275. }
  276. break;
  277. case TCP_CLOSE_WAIT:
  278. if ( conn->tcp_lstate == TCP_ESTABLISHED ) {
  279. conn->tcp_flags |= TCP_ACK;
  280. }
  281. break;
  282. case TCP_LAST_ACK:
  283. if ( conn->tcp_lstate == TCP_CLOSE_WAIT ) {
  284. conn->tcp_flags |= TCP_FIN;
  285. }
  286. if ( conn->tcp_lstate == TCP_ESTABLISHED ) {
  287. conn->tcp_flags |= ( TCP_FIN | TCP_ACK );
  288. }
  289. break;
  290. default:
  291. DBG ( "TCP_INVALID state %d\n", conn->tcp_state );
  292. return;
  293. }
  294. }
  295. void tcp_trans ( struct tcp_connection *conn, int nxt_state ) {
  296. /* Remember the last state */
  297. conn->tcp_lstate = conn->tcp_state;
  298. conn->tcp_state = nxt_state;
  299. DBG ( "Transition from %s to %s\n", tcp_states[conn->tcp_lstate], tcp_states[conn->tcp_state] );
  300. /* TODO: Check if this check is required */
  301. if ( conn->tcp_lstate == conn->tcp_state ||
  302. conn->tcp_state == TCP_INVALID ) {
  303. conn->tcp_flags = 0;
  304. return;
  305. }
  306. tcp_set_flags ( conn );
  307. }
  308. /**
  309. * Dump TCP header
  310. *
  311. * @v tcphdr TCP header
  312. */
  313. void tcp_dump ( struct tcp_header *tcphdr ) {
  314. DBG ( "TCP %p src:%d dest:%d seq:%lx ack:%lx hlen:%hd flags:%#hx\n",
  315. tcphdr, ntohs ( tcphdr->src ), ntohs ( tcphdr->dest ), ntohl ( tcphdr->seq ),
  316. ntohl ( tcphdr->ack ), ( ( tcphdr->hlen & TCP_MASK_HLEN ) / 16 ), ( tcphdr->flags & TCP_MASK_FLAGS ) );
  317. }
  318. /**
  319. * Initialize a TCP connection
  320. *
  321. * @v conn TCP connection
  322. *
  323. * This function assigns initial values to some fields in the connection
  324. * structure. The application should call tcp_init_conn after creating a new
  325. * connection before calling any other "tcp_*" function.
  326. *
  327. * struct tcp_connection my_conn;
  328. * tcp_init_conn ( &my_conn );
  329. * ...
  330. */
  331. void tcp_init_conn ( struct tcp_connection *conn ) {
  332. conn->local_port = 0;
  333. conn->tcp_state = TCP_CLOSED;
  334. conn->tcp_lstate = TCP_INVALID;
  335. conn->tx_pkb = NULL;
  336. conn->tcp_op = NULL;
  337. }
  338. /** Retry timer
  339. *
  340. * @v timer Retry timer
  341. * @v over Failure indicator
  342. */
  343. void tcp_expired ( struct retry_timer *timer, int over ) {
  344. struct tcp_connection *conn =
  345. container_of ( timer, struct tcp_connection, timer );
  346. DBG ( "Timer expired in %s\n", tcp_states[conn->tcp_state] );
  347. switch ( conn->tcp_state ) {
  348. case TCP_SYN_SENT:
  349. if ( over ) {
  350. list_del ( &conn->list );
  351. tcp_trans ( conn, TCP_CLOSED );
  352. if ( conn->tcp_op->closed )
  353. conn->tcp_op->closed ( conn, -ETIMEDOUT );
  354. DBG ( "Timeout! Connection closed\n" );
  355. return;
  356. }
  357. goto send_tcp_nomsg;
  358. case TCP_SYN_RCVD:
  359. if ( over ) {
  360. list_del ( &conn->list );
  361. tcp_trans ( conn, TCP_CLOSED );
  362. if ( conn->tcp_op->closed )
  363. conn->tcp_op->closed ( conn, -ETIMEDOUT );
  364. goto send_tcp_nomsg;
  365. }
  366. goto send_tcp_nomsg;
  367. case TCP_ESTABLISHED:
  368. if ( conn->tcp_lstate == TCP_SYN_SENT ) {
  369. goto send_tcp_nomsg;
  370. }
  371. break;
  372. case TCP_CLOSE_WAIT:
  373. if ( conn->tcp_lstate == TCP_ESTABLISHED ) {
  374. goto send_tcp_nomsg;
  375. }
  376. break;
  377. case TCP_FIN_WAIT_1:
  378. case TCP_FIN_WAIT_2:
  379. goto send_tcp_nomsg;
  380. case TCP_CLOSING:
  381. case TCP_LAST_ACK:
  382. if ( conn->tcp_lstate == TCP_CLOSE_WAIT ) {
  383. goto send_tcp_nomsg;
  384. }
  385. return;
  386. case TCP_TIME_WAIT:
  387. list_del ( &conn->list );
  388. tcp_trans ( conn, TCP_CLOSED );
  389. if ( conn->tcp_op->closed )
  390. conn->tcp_op->closed ( conn, 0 );
  391. return;
  392. }
  393. /* Retransmit the data */
  394. tcp_set_flags ( conn );
  395. tcp_senddata ( conn );
  396. return;
  397. send_tcp_nomsg:
  398. free_pkb ( conn->tx_pkb );
  399. conn->tx_pkb = alloc_pkb ( MIN_PKB_LEN );
  400. pkb_reserve ( conn->tx_pkb, MAX_HDR_LEN );
  401. tcp_set_flags ( conn );
  402. int rc;
  403. if ( ( rc = tcp_send ( conn, TCP_NOMSG, TCP_NOMSG_LEN ) ) != 0 ) {
  404. DBG ( "Error sending TCP message (rc = %d)\n", rc );
  405. }
  406. return;
  407. }
  408. /**
  409. * Connect to a remote server
  410. *
  411. * @v conn TCP connection
  412. * @v peer Remote socket address
  413. *
  414. * This function initiates a TCP connection to the socket address specified in
  415. * peer. It sends a SYN packet to peer. When the connection is established, the
  416. * TCP stack calls the connected() callback function.
  417. */
  418. int tcp_connectto ( struct tcp_connection *conn,
  419. struct sockaddr_tcpip *peer ) {
  420. int rc;
  421. /* A connection can only be established from the CLOSED state */
  422. if ( conn->tcp_state != TCP_CLOSED ) {
  423. DBG ( "Error opening connection: Invalid state %s\n",
  424. tcp_states[conn->tcp_state] );
  425. return -EISCONN;
  426. }
  427. #warning "Fix the port re-use bug"
  428. /* If we re-use the same port, the connection should be reset
  429. * and a new connection set up. This doesn't happen yet, so
  430. * force the use of a new (random) port to avoid hitting the
  431. * problem.
  432. */
  433. conn->local_port = 0;
  434. /* Add the connection to the set of listening connections */
  435. if ( ( rc = tcp_listen ( conn, conn->local_port ) ) != 0 ) {
  436. return rc;
  437. }
  438. memcpy ( &conn->peer, peer, sizeof ( conn->peer ) );
  439. /* Initialize the TCP timer */
  440. conn->timer.expired = tcp_expired;
  441. /* Send a SYN packet and transition to TCP_SYN_SENT */
  442. conn->snd_una = random();
  443. tcp_trans ( conn, TCP_SYN_SENT );
  444. /* Allocate space for the packet */
  445. free_pkb ( conn->tx_pkb );
  446. conn->tx_pkb = alloc_pkb ( MIN_PKB_LEN );
  447. pkb_reserve ( conn->tx_pkb, MAX_HDR_LEN );
  448. conn->rcv_win = MAX_PKB_LEN - MAX_HDR_LEN; /* TODO: Is this OK? */
  449. return tcp_send ( conn, TCP_NOMSG, TCP_NOMSG_LEN );
  450. }
  451. int tcp_connect ( struct tcp_connection *conn ) {
  452. return tcp_connectto ( conn, &conn->peer );
  453. }
  454. /**
  455. * Close the connection
  456. *
  457. * @v conn
  458. *
  459. * This function sends a FIN packet to the remote end of the connection. When
  460. * the remote end of the connection ACKs the FIN (FIN consumes one byte on the
  461. * snd stream), the stack invokes the closed() callback function.
  462. */
  463. int tcp_close ( struct tcp_connection *conn ) {
  464. /* A connection can only be closed if it is a connected state */
  465. switch ( conn->tcp_state ) {
  466. case TCP_SYN_RCVD:
  467. case TCP_ESTABLISHED:
  468. tcp_trans ( conn, TCP_FIN_WAIT_1 );
  469. /* FIN consumes one byte on the snd stream */
  470. // conn->snd_una++;
  471. goto send_tcp_nomsg;
  472. case TCP_SYN_SENT:
  473. case TCP_LISTEN:
  474. /**
  475. * Since the connection does not expect any packets from the
  476. * remote end, it can be removed from the set of listening
  477. * connections.
  478. */
  479. list_del ( &conn->list );
  480. tcp_trans ( conn, TCP_CLOSED );
  481. if ( conn->tcp_op->closed )
  482. conn->tcp_op->closed ( conn, 0 );
  483. return 0;
  484. case TCP_CLOSE_WAIT:
  485. tcp_trans ( conn, TCP_LAST_ACK );
  486. /* FIN consumes one byte on the snd stream */
  487. // conn->snd_una++;
  488. goto send_tcp_nomsg;
  489. default:
  490. DBG ( "tcp_close(): Invalid state %s\n",
  491. tcp_states[conn->tcp_state] );
  492. return -EPROTO;
  493. }
  494. send_tcp_nomsg:
  495. free_pkb ( conn->tx_pkb );
  496. conn->tx_pkb = alloc_pkb ( MIN_PKB_LEN );
  497. conn->tcp_flags = TCP_FIN;
  498. pkb_reserve ( conn->tx_pkb, MAX_HDR_LEN );
  499. return tcp_send ( conn, TCP_NOMSG, TCP_NOMSG_LEN );
  500. }
  501. /**
  502. * Bind TCP connection to local port
  503. *
  504. * @v conn TCP connection
  505. * @v local_port Local port, in network byte order
  506. * @ret rc Return status code
  507. */
  508. int tcp_bind ( struct tcp_connection *conn, uint16_t local_port ) {
  509. struct tcp_connection *existing;
  510. list_for_each_entry ( existing, &tcp_conns, list ) {
  511. if ( existing->local_port == local_port )
  512. return -EADDRINUSE;
  513. }
  514. conn->local_port = local_port;
  515. return 0;
  516. }
  517. /**
  518. * Listen for a packet
  519. *
  520. * @v conn TCP connection
  521. * @v local_port Local port, in network byte order
  522. *
  523. * This function adds the connection to a list of registered tcp
  524. * connections. If the local port is 0, the connection is assigned an
  525. * available port between MIN_TCP_PORT and 65535.
  526. */
  527. int tcp_listen ( struct tcp_connection *conn, uint16_t local_port ) {
  528. static uint16_t try_port = 1024;
  529. int rc;
  530. #warning "Fix the port re-use bug"
  531. /* If we re-use the same port, the connection should be reset
  532. * and a new connection set up. This doesn't happen yet, so
  533. * randomise the port to avoid hitting the problem.
  534. */
  535. try_port = random();
  536. /* If no port specified, find the first available port */
  537. if ( ! local_port ) {
  538. for ( ; try_port ; try_port++ ) {
  539. if ( try_port < 1024 )
  540. continue;
  541. if ( tcp_listen ( conn, htons ( try_port ) ) == 0 )
  542. return 0;
  543. }
  544. return -EADDRINUSE;
  545. }
  546. /* Attempt bind to local port */
  547. if ( ( rc = tcp_bind ( conn, local_port ) ) != 0 )
  548. return rc;
  549. /* Add to TCP connection list */
  550. list_add ( &conn->list, &tcp_conns );
  551. DBG ( "TCP opened %p on port %d\n", conn, ntohs ( local_port ) );
  552. return 0;
  553. }
  554. /**
  555. * Send data
  556. *
  557. * @v conn TCP connection
  558. *
  559. * This function allocates space to the transmit buffer and invokes the
  560. * senddata() callback function. It passes the allocated buffer to senddata().
  561. * The applicaion may use this space to write it's data.
  562. */
  563. int tcp_senddata ( struct tcp_connection *conn ) {
  564. /* The connection must be in a state in which the user can send data */
  565. switch ( conn->tcp_state ) {
  566. case TCP_LISTEN:
  567. tcp_trans ( conn, TCP_SYN_SENT );
  568. conn->snd_una = random();
  569. break;
  570. case TCP_ESTABLISHED:
  571. case TCP_CLOSE_WAIT:
  572. break;
  573. default:
  574. DBG ( "tcp_senddata: Invalid state %s\n",
  575. tcp_states[conn->tcp_state] );
  576. return -EPROTO;
  577. }
  578. /* Allocate space to the TX buffer */
  579. free_pkb ( conn->tx_pkb );
  580. conn->tx_pkb = alloc_pkb ( MAX_PKB_LEN );
  581. if ( !conn->tx_pkb ) {
  582. DBG ( "Insufficient memory\n" );
  583. return -ENOMEM;
  584. }
  585. pkb_reserve ( conn->tx_pkb, MAX_HDR_LEN );
  586. /* Set the advertised window */
  587. conn->rcv_win = pkb_available ( conn->tx_pkb );
  588. /* Call the senddata() call back function */
  589. if ( conn->tcp_op->senddata )
  590. conn->tcp_op->senddata ( conn, conn->tx_pkb->data,
  591. pkb_available ( conn->tx_pkb ) );
  592. /* Send pure ACK if senddata() didn't call tcp_send() */
  593. if ( conn->tx_pkb ) {
  594. tcp_send ( conn, TCP_NOMSG, TCP_NOMSG_LEN );
  595. }
  596. return 0;
  597. }
  598. /**
  599. * Transmit data
  600. *
  601. * @v conn TCP connection
  602. * @v data Data to be sent
  603. * @v len Length of the data
  604. *
  605. * This function sends data to the peer socket address
  606. */
  607. int tcp_send ( struct tcp_connection *conn, const void *data, size_t len ) {
  608. struct sockaddr_tcpip *peer = &conn->peer;
  609. struct pk_buff *pkb;
  610. int slen;
  611. /* Take ownership of the TX buffer from the connection */
  612. pkb = conn->tx_pkb;
  613. conn->tx_pkb = NULL;
  614. /* Determine the amount of data to be sent */
  615. slen = len < conn->snd_win ? len : conn->snd_win;
  616. /* Copy payload */
  617. memmove ( pkb_put ( pkb, slen ), data, slen );
  618. /* Fill up the TCP header */
  619. struct tcp_header *tcphdr = pkb_push ( pkb, sizeof ( *tcphdr ) );
  620. /* Source port, assumed to be in network byte order in conn */
  621. tcphdr->src = conn->local_port;
  622. /* Destination port, assumed to be in network byte order in peer */
  623. tcphdr->dest = peer->st_port;
  624. tcphdr->seq = htonl ( conn->snd_una );
  625. tcphdr->ack = htonl ( conn->rcv_nxt );
  626. /* Header length, = 0x50 (without TCP options) */
  627. tcphdr->hlen = ( uint8_t ) ( ( sizeof ( *tcphdr ) / 4 ) << 4 );
  628. /* Copy TCP flags, and then reset the variable */
  629. tcphdr->flags = conn->tcp_flags;
  630. conn->tcp_flags = 0;
  631. /* Advertised window, in network byte order */
  632. tcphdr->win = htons ( conn->rcv_win );
  633. /* Set urgent pointer to 0 */
  634. tcphdr->urg = 0;
  635. /* Calculate and store partial checksum, in host byte order */
  636. tcphdr->csum = 0;
  637. tcphdr->csum = tcpip_chksum ( pkb->data, pkb_len ( pkb ) );
  638. /* Dump the TCP header */
  639. tcp_dump ( tcphdr );
  640. /* Start the timer */
  641. if ( ( conn->tcp_state == TCP_ESTABLISHED && conn->tcp_lstate == TCP_SYN_SENT ) ||
  642. ( conn->tcp_state == TCP_LISTEN && conn->tcp_lstate == TCP_SYN_RCVD ) ||
  643. ( conn->tcp_state == TCP_CLOSED && conn->tcp_lstate == TCP_SYN_RCVD ) ||
  644. ( conn->tcp_state == TCP_ESTABLISHED && ( len == 0 ) ) ) {
  645. // Don't start the timer
  646. } else {
  647. start_timer ( &conn->timer );
  648. }
  649. /* Transmit packet */
  650. return tcpip_tx ( pkb, &tcp_protocol, peer );
  651. }
  652. /**
  653. * Process received packet
  654. *
  655. * @v pkb Packet buffer
  656. * @v partial Partial checksum
  657. */
  658. static int tcp_rx ( struct pk_buff *pkb,
  659. struct sockaddr_tcpip *st_src __unused,
  660. struct sockaddr_tcpip *st_dest __unused ) {
  661. struct tcp_connection *conn;
  662. struct tcp_header *tcphdr;
  663. int32_t acked, toack;
  664. unsigned int hlen;
  665. int rc;
  666. /* Sanity check */
  667. if ( pkb_len ( pkb ) < sizeof ( *tcphdr ) ) {
  668. DBG ( "Packet too short (%d bytes)\n", pkb_len ( pkb ) );
  669. rc = -EINVAL;
  670. goto done;
  671. }
  672. /* Process TCP header */
  673. tcphdr = pkb->data;
  674. tcp_dump ( tcphdr );
  675. /* Verify header length */
  676. hlen = ( ( tcphdr->hlen & TCP_MASK_HLEN ) / 16 ) * 4;
  677. if ( hlen < sizeof ( *tcphdr ) ) {
  678. DBG ( "Bad header length (%d bytes)\n", hlen );
  679. rc = -EINVAL;
  680. goto done;
  681. }
  682. /* TODO: Parse TCP options */
  683. if ( hlen != sizeof ( *tcphdr ) ) {
  684. DBG ( "Ignoring TCP options\n" );
  685. }
  686. /* TODO: Verify checksum */
  687. /* Demux TCP connection */
  688. list_for_each_entry ( conn, &tcp_conns, list ) {
  689. if ( tcphdr->dest == conn->local_port ) {
  690. goto found_conn;
  691. }
  692. }
  693. DBG ( "No connection found on port %d\n", ntohs ( tcphdr->dest ) );
  694. rc = 0;
  695. goto done;
  696. found_conn:
  697. /* Stop the timer */
  698. stop_timer ( &conn->timer );
  699. /* Set the advertised window */
  700. conn->snd_win = tcphdr->win;
  701. /* TCP State Machine */
  702. conn->tcp_lstate = conn->tcp_state;
  703. switch ( conn->tcp_state ) {
  704. case TCP_CLOSED:
  705. DBG ( "tcp_rx(): Invalid state %s\n",
  706. tcp_states[conn->tcp_state] );
  707. rc = -EINVAL;
  708. goto done;
  709. case TCP_LISTEN:
  710. if ( tcphdr->flags & TCP_SYN ) {
  711. tcp_trans ( conn, TCP_SYN_RCVD );
  712. /* Synchronize the sequence numbers */
  713. conn->rcv_nxt = ntohl ( tcphdr->seq ) + 1;
  714. conn->tcp_flags |= TCP_ACK;
  715. /* Set the sequence number for the snd stream */
  716. conn->snd_una = random();
  717. conn->tcp_flags |= TCP_SYN;
  718. /* Send a SYN,ACK packet */
  719. goto send_tcp_nomsg;
  720. }
  721. /* Unexpected packet */
  722. goto unexpected;
  723. case TCP_SYN_SENT:
  724. if ( tcphdr->flags & TCP_SYN ) {
  725. /* Synchronize the sequence number in rcv stream */
  726. conn->rcv_nxt = ntohl ( tcphdr->seq ) + 1;
  727. conn->tcp_flags |= TCP_ACK;
  728. if ( tcphdr->flags & TCP_ACK ) {
  729. tcp_trans ( conn, TCP_ESTABLISHED );
  730. /**
  731. * Process ACK of SYN. This does not invoke the
  732. * acked() callback function.
  733. */
  734. conn->snd_una = ntohl ( tcphdr->ack );
  735. if ( conn->tcp_op->connected )
  736. conn->tcp_op->connected ( conn );
  737. conn->tcp_flags |= TCP_ACK;
  738. tcp_senddata ( conn );
  739. rc = 0;
  740. goto done;
  741. } else {
  742. tcp_trans ( conn, TCP_SYN_RCVD );
  743. conn->tcp_flags |= TCP_SYN;
  744. goto send_tcp_nomsg;
  745. }
  746. }
  747. /* Unexpected packet */
  748. goto unexpected;
  749. case TCP_SYN_RCVD:
  750. if ( tcphdr->flags & TCP_RST ) {
  751. tcp_trans ( conn, TCP_LISTEN );
  752. if ( conn->tcp_op->closed )
  753. conn->tcp_op->closed ( conn, -ECONNRESET );
  754. rc = 0;
  755. goto done;
  756. }
  757. if ( tcphdr->flags & TCP_ACK ) {
  758. tcp_trans ( conn, TCP_ESTABLISHED );
  759. /**
  760. * Process ACK of SYN. It neither invokes the callback
  761. * function nor does it send an ACK.
  762. */
  763. conn->snd_una = tcphdr->ack - 1;
  764. if ( conn->tcp_op->connected )
  765. conn->tcp_op->connected ( conn );
  766. rc = 0;
  767. goto done;
  768. }
  769. /* Unexpected packet */
  770. goto unexpected;
  771. case TCP_ESTABLISHED:
  772. if ( tcphdr->flags & TCP_FIN ) {
  773. if ( tcphdr->flags & TCP_ACK ) {
  774. tcp_trans ( conn, TCP_LAST_ACK );
  775. conn->tcp_flags |= TCP_FIN;
  776. } else {
  777. tcp_trans ( conn, TCP_CLOSE_WAIT );
  778. }
  779. /* FIN consumes one byte */
  780. conn->rcv_nxt++;
  781. conn->tcp_flags |= TCP_ACK;
  782. /* Send the packet */
  783. goto send_tcp_nomsg;
  784. }
  785. /* Packet might contain data */
  786. break;
  787. case TCP_FIN_WAIT_1:
  788. if ( tcphdr->flags & TCP_FIN ) {
  789. conn->rcv_nxt++;
  790. conn->tcp_flags |= TCP_ACK;
  791. if ( tcphdr->flags & TCP_ACK ) {
  792. tcp_trans ( conn, TCP_TIME_WAIT );
  793. } else {
  794. tcp_trans ( conn, TCP_CLOSING );
  795. }
  796. /* Send an acknowledgement */
  797. goto send_tcp_nomsg;
  798. }
  799. if ( tcphdr->flags & TCP_ACK ) {
  800. tcp_trans ( conn, TCP_FIN_WAIT_2 );
  801. }
  802. /* Packet might contain data */
  803. break;
  804. case TCP_FIN_WAIT_2:
  805. if ( tcphdr->flags & TCP_FIN ) {
  806. tcp_trans ( conn, TCP_TIME_WAIT );
  807. /* FIN consumes one byte */
  808. conn->rcv_nxt++;
  809. conn->tcp_flags |= TCP_ACK;
  810. goto send_tcp_nomsg;
  811. }
  812. /* Packet might contain data */
  813. break;
  814. case TCP_CLOSING:
  815. if ( tcphdr->flags & TCP_ACK ) {
  816. tcp_trans ( conn, TCP_TIME_WAIT );
  817. start_timer ( &conn->timer );
  818. rc = 0;
  819. goto done;
  820. }
  821. /* Unexpected packet */
  822. goto unexpected;
  823. case TCP_TIME_WAIT:
  824. /* Unexpected packet */
  825. goto unexpected;
  826. case TCP_CLOSE_WAIT:
  827. /* Packet could acknowledge data */
  828. break;
  829. case TCP_LAST_ACK:
  830. if ( tcphdr->flags & TCP_ACK ) {
  831. list_del ( &conn->list );
  832. tcp_trans ( conn, TCP_CLOSED );
  833. if ( conn->tcp_op->closed )
  834. conn->tcp_op->closed ( conn, 0 );
  835. rc = 0;
  836. goto done;
  837. }
  838. /* Unexpected packet */
  839. goto unexpected;
  840. }
  841. /**
  842. * Any packet reaching this point either contains new data or
  843. * acknowledges previously transmitted data.
  844. */
  845. assert ( ( tcphdr->flags & TCP_ACK ) ||
  846. pkb_len ( pkb ) > sizeof ( *tcphdr ) );
  847. /**
  848. * Check if the received packet ACKs sent data
  849. */
  850. if ( tcphdr->flags & TCP_ACK ) {
  851. acked = ntohl ( tcphdr->ack ) - conn->snd_una;
  852. if ( acked < 0 ) {
  853. /* Packet ACKs previously ACKed data */
  854. DBG ( "Previously ACKed data %lx\n",
  855. ntohl ( tcphdr->ack ) );
  856. rc = 0;
  857. goto done;
  858. }
  859. /* Invoke the acked() callback */
  860. conn->snd_una += acked;
  861. if ( conn->tcp_op->acked )
  862. conn->tcp_op->acked ( conn, acked );
  863. }
  864. /**
  865. * Check if packet contains new data
  866. */
  867. toack = pkb_len ( pkb ) - hlen;
  868. if ( toack >= 0 ) {
  869. /* Check the sequence number */
  870. if ( conn->rcv_nxt == ntohl ( tcphdr->seq ) ) {
  871. conn->rcv_nxt += toack;
  872. if ( conn->tcp_op->newdata )
  873. conn->tcp_op->newdata ( conn, pkb->data + hlen,
  874. toack );
  875. } else {
  876. DBG ( "Unexpected sequence number %lx (wanted %lx)\n",
  877. ntohl ( tcphdr->ack ), conn->rcv_nxt );
  878. }
  879. conn->tcp_flags |= TCP_ACK;
  880. }
  881. /**
  882. * Send data
  883. */
  884. tcp_senddata ( conn );
  885. rc = 0;
  886. goto done;
  887. send_tcp_nomsg:
  888. free_pkb ( conn->tx_pkb );
  889. conn->tx_pkb = alloc_pkb ( MIN_PKB_LEN );
  890. pkb_reserve ( conn->tx_pkb, MAX_HDR_LEN );
  891. if ( ( rc = tcp_send ( conn, TCP_NOMSG, TCP_NOMSG_LEN ) ) != 0 ) {
  892. DBG ( "Error sending TCP message (rc = %d)\n", rc );
  893. }
  894. goto done;
  895. unexpected:
  896. DBG ( "Unexpected packet received in %s with flags = %#hx\n",
  897. tcp_states[conn->tcp_state], tcphdr->flags & TCP_MASK_FLAGS );
  898. tcp_close ( conn );
  899. free_pkb ( conn->tx_pkb );
  900. conn->tx_pkb = NULL;
  901. rc = -EINVAL;
  902. goto done;
  903. done:
  904. free_pkb ( pkb );
  905. return rc;
  906. }
  907. /** TCP protocol */
  908. struct tcpip_protocol tcp_protocol __tcpip_protocol = {
  909. .name = "TCP",
  910. .rx = tcp_rx,
  911. .tcpip_proto = IP_TCP,
  912. .csum_offset = 16,
  913. };
  914. #endif /* USE_UIP */