diff options
author | Henning Baldersheim <balder@yahoo-inc.com> | 2019-01-15 12:45:02 +0000 |
---|---|---|
committer | Henning Baldersheim <balder@yahoo-inc.com> | 2019-01-15 12:45:02 +0000 |
commit | 49f12678bfe994d1b4893a9e48ecd1443757ebd9 (patch) | |
tree | 1304f411570c7f139d1b8f15bc38ab30264ddc73 /fastos/src | |
parent | e207b1d597a2ba2a749a3337ed99d64788f5f9fd (diff) |
GC unused code.
Diffstat (limited to 'fastos/src')
-rw-r--r-- | fastos/src/tests/CMakeLists.txt | 7 | ||||
-rw-r--r-- | fastos/src/tests/sockettest.cpp | 855 | ||||
-rw-r--r-- | fastos/src/tests/tests.h | 8 | ||||
-rw-r--r-- | fastos/src/tests/typetest.cpp | 4 | ||||
-rw-r--r-- | fastos/src/vespa/fastos/CMakeLists.txt | 4 | ||||
-rw-r--r-- | fastos/src/vespa/fastos/app.cpp | 38 | ||||
-rw-r--r-- | fastos/src/vespa/fastos/serversocket.cpp | 123 | ||||
-rw-r--r-- | fastos/src/vespa/fastos/serversocket.h | 176 | ||||
-rw-r--r-- | fastos/src/vespa/fastos/socket.cpp | 343 | ||||
-rw-r--r-- | fastos/src/vespa/fastos/socket.h | 303 | ||||
-rw-r--r-- | fastos/src/vespa/fastos/socketevent.cpp | 312 | ||||
-rw-r--r-- | fastos/src/vespa/fastos/socketevent.h | 244 | ||||
-rw-r--r-- | fastos/src/vespa/fastos/unix_socket.cpp | 132 | ||||
-rw-r--r-- | fastos/src/vespa/fastos/unix_socket.h | 44 |
14 files changed, 9 insertions, 2584 deletions
diff --git a/fastos/src/tests/CMakeLists.txt b/fastos/src/tests/CMakeLists.txt index 0a1eddf5262..87d56a56154 100644 --- a/fastos/src/tests/CMakeLists.txt +++ b/fastos/src/tests/CMakeLists.txt @@ -12,13 +12,6 @@ vespa_add_executable(fastos_filetest_app TEST fastos ) vespa_add_test(NAME fastos_filetest_app NO_VALGRIND COMMAND fastos_filetest_app) -vespa_add_executable(fastos_sockettest_app TEST - SOURCES - sockettest.cpp - DEPENDS - fastos -) -vespa_add_test(NAME fastos_sockettest_app NO_VALGRIND COMMAND fastos_sockettest_app) vespa_add_executable(fastos_thread_stats_test_app TEST SOURCES thread_stats_test.cpp diff --git a/fastos/src/tests/sockettest.cpp b/fastos/src/tests/sockettest.cpp deleted file mode 100644 index 29dcb1b089e..00000000000 --- a/fastos/src/tests/sockettest.cpp +++ /dev/null @@ -1,855 +0,0 @@ -// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. - -#include "tests.h" -#include <vespa/fastos/file.h> -#include <vespa/fastos/serversocket.h> -#include <cassert> -#include <arpa/inet.h> - -#define MAZE_FILE_OFFSET 1078 - -#define MAZE_WIDTH 776 -#define MAZE_HEIGHT 483 -#define MAZE_START_X 3 -#define MAZE_START_Y 399 -#define MAZE_END_X 759 -#define MAZE_END_Y 63 - -#define MAZE_WALL 0 -#define MAZE_EXIT_LEFT 1 -#define MAZE_EXIT_RIGHT 2 - -#define MAZE_DIRECTION_EAST 0 -#define MAZE_DIRECTION_SOUTH 1 -#define MAZE_DIRECTION_WEST 2 -#define MAZE_DIRECTION_NORTH 3 - -#define MAZE_QUERY_HALLWAY 1234 -#define MAZE_QUERY_QUIT 1235 - - -#define MAX_CONNECTIONS 20 - -#define SEARCHBUF_SIZE (1024*1024/(sizeof(u_short))) - - -class MazeServices -{ -public: - int TurnLeft (int direction) - { - direction--; - if(direction == -1) - direction = 3; - return direction; - } - - int TurnRight (int direction) - { - return (direction+1) % 4; - } - - void SetDirection(int &dx, int &dy, int direction) - { - switch(direction) - { - case MAZE_DIRECTION_EAST: - dx = 2; - dy = 0; - break; - - case MAZE_DIRECTION_SOUTH: - dx = 0; - dy = 2; - break; - - case MAZE_DIRECTION_WEST: - dx = -2; - dy = 0; - break; - - case MAZE_DIRECTION_NORTH: - dx = 0; - dy = -2; - break; - } - } - virtual ~MazeServices(void) { } -}; - -class MazeServer; - - -#define BUFFER_SIZE 20000 -class MazeServerConnection -{ -private: - MazeServerConnection(const MazeServerConnection&); - MazeServerConnection& operator=(const MazeServerConnection&); - - MazeServer *_server; - u_short _receiveBuffer[BUFFER_SIZE/sizeof(u_short)]; - u_short _sendBuffer[BUFFER_SIZE/sizeof(u_short)]; - unsigned char *_sendPtr, *_receivePtr; - int _bytesToSend; - - int ReceiveBufferSpace () - { - return static_cast<int> - (reinterpret_cast<unsigned char *>(_receiveBuffer + BUFFER_SIZE) - - _receivePtr); - } - - int SendBufferSpace () - { - return static_cast<int> - (reinterpret_cast<unsigned char *>(&_sendBuffer[BUFFER_SIZE]) - - _sendPtr); - } - - unsigned int ReceiveBufferBytes () - { - return BUFFER_SIZE - ReceiveBufferSpace(); - } - - unsigned int SendBufferBytes () - { - return BUFFER_SIZE - SendBufferSpace(); - } - -public: - FastOS_Socket *_socket; - bool _shouldFree; - - MazeServerConnection (MazeServer *server, FastOS_Socket *sock) - : _server(server), - _sendPtr(reinterpret_cast<unsigned char *>(_sendBuffer)), - _receivePtr(reinterpret_cast<unsigned char *>(_receiveBuffer)), - _bytesToSend(0), - _socket(sock), - _shouldFree(false) - { - } - - bool ReadEvent (); - bool WriteEvent (); -}; - - -class MazeServer : public MazeServices -{ -private: - MazeServer(const MazeServer&); - MazeServer& operator=(const MazeServer&); - -public: - unsigned char _mazeBitmap[MAZE_HEIGHT][MAZE_WIDTH]; - unsigned char _mazeBitmap2[MAZE_HEIGHT][MAZE_WIDTH]; - - FastOS_ServerSocket *_serverSocket; - BaseTest *_app; - - MazeServer(BaseTest *app) - : _serverSocket(nullptr), - _app(app) - { - } - - bool Initialize() - { - bool rc; - const char *filename = "mazebitmap.bmp"; - - FastOS_File file; - - rc = file.OpenReadOnly(filename); - - _app->Progress(rc, "Opening maze bitmap (%s)", filename); - - if(rc) - { - rc = file.SetPosition(MAZE_FILE_OFFSET); - - _app->Progress(rc, "Setting file position (%d)", MAZE_FILE_OFFSET); - - if(rc) - { - int readBytes = file.Read(_mazeBitmap, MAZE_WIDTH * MAZE_HEIGHT); - - rc = (readBytes == MAZE_WIDTH*MAZE_HEIGHT); - - _app->Progress(rc, "Reading %d bytes from '%s'", - MAZE_WIDTH*MAZE_HEIGHT, filename); - - if(rc) - { - int serverPort = 18334; - _serverSocket = new FastOS_ServerSocket(serverPort); - _app->Progress(_serverSocket != nullptr, - "Creating ServerSocket instance"); - - _app->Progress(_serverSocket->SetSoBlocking(false), - "Set non-blocking"); - - _app->Progress(_serverSocket->Listen(), - "Bind socket to port %d. Listen for " - "incoming connections.", serverPort); - } - } - } - - return rc; - } - - void Run () - { - if(Initialize()) - { - MazeServerConnection *connections[MAX_CONNECTIONS], *conn; - FastOS_SocketEvent socketEvent; - int i; - - memset(connections, 0, sizeof(connections)); - - _serverSocket->SetSocketEvent(&socketEvent); - _serverSocket->EnableReadEvent(true); - - for(;;) - { - bool waitError=false; - - if(socketEvent.Wait(waitError, 200)) - { - if(socketEvent.QueryReadEvent(_serverSocket)) - { - FastOS_Socket *connSocket = _serverSocket->AcceptPlain(); - - _app->Progress(connSocket != nullptr, "Accepting socket (%p)", - connSocket); - - for(i=0; i<MAX_CONNECTIONS; i++) - { - if(connections[i] == nullptr) - { - // Found a free positions for the new connection - break; - } - } - if(i < MAX_CONNECTIONS) - { - if(connSocket != nullptr) - { - connections[i] = new MazeServerConnection(this, connSocket); - - assert(connections[i] != nullptr); - - connSocket->SetSocketEvent(&socketEvent); - connSocket->EnableReadEvent(true); - } - } - else - { - _app->Progress(false, "Rejecting connection. Only %d allowed.", MAX_CONNECTIONS); - delete(connSocket); - } - } - - for(i=0; i<MAX_CONNECTIONS; i++) - { - if((conn = connections[i]) != nullptr) - { - if(socketEvent.QueryReadEvent(conn->_socket)) - { - if(conn->ReadEvent()) - conn->_socket->EnableWriteEvent(true); - } - - if(socketEvent.QueryWriteEvent(conn->_socket)) - { - if(!conn->WriteEvent()) - conn->_socket->EnableWriteEvent(false); - } - - if(conn->_shouldFree) - { - delete(conn); - connections[i] = nullptr; - } - } - } - } - } - } - } - - int Read (int x, int y, int direction, u_short *p) - { - int leftDx = 0, leftDy = 0, rightDx = 0, rightDy = 0; - int forwardDx = 0, forwardDy = 0; - - int entries=0; - int distance=0; - - SetDirection(forwardDx, forwardDy, direction); - SetDirection(leftDx, leftDy, TurnLeft(direction)); - SetDirection(rightDx, rightDy, TurnRight(direction)); - - u_short *numEntries = p; - p++; - - for(;;) - { - x += forwardDx; - y += forwardDy; - - distance++; - - if(_mazeBitmap[MAZE_HEIGHT-1-(y)][x] == 0) // Did we run into wall? - { - *p++ = htons(MAZE_WALL); - *p++ = htons(distance); - entries++; - break; - } - - if(_mazeBitmap[MAZE_HEIGHT-1-(y+leftDy)][x+leftDx] != 0) - { - *p++ = htons(MAZE_EXIT_LEFT); - *p++ = htons(distance); - distance=0; - entries++; - } - - if(_mazeBitmap[MAZE_HEIGHT-1-(y+rightDy)][x+rightDx] != 0) - { - *p++ = htons(MAZE_EXIT_RIGHT); - *p++ = htons(distance); - distance=0; - entries++; - } - } - - *numEntries = htons(entries); - - return sizeof(u_short) * ((entries*2)+1); - } -}; - - - -bool MazeServerConnection::ReadEvent () -{ - bool startSending=false; - - int bytesRead = _socket->Read(_receivePtr, ReceiveBufferSpace()); - - if(bytesRead > 0) - { - _receivePtr = &_receivePtr[bytesRead]; - - if(ReceiveBufferBytes() >= (sizeof(u_short)*4)) - { - _receivePtr = reinterpret_cast<unsigned char *>(_receiveBuffer); - u_short *p = _receiveBuffer; - - if(ntohs(p[0]) == MAZE_QUERY_HALLWAY) - { - int x = ntohs(p[1]); - int y = ntohs(p[2]); - int direction = ntohs(p[3]); - - _sendPtr = reinterpret_cast<unsigned char *>(_sendBuffer); - _bytesToSend = _server->Read(x, y, direction, - static_cast<u_short *>(_sendBuffer)); - - startSending = true; - } - } - } - else - { - _shouldFree = true; - _server->_app->Progress(true, "Closing connection"); - } - - return startSending; -} - -bool MazeServerConnection::WriteEvent () -{ - bool sendMoreLater=false; - - if(_bytesToSend > 0) - { - int bytesWritten= _socket->Write(_sendPtr, _bytesToSend); - - if(bytesWritten > 0) - { - _bytesToSend -= bytesWritten; - _sendPtr = &_sendPtr[bytesWritten]; - } - else - { - _server->_app->Progress(false, - "Error writing %d bytes to socket", _bytesToSend); - } - - sendMoreLater = _bytesToSend > 0; - } - - return sendMoreLater; -} - - - - -class MazeClient : public MazeServices -{ -private: - MazeClient(const MazeClient&); - MazeClient& operator=(const MazeClient&); - - bool _visitedPoints[MAZE_WIDTH][MAZE_HEIGHT]; - u_short _searchTreeBuffer[SEARCHBUF_SIZE]; - u_short *_bufferPosition; - bool _foundExit; - FastOS_Socket *_sock; - BaseTest *_app; - -public: - MazeClient(BaseTest *app, FastOS_Socket *sock) - : MazeServices(), - _bufferPosition(_searchTreeBuffer), - _foundExit(false), - _sock(sock), - _app(app) - { - memset(_visitedPoints, 0, sizeof(_visitedPoints)); - } - - void Run () - { - int x = MAZE_START_X; - int y = MAZE_START_Y; - - Search(x, y, 1); - } - -#if 0 - void PrintOut() - { - if(_server != nullptr) - { - for(int y=0; y<MAZE_HEIGHT; y++) - { - for(int x=0; x<MAZE_WIDTH; x++) - { - if(_server->_mazeBitmap[MAZE_HEIGHT-1-y][x] == 0) - printf("*"); - else if(_server->_mazeBitmap2[MAZE_HEIGHT-1-y][x] == 200) - printf("X"); - else - printf("%c", _server->_mazeBitmap2[MAZE_HEIGHT-1-y][x] == 50 ? '.' : ' '); - } - printf("\n"); - } - } - } -#endif - -#if 0 - void MarkPath (int x, int y, int direction, int length) - { - if(_server != nullptr) - { - int dx, dy; - SetDirection(dx, dy, direction); - - while(length > 0) - { - x += dx; - y += dy; - - _server->_mazeBitmap2[MAZE_HEIGHT-1-y][x] = 200; - length--; - } - } - } -#endif - - bool Move (int &x, int &y, int direction, int length) - { - int dx = 0, dy = 0; - - int startx = x; - int starty = y; - - SetDirection(dx, dy, direction); - - bool continueAfterMove=true; - - while(length > 0) - { - x += dx; - y += dy; - - if((x == MAZE_END_X) && (y == MAZE_END_Y)) - { - _app->Progress(true, "Found exit at (%d, %d).", x, y); - _foundExit = true; - continueAfterMove = false; - break; - } - - if(_visitedPoints[x][y]) - { - continueAfterMove = false; - break; - } - else - { - _visitedPoints[x][y] = true; - } - length--; - } - - if(!continueAfterMove) - { - x = startx; - y = starty; - } - - return continueAfterMove; - } - - int ReadFromServer (int x, int y, int direction, u_short *p) - { - int readItems=0; - - - u_short *writePtr=p; - - *writePtr++ = htons(MAZE_QUERY_HALLWAY); - *writePtr++ = htons(static_cast<u_short>(x)); - *writePtr++ = htons(static_cast<u_short>(y)); - *writePtr++ = htons(static_cast<u_short>(direction)); - - int sendBytes = static_cast<int> - (reinterpret_cast<char *>(writePtr) - - reinterpret_cast<char *>(p)); - - int actualSent = _sock->Write(p, sendBytes); - - if(actualSent != sendBytes) - { - _app->Progress(false, "Sending %d bytes to maze server (rc=%d)", - sendBytes, actualSent); - } - else - { - int actualRead = _sock->Read(p, sizeof(u_short)); - - if(actualRead != sizeof(u_short)) - { - _app->Progress(false, "Reading %d bytes from maze server (rc=%d)", - sizeof(u_short), actualRead); - } - else - { - int packetSize = ntohs(*p); - p++; - int readBytes = packetSize * 2 * sizeof(u_short); - - actualRead = _sock->Read(p, readBytes); - - if(actualRead != readBytes) - { - _app->Progress(false, "Reading %d bytes from maze server (rc=%d)", - readBytes, actualRead); - } - - readItems = 1 + actualRead/sizeof(u_short); - } - } - - return readItems; - } - - void Search (int startX, int startY, int direction); -}; - - -void MazeClient::Search (int startX, int startY, int direction) -{ - u_short *p = _bufferPosition; - - int readEntries = ReadFromServer(startX, startY, direction, p); - - p++; - - _bufferPosition = &_bufferPosition[readEntries]; - assert(_bufferPosition < &_searchTreeBuffer[SEARCHBUF_SIZE]); - - bool continueSearching = true; - - int x=startX; - int y=startY; - int length=0; - - while(continueSearching) - { - u_short code = ntohs(*p++); - u_short distance = ntohs(*p++); - - switch(code) - { - case MAZE_WALL: - { - distance--; - // Make sure we have visited all the points - Move(x, y, direction, distance); - continueSearching = false; - break; - } - - case MAZE_EXIT_LEFT: - { - if(Move(x, y, direction, distance)) - Search(x, y, TurnLeft(direction)); - break; - } - - case MAZE_EXIT_RIGHT: - { - if(Move(x, y, direction, distance)) - Search(x, y, TurnRight(direction)); - break; - } - - default: - { - _app->Progress(false, "Unknown maze code (%d, %d) in packet", code, distance); - continueSearching = false; - break; - } - } - - length += distance; - - if(_foundExit) - { - continueSearching = false; - } - } -} - - -class SocketTest : public BaseTest -{ -public: - void StrictBindTest () - { - bool rc; - - TestHeader("Strict Bind Test"); - - // Fallback to localhost if we can't get the hostname - std::string strictBindHost("localhost"); - - FastOS_ServerSocket *serverSocket = - new FastOS_ServerSocket(18333, 5, nullptr, strictBindHost.c_str()); - - Progress(serverSocket != nullptr, "Allocating serversocket instance"); - - rc = serverSocket->GetValidAddressFlag(); - Progress(rc, "Address Valid Flag check"); - - if(rc) - { - Progress(rc = serverSocket->Listen(), - "Strict bind socket to %s on port %d. Listen " - "for incoming connections.", strictBindHost.c_str(), 18333); - } - - delete(serverSocket); - Progress(true, "Deleted serversocket"); - - PrintSeparator(); - } - - void HttpClientTest () - { - bool rc=false; - - TestHeader("HTTP Client Test"); - - FastOS_Socket *sock = new FastOS_Socket(); - Progress(sock != nullptr, "Allocating socket instance"); - - char hostAddress[] = "www.vg.no"; - - rc = sock->SetAddress(80, hostAddress); - Progress(rc, "Setting hostAddress (%s)", hostAddress); - - if(rc) - Progress(rc = sock->Connect(), "Connecting to %s", hostAddress); - - if(rc) - { - int localPort = sock->GetLocalPort(); - - Progress(localPort != -1, "Localport = %d", localPort); - - char sendCommand[] = "GET / HTTP/1.1\r\nHost: www.vg.no\r\n\r\n"; - int sendLength = strlen(sendCommand)+1; - - int wroteBytes = sock->Write(sendCommand, sendLength); - Progress(rc = (wroteBytes == sendLength), - "Write %d bytes to socket (GET / HTTP/1.1 ...)", wroteBytes); - - if(rc) - { - char expectedResult[] = "HTTP/1.X 200 Ok"; - - int readLength = strlen(expectedResult); - char *readBuffer = new char[readLength+1]; - - if(readBuffer != nullptr) - { - memset(readBuffer, 0, readLength+1); - - int actualRead = sock->Read(readBuffer, readLength); - Progress(rc = (actualRead == readLength), "Read %d bytes from socket", actualRead); - Progress(true, "Contents: [%s]", readBuffer); - - expectedResult[7] = '0'; - rc = (strcasecmp(expectedResult, readBuffer) == 0); - expectedResult[7] = '1'; - rc |= (strcasecmp(expectedResult, readBuffer) == 0); - expectedResult[7] = '2'; - rc |= (strcasecmp(expectedResult, readBuffer) == 0); - - expectedResult[7] = 'X'; - - Progress(rc, "Comparing read result to expected result (%s)", expectedResult); - - delete [] readBuffer; - } - else - Fail("Allocating read buffer"); - } - - Progress(sock->Shutdown(), "Socket shutdown"); - Progress(rc = sock->Close(), "Closing socket"); - } - - delete(sock); - Progress(true, "Deleted socket"); - - PrintSeparator(); - } - - void ClientServerTest () - { - bool rc; - - TestHeader("Client/Server Test"); - - FastOS_ServerSocket *serverSocket = new FastOS_ServerSocket(18333); - Progress(serverSocket != nullptr, "Allocating serversocket instance"); - - Progress(rc = serverSocket->Listen(), "Bind socket to port %d. Listen for incoming connections.", 18333); - assert(rc); - - delete(serverSocket); - Progress(true, "Deleted serversocket"); - - PrintSeparator(); - } - - - void MazeTest (char *serverAddress) - { - TestHeader("Maze Test"); - - bool rc; - FastOS_Socket *sock = new FastOS_Socket(); - - Progress(rc = (sock != nullptr), "Allocating socket instance"); - if(rc) - { - sock->SetAddress(8001, serverAddress); - Progress(true, "Setting hostAddress (%s)", serverAddress); - - Progress(rc = sock->Connect(), "Connecting to %s", serverAddress); - if(rc) - { - MazeClient *client = new MazeClient(this, sock); - - Progress(rc = (client != nullptr), "Allocating MazeClient instance"); - if(rc) - { - client->Run(); - delete(client); - } - } - - delete(sock); - } - - PrintSeparator(); - } - - void DoMazeServer () - { - TestHeader("Maze Server"); - - MazeServer *server = new MazeServer(this); - server->Run(); - - PrintSeparator(); - } - - int Main () override - { - printf("This test should be run in the 'test/workarea' directory.\n\n"); - printf("grep for the string '%s' to detect failures.\n\n", failString); - -#if DO_MAZE_SERVER - DoMazeServer(); -#else - char *mazeServerAddress = nullptr; - - if(_argc == 3) - { - if(strcmp("/mazeserver", _argv[1]) == 0) - { - mazeServerAddress = _argv[2]; - } - } - - HttpClientTest(); - ClientServerTest(); - StrictBindTest(); - - if(mazeServerAddress != nullptr) - MazeTest(mazeServerAddress); -#endif - - - PrintSeparator(); - - printf("END OF TEST (%s)\n", _argv[0]); - - return 0; - } -}; - - -int main (int argc, char **argv) -{ - SocketTest app; - - setvbuf(stdout, nullptr, _IOLBF, 8192); - return app.Entry(argc, argv); -} diff --git a/fastos/src/tests/tests.h b/fastos/src/tests/tests.h index 71fd32dad2d..c149c0ab428 100644 --- a/fastos/src/tests/tests.h +++ b/fastos/src/tests/tests.h @@ -1,7 +1,6 @@ // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/fastos/app.h> -#include <vespa/fastos/socket.h> #include <vespa/fastos/thread.h> #include <cstring> @@ -78,13 +77,6 @@ public: return Progress(result, string); } - bool Progress (bool result, const char *str, const FastOS_Socket *s1) - { - char string[MAX_STR_LEN-100]; - snprintf(string, sizeof(string), str, s1); - return Progress(result, string); - } - bool Progress (bool result, const char *str, const char *s1, const char *s2) { char string[MAX_STR_LEN-100]; diff --git a/fastos/src/tests/typetest.cpp b/fastos/src/tests/typetest.cpp index 503c9a30d24..1e0fc53ec1e 100644 --- a/fastos/src/tests/typetest.cpp +++ b/fastos/src/tests/typetest.cpp @@ -3,7 +3,6 @@ #include "tests.h" #include <vespa/fastos/file.h> #include <vespa/fastos/time.h> -#include <vespa/fastos/serversocket.h> #include <cstdlib> @@ -19,9 +18,6 @@ private: Progress(true, "FastOS_DirectoryScan %d", sizeof(FastOS_DirectoryScan)); Progress(true, "FastOS_File: %d", sizeof(FastOS_File)); Progress(true, "FastOS_Runnable %d", sizeof(FastOS_Runnable)); - Progress(true, "FastOS_ServerSocket %d", sizeof(FastOS_ServerSocket)); - Progress(true, "FastOS_Socket: %d", sizeof(FastOS_Socket)); - Progress(true, "FastOS_SocketFactory %d", sizeof(FastOS_SocketFactory)); Progress(true, "FastOS_StatInfo %d", sizeof(FastOS_StatInfo)); Progress(true, "FastOS_Thread: %d", sizeof(FastOS_Thread)); Progress(true, "FastOS_ThreadPool: %d", sizeof(FastOS_ThreadPool)); diff --git a/fastos/src/vespa/fastos/CMakeLists.txt b/fastos/src/vespa/fastos/CMakeLists.txt index b4bb8e47622..48f1e587918 100644 --- a/fastos/src/vespa/fastos/CMakeLists.txt +++ b/fastos/src/vespa/fastos/CMakeLists.txt @@ -6,9 +6,6 @@ vespa_add_library(fastos_objects OBJECT file.cpp linux_file.cpp process.cpp - serversocket.cpp - socket.cpp - socketevent.cpp thread.cpp time.cpp timestamp.cpp @@ -17,7 +14,6 @@ vespa_add_library(fastos_objects OBJECT unix_file.cpp unix_ipc.cpp unix_process.cpp - unix_socket.cpp unix_thread.cpp unix_time.cpp ) diff --git a/fastos/src/vespa/fastos/app.cpp b/fastos/src/vespa/fastos/app.cpp index 822683540f7..aecdc683649 100644 --- a/fastos/src/vespa/fastos/app.cpp +++ b/fastos/src/vespa/fastos/app.cpp @@ -7,7 +7,6 @@ */ #include "app.h" -#include "socket.h" #include "file.h" #include "process.h" @@ -55,34 +54,18 @@ bool FastOS_ApplicationInterface::Init () { bool rc=false; - if(PreThreadInit()) - { - if(FastOS_Thread::InitializeClass()) - { - if(FastOS_File::InitializeClass()) - { - const char *errorMsg = FastOS_Socket::InitializeServices(); - - if(errorMsg == nullptr) - { + if(PreThreadInit()) { + if(FastOS_Thread::InitializeClass()) { + if(FastOS_File::InitializeClass()) { + _processListMutex = new std::mutex; _threadPool = new FastOS_ThreadPool(128 * 1024); rc = true; - } - else - { - fprintf(stderr, - "FastOS_Socket::InitializeServices() returned:\n[%s]\n", - errorMsg); - } - } - else + } else fprintf(stderr, "FastOS_File class initialization failed.\n"); - } - else + } else fprintf(stderr, "FastOS_Thread class initialization failed.\n"); - } - else + } else fprintf(stderr, "FastOS_PreThreadInit failed.\n"); return rc; @@ -91,8 +74,7 @@ bool FastOS_ApplicationInterface::Init () void FastOS_ApplicationInterface::Cleanup () { - if(_threadPool != nullptr) - { + if(_threadPool != nullptr) { // printf("Closing threadpool...\n"); _threadPool->Close(); // printf("Deleting threadpool...\n"); @@ -100,13 +82,11 @@ void FastOS_ApplicationInterface::Cleanup () _threadPool = nullptr; } - if(_processListMutex != nullptr) - { + if(_processListMutex != nullptr) { delete _processListMutex; _processListMutex = nullptr; } - FastOS_Socket::CleanupServices(); FastOS_File::CleanupClass(); FastOS_Thread::CleanupClass(); } diff --git a/fastos/src/vespa/fastos/serversocket.cpp b/fastos/src/vespa/fastos/serversocket.cpp deleted file mode 100644 index a79e163db17..00000000000 --- a/fastos/src/vespa/fastos/serversocket.cpp +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. - -#include "serversocket.h" -#include <netinet/in.h> -#include <cstring> - - -/** - * Set the socket factory object. Usefull if you want the ServerSocket to - * create a custom typed socket on incoming connections. - * @param socketFactory Pointer to socket factory object to be used. - */ -void FastOS_ServerSocket::SetSocketFactory(FastOS_SocketFactory *socketFactory) -{ - _socketFactory = socketFactory; -} - - -FastOS_SocketInterface *FastOS_ServerSocket::CreateHandlerSocket(void) -{ - - return (_socketFactory != nullptr) - ? _socketFactory->CreateSocket() - : (FastOS_SocketInterface *)new FastOS_Socket(); -} - - -FastOS_SocketInterface *FastOS_ServerSocket::Accept() -{ - struct sockaddr_storage clientAddress; - - socklen_t clientAddressLength = sizeof(clientAddress); - - memset(&clientAddress, 0, sizeof(clientAddress)); - - int handlerSocketHandle = accept(_socketHandle, reinterpret_cast<struct sockaddr *>(&clientAddress), - &clientAddressLength); - - if (handlerSocketHandle >= 0) { - FastOS_SocketInterface *handlerSocket = CreateHandlerSocket(); - - if (handlerSocket != nullptr) { - handlerSocket->SetUp(handlerSocketHandle, reinterpret_cast<struct sockaddr *>(&clientAddress)); - } - return handlerSocket; - } - - return nullptr; -} - -FastOS_Socket *FastOS_ServerSocket::AcceptPlain() -{ - struct sockaddr_storage clientAddress; - - socklen_t clientAddressLength = sizeof(clientAddress); - - memset(&clientAddress, 0, sizeof(clientAddress)); - - int handlerSocketHandle = accept(_socketHandle, reinterpret_cast<struct sockaddr *>(&clientAddress), - &clientAddressLength); - - if (handlerSocketHandle >= 0) { - FastOS_Socket *handlerSocket = new FastOS_Socket(); - - if (handlerSocket != nullptr) { - handlerSocket->SetUp(handlerSocketHandle, reinterpret_cast<struct sockaddr *>(&clientAddress)); - } - return handlerSocket; - } - - return nullptr; -} - -FastOS_ServerSocket::FastOS_ServerSocket(int socketHandle, FastOS_SocketFactory *socketFactory) - : _portNumber(-1), - _backLog(-1), - _socketFactory(socketFactory), - _validAddress(false) -{ - _socketHandle = socketHandle; - memset(&_address, 0, sizeof(_address)); - _validAddress = true; -} - -bool FastOS_ServerSocket::Listen () -{ - bool rc=false; - bool reuseAddr = false; - - if(CreateIfNoSocketYet()) - { - if ((_address.ss_family == AF_INET && - reinterpret_cast<const sockaddr_in &>(_address).sin_port != 0) || - (_address.ss_family == AF_INET6 && - reinterpret_cast<const sockaddr_in6 &>(_address).sin6_port != 0)) - reuseAddr = true; - if (SetSoReuseAddr(reuseAddr)) { - size_t socketAddrLen; - switch (_address.ss_family) - { - case AF_INET: - socketAddrLen = sizeof(sockaddr_in); - break; - case AF_INET6: - socketAddrLen = sizeof(sockaddr_in6); - { - int disable = 0; - ::setsockopt(_socketHandle, IPPROTO_IPV6, IPV6_V6ONLY, &disable, sizeof(disable)); - } - break; - default: - socketAddrLen = sizeof(sockaddr_storage); - } - if(bind(_socketHandle, reinterpret_cast<struct sockaddr *>(&_address), socketAddrLen) >= 0) { - if(listen(_socketHandle, _backLog) >= 0) { - rc = true; - } - } - } - } - - return rc; -} diff --git a/fastos/src/vespa/fastos/serversocket.h b/fastos/src/vespa/fastos/serversocket.h deleted file mode 100644 index 2e0690ffc3b..00000000000 --- a/fastos/src/vespa/fastos/serversocket.h +++ /dev/null @@ -1,176 +0,0 @@ -// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. -//************************************************************************ -/** - * @file - * Class definitons for FastOS_SocketFactory and FastOS_ServerSocket. - * - * @author Div, Oivind H. Danielsen - */ - -#pragma once - - -#include "socket.h" - - -/** - * This base class is used to create Socket objects. You can supply - * a subclassed @ref FastOS_SocketFactory to an instance of - * @ref FastOS_ServerSocket, to have your own type of socket created - * by @ref FastOS_ServerSocket::Accept(). - */ -class FastOS_SocketFactory -{ -public: - /** - * Destructor. No cleanup needed for base class. - */ - virtual ~FastOS_SocketFactory(void) { } - - /** - * Create a socket object. Override this method to create - * your own subclassed socket objects. It is not allowed - * for the constructor to use the socket object, as it - * is not set up yet at this point. - */ - virtual FastOS_SocketInterface *CreateSocket() - { - return new FastOS_Socket(); - } -}; - - -/** - * This socket class provides a listening server socket that is - * able to accept connections on a specified port number. - * - * The port number and connection backlog are specified in the - * constructor * (FastOS_ServerSocket(int portnum, int backLog)). - * - * Call @ref Listen() to create and configure the socket for - * listening on the specified port number. - * - * To accept an incoming connection, call @ref Accept(). This will - * return a newly created @ref FastOS_Socket object to handle - * the new connection. If you want a different type of socket, - * specify your own @ref FastOS_SocketFactory with @ref SetSocketFactory(). - */ -class FastOS_ServerSocket : public FastOS_Socket -{ -private: - FastOS_ServerSocket(const FastOS_ServerSocket&); - FastOS_ServerSocket& operator=(const FastOS_ServerSocket&); - -protected: - /** - * The TCP port number to listen to. - */ - int _portNumber; - - /** - * Max number of connections in backlog. - */ - int _backLog; - - /** - * The socket factory to use for incoming connections. - * If this is nullptr, the default action is to create an - * instance of the regular @ref FastOS_Socket. - */ - FastOS_SocketFactory *_socketFactory; - - /** - * Create socket for handling an incoming connection - * @return Returns pointer to newly created socket, or nullptr on - * failure. - */ - FastOS_SocketInterface *CreateHandlerSocket(); - - bool _validAddress; - -public: - /** - * Constructor. If strict binding is used, call @ref GetValidAddressFlag() - * to check if setting the specified address was successful or not. - * @param portnum Listen on this port number. - * @param backLog Max number of connections in backlog. - * @param socketFactory See @ref SetSocketFactory(). - * @param strictBindHostName IP address or hostname for strict binding - */ - FastOS_ServerSocket (int portnum, int backLog=5, - FastOS_SocketFactory *socketFactory=nullptr, - const char *strictBindHostName=nullptr) - : _portNumber(portnum), - _backLog(backLog), - _socketFactory(socketFactory), - _validAddress(false) - { - setPreferIPv6(true); - _validAddress = SetAddress(_portNumber, strictBindHostName); - } - - bool GetValidAddressFlag () { return _validAddress; } - - /** - * Use this constructor to supply a pre-created, configured, - * bound and listening socket. When using this constructor, - * don't call @ref Listen(). - * @param socketHandle OS handle of supplied socket. - * @param socketFactory See @ref SetSocketFactory(). - */ - FastOS_ServerSocket(int socketHandle, FastOS_SocketFactory *socketFactory); - - /** - * Create a listening socket. This involves creating an OS - * socket, setting SO_REUSEADDR(true), binding the socket and - * start to listen for incoming connections. You should - * call @ref Listen() if you have supplied a pre-created listening - * socket handle trough the constructor - * @ref FastOS_ServerSocket(int listenSocketHandle, FastOS_SocketFactory *socketFactory=nullptr). - * @return Boolean success/failure - */ - bool Listen (); - - /** - * Accept incoming connections. The socket factory (if present) - * is used to create a socket instance for the new connection. - * Make sure you have a listening socket (see @ref Listen()) before - * calling @ref Accept(). - * @return Returns pointer to newly created socket object for the - * connection that was accepted, or nullptr on failure. - */ - FastOS_SocketInterface *Accept (); - - /** - * Accept incoming connections. This version does not use the - * associated socket factory. - * Make sure you have a listening socket (see @ref Listen()) before - * calling @ref AcceptPlain(). - * @return Returns pointer to newly created socket object for the - * connection that was accepted, or nullptr on failure. - */ - FastOS_Socket *AcceptPlain (); - - /** - * Specify your own @ref FastOS_SocketFactory for this serversocket. - * When new connections are accepted with @ref Accept, this socket - * factory will be called to create a new socket object for the - * connection. - * - * SetSocketFactory(nullptr) will enable the default socket factory - * mechanism which will create regular @ref FastOS_Socket instances - * on accepted connections. - */ - void SetSocketFactory(FastOS_SocketFactory *socketFactory); - - /** - * Return the portnumber of the listing socket. - * @return Port number. - */ - int GetPortNumber () - { - return _portNumber; - } -}; - - diff --git a/fastos/src/vespa/fastos/socket.cpp b/fastos/src/vespa/fastos/socket.cpp deleted file mode 100644 index c274f42bc68..00000000000 --- a/fastos/src/vespa/fastos/socket.cpp +++ /dev/null @@ -1,343 +0,0 @@ -// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. - -#include "socket.h" -#include <sstream> -#include <cassert> -#include <cstring> -#include <netinet/tcp.h> -#include <netinet/in.h> -#include <netdb.h> - -FastOS_SocketInterface::FastOS_SocketInterface() - : _readEventEnabled(false), - _writeEventEnabled(false), - _readPossible(false), - _writePossible(false), - _epolled(false), - _socketEvent(nullptr), - _eventAttribute(nullptr), - _socketEventArrayPos(-1), - _address(), - _socketHandle(-1), - _preferIPv6(false) -{ - ConstructorWork(); -} - -FastOS_SocketInterface::FastOS_SocketInterface(int socketHandle, struct sockaddr *hostAddress) - : _readEventEnabled(false), - _writeEventEnabled(false), - _readPossible(false), - _writePossible(false), - _epolled(false), - _socketEvent(nullptr), - _eventAttribute(nullptr), - _socketEventArrayPos(-1), - _address(), - _socketHandle(-1), - _preferIPv6(false) -{ - ConstructorWork(); - SetUp(socketHandle, hostAddress); -} - -FastOS_SocketInterface::~FastOS_SocketInterface() { } - -bool FastOS_SocketInterface::Connect() -{ - bool rc=false; - - if (CreateIfNoSocketYet()) { - switch (_address.ss_family) { - case AF_INET: - rc = (0 == connect(_socketHandle, - reinterpret_cast<struct sockaddr *>(&_address), - sizeof(sockaddr_in))); - break; - case AF_INET6: - rc = (0 == connect(_socketHandle, - reinterpret_cast<struct sockaddr *>(&_address), - sizeof(sockaddr_in6))); - break; - default: - rc = false; - } - } - - return rc; -} - -bool FastOS_SocketInterface::SetAddress (const int portNum, const char *address) -{ - bool rc = false; - memset(&_address, 0, sizeof(_address)); - - addrinfo hints; - memset(&hints, 0, sizeof(addrinfo)); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = 0; - hints.ai_flags = (AI_PASSIVE | AI_NUMERICSERV | AI_ADDRCONFIG); - char service[32]; - snprintf(service, sizeof(service), "%d", portNum); - addrinfo *list = nullptr; - if (getaddrinfo(address, service, &hints, &list) == 0) { - const addrinfo *best = nullptr; - for (const addrinfo *info = list; info != nullptr; info = info->ai_next) { - if (best == nullptr) { - best = info; - } else if (_preferIPv6) { - if ((best->ai_family != AF_INET6) && (info->ai_family == AF_INET6)) { - best = info; - } - } else { - if ((best->ai_family != AF_INET) && (info->ai_family == AF_INET)) { - best = info; - } - } - } - if (best != nullptr) { - memcpy(&_address, best->ai_addr, best->ai_addrlen); - rc = true; - } - freeaddrinfo(list); - } - return rc; -} - -bool FastOS_SocketInterface::SetAddressByHostName (const int portNum, const char *hostName) -{ - return SetAddress(portNum, hostName); -} - -void FastOS_SocketInterface::SetUp(int socketHandle, struct sockaddr *hostAddress) -{ - Close(); - - _socketHandle = socketHandle; - switch (hostAddress->sa_family) { - case AF_INET: - memcpy(&_address, hostAddress, sizeof(sockaddr_in)); - break; - case AF_INET6: - memcpy(&_address, hostAddress, sizeof(sockaddr_in6)); - break; - default: - ; - } -} - -bool FastOS_SocketInterface::CreateIfNoSocketYet () -{ - if (ValidHandle()) { - return true; - } else if (_address.ss_family == AF_INET) { - _socketHandle = socket(AF_INET, SOCK_STREAM, 0); - return (_socketHandle != -1); - } else if (_address.ss_family == AF_INET6) { - _socketHandle = socket(AF_INET6, SOCK_STREAM, 0); - return (_socketHandle != -1); - } - return false; -} - -void FastOS_SocketInterface::ConstructorWork () -{ - _socketHandle = -1; - _epolled = false; - _socketEvent = nullptr; - _readEventEnabled = false; - _writeEventEnabled = false; - _eventAttribute = nullptr; - _socketEventArrayPos = -1; -} - -bool FastOS_SocketInterface::SetSoLinger( bool doLinger, int seconds ) -{ - bool rc=false; - - struct linger lingerTime; - lingerTime.l_onoff = doLinger ? 1 : 0; - lingerTime.l_linger = seconds; - - if (CreateIfNoSocketYet()) { - rc = (0 == setsockopt(_socketHandle, SOL_SOCKET, SO_LINGER, &lingerTime, sizeof(lingerTime))); - } - - return rc; -} - -bool -FastOS_SocketInterface::SetNoDelay(bool noDelay) -{ - bool rc = false; - int noDelayInt = noDelay ? 1 : 0; - - if (CreateIfNoSocketYet()) { - rc = (setsockopt(_socketHandle, IPPROTO_TCP, TCP_NODELAY, &noDelayInt, sizeof(noDelayInt)) == 0); - } - return rc; -} - -int FastOS_SocketInterface::GetSoError () -{ - if (!ValidHandle()) { return EINVAL; } - - // Fetch this first, as getsockopt(..SO_ERROR, resets the - // WSAGetLastError() - int lastError = FastOS_Socket::GetLastError(); - int soError = 0; - - socklen_t soErrorLen = sizeof(soError); - - if (getsockopt(_socketHandle, SOL_SOCKET, SO_ERROR, &soError, &soErrorLen) != 0) { - return lastError; - } - - if (soErrorLen != sizeof(soError)) { - return EINVAL; // 'invalid argument' - } - - return soError; -} - -bool FastOS_SocketInterface::SetSoIntOpt (int option, int value) -{ - bool rc=false; - - if (CreateIfNoSocketYet()) { - rc = (0 == setsockopt(_socketHandle, SOL_SOCKET, option, &value, sizeof(value))); - } - - return rc; -} - -bool FastOS_SocketInterface::GetSoIntOpt(int option, int &value) -{ - bool rc=false; - - if (CreateIfNoSocketYet()) { - socklen_t len = sizeof(value); - - int retval = getsockopt(_socketHandle, SOL_SOCKET, option, &value, &len); - - if (len != sizeof(value)) { - // FIX! - What about GetLastError() in this case? - return false; - } - - rc = (0 == retval); - } - - return rc; -} - -void FastOS_SocketInterface::CleanupEvents () -{ - if (_socketEvent != nullptr) { - _socketEvent->Detach(this); - assert(!_epolled); - _socketEvent = nullptr; - } -} - -bool FastOS_SocketInterface::TuneTransport () -{ - if (!SetSoIntOpt(SO_KEEPALIVE, 1)) { return false; } - if (!SetSoLinger(true, 0)) { return false; } - return true; -} - -int FastOS_SocketInterface::GetLocalPort () -{ - int result = -1; - sockaddr_storage addr; - socklen_t len = sizeof(addr); - if(getsockname(_socketHandle, reinterpret_cast<struct sockaddr *>(&addr), &len) == 0) { - if ((addr.ss_family == AF_INET) && (len == sizeof(sockaddr_in))) { - const sockaddr_in *my_addr = reinterpret_cast<const sockaddr_in *>(&addr); - result = ntohs(my_addr->sin_port); - } - if ((addr.ss_family == AF_INET6) && (len == sizeof(sockaddr_in6))) { - const sockaddr_in6 *my_addr = reinterpret_cast<const sockaddr_in6 *>(&addr); - result = ntohs(my_addr->sin6_port); - } - } - return result; -} - -unsigned short -FastOS_SocketInterface::GetPort () const -{ - switch (_address.ss_family) { - case AF_INET: - return reinterpret_cast<const sockaddr_in &>(_address).sin_port; - case AF_INET6: - return reinterpret_cast<const sockaddr_in6 &>(_address).sin6_port; - default: - return 0; - } -} - -std::string -FastOS_SocketInterface::getLastErrorString(void) { - return FastOS_Socket::getErrorString(FastOS_Socket::GetLastError()); -} - -const char * -FastOS_SocketInterface::InitializeServices(void) { - FastOS_SocketEventObjects::InitializeClass(); - return nullptr; -} - -void FastOS_SocketInterface::CleanupServices () { - FastOS_SocketEventObjects::ClassCleanup(); -} - -bool FastOS_SocketInterface::SetSocketEvent (FastOS_SocketEvent *event, void *attribute) { - bool rc=false; - - _eventAttribute = attribute; - - if (CreateIfNoSocketYet()) { - if (_socketEvent != event) { - if (_socketEvent != nullptr) { - // Disable events for this socket on the old SocketEvent - _socketEvent->Detach(this); - assert(!_epolled); - _socketEvent = nullptr; - } - - if (event != nullptr) { - event->Attach(this, _readEventEnabled, _writeEventEnabled); - _socketEvent = event; - } - } - rc = true; - } - - return rc; -} - -void FastOS_SocketInterface::EnableReadEvent (bool enabled) { - if (_readEventEnabled == enabled) { return; } - _readEventEnabled = enabled; - if (_socketEvent != nullptr) { - _socketEvent->EnableEvent(this, _readEventEnabled, _writeEventEnabled); - } -} - -/** - * Enable or disable write events for the socket. - * The behaviour caused by invoking this method while waiting for - * socket events is undefined. - * A @ref FastOS_SocketEvent must be associated with the socket prior - * to calling @ref EnableReadEvent and @ref EnableWriteEvent. - */ -void FastOS_SocketInterface::EnableWriteEvent (bool enabled) { - if (_writeEventEnabled == enabled) { return; } - _writeEventEnabled = enabled; - if (_socketEvent != nullptr) { - _socketEvent->EnableEvent(this, _readEventEnabled, _writeEventEnabled); - } -} diff --git a/fastos/src/vespa/fastos/socket.h b/fastos/src/vespa/fastos/socket.h deleted file mode 100644 index 31b8903a4e4..00000000000 --- a/fastos/src/vespa/fastos/socket.h +++ /dev/null @@ -1,303 +0,0 @@ -// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. - -#pragma once - -#include <vespa/fastos/types.h> -#include <string> -#include <sys/socket.h> - -class FastOS_SocketInterface; -class FastOS_ServerSocket; -class FastOS_SocketEvent; - -#include <vespa/fastos/socketevent.h> - -/** - * This class implements TCP/IP network socket. - */ -class FastOS_SocketInterface -{ -private: - friend class FastOS_SocketEvent; - -protected: - bool _readEventEnabled; - bool _writeEventEnabled; - bool _readPossible; - bool _writePossible; - bool _epolled; // true -> part of epoll set - FastOS_SocketEvent *_socketEvent; - void *_eventAttribute; - int _socketEventArrayPos; - struct sockaddr_storage _address; - int _socketHandle; - bool _preferIPv6; - - /** - * Cancel all socket events and detach from the current socket - * event, if any. - */ - void CleanupEvents (); - - /** - * Is a valid socket handle associated with this instance? - * @return True if the handle is valid, else false. - */ - bool ValidHandle () const { return (_socketHandle != -1); } - - /** - * If no OS socket is yet associated with this instance, - * create one. - * @return Boolean success/failure - */ - bool CreateIfNoSocketYet(); - - void ConstructorWork(); - -public: - FastOS_SocketInterface (const FastOS_SocketInterface&) = delete; - FastOS_SocketInterface& operator=(const FastOS_SocketInterface&) = delete; - // Static members - - /** - * Convenience method. Does GetErrorString(GetLastError()) - * @return Error string - */ - static std::string getLastErrorString(); - - static const char *InitializeServices (); - static void CleanupServices (); - - /** - * Default constructor. Use @ref SetUp() or the various SetAddress..() - * methods to complete the socket setup. - */ - FastOS_SocketInterface(); - /** - * This constructor does @ref SetUp() with the specified parameters. - * @param socketHandle OS handle to already created socket - * @param hostAddress IP address or host name of remote host - */ - FastOS_SocketInterface(int socketHandle, struct sockaddr *hostAddress); - - /** - * Destructor - * The socket will be closed unless it was supplied by the caller. - */ - virtual ~FastOS_SocketInterface(); - - /** - * Setup of socket parameters from explicit address and socket handle - * If a socket is already associated with this instance it will be - * closed (see @ref Close()). - * The socket is closed when the socket instance is deleted. - * @param socketHandle OS handle to already created socket - * @param hostAddress Address of remote host - */ - void SetUp(int socketHandle, struct sockaddr *hostAddress); - - /** - * Set address of host to connect to. - * @param portNum IP port number of remote host - * @param hostAddress IP address or host name of remote host - * @return Boolean success/failure - */ - bool SetAddress(const int portNum, const char *hostAddress); - - /** - * Set address of host to connect to - * @param portNum IP port number of remote host - * @param hostName Hostname of remote host - * @return Boolean success/failure - */ - bool SetAddressByHostName (const int portNum, const char *hostName); - - /** - * Connects to the host using the IP Address and port number predefined. - * @return Boolean success/failure - */ - bool Connect(); - - /** - * Connects to the host using the IP Address and port number specified. - * @return Boolean success/failure - */ - bool Connect(const char *hostNameOrIPaddress, const int portNum) { - return SetAddress(portNum, hostNameOrIPaddress) ? Connect() : false; - } - - /** - * Attempts to retrieve the local port number for the socket. - * The socket must be connected when this method is called. - * @return Local port number or -1 on error. - */ - int GetLocalPort (); - - /** - * Read [buffersize] bytes to [readbuffer]. The socket must - * have a connection (see @ref Connect()) before a read is - * attempted. - * @param readBuffer Pointer to target memory buffer - * @param bufferSize Size of the buffer / bytes to read - * @return Returns number of bytes read. - */ - virtual ssize_t Read (void *readBuffer, size_t bufferSize) = 0; - - /** - * Write [buffersize] bytes from [readbuffer]. The socket must - * have a connection (see @ref Connect()) before a write is - * attempted. - * @param writeBuffer Pointer to target memory buffer - * @param bufferSize Size of the buffer / bytes to write - * @return Returns number of bytes written. - */ - virtual ssize_t Write (const void *writeBuffer, size_t bufferSize) = 0; - - /** - * Close the socket. - * Only socket handles created within this class are closed. This - * means user-supplied socket handles (through constructor or - * @ref SetUp) will not be closed. - * If the socket is already closed, the method call will return - * success. - * @return Boolean success/failure - */ - virtual bool Close () = 0; - - /** - * Shut down a connection. - * If the socket is already closed, the method call will return - * success. Socket write events are disabled. - * @return Boolean success/failure - */ - virtual bool Shutdown() = 0; - - /** - * Get socket error - * If getting the socket error fails, the error code of GetLastError() - * is returned instad. If getting the socket error succeds with a wrong - * parameter EINVAL is returned. - * @return Socket error - */ - int GetSoError(); - - /** - * Set SO_KEEPALIVE flag on socket - * @param keep SO_KEEPALIVE on (true) / off (false) - * @return Boolean success/failure - */ - bool SetSoKeepAlive (bool keep) { - return SetSoIntOpt(SO_KEEPALIVE, keep ? 1 : 0); - } - - /** - * Set SO_REUSEADDR flag on socket - * @param reuse SO_REUSEADDR on (true) / off (false) - * @return Boolean success/failure - */ - bool SetSoReuseAddr (bool reuse) { - return SetSoIntOpt(SO_REUSEADDR, reuse ? 1 : 0); - } - - /** - * Set SO_LINGER flag on socket - * @param doLinger SO_LINGER on (true) / off (false) - * @param seconds Seconds to linger after close - * @return Boolean success/failure - */ - bool SetSoLinger (bool doLinger, int seconds); - - /** - * Set TCP Nodelay option on socket - * @param noDelay Don't delay data (true) / delay data (false) - * @return Boolean success/failure - */ - bool SetNoDelay(bool noDelay); - /** - * Set socket option - * @param option Number of option to set - * @param value Value of option to set - * @return Boolean success/failure - */ - bool SetSoIntOpt (int option, int value); - - /** - * Get socket option - * @param option Number of option to get - * @param value Ref to variable for holding the value of option - * @return Boolean success/failure - */ - bool GetSoIntOpt (int option, int &value); - - /** - * Set blocking flag on socket - * @param blockingEnabled SO_BLOCKING on (true) / off (false) - * @return Boolean success/failure - */ - virtual bool SetSoBlocking (bool blockingEnabled)=0; - - /** - * Associate a socket event object with this socket. - * Any events registered with an already associated event - * object is cancelled. - * @param event Socket event object - * @param attribute Event attribute pointer - * @return Boolean success/failure. - */ - bool SetSocketEvent (FastOS_SocketEvent *event, void *attribute=nullptr); - - /** - * Get socket event object - * @return Associated socket event object or nullptr - */ - FastOS_SocketEvent *GetSocketEvent () { return _socketEvent; } - - /** - * Enable or disable read events for the socket. - * The behaviour caused by invoking this method while waiting for - * socket events is undefined. - * A @ref FastOS_SocketEvent must be associated with the socket prior - * to calling @ref EnableReadEvent and @ref EnableWriteEvent. - */ - void EnableReadEvent (bool enabled); - - /** - * Enable or disable write events for the socket. - * The behaviour caused by invoking this method while waiting for - * socket events is undefined. - * A @ref FastOS_SocketEvent must be associated with the socket prior - * to calling @ref EnableReadEvent and @ref EnableWriteEvent. - */ - void EnableWriteEvent (bool enabled); - - /** - * Is the socket open? - * @return True if opened, false if cloed. - */ - bool IsOpened () const { - return ValidHandle(); - } - - /** - * Return socket port. - */ - unsigned short GetPort () const; - - /** - * Tune the socket for transport use. - * This includes: - * SO_KEEPALIVE = 1 - * SO_LINGER = 0 - * - * @return Boolean success/failure - */ - bool TuneTransport (); - bool getPreferIPv6(void) const { return _preferIPv6; } - void setPreferIPv6(bool preferIPv6) { _preferIPv6 = preferIPv6; } -}; - -#include <vespa/fastos/unix_socket.h> -typedef FastOS_UNIX_Socket FASTOS_PREFIX(Socket); - - - diff --git a/fastos/src/vespa/fastos/socketevent.cpp b/fastos/src/vespa/fastos/socketevent.cpp deleted file mode 100644 index 5e542390a53..00000000000 --- a/fastos/src/vespa/fastos/socketevent.cpp +++ /dev/null @@ -1,312 +0,0 @@ -// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. - -#include "socketevent.h" -#include "socket.h" -#include <cassert> -#include <unistd.h> - - -FastOS_SocketEventObjects *FastOS_SocketEventObjects::_objects = nullptr; -std::mutex FastOS_SocketEventObjects::_listMutex; -int FastOS_SocketEventObjects::_objectCount = 0; -bool FastOS_SocketEventObjects::_initialized = false; - -FastOS_SocketEvent::FastOS_SocketEvent () : - _epollfd(-1), - _epollEvents(), - _socketsInArray(0), - _getEventsIndex(0), - _wokeUp(false), - _objs(nullptr) -{ - - _objs = FastOS_SocketEventObjects::ObtainObject(this); - - if(_objs != nullptr) { - if(_objs->_initOk) { - } - } - epollInit(); // must be done after obtaining _objs -} - -FastOS_SocketEvent::~FastOS_SocketEvent () -{ - // Clean out potential remaining wakeup events. - bool error; - Wait(error, 0); - - epollFini(); // must be done before releasing _objs - FastOS_SocketEventObjects::ReleaseObject(_objs); -} - -bool FastOS_SocketEvent::HandleWakeUp () -{ - int wakeUpReadHandle = _objs->_wakeUpPipe[0]; - - const int MAX_WAKEUP_PIPE_READ = 128; - char dummyBytes[MAX_WAKEUP_PIPE_READ]; - - ssize_t readCount = read(wakeUpReadHandle, dummyBytes, MAX_WAKEUP_PIPE_READ); - (void) readCount; - _wokeUp = true; - return true; -} - -FastOS_SocketEventObjects *FastOS_SocketEventObjects::ObtainObject (FastOS_SocketEvent *event) -{ - FastOS_SocketEventObjects *node; - std::unique_lock<std::mutex> guard(_listMutex); - - if(_objects == nullptr) - { - _objectCount++; - guard.unlock(); - - node = new FastOS_SocketEventObjects(event); - node->_next = nullptr; - } - else - { - node = _objects; - _objects = node->_next; - node->_next = nullptr; - } - - return node; -} - -void FastOS_SocketEventObjects::ReleaseObject (FastOS_SocketEventObjects *node) -{ - if (node != nullptr) - node->ReleasedCleanup(); - std::lock_guard<std::mutex> guard(_listMutex); - - if (_initialized) { - node->_next = _objects; - _objects = node; - } else { - delete node; - _objectCount--; - } -} - - -bool -FastOS_SocketEvent::epollInit() -{ - _epollfd = epoll_create(4093); - if (_epollfd != -1 && _objs != nullptr && _objs->_initOk) { - epoll_event evt; - evt.events = EPOLLIN; - evt.data.ptr = 0; - if (epoll_ctl(_epollfd, EPOLL_CTL_ADD, _objs->_wakeUpPipe[0], &evt) == 0) { - return true; // SUCCESS - } - } - epollFini(); - return false; -} - -bool -FastOS_SocketEvent::epollEnableEvent(FastOS_SocketInterface *sock, - bool read, bool write) -{ - int res = 0; - epoll_event evt; - evt.events = (read ? static_cast<uint32_t>(EPOLLIN) : 0) | (write ? static_cast<uint32_t>(EPOLLOUT) : 0); - evt.data.ptr = (void *) sock; - if (sock->_epolled) { - if (evt.events != 0) { // modify - res = epoll_ctl(_epollfd, EPOLL_CTL_MOD, sock->_socketHandle, &evt); - } else { // remove - // NB: old versions of epoll_ctl needs evt also for remove - res = epoll_ctl(_epollfd, EPOLL_CTL_DEL, sock->_socketHandle, &evt); - sock->_epolled = false; - } - } else { - if (evt.events != 0) { // add - res = epoll_ctl(_epollfd, EPOLL_CTL_ADD, sock->_socketHandle, &evt); - sock->_epolled = true; - } - } - if (res == -1) { - perror("epollEnableEvent"); - return false; - } - return true; -} - -bool -FastOS_SocketEvent::epollWait(bool &error, int msTimeout) -{ - _wokeUp = false; - int maxEvents = 256; - if ((int)_epollEvents.size() < maxEvents) { - _epollEvents.resize(maxEvents); - } - int res = epoll_wait(_epollfd, &_epollEvents[0], maxEvents, msTimeout); - error = (res == -1); - for (int i = 0; i < res; ++i) { - const epoll_event &evt = _epollEvents[i]; - FastOS_SocketInterface *sock = (FastOS_SocketInterface *) evt.data.ptr; - if (sock == nullptr) { - HandleWakeUp(); - } else { - sock->_readPossible = sock->_readEventEnabled && - ((evt.events & (EPOLLIN | EPOLLERR | EPOLLHUP)) != 0); - sock->_writePossible = sock->_writeEventEnabled && - ((evt.events & (EPOLLOUT | EPOLLERR | EPOLLHUP)) != 0); - } - } - return (res > 0); -} - -int -FastOS_SocketEvent::epollGetEvents(bool *wakeUp, int msTimeout, - FastOS_IOEvent *events, int maxEvents) -{ - _wokeUp = false; - if ((int)_epollEvents.size() < maxEvents) { - _epollEvents.resize(maxEvents); - } - int res = epoll_wait(_epollfd, &_epollEvents[0], maxEvents, msTimeout); - if (res <= 0) { - return res; - } - int idx = 0; // application event index - for (int i = 0; i < res; ++i) { - const epoll_event &evt = _epollEvents[i]; - FastOS_IOEvent &appEvt = events[idx]; - FastOS_SocketInterface *sock = (FastOS_SocketInterface *) evt.data.ptr; - if (sock == nullptr) { - HandleWakeUp(); // sets _wokeUp - } else { - appEvt._readOccurred = sock->_readEventEnabled && - ((evt.events & (EPOLLIN | EPOLLERR | EPOLLHUP)) != 0); - appEvt._writeOccurred = sock->_writeEventEnabled && - ((evt.events & (EPOLLOUT | EPOLLERR | EPOLLHUP)) != 0); - appEvt._eventAttribute = sock->_eventAttribute; - ++idx; - } - } - *wakeUp = _wokeUp; - return idx; -} - -void -FastOS_SocketEvent::epollFini() -{ - if (_epollfd != -1) { - // do we need to unregister pipe read before closing? - int res = close(_epollfd); - if (res == -1) { - perror("epollFini"); - } - _epollfd = -1; - } -} - -void -FastOS_SocketEventObjects::InitializeClass(void) -{ - std::lock_guard<std::mutex> guard(_listMutex); - _initialized = true; -} - - -void FastOS_SocketEventObjects::ClassCleanup(void) -{ - std::lock_guard<std::mutex> guard(_listMutex); - _initialized = false; - for (;;) - { - FastOS_SocketEventObjects *node = _objects; - - if(node == nullptr) - break; - else - { - _objects = node->_next; - delete node; - _objectCount--; - } - } -} - - -FastOS_SocketEventObjects::FastOS_SocketEventObjects(FastOS_SocketEvent *event) - : _next(nullptr), - _initOk(false), - _socketArray(nullptr), - _socketArrayAllocSize(0u), - _pollfds(nullptr), - _pollfdsAllocSize(0) -{ - // Connect ourselves to the socketevent object. - event->_objs = this; - - _initOk = Init(event); -} - -void -FastOS_SocketEventObjects::ReleasedCleanup(void) -{ - if (_socketArrayAllocSize > 16) { - delete [] _socketArray; - _socketArray = nullptr; - _socketArrayAllocSize = 0; - } - if (_pollfdsAllocSize > 16) { - free(_pollfds); - _pollfds = nullptr; - _pollfdsAllocSize = 0; - } -} - - -FastOS_SocketEventObjects::~FastOS_SocketEventObjects () -{ - Cleanup(); - delete [] _socketArray; - free(_pollfds); -} - - -void -FastOS_SocketEvent::Attach(FastOS_SocketInterface *sock, - bool readEnabled, - bool writeEnabled) -{ - assert(!sock->_epolled); - if (readEnabled || writeEnabled) - EnableEvent(sock, readEnabled, writeEnabled); -} - - -void -FastOS_SocketEvent::Detach(FastOS_SocketInterface *sock) -{ - if (sock->_readEventEnabled || sock->_writeEventEnabled) - EnableEvent(sock, false, false); -} - -void FastOS_SocketEvent::AsyncWakeUp (void) -{ - char dummy = 'c'; - size_t writeCount = write(_objs->_wakeUpPipe[1], &dummy, 1); - (void) writeCount; -} - -bool FastOS_SocketEvent::QueryReadEvent (FastOS_SocketInterface *sock) -{ - bool ret = sock->_readPossible; - sock->_readPossible = false; - return ret; -} - -bool FastOS_SocketEvent::QueryWriteEvent (FastOS_SocketInterface *sock) -{ - bool ret = sock->_writePossible; - sock->_writePossible = false; - return ret; -} diff --git a/fastos/src/vespa/fastos/socketevent.h b/fastos/src/vespa/fastos/socketevent.h deleted file mode 100644 index 267f948caf9..00000000000 --- a/fastos/src/vespa/fastos/socketevent.h +++ /dev/null @@ -1,244 +0,0 @@ -// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. - -#pragma once - -#include "types.h" -#include <poll.h> - -#include <sys/epoll.h> -#include <vector> -#include <mutex> - -class FastOS_IOEvent -{ -public: - bool _readOccurred, _writeOccurred; - void *_eventAttribute; -}; - -class FastOS_SocketEvent; -class FastOS_SocketInterface; - -class FastOS_SocketEventObjects -{ -private: - FastOS_SocketEventObjects(const FastOS_SocketEventObjects&); - FastOS_SocketEventObjects& operator=(const FastOS_SocketEventObjects&); - - static std::mutex _listMutex; - static int _objectCount; - static bool _initialized; - - bool Init (FastOS_SocketEvent *event); - void Cleanup (); - void ReleasedCleanup(void); - -public: - FastOS_SocketEventObjects *_next; - bool _initOk; - FastOS_SocketInterface **_socketArray; - unsigned int _socketArrayAllocSize; - pollfd *_pollfds; - unsigned int _pollfdsAllocSize; - int _wakeUpPipe[2]; - - FastOS_SocketEventObjects(FastOS_SocketEvent *event); - ~FastOS_SocketEventObjects (); - static FastOS_SocketEventObjects *_objects; - static FastOS_SocketEventObjects *ObtainObject (FastOS_SocketEvent *event); - static void ReleaseObject (FastOS_SocketEventObjects *node); - static void ClassCleanup(); - static void InitializeClass(); -}; - - -/** - * This class is used to handle events caused by @ref FastOS_Socket - * instances. - * - * A @ref FastOS_SocketEvent can be associated with multiple sockets. - * Use @ref FastOS_Socket::EnableReadEvent() and - * @ref FastOS_Socket::EnableWriteEvent() to register for read and - * and write events. - * - * A @ref Wait() sleeps until either the specified timeout elapses, - * or one or more socket events trigger. - * - * After a @ref Wait() with return code true, @ref QueryReadEvent() - * and @ref QueryWriteEvent() is used to find the socket(s) that - * caused an event. - * - * Example: - * @code - * // Simple connection class - * class Connection - * { - * public: - * Connection *_next; // Single-linked list of connections - * - * FastOS_Socket *_socket; - * void HandleReadEvent (); - * void HandleWriteEvent (); - * }; - * - * void EventExample (Connection *connections) - * { - * Connection *conn; - * FastOS_SocketEvent socketEvent; - * - * // Walk through single-linked list of connections - * for(conn=connections; conn!=nullptr; conn = conn->_next) - * { - * // Associate each socket with socketEvent - * conn->_socket->SetSocketEvent(&socketEvent); - * - * // Enable read event notifications - * conn->_socket->EnableReadEvent(true); - * - * // In this example, we pretend that write events are turned - * // on somewhere else. - * } - * - * for(;;) // Event handling loop (loop forever) - * { - * // Wait for events (timeout = 200ms) - * if(socketEvent.Wait(200)) - * { - * // Walk through list of connections - * for(conn=connections; conn!=nullptr; conn = conn->_next) - * { - * // For each socket, check for read event - * if(socketEvent.QueryReadEvent(conn->_socket)) - * { - * conn->HandleReadEvent(); - * } - * - * // ..and write event - * if(socketEvent.QueryWriteEvent(conn->_socket)) - * { - * conn->HandleWriteEvent(); - * } - * } - * } - * else - * { - * // Timeout - * } - * } - * } - * @endcode - */ -class FastOS_SocketEvent -{ - friend class FastOS_SocketInterface; - friend class FastOS_SocketEventObjects; - -private: - FastOS_SocketEvent(const FastOS_SocketEvent&); - FastOS_SocketEvent& operator=(const FastOS_SocketEvent&); -protected: - - int _epollfd; // fd of epoll kernel service - std::vector<epoll_event> _epollEvents; // internal epoll event storage - - int _socketsInArray; - int _getEventsIndex; - - bool _wokeUp; - - FastOS_SocketEventObjects *_objs; - - bool HandleWakeUp (); - void EnableEvent (FastOS_SocketInterface *sock, bool read, bool write) { - epollEnableEvent(sock, read, write); - } - - bool epollInit(); - bool epollEnableEvent(FastOS_SocketInterface *sock, bool read, bool write); - bool epollWait(bool &error, int msTimeout); - int epollGetEvents(bool *wakeUp, int msTimeout, - FastOS_IOEvent *events, int maxEvents); - void epollFini(); - -public: - FastOS_SocketEvent (); - ~FastOS_SocketEvent (); - - /** - * Was the socketevent object created successfully? - * @return Boolean success/failure - */ - bool GetCreateSuccess () { - if (_epollfd == -1) { - return false; - } - return (_objs != nullptr) ? _objs->_initOk : false; - } - - /** - * Wait for a socket event, or timeout after [msTimeout] milliseconds. - * - * @param error This will be set to true if an error occured. - * If Wait succeeds, this will always be false. - * @param msTimeout Number of milliseconds to wait for an event - * before timeout. -1 means wait forever. - * - * @return True if an event occurred, else false. - */ - bool Wait (bool &error, int msTimeout) { - return epollWait(error, msTimeout); - } - - /** - * Wait for socket event, or timeout after [msTimeout] milliseconds. - * An array of IO events is filled in. - * - * @param wakeUp Has a wakeup occurred? (out parameter) - * @param msTimeout Number of milliseconds to wait for an event - * before timeout. -1 means wait forever. - * @param events Pointer to FastOS_IOEvent array - * @param maxEvents Size of event array. Up to this many events - * may be filled in the array. Invoke the method - * multiple times to get all events if the array - * is too small to hold all events that occurred. - * - * @return Number of events occurred, or -1 on failure. - */ - int GetEvents (bool *wakeUp, int msTimeout, FastOS_IOEvent *events, int maxEvents) { - return epollGetEvents(wakeUp, msTimeout, events, maxEvents); - } - - /** - * Make FastOS_SocketEvent methods Wait/GetEvents - * stop waiting and return ASAP. - */ - void AsyncWakeUp (void); - - void Attach(FastOS_SocketInterface *sock, bool read, bool write); - - void Detach(FastOS_SocketInterface *sock); - - /** - * Check for a read-event with socket [socket]. - * - * This method will also clear the read event indication for the - * given socket, making this method return false for the given - * socket until another event has been detected by invoking - * Wait/GetEvents. - * - * @return True if an event occurred, else false. - */ - bool QueryReadEvent (FastOS_SocketInterface *socket); - - /** - * Check for a write-event with socket [socket]. - * - * This method will also clear the write event indication for the - * given socket, making this method return false for the given - * socket until another event has been detected by invoking - * Wait/GetEvents. - * - * @return True if an event occurred, else false. - */ - bool QueryWriteEvent (FastOS_SocketInterface *socket); -}; diff --git a/fastos/src/vespa/fastos/unix_socket.cpp b/fastos/src/vespa/fastos/unix_socket.cpp deleted file mode 100644 index ba1d2f50417..00000000000 --- a/fastos/src/vespa/fastos/unix_socket.cpp +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. - -#include "socket.h" -#include <cassert> -#include <cstring> -#include <unistd.h> -#include <fcntl.h> - -FastOS_UNIX_Socket::~FastOS_UNIX_Socket() -{ - FastOS_UNIX_Socket::Close(); -} - -bool FastOS_UNIX_Socket::Close() -{ - bool rc=true; - - if (ValidHandle()) { - CleanupEvents(); - rc = (0 == close(_socketHandle)); - _socketHandle = -1; - } - - return rc; -} - -bool FastOS_UNIX_Socket::Shutdown() -{ - bool rc=true; - - if (ValidHandle()) { - if(_socketEvent != nullptr) { - EnableWriteEvent(false); - } - rc = (0 == shutdown(_socketHandle, SHUT_WR)); - } - - return rc; -} - -bool FastOS_UNIX_Socket::SetSoBlocking (bool blockingEnabled) -{ - bool rc=false; - - if (CreateIfNoSocketYet()) { - int flags = fcntl(_socketHandle, F_GETFL, nullptr); - - if (flags >= 0) { - if (blockingEnabled) { - flags &= ~O_NONBLOCK; // clear nonblocking - } else { - flags |= O_NONBLOCK; // set nonblocking - } - - if (fcntl(_socketHandle, F_SETFL, flags) >= 0) { - rc = true; - } - } - } - - return rc; -} - -ssize_t FastOS_UNIX_Socket::Write (const void *writeBuffer, size_t bufferSize) -{ - assert(ValidHandle()); - - ssize_t got; - do { - got = ::write(_socketHandle, writeBuffer, bufferSize); - } while (got<0 && errno == EINTR); // caught interrupt; nonBlocking sock.s - - return got; -} - - -ssize_t FastOS_UNIX_Socket::Read (void *readBuffer, size_t bufferSize) -{ - assert(ValidHandle()); - - ssize_t got; - do { - got = ::read(_socketHandle, readBuffer, bufferSize); - } while (got<0 && errno == EINTR); // caught interrupt; nonBlocking sock.s - - return got; -} - - -std::string -FastOS_UNIX_Socket::getErrorString(int error) -{ - char errorBuf[100]; - const char *errorString = strerror_r(error, errorBuf, sizeof(errorBuf)); - return std::string(errorString); -} - - -bool FastOS_SocketEventObjects::Init (FastOS_SocketEvent *event) -{ - (void)event; - - _wakeUpPipe[0] = -1; - _wakeUpPipe[1] = -1; - - if (pipe(_wakeUpPipe) == 0) { - int flags; - flags = fcntl(_wakeUpPipe[0], F_GETFL, 0); - if (flags != -1) { - flags |= O_NONBLOCK; - fcntl(_wakeUpPipe[0], F_SETFL, flags); - } - flags = fcntl(_wakeUpPipe[1], F_GETFL, 0); - if (flags != -1) { - flags |= O_NONBLOCK; - fcntl(_wakeUpPipe[1], F_SETFL, flags); - } - return true; - } else { - return false; - } -} - -void FastOS_SocketEventObjects::Cleanup () -{ - if(_wakeUpPipe[0] != -1) { - close(_wakeUpPipe[0]); - } - if(_wakeUpPipe[1] != -1) { - close(_wakeUpPipe[1]); - } -} diff --git a/fastos/src/vespa/fastos/unix_socket.h b/fastos/src/vespa/fastos/unix_socket.h deleted file mode 100644 index a1f25a8d159..00000000000 --- a/fastos/src/vespa/fastos/unix_socket.h +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. - -#pragma once - -#include "socket.h" - -class FastOS_UNIX_Socket : public FastOS_SocketInterface -{ -public: - ~FastOS_UNIX_Socket(); - - bool Close () override; - bool Shutdown() override; - bool SetSoBlocking (bool blockingEnabled) override; - ssize_t Read (void *readBuffer, size_t bufferSize) override; - ssize_t Write (const void *writeBuffer, size_t bufferSize) override; - - static int GetLastError () { return errno; } - static std::string getErrorString(int error); - - enum { - ERR_ALREADY = EALREADY, // New style error codes - ERR_AGAIN = EAGAIN, - ERR_INTR = EINTR, - ERR_ISCONN = EISCONN, - ERR_INPROGRESS = EINPROGRESS, - ERR_WOULDBLOCK = EWOULDBLOCK, - ERR_ADDRNOTAVAIL = EADDRNOTAVAIL, - ERR_MFILE = EMFILE, - ERR_NFILE = ENFILE, - ERR_CONNRESET = ECONNRESET, - - ERR_EAGAIN = EAGAIN, // Old style error codes - ERR_EINTR = EINTR, - ERR_EISCONN = EISCONN, - ERR_EINPROGRESS = EINPROGRESS, - ERR_EWOULDBLOCK = EWOULDBLOCK, - ERR_EADDRNOTAVAIL = EADDRNOTAVAIL, - ERR_EMFILE = EMFILE, - ERR_ENFILE = ENFILE - }; -}; - - |