@@ -490,21 +490,41 @@ int Polaris_Work(PolarisContext_t* context) {
490490 recv (context -> socket , context -> recv_buffer , POLARIS_RECV_BUFFER_SIZE , 0 );
491491#endif
492492
493+ #ifdef P1_FREERTOS
494+ // FreeRTOS does not use errno for recv() errors, but instead returns the
495+ // equivalent error value. On a socket timeout, it returns 0 instead of
496+ // ETIMEDOUT.
497+ //
498+ // We try to mimick the actual POSIX behavior to simplify the code below.
499+ if (bytes_read == 0 ) {
500+ bytes_read = -1 ;
501+ errno = ETIMEDOUT ;
502+ } else if (bytes_read < 0 ) {
503+ errno = (int )bytes_read ;
504+ }
505+ #endif
506+
493507 if (bytes_read < 0 ) {
494508 if (errno == EAGAIN || errno == ETIMEDOUT ) {
495509 P1_DebugPrint ("Socket timed out.\n" );
496510 return 0 ;
497511 } else {
498- P1_DebugPrint (
499- "Connection terminated. [ret=%d, errno=%d, "
500- "disconnected=%d]\n" ,
501- (int )bytes_read , errno , context -> disconnected );
502- CloseSocket (context , 1 );
512+ // Typically ENOTCONN, but could be another error condition.
513+ int ret ;
503514 if (context -> disconnected ) {
504- return 0 ;
515+ P1_DebugPrint (
516+ "Connection terminated by user request. [ret=%d, errno=%d]\n" ,
517+ (int )bytes_read , errno );
518+ ret = 0 ;
505519 } else {
506- return POLARIS_CONNECTION_CLOSED ;
520+ P1_DebugPrint (
521+ "Connection terminated upstream. [ret=%d, errno=%d]\n" ,
522+ (int )bytes_read , errno );
523+ ret = POLARIS_CONNECTION_CLOSED ;
507524 }
525+
526+ CloseSocket (context , 1 );
527+ return ret ;
508528 }
509529 } else if (bytes_read == 0 ) {
510530 // If recv() times out before we've gotten anything, the socket was probably
@@ -516,11 +536,17 @@ int Polaris_Work(PolarisContext_t* context) {
516536 CloseSocket (context , 1 );
517537 return POLARIS_FORBIDDEN ;
518538 }
519- // Otherwise, there may just not be new data available (e.g., user hasn't
520- // sent a position yet, network connection temporarily broken, etc.).
539+ // A 0 return means the socket had an "orderly shutdown", i.e., it was
540+ // either closed by user request or disconnected upstream by the Polaris
541+ // service.
521542 else {
522- P1_DebugPrint ("Received 0 bytes/socket timed out.\n" );
523- return 0 ;
543+ if (context -> disconnected ) {
544+ P1_DebugPrint ("Connection terminated by user request.\n" );
545+ } else {
546+ P1_DebugPrint ("Connection terminated upstream.\n" );
547+ }
548+ CloseSocket (context , 1 );
549+ return POLARIS_CONNECTION_CLOSED ;
524550 }
525551 } else {
526552 P1_DebugPrint ("Received %u bytes.\n" , (unsigned )bytes_read );
0 commit comments