Unix Network Programming
Unix Network Programming
with TCP/IP
UNIX Network
Programming with TCP/IP UNIX
Network Programming
with TCP/IP
http://www.hiraeth.com/alan/tutorials
Course
UNIX
Network Programming
with TCP/IP
Outline
Alan Dix
http://www.hcibook.com/alan
Session 5 Servers I
Session 6 Servers II
Session 7 Security
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 1
UNIX Network Programming
with TCP/IP Reading
Books:
1. W. Richard Stevens, "TCP/IP Illustrated. Vol. 1: The protocols", Addison
Wesley, 1994, (ISBN 0-201-63346-9).
Explains the protocols using network monitoring tools without programming.
See also:
• your local manual pages (man 2)
• RFCs
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2
UNIX
Network Programming
with TCP/IP
UNIX
Network Programming
with TCP/IP
UNIX
Network Programming
with TCP/IP
Session 1 UNIX
Network Programming
with TCP/IP
• origins
• internets and the Internet
• protocol layers
• addressing
• common applications
☞ using them
• TCP and UDP
• port numbers
• APIs
☞ information calls
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 1
Origins
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2
internets and the Internet
an internet is
a collection of
• interconnected networks
• (possibly different)
e.g. X25, AppleTalk
the Internet is
a particular internet which
• uses the TCP/IP protocols
• is global
• is hardware and network independent
• is non-proprietary
in addition
• supports commonly used applications
• publicly available standards (RFCs)
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3
Characteristics of the Internet
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 4
Global Connectivity
ethernet
routers
token ring
sub-network
PPP
star
network router
lots of networks:
• ethernet, FDDI, token ring
• AppleTalk (itself an internet!)
• etc. etc. etc.
connected (possibly indirectly)
• to each other
• to the central ‘ARPAnet’ backbone in the US
protocols can be used in isolation
? but is it the Internet
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 5
Protocols – the Language of the
Internet
TCP/IP OSI
electrical signals Physical
IP layer (end-to-end)
routers Network
ICMP (control and routing)
Standardisation:
• RFC (request for comments) and DoD MIL
RFCs also include (defined but not required):
• PPP, ethernet packaging, etc.
• FTP and other protocols
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6
Addressing
J. C. T. Jennings,
Linbury Court School,
Dunhambury,
Sussex,
England,
Europe,
Eastern Hemisphere,
Earth,
near Moon,
Solar System,
Space,
near More Space†
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7
IP addresses
• 32 bit integer – 2701966503
• Often represented as 4 octets – 161.12.188.167
• General structure:
net id { sub-net id } host id
• N.B. octets do not map simply onto components
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 8
Domain names
• Decentralised administration
• Mapping
from name to IP address
– domain name servers
also reverse mapping
• C API :
gethostbyname – name → IP address
gethostbyaddr – IP address → name
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 9
Common applications
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 10
Hands on
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 11
Network communications
• Connectionless
❍ address every message
❈ like letters
• Connection based
❍ use address to establish a fixed link
❍ send each message using the link
❈ like telephone
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 12
Network communications – 2
Other issues:
• Reliability
Do all messages arrive?
Do they arrive in the right order?
• Buffering
effects responsiveness
hides potential deadlock
• Messages or byte-stream
sent:
write 1 (len=26): “abcde....vwxyz”
write 2 (len=10): “0123456789”
received:
read 1 (len=20): “abcde....qrst”
read 2 (len=16): “uvwxyz012...89”
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 13
IP – the fundamental Internet protocol
point to point
❍ between machines
❍ addressed using IP address
unreliable
❍ network failures
❍ router buffers fill up
dynamic routing
⇒ order may be lost
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 14
TCP & UDP
Both
• built on top of IP
• addressed using port numbers
process to process
(on UNIX platforms)
TCP
• connection based
• reliable
• byte stream
used in: FTP, telnet, http, SMTP
UDP
• connectionless
• unreliable
• datagram (packet based)
used in: NFS, TFTP
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 15
Port numbers
• 16 bit integers
• unique within a machine
• to connect need IP address + port no
TCP
• connection defined by
IP address & port of server
+ IP address & port of client
UNIX
• port < 1023 – root only
• used for authentication
(e.g. rlogin)
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 16
Well known port numbers
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 17
API – the language of the programmer
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 18
Hands on
gethostname(buff,len)
returns error code
puts name into buff (maximum len bytes)
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 19
UNIX
Network Programming
with TCP/IP
UNIX
Network Programming
with TCP/IP
UNIX
Network Programming
with TCP/IP
Session 2 UNIX
Network Programming
with TCP/IP
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2/1
Sockets
• developed for Berkeley UNIX
❍ recall early Berkeley TCP/IP implementation
❍ first delivered with BSD 2.1
• central features
❍ central abstraction - the socket - an end-point
like an electrical connector
❍ not TCP/IP specific (e.g. UNIX named pipes)
❍ uses normal read/write system calls
❍ sockets associated with UNIX file descriptors
but some not for normal I/O
❍ some extra system calls
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2/2
Establishing a TCP Connection
Initial State
Internet
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2/3
Establishing a TCP Connection
Passive Open
21
151.100.17.25
server
161.112.192.5
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2/4
Establishing a TCP Connection
Active Open
161.112.192.5 : 21
21
2397
server
client 161.112.192.5
151.100.17.25
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2/5
Establishing a TCP Connection
Rendezvous
21
client server
151.100.17.25 161.112.192.5
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2/6
Establishing a TCP Connection
and more ...
21
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2/7
Passive & Active Open
passive active
waits for request for sends out request for
connection connection
waits for ever times out
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2/8
Simple client/server ‘talk’
• strict turntaking
user 1 user 2
zeus: s i m p l e - s e r v e r
start up complete
io: s i m p l e - c l i e n t - h o s t z e u s
You can send now
speak: h i t h e r e
client says: hi there
speak: n i c e d a y i s n ' t i t
server says: nice day isn't it
speak: b i t c o l d h e r e
client says: bit cold here
speak: ^D (EOF) bye bye
zeus:
server finished the conversation
io:
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2/9
Server Code
establish port
port_sk = tcp_passive_open(port)
/* only done once */
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2/10
Client Code
request connection to server
serv_sk = tcp_active_open(host,port)
/* waits for server to accept */
/* returns negative on failure */
/* host is server’s machine */
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2/11
☞ ☞ ☞ ☞ Hands on ✍ ✍ ✍ ✍
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2/12
read & write
Reminder:
ret = read(fd,buff,len)
int fd – a file descriptor (int), open for reading
char *buff – buffer in which to put chars
int len – maximum number of bytes to read
int ret – returns actual number read
ret = write(fd,buff,len)
int fd – a file descriptor (int), open for writing
char *buff – buffer from which to get chars
int len – number of bytes to write
int ret – returns actual number written
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2/13
read & write with sockets
• similar to normal UNIX pipes
• bi-directional byte stream
❍ read and write to same file descriptor
✘ difficult to close one direction
✔ special socket call shutdown(sock,dir)
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2/14
Wrapper Functions (1)
port_sk = tcp_passive_open(port)
server performs passive open
serv_sk = tcp_active_open(host,port)
client performs active open
client_sk = tcp_accept(port_sk)
server accepts client connection
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2/15
Wrapper Functions (2)
ret = parse_network_args( &argc, argv,
&host, &port, &errmess )
port_sk = tcp_passive_open(port)
int port – port number to use
int port_sk – file descriptor of socket
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2/16
Wrapper Functions (3)
serv_sk = tcp_active_open(hostname,port)
char *hostname – name of server’s machine
int port – port number to use
int serv_sk – file descriptor of socket
client_sk = tcp_accept(port_sk)
int port_sk – file descriptor of socket
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2/17
Special IP addresses
0.0.0.0
• source only
• default IP address – ‘local machine’
• filled in by socket API call
127.0.0.0
• loopback address,
• also means ‘the local machine’
• usually used as recipient for local server
• doesn’t normally hit network
• N.B. can also connect to own IP address
255.255.255.255
• limited broadcast (doesn’t pass routers)
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2/18
☞ ☞ ☞ ☞ Hands on ✍ ✍ ✍ ✍
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 2/19
UNIX
Network Programming
with TCP/IP
UNIX
Network Programming
with TCP/IP
UNIX
Network Programming
with TCP/IP
Session 3 UNIX
Network Programming
with TCP/IP
Application UNIX
Network Programming
Protocols
with TCP/IP
Session 3
UNIX
Network Programming
with TCP/IP Alan Dix
http://www.hcibook.com/alan
Standard Applications
• trusted login – rlogin
• negotiating options – telnet
• world wide web– http
☞ peeking
• file transfer – ftp
• standard response codes
• electronic mail – SMTP
☞ drive it by hand
• argc , argv & makefiles
☞ build your own mail client
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/1
Types of Protocol
user character stream
❍ used by remote terminal/login applications
( rlogin & telnet )
❍ most of the traffic is uninterpretted data
❍ some embedded control sequences
binary protocols
❍ used for low level protocols:
TCP/IP itself!
SNMP – simple network management protocol
NFS (built on top of RPC – remote procedure call)
❍ issues such as byte order important
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/2
Remote Terminal Access:
rlogin and telnet
• one of the earliest Internet application areas
• the client end – interacts with the user
• the server end – shell or command interpreter
Internet
➅
client
➀
➁ ➄
➂
shell server
➃
basic pattern:
① user types characters
② the client sends them to the server
③ the server passes them on to the shell
④ shell generates output
⑤ server passes output to client
⑥ client puts output on user’s screen
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/3
Remote Terminals – Issues
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/4
rlogin
• simple stable protocol
• responsibility
❍ echoing – server
❍ flow-control – client on server request
• client–server communication
❍ client→server initialisation string
❍ client→server window size change:
ctrl chars – 2 bytes of 255
followed by window size in 2 bytes
no protection against user typing it!
❍ server→client requests:
special characters (bytes x02,x10,x20,x80)
marked by URG (urgent) pointer
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/5
Urgent Data
• sometimes called out-of-band data
. . . but it’s not!
URG pointer
Berkeley URG pointer!
• client should:
① read until urgent data reached
② if necessary discard intervening data
(e.g. if insufficient buffer space to store it)
problem with ①
❍ URG pointer says where it ends . . .
. . . but how do you know where it starts?
❍ have to have special codes again
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/6
telnet
• client authentication
❍ not in protocol – application specific
e.g. getty
• responsibility
❍ client may handle echoing, line editing etc.
subject to option negotiation
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/7
telnet – 2
control codes
• introduced by byte 255
❍ called: IAC – interpret as command
• following byte is actual control code
examples:
255 – the actual byte 255 (needed for binary mode)
236 – end of file
241 – no op
243 – break
option negotiation control codes:
251 – WILL
252 – WONT
253 – DO
254 – DONT
250 – sub-option begin
240 – sub-option end
option negotiation
• many different options:
❍ echoing ❍ line editing,
❍ flow control ❍ window size information
• client and server play “will you/wont you”
to determine common protocol
• just like fax machines and modems
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/8
http
• protocol:
❍ ASCII control messages
❍ standard data formats for pages/images
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/9
☞ ☞ ☞ ☞ Hands on ✍ ✍ ✍ ✍
peeking
☞ use the program proxy in tcp/session3
☞ it sits between client and server
☞ use it to see how http works:
① run: proxy www.hud.ac.uk 80 -port 8800
② start up Netscape using background menu
③ go to the url:
http://www.hud.ac.uk/schools/comp+maths/private/alan/alandix.html
④ now edit the host name in the url field
if your machine is io
change //www.hud.ac.uk to //io.hud.ac.uk:8800
the 8800 is to set the port number used by proxy
⑤ hit return and watch the proxy window
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/10
File Transfer Protocol
FTP
• used to transfer files and list directory contents
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/11
FTP - 2
control and data
control connection
❍ server waits (passive open) on port 21
❍ client establishes connection (active open)
❍ client sends ascii commands – one per line
❍ server responds: single or multi-line response
❍ when required a data connection is established
data connection
❍ client performs a passive open on some port
(may leave OS to determine port number)
❍ client tells server using control connection
PORT 161.112.192.5.9.93
port 2397 (=9*256+93) on host 161.112.192.5
when data transfer is required
❍ client sends appropriate command
e.g. GET simple-client.c
then waits listening for connection
❍ server performs an active open on port
then sends data
❍ server tells client when transfer is complete
e.g. 226 Transfer complete.
then both sides (usually) close the data port
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/12
standard response codes
• ftp server replies with lines such as:
200 PORT command successful
• multi-line response
either:
hyphen means ‘more to come’
999-first line
999-one or more further lines
999 the last line
space here on last line
or
999-first line
lots of lines all starting with
at least one space
999 the last line
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/13
Simple Mail Transfer Protocol
SMTP
• allows:
❍ mail client (user interface) to send via server
❍ servers to talk to one another
(one server takes ‘client’ role)
• note:
• not used by user interface for receipt
• sendmail is common SMTP server under UNIX
• client commands:
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/14
SMTP – 2
❍ blank line
❍ body
Russell,
have you heard from Prentice Hall
yet concerning the web pages?
Alan
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/15
☞ ☞ ☞ ☞ Hands on ✍ ✍ ✍ ✍
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/16
☞ ☞ ☞ ☞ Hands on ✍ ✍ ✍ ✍
drive it by hand
☞ use telnet to send a message
type:
telnet zeus.hud.ac.uk 25
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/17
argc & argv
• recall: int main( int argc, char **argv ) ...
or: int main( int argc, char *argv[ ] ) ...
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/18
Make
‘make’ is a UNIX† command which:
• automates program construction and linking
• tracks dependencies
• keeps things up-to-date after changes
to use it:
❍ construct a file with rules in it
you can call it anything, but ‘makefile’ is the default
❍ run ‘make’ itself
make target
– (uses the default makefile)
make -f myfile target
– (uses the rule file myfile)
either rebuilds the program ‘target’ if necessary
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/19
Makefile format
Definitions
• general form:
variable = value
• example:
SDIR = tcp
MYLIBS = $(SDIR)/lib
N.B. one variable used in another's definition
• make variables are referred to later using $
e.g. $(SDIR), $(MYLIBS)
• expanded like #defines or shell variables
(some versions of make will expand shell variables also)
this says:
to make myprog you need myprog.o and another.o
if either of them is newer than myprog rebuild it using the
then rebuild it using the command: “cc -o myprog ...”
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/20
Helper Functions
standard response lines
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/21
Helper Functions – 2
for sending mail
int do_mail_init(int serv_fd);
All optionally echo all exchanges to a file (or terminal) set by:
FILE *do_mail_set_echo_fp(FILE *new_echo_fp)
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/22
☞ ☞ ☞ ☞ Hands on ✍ ✍ ✍ ✍
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/23
☞ ☞ ☞ ☞ Hands on ✍ ✍ ✍ ✍
mail client – 2
☞ resulting program structure:
(a) read (parse) to/from addresses from user
(b) read message from user (gets or scanf)
(c) open tcp connection to mail server on correct port
(d) wait for server response line(s)
(e) say hello to server
(f) wait for server response line(s)
(g) say who the mail is from
(h) wait for server response line(s)
(i) say who the mail is to
(j) wait for server response line(s)
(k) say that data is coming
(l) wait for server response line(s)
(m) send one line message
(n) send line with just full stop
(o) wait for server response line(s)
(p) say goodbye
(q) wait for server response line(s)
(r) close connection
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 3/24
UNIX
Network Programming
with TCP/IP
UNIX
Network Programming
with TCP/IP
UNIX
Network Programming
with TCP/IP
Session 4 UNIX
Network Programming
with TCP/IP
Concurrent UNIX
Network Programming
Clients
with TCP/IP
Session 4
UNIX
Network Programming
with TCP/IP Alan Dix
http://www.hcibook.com/alan
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 4/1
Sequential Clients
e.g. FTP
1. client waits for user input
2. user types “DIR”
3. client performs passive open on data port (2397)
4. client sends “PORT 161.112.192.5.9.93” to server
5. client waits for standard ‘200’ reply line
6. if not OK then fail
7. client sends “LIST” to server
8. client waits for standard ‘150’ reply line
9. if not OK then fail
10. client reads from data port
11. client waits for standard ‘226’ reply line
12. if not OK then fail
13. report success to user
• client is in control
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 4/2
Naturally Concurrent Clients
e.g. telnet
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 4/3
Concurrency for Usability
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 4/4
Programming Concurrency
Problem
• doing more than one thing at once
listening user terminal & TCP server port
Solutions
• polling
❍ use non-blocking I/O
✘ keeps processor busy
• threads
❍ needs built-in support (language or OS)
❍ program written as several sequential parts
❍ all executed at the same time
❍ communicate using shared data
(also semaphores etc.)
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 4/5
Event Loop
✓ programmer in control
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 4/6
Event–Based Languages
e.g. HyperCard
on mouseUp
set cursor to watch
put getServerAddress() into serverAddr
put getUserName() into userName
put cd fld "ToOrFrom" into toName
put cd fld "Message" into theMess
send "toServerSendMail" ¬
&& quote & toName & quote & comma ¬
&& quote & userName & quote & comma ¬
&& quote & theMess & quote ¬
to program serverAddr
end mouseUp
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 4/7
Call-backs
General pattern
Program
① define a function
② tell toolkit to attach it to event
③ give control to the toolkit
Toolkit
❊ when event happens
call user defined function
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 4/8
Example – X Motif Call-backs
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 4/9
What’s going on?
Sequential Programs
for ( ; ; ) { /* N.B. pseudo-C !!! */
gets(command);
if ( . . . )
if ( command is "quit" ) {
char response[MAX_LINE_SIZE+1]; ← ②
write(serv_sd,"QUIT\n",5);
①☞ read(serv_fd,response,MAX_LINE_SIZE);
if ( response[0] != '2' ) . . .
printf("session complete\n");
exit(0);
}
if ( . . . )
}
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 4/10
What’s going on? - 2
sequential concurrent
implicit explicit
• local variables
global variables
or dynamic data structures
e.g. partial line of user input
• program counter
mode variable
or finite state machines!
e.g. TELNET command sequences
server output modes:
① normal echoing
② waiting for command
③ waiting for option
not byte 255
253 – DO
byte 255 254 – DONT
1 2 3 any
other bytes option
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 4/11
Callback based client – 1
➀ Initialisation
main(...) {
/* request connection to server */
sd = tcp_active_open(host,port)
/* set-up callback for server */
inform_input(sd,read_socket,NULL);
/* set-up call-backs for interface */
...
/* give control to toolkit */
inform_loop();
}
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 4/12
Callback based client – 2
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 4/13
☞ ☞ ☞ ☞ Hands on ✍ ✍ ✍ ✍
an electronic conference
☞ copy the following from tcp/session4:
client.c
server.c
make4
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 4/14
UNIX
Network Programming
with TCP/IP
UNIX
Network Programming
with TCP/IP
UNIX
Network Programming
with TCP/IP
Session 5 UNIX
Network Programming
with TCP/IP
• types of server
• handling server concurrency
• server state
• stateless servers
• when things go wrong!
• survival – the 3 Rs
• callback–based server
☞ modify server
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 5/1
Servers
Kinds of server
① transaction based
e.g. database: 1 query → 1 result
② strict turn-taking
e.g. ftp
③ inherent concurrency
e.g. electronic conferences, MUDs
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 5/2
Server Concurrency
• in addition:
❍ when no intrinsic concurrency
❍ can use UNIX fork
✓ launch separate process to serve each client
so each is simpler
✓ uses standard UNIX process concurrency
✘ can be expensive (process creation)
especially with lots of small transactions
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 5/3
Server State
✘. disaster scenarios
❍ client establishes connection
❍ client crashes
❍ client restarts
❍ client establishes a new connection
❍ it crashes again ...
✓ solution – no state
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 5/4
Stateless Servers
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 5/5
When things go wrong
• probability of failure:
clients – prob. of failure = p
server – prob. of failure = q
n clients and only 1 server, so:
probability of some failure ≈ np+q
• good news!
❍ server failure less likely (or is it?)
• bad news!
❍ servers are more complex (q > p)
❍ what if client brings server down?
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 5/6
Causes of failure
➀ hardware failures
➁ programming errors
➂ unforeseen sequences of events
➃ system does not scale
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 5/7
Survival
• reconfigure
detect and respond to failure
• time-out or failure of I/O operations
• reset internal data structures
• inform other clients
• resynchronise
catch up when client restarts
• similar to new client
• N.B. client may not know (network)
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 5/8
Software faults
Defensive programming
• inconsistent client/server data structures
Verify
• close hand checks
• for production code – formal methods
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 5/9
Callback based server – 1
➀ Initialisation
main(...) {
/* establish port */
pd = tcp_passive_open(port)
/* set-up callback for port */
inform_input(pd,accept_client,NULL);
/* give control to notifier */
inform_loop();
}
accept_client(...) {
/* accept client’s connection */
fd = tcp_accept(port_fd);
/* record connection details */
client_fd[count] = fd;
/* set-up callback for client */
inform_input(fd,read_client,count);
/* keep track of number of clients */
count = count+1;
/* probably tell other clients also */
}
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 5/10
Callback based server – 2
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 5/11
My window-less callbacks – 1
int inform_loop( );
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 5/12
My window-less callbacks – 2
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 5/13
☞ ☞ ☞ ☞ Hands on ✍ ✍ ✍ ✍
❉ Harder bits
☞ add the user name to the per-client data structure
☞ alter the server so that all messages use the name
rather than client number
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 5/14
UNIX
Network Programming
with TCP/IP
UNIX
Network Programming
with TCP/IP
UNIX
Network Programming
with TCP/IP
Session 6 UNIX
Network Programming
with TCP/IP
Forking Servers
& TCP/IP behaviour
• UNIX processes and fork
• forking servers
• fork system call
• example code
• dup, exec and wait
☞ remote shell
• inet demon and remote login
☞ another echo server
• IP fragmentation
• TCP flow control
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/1
Loosely coupled services
• closely coupled:
strong client interaction
e.g. electronic conference
• loosely coupled:
little or no client interaction
e.g. WWW
• no interaction at all ⇒
separate process to serve each client
• weak interaction ⇒
need locking, database server etc.
i.e. some central point of control
client client client client
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/2
A UNIX process
UNIX process:
• identified by process id (pid)
• process includes:
❍ program code
❍ application data
❍ system data
❋ including file descriptors
pid = 597
code
data
system data
e.g. file descriptors
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/3
Forking
597 632
code code
data data
$ echo $$
597
$ (echo $$)
632
$
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/4
Forking – 2
• process ids
❍ allocated sequentially
❍ so effectively unique
(but do wrap after a very long time)
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/5
Use in servers
① the server passive opens a port
and waits for a client
client server
client server
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/6
Use in servers – 2
fork
client child server
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/7
Use in servers – 3
④ server closes the connection
child closes the passive port
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/8
Fork system call
pid_t p = fork();
( pid_t ≈ int )
• if successful
❍ process
❍ successful fork returns:
0 – to child process
child pid – to parent process
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/9
Execution – 1
• parent forks
597
int i = 3, c_pid = -1;
➡ c_pid = fork();
if ( c_pid == 0 )
printf("child\n");
else if ( c_pid > 0 )
printf("parent\n");
else
printf("failed\n");
DATA i = 3
c_pid = -1
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/10
Execution – 2
• because data are different
597 632
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/11
fork based shell server – 1
Basic structure:
• establish port
• loop forever
• on each loop:
❍ accept a single client connection
❍ fork a child to manage client
• child execs a copy of the shell
➀ Main loop
main(...) {
/* open port */
port_sk = tcp_passive_open(port)
/* loop forever accepting clients */
while ( accept_one(port_sk) > 0 );
/* on error close and exit */
close(port_sk);
exit(0);
}
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/12
fork based shell server – 2
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/13
fork based shell server – 3
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/14
dup2 system call
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/15
exec system call
• new process:
❍ code – replaced by prog
❍ data – reinitialised
❍ system data – partly retained
❇ file descriptors still open
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/16
exec vs. fork
• fork duplicates process
• exec replaces process
597 493
code code
data data
system system
fork exec
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/17
death of a forked process
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/18
SIGCHLD & wait3
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/19
fork and I/O
low-level I/O
• open file descriptors shared so:
❍ output is merged
❍ input goes to first read
– accept similar
❍ close down may be delayed
until all processes close fd
⇒ close all unwanted fds
or use ioctl to set close-on-exec
high-level I/O
• C stdio is buffered:
❍ duplicated at fork
❍ may get flushed after fork
⇒ duplicate writes
✓ stderr OK – unbuffered
⇒ careful with stdio
use stderr or setbuff(fd,NULL)
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/20
☞ ☞ ☞ Hands on ✍ ✍ ✍
☞ compile knife.c :
make -f make6 knife
☞ then try ps
☞ what happens?
☞ what is happening?
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/21
inet demon
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/22
remote login
First solution . . .
. . . simply fork a shell or getty
✘ no translation of codes
e.g. end of line sequence
Actual solution . . .
. . . intermediate process
• server-end process
between client and shell/getty
✓ can perform translation
✓ pseudo-tty between it and shell
⇒ server-end tty control
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/23
remote login – 2
① remote login client connects to server
client server
fork
client child server
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/24
remote login – 3
server
fork and
client child exec
/dev shell
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/25
remote login – 4
• general algorithm:
❍ echo terminal input to network
❍ echo network input to terminal
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/26
☞ ☞ ☞ Hands on ✍ ✍ ✍
echo server
☞ modify knife.c to make a forking echo server
your previous echo server (session 2) only dealt
with one client – this one will deal with any number
☞ an connect to it:
klah 23% telnet io 2345
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/27
MTUs
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/28
IP fragmentation
• what happens when size is too small?
• fragmentation
❍ any intermediate router detects problem
❍ IP datagram broken into pieces
❍ each sent separately (possibly different routes)
❍ reconstructed at further router or destination
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/29
fragmentation considered harmful
• fragmentation
⇒ IP transparent to underlying link layer MTU
. . . well almost . . .
• IP is not reliable
⇒ some packets (fragments) may be lost
• no re-transmission
❍ IP handles reconstruction . . .
. . . but not fragment retransmission
❍ fragment lost
⇒ whole IP datagram lost
❍ probability one fragment lost = p
n fragments
⇒ probability IP datagram lost ≈ n p
• avoiding fragmentation
❍ UDP – most protocols ≤ 512 bytes
❍ TCP – uses local (end-point) MTU
+ path MTU discovery algorithm
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/30
TCP reliability
• underlying IP unreliable
⇒ TCP must handshake
• stream protocol
❍ sender: this is bytes n–m of the data
❍ recipient: ack m – last byte received
• retransmission
❍ recipient: out of order receipt → repeat ack
❍ timeout or several repeat acks → retransmit
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/31
TCP flow control
Cannot send without limits:
● network capacity → packet loss
❍ exponential backoff
rapid resend → nightmare scenario
⇒ long delay before failure (2-9 mins)
❍ slow-start algorithm
● link-layer buffer
❍ MSS announcement
● TCP buffer
❍ window size announcement
only send to last ack + window size
window size
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 6/32
UNIX
Network Programming
with TCP/IP
UNIX
Network Programming
with TCP/IP
UNIX
Network Programming
with TCP/IP
Session 7 UNIX
Network Programming
with TCP/IP
Security
Session 7
UNIX
Network Programming
with TCP/IP Alan Dix
http://www.hcibook.com/alan
Select and
Security
• UNIX events
• select system call
• proxy server
☞ raw client
• security, secrecy and privacy
• under attack: viruses & worm
• the Internet worm
• levels of security
• encryption and authentication
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/1
UNIX Events
Computational programs:
• busy most of the time
• read/write when they are ready
Interactive programs:
• servers & clients
• idle most of the time
• respond to events
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/2
Responding to events
Events:
① signal (interrupt)
② time (alarm)
③ input (read) ready
④ output (write) ready
Responding
• interrupt handler – ①&②
use signal system call
use setitimer to send SIGALRM
• turntaking – ②,③&④
call read/write when ready
use sleep for delays
• polling – ②,③&④
use non-blocking read/write
use time to do things at specific times
• wait for several events
use select system call
timeout or SIGALRM
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/3
polling in UNIX
#include <sys/filio.h>
ioctl(fd,FIONBIO,1);
for(;;) {
/* any terminal input? */
n = read(tty_fd,buff,buff_len);
if ( n > 0 ) { /* yes! do something */ }
/* any network input? */
n = read(net_fd,buff,buff_len);
if ( n > 0 ) { /* yes! do something */ }
}
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/4
read & write
read:
• waits on one file descriptor
• returns when input data is ready
• and reads the data into a buffer
read(0,buff,len)
write:
• waits on one file descriptor
• returns when output is possible
• and writes the data from the buffer
write(1,buff,len)
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/5
select
select:
• waits on many file descriptor
• returns when input or output ready
• but does no actual I/O
+ also allows timeout
select(width,&in_fds,&out_fds,&err_fds,&timeout)
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/6
select system call – 2
int ret =
select(size,&in_fds,&out_fds,&err_fds,&timeout);
• in_fds, out_fds:
– bitmaps of file descriptors
❍ in_fds – wait for input
i.e. read will not block
❍ out_fds – wait for output
i.e. write will not block
Returns when:
• input ready on one of in_fds (ret > 0)
• output ready on one of out_fds (ret > 0)
• error occurs on one of err_fds (ret > 0)
• timeout expires (ret == 0)
• signal has been caught (ret < 0)
• some other error occurs (ret < 0)
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/7
select and I/O
#include <sys/types.h>
fd_set in_fds, out_fds, err_fds
• modified by call:
call – bit set = wait for file desc
return – bit set = file desc ready
return value from select
= number ready
FD_ZERO( &in_fds );
FD_SET( fd, &in_fds );
FD_CLR( fd, &in_fds );
❍ testing:
if ( FD_ISSET(fd,&in_fds) ) ...
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/8
select and I/O – 2
• input
❍ terminal/socket
– read will not block
❍ passive socket
– accept will not block
• output
❍ terminal/socket
– write ‘ready’
❍ write relies on system resources
❍ change between select and write?
⇒ write may block
❄ use non-blocking write
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/9
select and timeouts
#include <sys/time.h>
struct timeval timeout;
• timeout.tv_secs
timeout.tv_ms
– maximum time to wait in seconds and ms
• modified by call?
❍ ideally should return time remaining
❍ doesn’t now . . .
. . . but may do one day
⇒ don’t rely on timeout not being changed
reset for each call to select
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/10
select and signals
• signal caught . . .
① relevant handler called
② systems call returns with ‘error’
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/11
care with signals
int my_handler()
{
i = i + 1
}
main()
{
signal(my_handler,SIGINTR);
for(;;)
if ( i > 0 ) {
do_something();
i = i - 1;
}
}
• intention:
execute do_something once per interrupt
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/12
when to use select
• servers:
❍ where concurrency essential
❍ possibly ftp server
– listen to control & data
❍ telnet server
– listen to user over network
+ listen to shell/application
• clients
❍ not with most window managers
– instead use callback
❍ some event stream WMs
– single fd for WM events
– listen to WM and network
❍ terminal based clients
– not needed for turn-taking
– e.g. telnet/rlogin clients
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/13
proxy server
• structure of code
① passive open on own port
② wait for client connection
③ active open on remote server
④ loop forever
waiting for client or server input:
❍ when client data ready
read it
send to server
echo it to terminal
❍ when server data ready
read it
send to client
echo it to terminal
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/14
proxy code – 1
➀ Main loop
main(...) {
/* establish port */
port_sk = tcp_passive_open(port);
/* wait for client to connect */
client_sk = tcp_accept(port_sk);
exit(0);
}
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/15
proxy code – 2
② perform proxy loop
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/16
proxy code – 3
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/17
proxy code – 4
④ check for client input
client ready if bit is set in read_copy
if ( FD_ISSET(client_sk,&read_copy) ) {
int len = read( client_sk, buff, buf_len );
else {
write(serv_sk,buff,len);
log_from_client( buff, len );
}
}
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/18
☞ ☞ ☞ ☞ Hands on ✍ ✍ ✍ ✍
☞ proceed as follows:
① remove the code to open the client connection
(passive open and accept)
② remove the parameter to do_proxy which
corresponds to the client socket
③ modify the FD_SET calls so that select waits
for standard input (0) rather than the client
④ change all read calls from the client so that
they read from standard input (0)
⑤ change all write calls to the client so that
they write to standard output (1)
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/19
Security
• types of security:
❍ information:
– secrecy
– privacy
❍ resources:
– destructive access
– virus infection
• linked
❍ information → resources
e.g. password → login
❍ resources → information
e.g. modify /etc/passwd
• chain reaction
❍ small breach → complete loss
e.g. root password!
❍ N.B. special problem for computers
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/20
who are you afraid of?
• internal
❍ selling your secrets
❍ personal data
– payroll, debtor files etc
❍ using resources
– surfing, doom!
❍ downloading material
– indecent, possibly illegal
❍ backdoors
client_sk = tcp_accept(port_sk);
n= read(client_sk,buff,buff_len);
buff(len) = '\0';
if ( strcmp(buff,"Alan's secret way in") == 0 ) {
/* connect client_sk to a root shell */
}
/* normal operation * /
• external
❍ hackers
❍ accidental release
– e.g. forgotten portable on the train
❍ industrial espionage
❍ viruses
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/21
under attack
• types of attack
❍ virus
– embeds itself in another program
❍ Trojan horse
– masquerades as another program
❍ worm
– independent self-replicating program
N.B. names and definitions differ
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/22
viruses on the web?
• explicit download of code
❍ helpers – machine specific code
❍ general software
✘ both risk infection
• implicit download
❍ semi-compiled – JAVA
❍ interpreted – JAVA script
❍ embedded in HTML
✘ you may never know!
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/23
The Internet Worm
• for 2 days in 1988, the Internet was
under siege
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/24
What went wrong?
• between machines:
❍ debug mode in sendmail
❍ buffer overflow in fingerd
❍ once broken into a user on a machine
– rlogin/rsh to other hosts
• within a machine:
❍ simple password attacks
– permutations of user’s own name
– internal list of 432 common passwords
– system dictionary
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/25
sendmail attack
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/26
fingerd attack
• lessons:
❍ never use gets!
– at best may crash
- at worst is a loophole
❍ always be careful of buffer lengths
• never again?
❍ a popular WWW browser . . .
– corrected in later versions
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/27
physical security
• physical security:
❍ are the machines secure
can someone reboot, substitute disks etc.?
❍ is the network secure
can someone link-in their own computer?
• local or global?
① local network and machines
② backbone and routers
③ remote network and machines
• secure?
① possible
② reasonable for non-critical data
③ no way!
N.B. ‘listening in’ easy on many networks
e.g. ethernet
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/28
logical security
• secrecy:
❍ TCP/IP packets not secure
e.g. credit card by email
❍ use encryption
e.g. Netscape secure sockets layer for WWW
• authentication:
❍ who am I talking to?
❍ is it the real server?
✔ rely on correct routing and protected ports
✘ impostor machine, non-UNIX server host
❍ is it an acceptable client?
✔ user passwords
✘ often sent as plain text! – e.g. telnet
• audit:
❍ risk of detection deters
❍ keeping logs
❍ relies on authentication
✔ SMTP reverse name lookup
✘ can’t check FROM field – e.g. worm warning
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/29
low-level protection – firewalls
• simple measures
❍ isolation
– don’t connect to the global Internet
... but lose the benefits too
❍ anonymity
– don’t publish domain machine names
... but IP addresses still valid
• firewalls
❍ application independent
❍ act at router/gateway
❍ can only look at IP or TCP headers
• what is possible
❍ only allow friendly IP addresses
– N.B. impostors
❍ limited internal routing
– protect sensitive machines/data
❍ restrict incoming TCP packets
– only allow connection to protected ports
... but difficult for ftp
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/30
high-level protection – ring fences
• rlogin
❍ beware external root logins!
❍ passwords:
– if reasonable no ‘equiv’ hosts
– certainly no root ‘equiv’ hosts
? means lots of duplicate password files?
• servers
❍ never run as root?
– impossible! e.g. inetd, rshd
❍ never unnecessarily run as root?
– special login e.g. user ‘ftp’
– run as user ‘nobody’
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/31
encryption
• single key
cypher = code(key,input)
input = decode(key,cypher)
❍ in DES – code = decode
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/32
session keys and authentication
• result:
❍ A and B share a secret key
❍ A and B sure of each other’s identity
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/33
authentication servers
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/34
don’t panic!
• hacker ≈ burglar
– if they want in, you won’t stop them
• main differences
– rate of loss (Mbytes/sec)
– hidden loss (electronic copies)
– automatic attack
UNIX
TCP/IP Short Course Notes Alan Dix © 1996 7/35