• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef LOCALSOCKET_H
17 #define LOCALSOCKET_H
18 
19 #include <string>
20 
21 #ifdef _WIN32
22 #include <windows.h>
23 #else
24 #endif // _WIN32
25 
26 #include "EndianUtil.h"
27 
28 class LocalSocket {
29 public:
30     enum OpenMode { READ_ONLY = 0, WRITE_ONLY, READ_WRITE };
31 
32     enum TransMode { TRANS_BYTE = 0, TRANS_MESSAGE };
33 
34     LocalSocket();
35     virtual ~LocalSocket();
36     LocalSocket& operator=(const LocalSocket&) = delete;
37     LocalSocket(const LocalSocket&) = delete;
38     bool ConnectToServer(std::string name, OpenMode openMode, TransMode transMode = TRANS_BYTE);
39     std::string GetCommandPipeName(std::string baseName) const;
40     std::string GetImagePipeName(std::string baseName) const;
41     std::string GetTracePipeName(std::string baseName) const;
42     void DisconnectFromServer();
43     int64_t ReadData(char* data, size_t length) const;
44     size_t WriteData(const void* data, size_t length) const;
45 
46     template <class T, class = typename std::enable_if<std::is_integral<T>::value>::type>
47     const LocalSocket& operator<<(const T data) const
48     {
49         T dataToSend = EndianUtil::ToNetworkEndian<T>(data);
50         char* startPos = reinterpret_cast<char*>(&dataToSend);
51         char buffer[sizeof(T)];
52         std::copy(startPos, startPos + sizeof(dataToSend), buffer);
53         WriteData(buffer, sizeof(dataToSend));
54         return *this;
55     }
56 
57     const LocalSocket& operator<<(const std::string data) const;
58 
59     const LocalSocket& operator>>(std::string& data) const;
60 
61 private:
62 #ifdef _WIN32
63     HANDLE pipeHandle;
64     DWORD GetWinOpenMode(OpenMode mode) const;
65     DWORD GetWinTransMode(TransMode mode) const;
66 #else
67     int socketHandle;
68 #endif // _WIN32
69 };
70 
71 #endif // LOCALSOCKET_H
72