Move wsproxy and web utils into utils/ subdir.

This commit is contained in:
Joel Martin
2010-06-07 12:47:02 -05:00
parent 9e61a9c6f0
commit 7210e79e04
10 changed files with 6 additions and 6 deletions

12
utils/Makefile Normal file
View File

@@ -0,0 +1,12 @@
wsproxy: wsproxy.o websocket.o
$(CC) $^ -l ssl -l resolv -o $@
#websocket.o: websocket.c
# $(CC) -c $^ -o $@
#
#wsproxy.o: wsproxy.c
# $(CC) -c $^ -o $@
clean:
rm -f wsproxy wsproxy.o websocket.o

53
utils/web.py Executable file
View File

@@ -0,0 +1,53 @@
#!/usr/bin/python
'''
A super simple HTTP/HTTPS webserver for python. Automatically detect
You can make a cert/key with openssl using:
openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem
as taken from http://docs.python.org/dev/library/ssl.html#certificates
'''
import traceback, sys
import socket
import ssl
#import http.server as server # python 3.X
import SimpleHTTPServer as server # python 2.X
def do_request(connstream, from_addr):
x = object()
server.SimpleHTTPRequestHandler(connstream, from_addr, x)
def serve():
bindsocket = socket.socket()
#bindsocket.bind(('localhost', PORT))
bindsocket.bind(('', PORT))
bindsocket.listen(5)
print("serving on port", PORT)
while True:
try:
newsocket, from_addr = bindsocket.accept()
peek = newsocket.recv(1024, socket.MSG_PEEK)
if peek.startswith("\x16"):
connstream = ssl.wrap_socket(
newsocket,
server_side=True,
certfile='self.pem',
ssl_version=ssl.PROTOCOL_TLSv1)
else:
connstream = newsocket
do_request(connstream, from_addr)
except Exception:
traceback.print_exc()
try:
PORT = int(sys.argv[1])
except:
print "%s port" % sys.argv[0]
sys.exit(2)
serve()

349
utils/websocket.c Normal file
View File

@@ -0,0 +1,349 @@
/*
* WebSocket lib with support for "wss://" encryption.
*
* You can make a cert/key with openssl using:
* openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem
* as taken from http://docs.python.org/dev/library/ssl.html#certificates
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <resolv.h> /* base64 encode/decode */
#include "websocket.h"
const char server_handshake[] = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n\
Upgrade: WebSocket\r\n\
Connection: Upgrade\r\n\
WebSocket-Origin: %s\r\n\
WebSocket-Location: %s://%s%s\r\n\
WebSocket-Protocol: sample\r\n\
\r\n";
const char policy_response[] = "<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"*\" /></cross-domain-policy>\n";
/*
* Global state
*
* Warning: not thread safe
*/
int ssl_initialized = 0;
char *tbuf, *cbuf, *tbuf_tmp, *cbuf_tmp;
unsigned int bufsize, dbufsize;
client_settings_t client_settings;
void traffic(char * token) {
fprintf(stdout, "%s", token);
fflush(stdout);
}
void error(char *msg)
{
perror(msg);
}
void fatal(char *msg)
{
perror(msg);
exit(1);
}
/*
* SSL Wrapper Code
*/
ssize_t ws_recv(ws_ctx_t *ctx, void *buf, size_t len) {
if (ctx->ssl) {
//printf("SSL recv\n");
return SSL_read(ctx->ssl, buf, len);
} else {
return recv(ctx->sockfd, buf, len, 0);
}
}
ssize_t ws_send(ws_ctx_t *ctx, const void *buf, size_t len) {
if (ctx->ssl) {
//printf("SSL send\n");
return SSL_write(ctx->ssl, buf, len);
} else {
return send(ctx->sockfd, buf, len, 0);
}
}
ws_ctx_t *ws_socket(int socket) {
ws_ctx_t *ctx;
ctx = malloc(sizeof(ws_ctx_t));
ctx->sockfd = socket;
ctx->ssl = NULL;
ctx->ssl_ctx = NULL;
return ctx;
}
ws_ctx_t *ws_socket_ssl(int socket, char * certfile) {
int ret;
char msg[1024];
ws_ctx_t *ctx;
ctx = ws_socket(socket);
// Initialize the library
if (! ssl_initialized) {
SSL_library_init();
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
ssl_initialized = 1;
}
ctx->ssl_ctx = SSL_CTX_new(TLSv1_server_method());
if (ctx->ssl_ctx == NULL) {
ERR_print_errors_fp(stderr);
fatal("Failed to configure SSL context");
}
if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, certfile,
SSL_FILETYPE_PEM) <= 0) {
sprintf(msg, "Unable to load private key file %s\n", certfile);
fatal(msg);
}
if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, certfile,
SSL_FILETYPE_PEM) <= 0) {
sprintf(msg, "Unable to load certificate file %s\n", certfile);
fatal(msg);
}
// if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, "DEFAULT") != 1) {
// sprintf(msg, "Unable to set cipher\n");
// fatal(msg);
// }
// Associate socket and ssl object
ctx->ssl = SSL_new(ctx->ssl_ctx);
SSL_set_fd(ctx->ssl, socket);
ret = SSL_accept(ctx->ssl);
if (ret < 0) {
ERR_print_errors_fp(stderr);
return NULL;
}
return ctx;
}
int ws_socket_free(ws_ctx_t *ctx) {
if (ctx->ssl) {
SSL_free(ctx->ssl);
ctx->ssl = NULL;
}
if (ctx->ssl_ctx) {
SSL_CTX_free(ctx->ssl_ctx);
ctx->ssl_ctx = NULL;
}
if (ctx->sockfd) {
close(ctx->sockfd);
ctx->sockfd = 0;
}
free(ctx);
}
/* ------------------------------------------------------- */
int encode(u_char const *src, size_t srclength, char *target, size_t targsize) {
int sz = 0, len = 0;
target[sz++] = '\x00';
if (client_settings.do_seq_num) {
sz += sprintf(target+sz, "%d:", client_settings.seq_num);
client_settings.seq_num++;
}
if (client_settings.do_b64encode) {
len = __b64_ntop(src, srclength, target+sz, targsize-sz);
} else {
fatal("UTF-8 not yet implemented");
}
if (len < 0) {
return len;
}
sz += len;
target[sz++] = '\xff';
return sz;
}
int decode(char *src, size_t srclength, u_char *target, size_t targsize) {
char *start, *end;
int len, retlen = 0;
if ((src[0] != '\x00') || (src[srclength-1] != '\xff')) {
fprintf(stderr, "WebSocket framing error\n");
return -1;
}
start = src+1; // Skip '\x00' start
do {
/* We may have more than one frame */
end = strchr(start, '\xff');
if (end < (src+srclength-1)) {
printf("More than one frame to decode\n");
}
*end = '\x00';
if (client_settings.do_b64encode) {
len = __b64_pton(start, target+retlen, targsize-retlen);
} else {
fatal("UTF-8 not yet implemented");
}
if (len < 0) {
return len;
}
retlen += len;
start = end + 2; // Skip '\xff' end and '\x00' start
} while (end < (src+srclength-1));
return retlen;
}
ws_ctx_t *do_handshake(int sock) {
char handshake[4096], response[4096];
char *scheme, *line, *path, *host, *origin;
char *args_start, *args_end, *arg_idx;
int len;
ws_ctx_t * ws_ctx;
// Reset settings
client_settings.do_b64encode = 0;
client_settings.do_seq_num = 0;
client_settings.seq_num = 0;
len = recv(sock, handshake, 1024, MSG_PEEK);
handshake[len] = 0;
if (bcmp(handshake, "<policy-file-request/>", 22) == 0) {
len = recv(sock, handshake, 1024, 0);
handshake[len] = 0;
printf("Sending flash policy response\n");
send(sock, policy_response, sizeof(policy_response), 0);
close(sock);
return NULL;
} else if (bcmp(handshake, "\x16", 1) == 0) {
// SSL
ws_ctx = ws_socket_ssl(sock, "self.pem");
if (! ws_ctx) { return NULL; }
scheme = "wss";
printf("Using SSL socket\n");
} else {
ws_ctx = ws_socket(sock);
if (! ws_ctx) { return NULL; }
scheme = "ws";
printf("Using plain (not SSL) socket\n");
}
len = ws_recv(ws_ctx, handshake, 4096);
handshake[len] = 0;
//printf("handshake: %s\n", handshake);
if ((len < 92) || (bcmp(handshake, "GET ", 4) != 0)) {
fprintf(stderr, "Invalid WS request\n");
return NULL;
}
strtok(handshake, " "); // Skip "GET "
path = strtok(NULL, " "); // Extract path
strtok(NULL, "\n"); // Skip to Upgrade line
strtok(NULL, "\n"); // Skip to Connection line
strtok(NULL, "\n"); // Skip to Host line
strtok(NULL, " "); // Skip "Host: "
host = strtok(NULL, "\r"); // Extract host
strtok(NULL, " "); // Skip "Origin: "
origin = strtok(NULL, "\r"); // Extract origin
//printf("path: %s\n", path);
//printf("host: %s\n", host);
//printf("origin: %s\n", origin);
// TODO: parse out client settings
args_start = strstr(path, "?");
if (args_start) {
if (strstr(args_start, "#")) {
args_end = strstr(args_start, "#");
} else {
args_end = args_start + strlen(args_start);
}
arg_idx = strstr(args_start, "b64encode");
if (arg_idx && arg_idx < args_end) {
//printf("setting b64encode\n");
client_settings.do_b64encode = 1;
}
arg_idx = strstr(args_start, "seq_num");
if (arg_idx && arg_idx < args_end) {
//printf("setting seq_num\n");
client_settings.do_seq_num = 1;
}
}
sprintf(response, server_handshake, origin, scheme, host, path);
printf("response: %s\n", response);
ws_send(ws_ctx, response, strlen(response));
return ws_ctx;
}
void start_server(int listen_port,
void (*handler)(ws_ctx_t*)) {
int lsock, csock, clilen, sopt = 1;
struct sockaddr_in serv_addr, cli_addr;
ws_ctx_t *ws_ctx;
/* Initialize buffers */
bufsize = 65536;
if (! (tbuf = malloc(bufsize)) )
{ fatal("malloc()"); }
if (! (cbuf = malloc(bufsize)) )
{ fatal("malloc()"); }
if (! (tbuf_tmp = malloc(bufsize)) )
{ fatal("malloc()"); }
if (! (cbuf_tmp = malloc(bufsize)) )
{ fatal("malloc()"); }
lsock = socket(AF_INET, SOCK_STREAM, 0);
if (lsock < 0) { error("ERROR creating listener socket"); }
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(listen_port);
setsockopt(lsock, SOL_SOCKET, SO_REUSEADDR, (char *)&sopt, sizeof(sopt));
if (bind(lsock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
error("ERROR on binding listener socket");
}
listen(lsock,100);
while (1) {
clilen = sizeof(cli_addr);
printf("waiting for connection on port %d\n", listen_port);
csock = accept(lsock,
(struct sockaddr *) &cli_addr,
&clilen);
if (csock < 0) {
error("ERROR on accept");
}
printf("Got client connection from %s\n", inet_ntoa(cli_addr.sin_addr));
ws_ctx = do_handshake(csock);
if (ws_ctx == NULL) {
close(csock);
continue;
}
/* Calculate dbufsize based on client_settings */
if (client_settings.do_b64encode) {
/* base64 is 4 bytes for every 3
* 20 for WS '\x00' / '\xff', seq_num and good measure */
dbufsize = (bufsize * 3)/4 - 20;
} else {
fatal("UTF-8 not yet implemented");
/* UTF-8 encoding is up to 2X larger */
dbufsize = (bufsize/2) - 15;
}
handler(ws_ctx);
close(csock);
}
}

23
utils/websocket.h Normal file
View File

@@ -0,0 +1,23 @@
#include <openssl/ssl.h>
typedef struct {
int sockfd;
SSL_CTX *ssl_ctx;
SSL *ssl;
} ws_ctx_t;
typedef struct {
int do_b64encode;
int do_seq_num;
int seq_num;
} client_settings_t;
ssize_t ws_recv(ws_ctx_t *ctx, void *buf, size_t len);
ssize_t ws_send(ws_ctx_t *ctx, const void *buf, size_t len);
/* base64.c declarations */
//int b64_ntop(u_char const *src, size_t srclength, char *target, size_t targsize);
//int b64_pton(char const *src, u_char *target, size_t targsize);

124
utils/websocket.py Executable file
View File

@@ -0,0 +1,124 @@
#!/usr/bin/python
'''
Python WebSocket library with support for "wss://" encryption.
You can make a cert/key with openssl using:
openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem
as taken from http://docs.python.org/dev/library/ssl.html#certificates
'''
import sys, socket, ssl, traceback
from base64 import b64encode, b64decode
client_settings = {}
send_seq = 0
server_handshake = """HTTP/1.1 101 Web Socket Protocol Handshake\r
Upgrade: WebSocket\r
Connection: Upgrade\r
WebSocket-Origin: %s\r
WebSocket-Location: %s://%s%s\r
WebSocket-Protocol: sample\r
\r
"""
policy_response = """<cross-domain-policy><allow-access-from domain="*" to-ports="*" /></cross-domain-policy>\n"""
def traffic(token="."):
sys.stdout.write(token)
sys.stdout.flush()
def decode(buf):
""" Parse out WebSocket packets. """
if buf.count('\xff') > 1:
if client_settings["b64encode"]:
return [b64decode(d[1:]) for d in buf.split('\xff')]
else:
# Modified UTF-8 decode
return [d[1:].replace("\xc4\x80", "\x00").decode('utf-8').encode('latin-1') for d in buf.split('\xff')]
else:
if client_settings["b64encode"]:
return [b64decode(buf[1:-1])]
else:
return [buf[1:-1].replace("\xc4\x80", "\x00").decode('utf-8').encode('latin-1')]
def encode(buf):
global send_seq
if client_settings["b64encode"]:
buf = b64encode(buf)
else:
# Modified UTF-8 encode
buf = buf.decode('latin-1').encode('utf-8').replace("\x00", "\xc4\x80")
if client_settings["seq_num"]:
send_seq += 1
return "\x00%d:%s\xff" % (send_seq-1, buf)
else:
return "\x00%s\xff" % buf
def do_handshake(sock):
global client_settings, send_seq
send_seq = 0
# Peek, but don't read the data
handshake = sock.recv(1024, socket.MSG_PEEK)
#print "Handshake [%s]" % repr(handshake)
if handshake.startswith("<policy-file-request/>"):
handshake = sock.recv(1024)
print "Sending flash policy response"
sock.send(policy_response)
sock.close()
return False
elif handshake.startswith("\x16"):
retsock = ssl.wrap_socket(
sock,
server_side=True,
certfile='self.pem',
ssl_version=ssl.PROTOCOL_TLSv1)
scheme = "wss"
print "Using SSL/TLS"
else:
retsock = sock
scheme = "ws"
print "Using plain (not SSL) socket"
handshake = retsock.recv(4096)
req_lines = handshake.split("\r\n")
_, path, _ = req_lines[0].split(" ")
_, origin = req_lines[4].split(" ")
_, host = req_lines[3].split(" ")
# Parse settings from the path
cvars = path.partition('?')[2].partition('#')[0].split('&')
client_settings = {'b64encode': None, 'seq_num': None}
for cvar in [c for c in cvars if c]:
name, _, value = cvar.partition('=')
client_settings[name] = value and value or True
print "client_settings:", client_settings
retsock.send(server_handshake % (origin, scheme, host, path))
return retsock
def start_server(listen_port, handler):
lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
lsock.bind(('', listen_port))
lsock.listen(100)
while True:
try:
csock = None
print 'waiting for connection on port %s' % listen_port
startsock, address = lsock.accept()
print 'Got client connection from %s' % address[0]
csock = do_handshake(startsock)
if not csock: continue
handler(csock)
except Exception:
print "Ignoring exception:"
print traceback.format_exc()
if csock: csock.close()

266
utils/wsproxy.c Normal file
View File

@@ -0,0 +1,266 @@
/*
* A WebSocket to TCP socket proxy with support for "wss://" encryption.
*
* You can make a cert/key with openssl using:
* openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem
* as taken from http://docs.python.org/dev/library/ssl.html#certificates
*/
#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/select.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "websocket.h"
char traffic_legend[] = "\n\
Traffic Legend:\n\
} - Client receive\n\
}. - Client receive partial\n\
{ - Target receive\n\
\n\
> - Target send\n\
>. - Target send partial\n\
< - Client send\n\
<. - Client send partial\n\
";
void usage() {
fprintf(stderr,"Usage: <listen_port> <target_host> <target_port>\n");
exit(1);
}
char *target_host;
int target_port;
char *record_filename = NULL;
int recordfd = 0;
extern char *tbuf, *cbuf, *tbuf_tmp, *cbuf_tmp;
extern unsigned int bufsize, dbufsize;
void do_proxy(ws_ctx_t *ws_ctx, int target) {
fd_set rlist, wlist, elist;
struct timeval tv;
int i, maxfd, client = ws_ctx->sockfd;
unsigned int tstart, tend, cstart, cend, ret;
ssize_t len, bytes;
tstart = tend = cstart = cend = 0;
maxfd = client > target ? client+1 : target+1;
while (1) {
tv.tv_sec = 1;
tv.tv_usec = 0;
FD_ZERO(&rlist);
FD_ZERO(&wlist);
FD_ZERO(&elist);
FD_SET(client, &elist);
FD_SET(target, &elist);
if (tend == tstart) {
// Nothing queued for target, so read from client
FD_SET(client, &rlist);
} else {
// Data queued for target, so write to it
FD_SET(target, &wlist);
}
if (cend == cstart) {
// Nothing queued for client, so read from target
FD_SET(target, &rlist);
} else {
// Data queued for client, so write to it
FD_SET(client, &wlist);
}
ret = select(maxfd, &rlist, &wlist, &elist, &tv);
if (FD_ISSET(target, &elist)) {
fprintf(stderr, "target exception\n");
break;
}
if (FD_ISSET(client, &elist)) {
fprintf(stderr, "client exception\n");
break;
}
if (ret == -1) {
error("select()");
break;
} else if (ret == 0) {
//fprintf(stderr, "select timeout\n");
continue;
}
if (FD_ISSET(target, &wlist)) {
len = tend-tstart;
bytes = send(target, tbuf + tstart, len, 0);
if (bytes < 0) {
error("target connection error");
break;
}
tstart += bytes;
if (tstart >= tend) {
tstart = tend = 0;
traffic(">");
} else {
traffic(">.");
}
}
if (FD_ISSET(client, &wlist)) {
len = cend-cstart;
bytes = ws_send(ws_ctx, cbuf + cstart, len);
if (len < 3) {
fprintf(stderr, "len: %d, bytes: %d: %d\n", len, bytes, *(cbuf + cstart));
}
cstart += bytes;
if (cstart >= cend) {
cstart = cend = 0;
traffic("<");
if (recordfd) {
write(recordfd, "'>", 2);
write(recordfd, cbuf + cstart + 1, bytes - 2);
write(recordfd, "',\n", 3);
}
} else {
traffic("<.");
}
}
if (FD_ISSET(target, &rlist)) {
bytes = recv(target, cbuf_tmp, dbufsize , 0);
if (bytes <= 0) {
fprintf(stderr, "target closed connection");
break;
}
cstart = 0;
cend = encode(cbuf_tmp, bytes, cbuf, bufsize);
/*
printf("encoded: ");
for (i=0; i< bytes; i++) {
printf("%d,", *(cbuf+i));
}
printf("\n");
*/
if (cend < 0) {
fprintf(stderr, "encoding error\n");
break;
}
traffic("{");
}
if (FD_ISSET(client, &rlist)) {
bytes = ws_recv(ws_ctx, tbuf_tmp, bufsize-1);
if (bytes <= 0) {
fprintf(stderr, "client closed connection\n");
break;
}
if (recordfd) {
write(recordfd, "'", 1);
write(recordfd, tbuf_tmp + 1, bytes - 2);
write(recordfd, "',\n", 3);
}
len = decode(tbuf_tmp, bytes, tbuf, bufsize-1);
/*
printf("decoded: ");
for (i=0; i< bytes; i++) {
printf("%d,", *(tbuf+i));
}
printf("\n");
*/
if (len < 0) {
fprintf(stderr, "decoding error\n");
break;
}
traffic("}");
tstart = 0;
tend = len;
}
}
}
void proxy_handler(ws_ctx_t *ws_ctx) {
int tsock = 0;
struct sockaddr_in taddr;
struct hostent *thost;
printf("Connecting to: %s:%d\n", target_host, target_port);
tsock = socket(AF_INET, SOCK_STREAM, 0);
if (tsock < 0) {
error("Could not create target socket");
return;
}
thost = gethostbyname(target_host);
if (thost == NULL) {
error("Could not resolve server");
close(tsock);
return;
}
bzero((char *) &taddr, sizeof(taddr));
taddr.sin_family = AF_INET;
bcopy((char *) thost->h_addr,
(char *) &taddr.sin_addr.s_addr,
thost->h_length);
taddr.sin_port = htons(target_port);
if (connect(tsock, (struct sockaddr *) &taddr, sizeof(taddr)) < 0) {
error("Could not connect to target");
close(tsock);
return;
}
if (record_filename) {
recordfd = open(record_filename, O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
}
printf("%s", traffic_legend);
do_proxy(ws_ctx, tsock);
close(tsock);
if (recordfd) {
close(recordfd);
recordfd = 0;
}
}
int main(int argc, char *argv[])
{
int listen_port, idx=1;
if (strcmp(argv[idx], "--record") == 0) {
idx++;
record_filename = argv[idx++];
}
if ((argc-idx) != 3) { usage(); }
listen_port = strtol(argv[idx++], NULL, 10);
if (errno != 0) { usage(); }
target_host = argv[idx++];
target_port = strtol(argv[idx++], NULL, 10);
if (errno != 0) { usage(); }
/* Initialize buffers */
bufsize = 65536;
if (! (tbuf = malloc(bufsize)) )
{ fatal("malloc()"); }
if (! (cbuf = malloc(bufsize)) )
{ fatal("malloc()"); }
if (! (tbuf_tmp = malloc(bufsize)) )
{ fatal("malloc()"); }
if (! (cbuf_tmp = malloc(bufsize)) )
{ fatal("malloc()"); }
start_server(listen_port, &proxy_handler);
free(tbuf);
free(cbuf);
free(tbuf_tmp);
free(cbuf_tmp);
}

134
utils/wsproxy.py Executable file
View File

@@ -0,0 +1,134 @@
#!/usr/bin/python
'''
A WebSocket to TCP socket proxy with support for "wss://" encryption.
Copyright 2010 Joel Martin
Licensed under LGPL version 3 (see LICENSE.LGPL-3)
You can make a cert/key with openssl using:
openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem
as taken from http://docs.python.org/dev/library/ssl.html#certificates
'''
import sys, socket, ssl, optparse
from select import select
from websocket import *
buffer_size = 65536
rec = None
traffic_legend = """
Traffic Legend:
} - Client receive
}. - Client receive partial
{ - Target receive
> - Target send
>. - Target send partial
< - Client send
<. - Client send partial
"""
def do_proxy(client, target):
""" Proxy WebSocket to normal socket. """
global rec
cqueue = []
cpartial = ""
tqueue = []
rlist = [client, target]
while True:
wlist = []
if tqueue: wlist.append(target)
if cqueue: wlist.append(client)
ins, outs, excepts = select(rlist, wlist, [], 1)
if excepts: raise Exception("Socket exception")
if target in outs:
dat = tqueue.pop(0)
sent = target.send(dat)
if sent == len(dat):
traffic(">")
else:
tqueue.insert(0, dat[sent:])
traffic(".>")
##if rec: rec.write("Target send: %s\n" % map(ord, dat))
if client in outs:
dat = cqueue.pop(0)
sent = client.send(dat)
if sent == len(dat):
traffic("<")
##if rec: rec.write("Client send: %s ...\n" % repr(dat[0:80]))
if rec: rec.write("%s,\n" % repr(">" + dat[1:-1]))
else:
cqueue.insert(0, dat[sent:])
traffic("<.")
##if rec: rec.write("Client send partial: %s\n" % repr(dat[0:send]))
if target in ins:
buf = target.recv(buffer_size)
if len(buf) == 0: raise Exception("Target closed")
cqueue.append(encode(buf))
traffic("{")
##if rec: rec.write("Target recv (%d): %s\n" % (len(buf), map(ord, buf)))
if client in ins:
buf = client.recv(buffer_size)
if len(buf) == 0: raise Exception("Client closed")
if buf[-1] == '\xff':
if buf.count('\xff') > 1:
traffic(str(buf.count('\xff')))
traffic("}")
##if rec: rec.write("Client recv (%d): %s\n" % (len(buf), repr(buf)))
if rec: rec.write("%s,\n" % repr(buf[1:-1]))
if cpartial:
tqueue.extend(decode(cpartial + buf))
cpartial = ""
else:
tqueue.extend(decode(buf))
else:
traffic(".}")
##if rec: rec.write("Client recv partial (%d): %s\n" % (len(buf), repr(buf)))
cpartial = cpartial + buf
def proxy_handler(client):
global target_host, target_port, options, rec
print "Connecting to: %s:%s" % (target_host, target_port)
tsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tsock.connect((target_host, target_port))
if options.record:
print "Opening record file: %s" % options.record
rec = open(options.record, 'w')
print traffic_legend
try:
do_proxy(client, tsock)
except:
if tsock: tsock.close()
if rec: rec.close()
raise
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option("--record", dest="record",
help="record session to a file", metavar="FILE")
(options, args) = parser.parse_args()
if len(args) > 3: parser.error("Too many arguments")
if len(args) < 3: parser.error("Too few arguments")
try: listen_port = int(args[0])
except: parser.error("Error parsing listen port")
try: target_host = args[1]
except: parser.error("Error parsing target host")
try: target_port = int(args[2])
except: parser.error("Error parsing target port")
start_server(listen_port, proxy_handler)