68 lines
2.3 KiB
C
68 lines
2.3 KiB
C
/*
|
|
* This file is part of uIRCd. (https://git.redxen.eu/caskd/uIRCd)
|
|
* Copyright (c) 2019, 2020 Alex-David Denes
|
|
*
|
|
* uIRCd is free software: you can redistribute it and/or modify
|
|
* it under the terms of the GNU General Public License as published by
|
|
* the Free Software Foundation, either version 3 of the License, or
|
|
* any later version.
|
|
*
|
|
* uIRCd is distributed in the hope that it will be useful,
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
* GNU General Public License for more details.
|
|
*
|
|
* You should have received a copy of the GNU General Public License
|
|
* along with uIRCd. If not, see <https://www.gnu.org/licenses/>.
|
|
*/
|
|
#include "net.h"
|
|
|
|
signed int init_conn(Connection* info)
|
|
{
|
|
const struct timespec retry_timeout = {3, 0.0L};
|
|
int sockfd, getaddrres, connectres;
|
|
if (info->data.addr == NULL) return INIT_HARDFAIL;
|
|
struct addrinfo* conn;
|
|
if ((getaddrres = getaddrinfo(info->data.addr, info->data.port, NULL, &conn)) != 0) {
|
|
LOG(LOG_ERROR, "Failed to get address info for %s:%s. %s (%i)", info->data.addr, info->data.port, gai_strerror(getaddrres), getaddrres);
|
|
freeaddrinfo(conn);
|
|
if (getaddrres != EAI_AGAIN && getaddrres != EAI_NONAME) {
|
|
return INIT_HARDFAIL;
|
|
} else
|
|
return INIT_SOFTFAIL;
|
|
}
|
|
if ((sockfd = socket(conn->ai_family, conn->ai_socktype, conn->ai_protocol)) < 0) {
|
|
LOG(LOG_ERROR, "Failed to open a socket for " ADDRFMT ". " ERRNOFMT, info->data.addr, info->data.port, strerror(errno), errno);
|
|
freeaddrinfo(conn);
|
|
return INIT_HARDFAIL;
|
|
}
|
|
if ((connectres = connect(sockfd, conn->ai_addr, conn->ai_addrlen)) == -1) {
|
|
LOG(LOG_ERROR, "Failed to connect to host " ADDRFMT ". " ERRNOFMT, info->data.addr, info->data.port, strerror(errno), errno);
|
|
close(sockfd);
|
|
freeaddrinfo(conn);
|
|
if (errno != EADDRNOTAVAIL && errno != ETIMEDOUT && errno != ECONNRESET && errno != ECONNREFUSED) {
|
|
return INIT_HARDFAIL;
|
|
} else
|
|
return INIT_SOFTFAIL;
|
|
}
|
|
freeaddrinfo(conn);
|
|
return sockfd;
|
|
}
|
|
|
|
int flush_buffer(char* buf, int buflen, int fd)
|
|
{
|
|
int res;
|
|
char* pos = buf;
|
|
for (;;) {
|
|
if ((res = write(fd, pos, buflen - (pos - buf))) != buflen - (pos - buf)) {
|
|
if (res == -1) {
|
|
return -1;
|
|
} else {
|
|
pos += res;
|
|
}
|
|
} else
|
|
return res;
|
|
}
|
|
return pos - buf;
|
|
}
|