Read from the socket dealing with incomplete messages and signals. * Returns 0 on success or errno on failure. Stderr fd passed as * auxiliary data from other end is written to *errfd, or else stderr * fileno if not present. */
| 350 | * auxiliary data from other end is written to *errfd, or else stderr |
| 351 | * fileno if not present. */ |
| 352 | static apr_status_t sock_readhdr(int fd, int *errfd, void *vbuf, size_t buf_size) |
| 353 | { |
| 354 | int rc; |
| 355 | #ifndef HAVE_CGID_FDPASSING |
| 356 | char *buf = vbuf; |
| 357 | size_t bytes_read = 0; |
| 358 | |
| 359 | if (errfd) *errfd = 0; |
| 360 | |
| 361 | do { |
| 362 | do { |
| 363 | rc = read(fd, buf + bytes_read, buf_size - bytes_read); |
| 364 | } while (rc < 0 && errno == EINTR); |
| 365 | switch(rc) { |
| 366 | case -1: |
| 367 | return errno; |
| 368 | case 0: /* unexpected */ |
| 369 | return ECONNRESET; |
| 370 | default: |
| 371 | bytes_read += rc; |
| 372 | } |
| 373 | } while (bytes_read < buf_size); |
| 374 | |
| 375 | |
| 376 | #else /* with FD passing */ |
| 377 | struct msghdr msg = {0}; |
| 378 | struct iovec vec = {vbuf, buf_size}; |
| 379 | struct cmsghdr *cmsg; |
| 380 | union { /* union to ensure alignment */ |
| 381 | struct cmsghdr cm; |
| 382 | char buf[CMSG_SPACE(sizeof(int))]; |
| 383 | } u; |
| 384 | |
| 385 | msg.msg_iov = &vec; |
| 386 | msg.msg_iovlen = 1; |
| 387 | |
| 388 | if (errfd) { |
| 389 | msg.msg_control = u.buf; |
| 390 | msg.msg_controllen = sizeof(u.buf); |
| 391 | *errfd = 0; |
| 392 | } |
| 393 | |
| 394 | /* use MSG_WAITALL to skip loop on truncated reads */ |
| 395 | do { |
| 396 | rc = recvmsg(fd, &msg, MSG_WAITALL); |
| 397 | } while (rc < 0 && errno == EINTR); |
| 398 | |
| 399 | if (rc == 0) { |
| 400 | return ECONNRESET; |
| 401 | } |
| 402 | else if (rc < 0) { |
| 403 | return errno; |
| 404 | } |
| 405 | else if (rc != buf_size) { |
| 406 | /* MSG_WAITALL should ensure the recvmsg blocks until the |
| 407 | * entire length is read, but let's be paranoid. */ |
| 408 | return APR_INCOMPLETE; |
| 409 | } |