Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <thread>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
 
#include "dgrid.h"
#include "dgrid_auth.h"
#include "dgrid_config.h"
#include "dgrid_logger.h"
#include "dgridd_child.h"
#include "dgrid_req_structs.h"
#include "listener.h"
 
namespace DGrid {
 
DGriddChild::DGriddChild(DGriddListener* p)
    :DGriddThread(), parent(p)
{
}
 
DGriddChild::~DGriddChild()
{
}
 
bool DGriddChild::start(int fd)
{
    if(fd < 0) {
        return false;
    }
    connfd = fd;
    return DGriddThread::start();
}
 
void DGriddChild::run()
{
    sa_family_t address_family;
    struct sockaddr    *cliaddr = nullptr;
    struct sockaddr_in cliaddr_in;
    struct sockaddr_un cliaddr_un;
    socklen_t cliaddr_len = sizeof(address_family);
    struct timeval tv_timeout;
    fd_set   rd_set;
    FD_ZERO(&rd_set);
 
    writeLog(LOG_DEBUG, "DGridWorkerClient STA");
    if (getpeername(connfd, (struct sockaddr*)&address_family, &cliaddr_len)) {
        writeLog(LOG_ERR, "getpeername(%u) failed", connfd, errno, strerror(errno));
        return;
    }
    if(AF_UNIX == address_family) {
        cliaddr_len = sizeof(cliaddr_un);
        cliaddr = (struct sockaddr*)&cliaddr_un;
    } else {
        cliaddr_len = sizeof(cliaddr_in);
        cliaddr = (struct sockaddr*)&cliaddr_in;
    }
 
    if (getpeername(connfd, cliaddr, &cliaddr_len)) {
        writeLog(LOG_ERR, "getpeername(%u) failed", connfd, errno, strerror(errno));
        return;
    }
    if(AF_UNIX == address_family) {
        writeLog(LOG_INFO, "Incoming connection");
    } else {
        writeLog(LOG_INFO, "Incoming connection %s:%d", inet_ntoa(cliaddr_in.sin_addr), ntohs(cliaddr_in.sin_port));
    }
 
    if(AF_UNIX != address_family) {
        // try to disable TCP Nagle algorythm (to speedup short packeds sending)
        int nodelay_flag = 1;
        if (0 > setsockopt(connfd,
                            IPPROTO_TCP,
                            TCP_NODELAY,
                            (char*) &nodelay_flag,
                            sizeof(nodelay_flag))) {
            writeLog(LOG_ERR, "setsockopt failed: %s", strerror(errno));
        }
    }
    while(!hasStopReq()) {
        FD_SET(connfd, &rd_set);
        tv_timeout.tv_sec = SELECT_TIMEOUT_SEC; // 1 second time-out
        tv_timeout.tv_usec = SELECT_TIMEOUT_USEC;
 
        if (select(connfd+1, &rd_set, NULL, NULL, &tv_timeout) < 0) {
            writeLog(LOG_ERR, "Socket error: [%d] '%s'", errno, strerror(errno));
            if (EBADF == errno)
                goto quit;
            setStopReq();
        }
        if (FD_ISSET(connfd, &rd_set)) {
            if (!receiveData())
                setStopReq();
        }
    }
 
    shutdown(connfd, SHUT_RDWR);
    close(connfd);
quit:
    if(AF_UNIX == address_family) {
        writeLog(LOG_INFO, "Client disconnected");
    } else {
        writeLog(LOG_INFO, "Client disconnected %s:%d", inet_ntoa(cliaddr_in.sin_addr), ntohs(cliaddr_in.sin_port));
    }
    if(parent)
        parent->childFinished(this);
    writeLog(LOG_DEBUG, "DGridWorkerClient END");
}
 
bool DGriddChild::receiveData()
{
    int32_t    len;
    bool       crc_ok;
    PacketType type;
    std::vector<char> data_buf;
 
    len  = recvPacket(connfd, type, data_buf, crc_ok);
    if (len < 0) {
        if (errno)
            writeLog(LOG_ERR, "recvPacket failed: [%d] %s", errno, strerror(errno));
        return false;
    }
    if (!crc_ok) {
        writeLog(LOG_WARNING, "CRC missmatch! Possible network error!");
        sendReset(connfd);
        return true;
    }
#ifdef DEBUG_TRANSPORT
    writeLog(LOG_DEBUG, "RCVD packet %s, %d bytes", packetType2string(type).c_str(), data_buf.size());
#endif
    processData(type, data_buf);
    return true;
}
 
void DGriddChild::processData(PacketType type, const std::vector<char>& data_buf)
{
    switch(type) {
        case PKT_ECHO:
            if(!auth_done) {
                return; // небольшая защита от флуда
            }
            sendPacket(connfd, PKT_ECHO_RPL, data_buf.data(), sizeof(Network_pkt_echo));
            break;
        case PKT_AUTH: {
            AuthData auth_data(data_buf);
            AuthResponse auth_result;
            auth_result.result = checkAuth(auth_data, auth_result.message);
            writeLog(LOG_WARNING, "AUTH %s (method=%s)", auth_result.result ? "OK" : "FAIL", authType2string(auth_data.type).c_str());
            if(auth_result.result)
                auth_done = true;
            sendPacket(connfd, PKT_AUTH_RPL, auth_result.serialize());
            break;
        }
        case PKT_RESET:
            writeLog(LOG_INFO, "client requested connection reset!");
            sendReset(connfd);
            setStopReq();
            break;
        case PKT_REQ: {
            Network_pkt_request *req = (Network_pkt_request*) data_buf.data();
            if(!auth_done) {
                sendAck(connfd, req, DGRID_NOT_AUTHORIZED);
                return;
            }
            processRequest(req, data_buf.size() - Network_pkt_request_size);
            break;
        }
        case PKT_ECHO_RPL:
            break;
        default:
            writeLog(LOG_INFO, "invalid packet!");
            sendPacket(connfd, PKT_INVALID);
            break;
    }
}
 
void DGriddChild::processRequest(const Network_pkt_request* req, uint32_t dlen)
{
    if(!req) return;
    std::vector<char> ret_data;
    std::string err_details;
    std::vector<char> payload;
    if (dlen) {
        payload.assign((char*)(req+1), (char*)(req+1) + dlen);
    }
 
#ifdef DEBUG_TRANSPORT
    writeLog(LOG_DEBUG, "REQ [%d] %s, payload %d bytes", req->type, requestType2string(req->type).c_str(), dlen);
#endif
    DGridResult result = processRequest(int2requestType(req->type), int2requestSubType(req->subtype), payload, ret_data, err_details);
 
    if (DGRID_OK != result) {
        writeLog(LOG_WARNING, "[%s/%s] %s : %s",
            requestType2string(req->type).c_str(),
            requestSubType2string(req->subtype).c_str(),
            DGridResultString(result).c_str(),
            err_details.c_str());
    }
    if (DGRID_OK == result || (DGRID_NOT_FOUND_INDEX_SUGGESTED == result && ret_data.size()>0)) {
        sendAck(connfd, req, result, ret_data.data(), ret_data.size());
    } else {
        sendAck(connfd, req, result, err_details.data(), err_details.length());
    }
}
 
bool DGriddChild::checkAuth(const AuthData& auth_data, std::string& message)
{
    switch(auth_data.type) {
        case AUTH_KEY: {
            const std::string cluster_key = Config::instance()->get_cluster_key();
            bool r = !cluster_key.empty() && auth_data.key == cluster_key;
            if(!r)
                message = "Invalid cluster key";
            return r;
        }
        case AUTH_USER: {
            bool r = checkUserPasswd(auth_data.user, auth_data.passwd, message);
            if(!r && message.empty())
                message = "Invalid user/password";
            return r;
        }
        default:
            break;
    }
    message = "Invalid auth type";
    return false;
}
 
} // namespace DGrid