TSVConnFdCreate

Create a TSVConn from a socket.

Synopsis

include <ts/ts.h>

TSVConn TSVConnFdCreate(int fd)

Description

TSVConnFdCreate() accepts a network socket fd and returns a new TSVConn constructed from the socket. The socket descriptor must be an already connected socket. It will be placed into non-blocking mode.

Return Values

On success, the returned TSVConn object owns the socket and the caller must not close it. If TSVConnFdCreate() fails, NULL is returned, the socket is unchanged and the caller must close it.

Examples

The example below is excerpted from example/intercept/intercept.cc in the Traffic Server source distribution. It demonstrates how to use TSVConnFdCreate() to construct a TSVConn from a connected socket.

  1. // attached in InterceptTxnHook, so the continuation data is
  2. // the TSHttpTxn pointer.
  3. VDEBUG("allocated server intercept state istate=%p for txn=%p", istate, cdata.txn);
  4. // Set up a connection to our real origin, which will be
  5. // 127.0.0.1:$PORT.
  6. memset(&addr, 0, sizeof(addr));
  7. addr.sin.sin_family = AF_INET;
  8. addr.sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK); // XXX config option
  9. addr.sin.sin_port = htons(PORT); // XXX config option
  10. // Normally, we would use TSNetConnect to connect to a secondary service, but to demonstrate
  11. // the use of TSVConnFdCreate, we do a blocking connect inline. This it not recommended for
  12. // production plugins, since it might block an event thread for an arbitrary time.
  13. fd = ::socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
  14. TSReleaseAssert(fd != -1);
  15. if (::connect(fd, &addr.sa, sizeof(addr.sin)) == -1) {
  16. // We failed to connect to the intercepted origin. Abort the
  17. // server intercept since we cannot handle it.
  18. VDEBUG("connect failed with %s (%d)", strerror(errno), errno);
  19. TSVConnAbort(arg.vc, TS_VC_CLOSE_ABORT);
  20. delete istate;
  21. TSContDestroy(contp);
  22. ::close(fd);
  23. return TS_EVENT_NONE;
  24. }
  25. if ((istate->server.vc = TSVConnFdCreate(fd)) == nullptr) {
  26. VDEBUG("TSVconnFdCreate() failed");
  27. TSVConnAbort(arg.vc, TS_VC_CLOSE_ABORT);
  28. delete istate;
  29. TSContDestroy(contp);
  30. ::close(fd);
  31. return TS_EVENT_NONE;
  32. }
  33. VDEBUG("binding client vc=%p to %s:%u", istate->client.vc, inet_ntop(AF_INET, &addr.sin.sin_addr, buf, sizeof(buf)),
  34. (unsigned)ntohs(addr.sin.sin_port));
  35. istate->txn = cdata.txn;
  36. istate->client.vc = arg.vc;
  37. // Reset the continuation data to be our intercept state
  38. // block. We will need this so that we can access both of the

See Also

TSAPI(3ts)