This repository has been archived on 2021-02-08. You can view files and clone it, but cannot push or open issues or pull requests.
uIRCd/src/net.c

67 lines
2.2 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)
{
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;
}
ssize_t flush_buffer(char* buf, size_t buflen, int fd)
{
ssize_t res;
char* pos = buf;
for (;;) {
if ((size_t)(res = write(fd, pos, buflen - (size_t)(pos - buf))) != buflen - (size_t)(pos - buf)) {
if (res == -1)
return -1;
else
pos += res;
} else
return res;
}
}