TSVConnFdCreate

Create a TSVConn from a socket.

Synopsis

  1. #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/plugins/c-api/intercept/intercept.cc in the Traffic Server source distribution. It demonstrates how to use TSVConnFdCreate() to construct a TSVConn from a connected socket.

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

See Also

TSAPI(3ts)