socat [options] <address> <address>
socat -V
socat -?[?]
filan
procan
Socat is a command line based utility that establishes two bidirectional byte streams and transfers data between them. Because the streams can be constructed from a large set of different types of data sinks and sources (see address types), and because lots of address options may be applied to the streams, socat can be used for many different purposes. It might be one of the tools that one `has already needed'.
Filan is a utility that prints information about its active file descriptors to stdout. It has been written for debugging socat, but might be useful for other purpses too.
Procan is a utility that prints information about process related system parameters to stdout. It has been written to better understand some UNIX process properties and for debugging socat, but might be useful for other purpses too.
The lifecycle of a socat instance typically consists of four phases.
In the init phase, the command line options are parsed and logging is initialized.
During the open phase, socat opens the first address and afterwards the second address. These steps are usually blocking; thus, for complex address types like socks, connection requests or authentication dialogs must be completed before the next step is started.
In the transfer phase, socat watches both streams' read file descriptors
via select()
, and, when data is available, reads it in portions of at most 8192
bytes (change with option -b), performs newline character
conversions if required, and writes the data to the other stream.
When one of the streams effectively reaches EOF, the closing phase begins. Socat tries to transfer the EOF condition to the other stream, giving it a chance to terminate gracefully.
Socat provides some command line options that modify the behaviour of the program. They have nothing to do with so called address options that are used as parts of address specifications.
-V
-?
-??
-d
-d -d
-d -d -d
-d -d -d -d
-D
-ly[<facility>]
-lf
<logfile>
-ls
-lm[<facility>]
-v
-x
-v
.
-b
<size>
-s
-t
<timeout>
-u
-g
With the address command line arguments, the user gives socat instructions and the necessary information for establishing the byte streams.
An address specification usually consists of an address type keyword, zero or more address parameters separated by ':' from the keyword and from each other, and zero or more address options separated by ','.
The keyword specifies the address type (e.g., TCP4, OPEN, EXEC). For some keywords there exist synonyms (- for STDIO, TCP for TCP4). Keywords are case insensitive. For a few special address types, the keyword may be omitted: Address specifications starting with a number are assumed to be FD addresses; if a '/' is found before the first ':' or ',', GOPEN is assumed.
The required number and type of address parameters depend on the address type. E.g., TCP4 requires a server name or server address, and a port or service specification.
Zero or more address options may be given with each address. Options are members of option groups. With each address type there is a set of option groups defined. Only options belonging to one of these address groups may be used (except with option -g). Options consist of an option keyword or an option keyword and a value, separated by '='. Option keywords are case insensitive.
Address specifications following the above schema are also called single address specifications. Two single addresses can be combined with "!!" to form a dual type address for one channel. Here, the first address is used by socat for reading data, and the second address for writing data. There is no way to specify an option only once for being applied to both single addresses.
Usually, addresses are opened in read/write mode. When an address is part of a dual address specification, or when option -u is used, an address might be used only for reading or for writing. Considering this is important with some address types.
This section describes the available address types with their keywords, parameters, and semantics.
CREATE:<filename>
creat()
and uses the file
descriptor for writing.
This address type requires write-only context.
<filename> must be a valid existing or not existing path.
If <filename> is a named pipe, creat()
might block;
if <filename> refers to a socket, this is an error.EXEC:<command-line>
execvp()
.
<command-line> is a simple command
with arguments separated by single spaces. If the program name
contains a '/', the part behind the last '/' is taken as ARGV[0]. If the
program name is a relative
path, the execvp()
semantics for finding the program via
$PATH
apply. After successful program start, socat writes data to stdin of the
process and reads from its stdout using a UNIX domain socket generated by
socketpair()
per default. FD:<fdnum>
GOPEN:<filename>
sendto()
calls.
If the entry is not a socket, socat opens it applying the O_APPEND
flag.
If it does not exist, it is opened with flag
O_CREAT
as a regular file.IP4:<host>:<protocol>
IP6:<host>:<protocol>
OPEN:<filename>
open()
system call.
This operation fails on UNIX domain sockets. PIPE:<filename>
PIPE
READLINE
SOCKS4:<socks-server>:<host>:<port>
SOCKS4A:<socks-server>:<host>:<port>
STDERR
STDIN
STDIO
STDOUT
SYSTEM:<shell-command>
system()
. Please note that
<shell-command> [string] must
not contain ',' or "!!", and that shell meta characters may have to be
protected.
After successful program start, socat writes data to stdin of the
process and reads from its stdout.TCP4:<host>:<port>
TCP4-LISTEN:<port>
TCP6:<host>:<port>
TCP6-LISTEN:<port>
UDP4:<host>:<port>
UDP4-LISTEN:<port>
UDP6:<host>:<port>
UDP6-LISTEN:<port>
UNIX-CONNECT:<filename>
UNIX-LISTEN:<filename>
Address options can be applied to address specifications to influence the process of opening the addresses and the properties of the resulting data channels.
For technical reasons not every option can be applied to every address type; e.g., applying a socket option to a regular file will fail. To catch most useless combinations as early as in the open phase, the concept of option groups was introduced. Each option belongs to one or more option groups. Options can be used only with address types that support at least one of their option groups (but see option -g).
Address options have data types that their values must conform to.
Every address option consists of just a keyword or a keyword followed by
"=value", where value must conform to the options type.
Some address options manipulate parameters of system calls;
e.g., option sync sets the O_SYNC
flag with the open()
call.
Other options cause a system or library call; e.g., with option `ttl=value'
the setsockopt(fd, SOL_IP, IP_TTL, value, sizeof(int))
call is applied.
Other
options set internal socat variables that are used during data transfer;
e.g., `crnl' causes explicit character conversions.
A few options have more complex implementations; e.g., su-d
(substuser-delayed) inquires some user and group infos, stores them, and
applies them later after a possible chroot()
call.
If multiple options are given to an address, their sequence in the address specification has (almost) no effect on the sequence of their execution/application. Instead, socat has built in an option phase model that tries to bring the options in a useful order. Some options exist in different forms (e.g., unlink, unlink-early, unlink-late) to control the time of their execution.
If the same option is specified more than once within one address
specification, with equal or different values, the effect depends on the kind of option. Options
resulting in function calls like setsockopt()
cause multiple
invokations. With options that set parameters for a required call like
open()
or set internal flags, the value of the last option occurrence is effective.
The existence or semantics of many options are system dependent. Socat usually does NOT try to emulate missing libc or kernel features, it just provides an interface to the underlying system. So, if an operating system lacks a feature, the related option is simply not available on this platform.
The following paragraphs introduce just the more common address options. For
a comprehensive reference and to find information about canonical option names,
alias names, option phases, and platforms see file xio.help.
FD option group
This option group contains options that are applied to a UN*X
style file descriptor, no matter how it was generated.
Because all current socat address types are file descriptor based, these
options may be applied to any address.
Note: Some of these options are also member of another option group, that
provides an other, non-fd based mechanism.
For these options, it depends on the actual address type and its option groups
which mechanism is used. The second, non-fd based mechanism is prioritized.
cloexec=<bool>
FD_CLOEXEC
flag with the fcntl()
system call to value
<bool>. If set,
the file descriptor is closed on exec()
family function calls. Socat
internally handles
this flag for the fds it controls, so in most cases there will be no need to
apply this option.
setlk
fcntl(fd,
F_SETLK, ...)
system call. If the file is already locked, this call results
in an error.
setlkw
fcntl(fd, F_SETLKW, ...)
system call. If the file is already locked,
this call blocks.
flock
flock(fd, LOCK_EX)
system call.
lock
user=<user>
chown()
system call after opening the
file or binding to the UNIX domain socket (race condition!).
Otherwise (without filesystem entry), socat sets the user of the stream
using the fchown()
system call.
These calls might require root privilege.
user-late=<user>
fchown()
system call after opening
or connecting the channel.
This is useful only on file system entries.
group=<group>
chown()
system call after opening the
file or binding to the UNIX domain socket (race condition!).
Otherwise (without filesystem entry), socat sets the group of the stream
with the fchown()
system call.
These calls might require group membership or root privilege.
group-late=<group>
fchown()
system call after opening
or connecting the channel.
This is useful only on file system entries.
mode=<mode>
open()
or creat()
call, the mode is applied with these.
If the address is member of the NAMED option group without using these
system calls, socat uses the chmod()
system call after opening the
filesystem entry or binding to the UNIX domain socket (race condition!).
Otherwise, socat sets the mode of the stream
using fchmod()
.
These calls might require ownership or root privilege.
perm-late=<mode>
fchmod()
system call after
opening or connecting the channel.
This is useful only on file system entries.
append=<bool>
O_APPEND
flag with the open()
system call.
Otherwise, socat applies the fcntl(fd, F_SETFL, O_APPEND)
call.
nonblock=<bool>
connect()
call of TCP addresses does not block, and that opening a
named pipe for reading does not block.
If the address is member of the OPEN option group,
socat uses the O_NONBLOCK
flag with the open()
system call.
Otherwise, socat applies the fcntl(fd, F_SETFL, O_NONBLOCK)
call.
NAMED option group
These options work on file system entries.
See also options user, group, and
mode.
user-early=<user>
chown()
system call. This call might require root privilege.
group-early=<group>
chown()
system call. This call might require group membership or root
privilege.
perm-early=<mode>
chmod()
system call. This call might require ownership or root
privilege.
umask=<mode>
unlink-early
unlink
unlink-late
OPEN option group
The OPEN group options allow to set flags with the open()
system call.
E.g., option `creat' sets the O_CREAT
flag.
See also options append and
nonblock.
creat=<bool>
dsync=<bool>
write()
calls until metainfo is physically written to media.
excl=<bool>
largefile=<bool>
noctty=<bool>
nofollow=<bool>
nshare=<bool>
rshare=<bool>
rsync=<bool>
write()
until metainfo is physically written to media.
sync=<bool>
write()
until data is physically written to media.
rdonly=<bool>
wronly=<bool>
trunc
ftruncate()
system call.
REG and BLK option group
These options are usually applied to a UN*X file descriptor, but their semantics make sense only on a file supporting random access.
seek=<offset>
lseek(fd, <offset>, SEEK_SET)
system call, thus
positioning the file pointer absolutely to <offset> [long].
seek-cur=<offset>
lseek(fd, <offset>, SEEK_CUR)
system call, thus
positioning the file pointer <offset> [long] bytes
relatively to its current position (which is usually 0).
seek-end=<offset>
lseek(fd, <offset>, SEEK_END)
system call, thus
positioning the file pointer <offset> [long] bytes
relatively to the files current end.
PROCESS option group
Options of this group change the process properties instead of just affecting one data channel. For EXEC and SYSTEM addresses and for LISTEN type addresses with option FORK, these options apply to the child processes instead of the main socat process.
chroot=<directory>
chroot()
operation to <directory>
after processing the address. This call might require root privilege.
chroot-early=<directory>
chroot()
operation to <directory>
before opening the address. This call might require root privilege.
setgid=<group>
setgid-early=<group>
setuid=<user>
setuid-early=<user>
su=<user>
su-d=<user>
substuser-delayed
.
Changes the <user>
(owner) and groups of the process after processing the address.
The user and his groups are retrieved before a possible
chroot()
. This call might require root privilege.
READLINE option group
These options apply to the readline address type.
history=<filename>
APPLICATION option group
This group contains options that work at data level.
cr
crnl
ignoreeof
SOCKET option group
These options are intended for all kinds of sockets, e.g. IP or UNIX domain. Most are applied with a setsockopt()
call.
bind=<sockname>
bind()
system
call. The form of <sockname> is socket domain dependent:
IP4 and IP6 allow the form [hostname|hostaddress][:[service|port]],
UNIX domain sockets require <filename>.
interface=<interface>
broadcast
bsdcompat
debug
dontroute
keepalive
linger=<seconds>
shutdown()
or close()
until data transfers have finished
or the given timeout [int] expired.
oobinline
priority=<priority>
rcvbuf=<bytes>
socket()
call to
<bytes> [int]. With TCP
sockets, this value correspondends to the socket's maximal window size.
rcvbuf-late=<bytes>
rcvlowat=<bytes>
rcvtimeo=<seconds>
reuseaddr
sndbuf=<bytes>
socket()
call to
<bytes> [int].
sndbuf-late=<bytes>
sndlowat=<bytes>
sndtimeo=<seconds>
type=<type>
socket()
or
socketpair()
call, to <type> [int].
Under Linux, 1 means stream oriented socket, 2 means datagram socket, and 3
means raw socket.
IP option group
These options can be used with IPv4 and IPv6 based sockets.
tos=<tos>
ttl=<ttl>
ipoptions=<data>
ipoptions=x8307040a000001
.mtudiscover=<0|1|2>
TCP option group
These options may be applied to TCP sockets. They work by invoking setsockopt()
with the appropriate parameters.
cork
defer-accept
keepcnt=<count>
keepidle=<seconds>
keepintvl=<seconds>
linger2=<seconds>
mss=<bytes>
socket()
call to <bytes>
[int]. This
value is then proposed to the peer with the SYN or SYN/ACK packet.
mss-late=<bytes>
nodelay
rfc1323
stdurg
syncnt=<count>
UDP and TCP option groups
Here we find options that are related to the network port mechanism and that thus can be used with UDP and TCP addresses.
sourceport=<port>
bind()
call.
SOCKS option group
When using SOCKS type addresses, some socks specific options can be set.
socksport=<port>
socksuser=<user>
RANGE option group
The range option can be applied to listening network sockets.
range=<address-range>
LISTEN option group
Options specific to listening sockets.
backlog=<count>
listen()
system call to <count>
[int]. Default is 5.
CHILD option group
Options for listen addresses with child processes.
fork
EXEC option group
Options for addresses that invoke a program.
path=<string>
$PATH
value is effective in the child process too.
login
argv[0]
for the execvp()
call with '-', thus making a
shell behave as login shell.
FORK option group
EXEC or SYSTEM addresses invoke a program using a child process and transfer data between socat and the program. The interprocess communication mechanism can be influenced with the following options. Per
default, a socketpair()
is created and assigned to stdin and stdout of
the child process, while stderr is inherited from the socat process, and the
child process uses file descriptors 0 and 1 for communicating with the main
socat process.
pipes
openpty
openpty()
instead of a socket pair.
ptmx
pty
ctty
stderr
dup()
of stdout.
fdin=<fdnum>
fdout=<fdnum>
setpgid=<pid_t>
setsid
TERMIOS option group
For addresses that work on a tty (e.g., stdio, file:/dev/tty, exec:...,pty), the terminal parameters defined in the UN*X termios mechanism are made available as address option parameters. Please note that changes of the parameters of your interactive terminal remain effective after socat's termination, so you might have to enter "reset" or "stty sane" in your shell afterwards. For EXEC and SYSTEM addresses with option PTY, these options apply to the pty by the child processes.
echo=<bool>
icanon=<bool>
raw
ignbrk=<bool>
echoctl=<bool>
opost=<bool>
sane
This section explains the different data types that address parameters and address options can take.
strtoul()
, lower or equal to
UCHAR_MAX
.
strtoul()
, specifying a UN*X file
descriptor.
strtoul()
as unsigned integer specifying a group id. Otherwise, it
must be an existing group name.
strtol()
function with base
"0", i.e. decimal number, octal number with leading "0", or hexadecimal
number with leading "0x". The value must fit into a C int.
gethostbyname()
, or an
address in numbers-and-dots notation.gethostbyname()
, or an
address in hexnumbers-and-colons notation.strtol()
. The value must fit into a C long.
strtoul()
, specifying mode (permission)
bits.
strtol()
, specifying a process id.
strtoul()
.
strtoul()
.
strtoul
.
getservbyname()
, or an unsigned int 16 bit number read with
strtoul()
.
getservbyname()
, or an unsigned int 16 bit number read with
strtoul()
.
strtoul()
. The value must fit into a C unsigned
int.
strtoul()
as unsigned integer specifying a user id. Otherwise, it must
be an existing user name.
socat - TCP4:www.domain.org:80
Transfers data between STDIO (-) and a TCP4 connection to port 80 of host www.domain.org. This example results in an interactive connection similar to telnet or netcat. The stdin terminal parameters are not changed, so you may close the relay with ^D or abort it with ^C.
socat -d -d READLINE,history=$HOME/.http_history \
TCP4:www.domain.org:www,crnl
This is similar to the previous example, but you can edit the current line in a bash like manner (READLINE) and use the history file .http_history; socat prints messages about progress (-d -d). The port is specified by service name (www), and correct network line termination characters (crnl) instead of NL are used.
socat TCP4-LISTEN:www TCP4:www.domain.org:www
Installs a simple TCP port forwarder. With TCP4-LISTEN it listens on local port "www" until a connection comes in, accepts it, then connects to the remote host (TCP4) and starts data transfer. It will not accept a second connection.
socat -d -d -lmlocal2 \
TCP4-LISTEN:80,bind=myaddr1,su=nobody,fork,range=10.0.0.0/8,reuseaddr \
TCP4:www.domain.org:80,bind=myaddr2
TCP port forwarder, each side bound to another local IP address
(bind). This example handles an almost
arbitrary number of parallel or consecutive connections by
fork'ing a new
process after each accept()
. It provides a little security by
su'ing to user
nobody after forking; it only permits connections from the private 10 network (range);
due to reuseaddr, it allows immediate restart after master process's
termination, even if some child sockets are not completely shut down.
With -lmlocal2, socat logs to stderr until successfully
reaching the accept loop. Further logging is directed to syslog with facility
local2.
socat TCP4-LISTEN:5555,fork \
EXEC:/bin/myscript,chroot=/home/sandbox,su-d=sandbox,pty,stderr
A simple server that accepts connections (TCP4-LISTEN) and fork's a new child process for each connection; every child acts as single relay. For EXEC'uting the program, it chroot's to /home/sandbox, su's to user sandbox, and then starts the program /home/sandbox/bin/myscript. Socat and myscript communicate via a pseudo tty (pty); myscript's stderr is redirected to stdout, so its error messages are transferred via socat to the connected client.
socat EXEC:"mail.sh target@domain.com",fdin=3,fdout=4 \
TCP4:mail.relay.org:25,crnl,bind=alias1.server.org,mss=512
mail.sh is a shell script, distributed with socat, that implements a simple SMTP client. It is programmed to "speak" SMTP on its FDs 3 (in) and 4 (out). The fdin and fdout options tell socat to use these FDs for communication with the program. Because mail.sh inherits stdin and stdout while socat does not use them, the script can read a mail body from stdin. Socat makes alias1 your local source address (bind), cares for correct network line termination (crnl) and sends at most 512 data bytes per packet (mss).
socat - /dev/ttyS0,raw,echo=0,crnl
Opens an interactive connection via the serial line, e.g. for talking with a modem. raw and echo set ttyS0's terminal parameters to practicable values, crnl converts to correct newline characters. Consider using READLINE instead of `-'.
socat UNIX-LISTEN:/tmp/.X11-unix/X1,fork \
SOCKS4:host.victim.org:127.0.0.1:6000,socksuser=nobody,sourceport=20
With UNIX-LISTEN, socat opens a listening UNIX domain socket /tmp/.X11-unix/X1. This path correspondents with local XWindow display :1 on your machine, so XWindow client connections to DISPLAY=:1 are accepted. Socat then speaks with the SOCKS4 server host.victim.org that might permit sourceport 20 based connections due to an FTP related weakness in its static IP filters. Socat pretends to be invoked by socksuser nobody, and requests to be connected to loopback port 6000 (only weak sockd configurations will allow this). So we get a connection to the victims XWindow server and, if it does not require MIT cookies or Kerberos authentication, we can start work. Please note that there can only be one connection at a time, because TCP can establish only one session with a given set of addresses and ports.
socat -u /tmp/readdata,seek-end=0,ignoreeof -
This is an example for unidirectional data transfer (-u). Socat transfers data from file /tmp/readdata (implicit address GOPEN), starting at its end (seek-end=0 lets socat start reading at current end of file; use seek=0 or no seek* options at all to work through existing file data) in a "tail -f" like mode (ignoreeof). The "file" might also be a listening UNIX domain socket (do not use seek-* then).
(echo PASSWORD; sleep 5; echo ls; sleep 1) |
socat - EXEC:'ssh -l user server',pty,setsid,ctty
EXEC'utes an ssh session to server. Uses a pty for communication between socat and ssh, makes it ssh's controlling tty (ctty), and makes this pty the owner of a new process group (setsid), so ssh accepts the password from socat.
socat -u TCP4-LISTEN:3334,reuseaddr,fork \
OPEN:/tmp/in.log,creat,append
Implements a simple network based message collector. For each client connecting to port 3334, a new child process is generated (option fork). All data sent by the clients are append'ed to the file /tmp/in.log. If the file does not exist, socat creat's it. Option reuseaddr allows immediate restart of the server process.
socat readline exec:'ftp ftp.server.com',pty
Wraps a command line history around the ftp client utility. This allows editing and reuse of FTP commands for relatively comfortable browsing through the ftp directory hierarchy. The password is read directly from the terminal and therefore not echoed. Nevertheless, there may occur some confusion with the password and FTP prompts.
Socat uses a logging mechanism that allows to filter messages by severity. The severities provided are more or less compatible to the appropriate syslog priority. With one or up to four occurrences of the -d command line option, the lowest priority of messages that are issued can be selected.
Log messages can be written to stderr, to a file, or to syslog.
On exit, socat gives status 0 if it terminated due to EOF or inactivity timeout, with a positive value on error, and with a negative value on fatal error.
/usr/local/bin/socat
/usr/local/bin/filan
/usr/local/bin/procan
The work of the following groups and organizations was invaluable for this project:
The FSF (GNU, http://www.fsf.org/ project with their free and portable development software and lots of other useful tools and libraries.
The Linux developers community (http://www.linux.org/) for providing a free, open source operating system.
Sourceforge (http://www.sourceforge.net/) for providing a compile farm with Solaris, FreeBSD, and MacOS X machines, making these ports possible.
The Open Group (http://www.unix-systems.org/) for making their standard specifications available on the Internet for free.
This man page describes version 1.1.0 of socat.
In address specifications, characters with special meaning (':', ',', '!!') cannot be escaped, so it is hardly possible to directly invoke a second socat instance from an exec type addresses.
IPv6 address specification does not allow '[' and ']'.
Send bug reports to <socat@dest-unreach.org>
nc(1), sock(1), rinetd(8), cage(1)
Socat home page http://www.dest-unreach.org/socat/
Gerhard Rieger <rieger@dest-unreach.org>