[Bloat] [Cake] access to cmsg from go?

Hal Murray halmurray+bufferbloat at sonic.net
Sun Jun 20 16:08:33 EDT 2021

> Is there running code in C?

Yes.  The NTPsec code is full of #ifdef kludgery.

The C API started with SO_TIMESTAMP for microsecond precision then added 
SO_TIMESTAMPNS for nanosecond precision: timeval vs timespec


The basic idea is to use recvmsg rather than recv.  In addition to the data 
buffer, you feed it another buffer where it can put meta data like timestamps. 
 Then you have to scan that buffer to find the part you want.  Both buffers 
are passed to the kernel via a single msghdr parameter (which also has a 
pointer for the addr you get via recvfrom).

Details are in man recvmsg and man cmsg
I thought they were reasonably clear.

Without the ifdefs:

You have to start by using setsockopt to turn on SO_TIMESTAMPNS.
  setsockopt(fd, SOL_SOCKET, SO_TIMESTAMPNS,
                               (const void *)&on, sizeof(on)));

The setup code for recvmsg:
        struct msghdr msghdr;
        struct iovec iovec;
        char control[100];   /* FIXME: Need space for time stamp plus overhead 

        iovec.iov_base        = &rb->recv_buffer;
        iovec.iov_len         = sizeof(rb->recv_buffer);
        memset(&msghdr, '\0', sizeof(msghdr));
        msghdr.msg_name       = &rb->recv_srcadr;
        msghdr.msg_namelen    = fromlen;
        msghdr.msg_iov        = &iovec;
        msghdr.msg_iovlen     = 1;
        msghdr.msg_flags      = 0;
        msghdr.msg_control    = (void *)&control;
        msghdr.msg_controllen = sizeof(control);

The actual call:
        buflen                = recvmsg(fd, &msghdr, 0);

The extract code:
        struct timespec *       tsp;
        cmsghdr = CMSG_FIRSTHDR(msghdr);
        if (NULL == cmsghdr) {
             extra checking because this code is in a subroutine
        if (SCM_TIMESTAMPNS != cmsghdr->cmsg_type) {
             There is only one -- no need to loop
        tsp = (struct timespec *)CMSG_DATA(cmsghdr);

Actual code is in:
  read_network_packet in ntpd/ntp_io.c
  fetch_packetstamp() in ntpd/ntp_packetstamp.c

These are my opinions.  I hate spam.

More information about the Bloat mailing list