/* --- Copyright University of Sussex 1994. All rights reserved. ----------
 > File:            C.unix/lib/lib/sockets.p
 > Purpose:			Unix socket interface
 > Author:          John Gibson May  6 1994
 > Documentation:
 */
compile_mode :pop11 +strict;

include sysdefs.ph;

#_IF not(DEF BERKELEY or DEFV SYSTEM_V >= 4.0)
	#_TERMIN_IF DEF POPC_COMPILING
	mishap(0, 'SOCKETS NOT SUPPORTED IN THIS SYSTEM')
#_ENDIF


section;
exload_batch;

exload sockets
	#_IF DEFV SYSTEM_V >= 4.0
		['-lsocket']
	#_ENDIF

lconstant
	UNIX_socket(domain,type,protocol) :int			<- socket,
	UNIX_socketpair(domain,type,protocol,sv) :int	<- socketpair,

endexload;

lconstant
	spairbuf	= writeable initintvec(2),
	sock_name	= 'socket',
	;

define lconstant Create_socks(af, type, protocol, routine) -> res;
	lvars af, type, protocol, res, routine, retry = 1;

	checkinteger(af, 0, false);
	checkinteger(type, 0, false);
	checkinteger(protocol, 0, false);

	repeat
		exacc (4):int routine(af, type, protocol, spairbuf) -> res;
		quitif((Sys_fd_open_check(res, false, retry) ->> retry) fi_< 0)
	endrepeat;

	if res fi_< 0 then
		mishap(af, type, protocol, 3,
					'CAN\'T CREATE SOCKET(S)' sys_>< sysiomessage())
	endif;
enddefine;

define sys_socket(/*af, type, protocol,*/ arg3) with_nargs 4;
	lvars arg3, fd = Create_socks(UNIX_socket);
	Sys_cons_device(sock_name, false, 2, arg3, fd, true)
enddefine;

define sys_socket_pair(/*af, type, protocol,*/ arg3) with_nargs 4;
	lvars arg3, s1, s2;
	Create_socks(UNIX_socketpair) -> ;
	explode(spairbuf) -> (s1, s2);
	Sys_cons_device(sock_name, false, 2, arg3, s1, true);
	Sys_cons_device(sock_name, false, 2, arg3, s2, true);
enddefine;

constant sockets = true;

endexload_batch;
endsection;
