#include <sys/cdefs.h>
#ifndef __APPLE__
__FBSDID("$FreeBSD: src/usr.bin/talk/io.c,v 1.16 2004/05/10 15:52:16 cognet Exp $");
#ifndef lint
static const char sccsid[] = "@(#)io.c 8.1 (Berkeley) 6/6/93";
#endif
#endif
#include <sys/filio.h>
#ifdef __APPLE__
#include <sys/ioctl.h>
#endif
#include <errno.h>
#include <signal.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "talk.h"
#include "talk_ctl.h"
#define A_LONG_TIME 10000000
volatile sig_atomic_t gotwinch = 0;
void
talk()
{
struct hostent *hp, *hp2;
int nb;
fd_set read_set, read_template;
char buf[BUFSIZ], **addr, *his_machine_name;
struct timeval wait;
his_machine_name = NULL;
hp = gethostbyaddr((const char *)&his_machine_addr.s_addr,
sizeof(his_machine_addr.s_addr), AF_INET);
if (hp != NULL) {
hp2 = gethostbyname(hp->h_name);
if (hp2 != NULL && hp2->h_addrtype == AF_INET &&
hp2->h_length == sizeof(his_machine_addr))
for (addr = hp2->h_addr_list; *addr != NULL; addr++)
if (memcmp(*addr, &his_machine_addr,
sizeof(his_machine_addr)) == 0) {
his_machine_name = strdup(hp->h_name);
break;
}
}
if (his_machine_name == NULL)
his_machine_name = strdup(inet_ntoa(his_machine_addr));
snprintf(buf, sizeof(buf), "Connection established with %s@%s.",
msg.r_name, his_machine_name);
free(his_machine_name);
message(buf);
write(STDOUT_FILENO, "\007\007\007", 3);
current_line = 0;
FD_ZERO(&read_template);
FD_SET(sockt, &read_template);
FD_SET(fileno(stdin), &read_template);
for (;;) {
read_set = read_template;
wait.tv_sec = A_LONG_TIME;
wait.tv_usec = 0;
nb = select(sockt + 1, &read_set, 0, 0, &wait);
if (gotwinch) {
resize_display();
gotwinch = 0;
}
if (nb <= 0) {
if (errno == EINTR) {
read_set = read_template;
continue;
}
p_error("Unexpected error from select");
quit();
}
if (FD_ISSET(sockt, &read_set)) {
nb = read(sockt, buf, sizeof buf);
if (nb <= 0) {
message("Connection closed. Exiting");
quit();
}
display(&his_win, buf, nb);
}
if (FD_ISSET(fileno(stdin), &read_set)) {
int i;
ioctl(0, FIONREAD, (void *) &nb);
if (nb > sizeof buf)
nb = sizeof buf;
nb = read(STDIN_FILENO, buf, nb);
display(&my_win, buf, nb);
for (i = 0; i < nb; ++i)
if (buf[i] == '\r')
buf[i] = '\n';
write(sockt, buf, nb);
}
}
}
void
p_error(string)
const char *string;
{
wmove(my_win.x_win, current_line, 0);
wprintw(my_win.x_win, "[%s : %s (%d)]\n",
string, strerror(errno), errno);
wrefresh(my_win.x_win);
move(LINES-1, 0);
refresh();
quit();
}
void
message(string)
const char *string;
{
wmove(my_win.x_win, current_line, 0);
wprintw(my_win.x_win, "[%s]\n", string);
if (current_line < my_win.x_nlines - 1)
current_line++;
wrefresh(my_win.x_win);
}