blob: 6c1a5c4ee2f17a822957f41cfd8f68f7a8a958c2 [file] [log] [blame] [raw]
/*
* Copyright 2015-2019 Rivoreo
*
* This program 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 (at your
* option) any later version.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <unistd.h>
#include <string.h>
#include <stdio.h>
//#define FIO_INCLUDE_STR
#include <fio.h>
#include <cli/fio_cli.h>
#include <fiobj/fiobj_str.h>
#include <http/http.h>
static ws_s *websocket_instance;
static void on_ws_open(ws_s *ws) {
fprintf(stderr, "function: on_ws_open(%p)\n", ws);
websocket_instance = ws;
}
static void on_ws_message(ws_s *ws, fio_str_info_s msg, uint8_t is_text) {
write(STDOUT_FILENO, msg.data, msg.len);
}
static void on_ws_close(intptr_t uuid, void *udata) {
fprintf(stderr, "function: on_ws_close(%ld, %p)\n", (long int)uuid, udata);
exit(uuid == -1 ? 1 : 0);
}
static void on_stdin_data(intptr_t uuid, fio_protocol_s *proto) {
//fprintf(stderr, "function: on_stdin_data(%ld, %p)\n", (long int)uuid, proto);
if(!websocket_instance) return;
char buffer[4096];
while(1) {
errno = 0;
int s = fio_read(uuid, buffer, sizeof buffer);
if(s < 0) {
if(errno) {
perror("fio_read");
exit(1);
} else {
exit(0);
}
}
if(!s) return;
fio_str_info_s buffer_info = {
.capa = sizeof buffer,
.len = s,
.data = buffer
};
if(websocket_write(websocket_instance, buffer_info, 0) < 0) {
perror("websocket_write");
exit(1);
}
}
}
static void on_stdin_close(intptr_t uuid, fio_protocol_s *proto) {
fprintf(stderr, "function: on_stdin_close(%ld, %p)\n", (long int)uuid, proto);
exit(uuid == -1 ? 1 : 0);
}
int main(int argc, char **argv) {
FIO_LOG_LEVEL = FIO_LOG_LEVEL_INFO;
fio_cli_start(argc, argv, 1, 1, "WebSocket client",
FIO_CLI_PRINT("wscat <url>"));
const char *url = fio_cli_unnamed(0);
void *tls = strncmp(url, "wss:", 4) == 0 ? fio_tls_new(NULL, NULL, NULL, NULL) : NULL;
if(websocket_connect(url, .on_open = on_ws_open, .on_message = on_ws_message, .on_close = on_ws_close, .tls = tls) == -1) {
perror("websocket_connect");
return 1;
}
fio_protocol_s stdin_protocol = {
//.service = "pipe-to-ws",
.on_data = on_stdin_data,
.on_close = on_stdin_close,
};
fio_set_non_block(STDIN_FILENO);
fio_attach_fd(STDIN_FILENO, &stdin_protocol);
fio_start(.threads = 1, .workers = 1);
fio_cli_end();
return 0;
}