3 {socket code by plugwash}
\r
5 { Copyright (C) 2005 Bas Steendijk and Peter Green
\r
6 For conditions of distribution and use, see copyright notice in zlib_license.txt
\r
7 which is included in the package
\r
8 ----------------------------------------------------------------------------- }
\r
10 changes by plugwash (20030728)
\r
11 * created handlefdtrigger virtual method in tlasio (overridden in tlsocket) and moved a lot of code from messageloop into it
\r
12 * changed tlasio to tlasio
\r
13 * split fdhandle into fdhandlein and fdhandleout
\r
14 * i now use fdsrmaster and fdswmaster instead of rebuilding the lists every loop
\r
15 * split lsocket.pas into lsocket.pas and lcore.pas
\r
18 changes by beware (20030903)
\r
19 * added getxaddr, getxport (local addr, port, as string)
\r
20 * added getpeername, remote addr+port as binary
\r
21 * added htons and htonl functions (endian swap, same interface as windows API)
\r
24 * if connect failed (conn refused) set state to connected and call internalclose, to get closed handler (instead of fdclose)
\r
25 * (lcore) if closing the fd's in internalcose, set fd's to -1 because closing an fd makes it invalid
\r
28 * fixed: on connect failed, tried to close fdhandle's which were already set to -1, added check
\r
31 * added getpeeraddr, getpeerport, remote addr+port as string
\r
40 {$include lcoreconfig.inc}
\r
52 baseunix,unix,unixutil,
\r
56 classes,{pgdebugout,}pgtypes,lcore,fd_utils,binipstuff,dnssync;
\r
59 {$define secondlistener}
\r
61 v4listendefault:boolean=false;
\r
66 sunB = packed record
\r
67 s_b1, s_b2, s_b3, s_b4: byte;
\r
70 SunW = packed record
\r
74 TInAddr = packed record
\r
78 2: (S_addr: cardinal);
\r
82 TLsocket = class(tlasio)
\r
86 inAddr : TInetSockAddrV;
\r
88 biniplist:tbiniplist;
\r
91 connecttimeout:tltimer;
\r
93 { inAddrSize:integer;}
\r
95 //host : THostentry ;
\r
97 //mainthread : boolean ; //for debuggin only
\r
104 listenqueue:integer;
\r
105 {$ifdef secondlistener}
\r
106 secondlistener:tlsocket;
\r
107 lastsessionfromsecond:boolean;
\r
108 procedure secondaccepthandler(sender:tobject;error:word);
\r
109 procedure internalclose(error:word);override;
\r
111 procedure connectionfailedhandler(error:word);
\r
112 procedure connecttimeouthandler(sender:tobject);
\r
113 procedure connectsuccesshandler;
\r
114 function getaddrsize:integer;
\r
115 procedure connect; virtual;
\r
116 procedure realconnect;
\r
117 procedure bindsocket;
\r
119 function accept : longint;
\r
120 function sendto(dest:TInetSockAddrV;destlen:integer;data:pointer;len:integer):integer; virtual;
\r
121 function receivefrom(data:pointer;len:integer;var src:TInetSockAddrV;var srclen:integer):integer; virtual;
\r
123 procedure handlefdtrigger(readtrigger,writetrigger:boolean); override;
\r
124 function send(data:pointer;len:integer):integer;override;
\r
125 procedure sendstr(const str : string);override;
\r
126 function Receive(Buf:Pointer;BufSize:integer):integer; override;
\r
127 function getpeername(var addr:tsockaddrin;addrlen:integer):integer; virtual;
\r
128 procedure getXaddrbin(var binip:tbinip); virtual;
\r
129 procedure getpeeraddrbin(var binip:tbinip); virtual;
\r
130 function getXaddr:string; virtual;
\r
131 function getpeeraddr:string; virtual;
\r
132 function getXport:string; virtual;
\r
133 function getpeerport:string; virtual;
\r
134 constructor Create(AOwner: TComponent); override;
\r
136 procedure myfdclose(fd : integer); override;
\r
137 function myfdwrite(fd: LongInt;const buf;size: LongInt):LongInt; override;
\r
138 function myfdread(fd: LongInt;var buf;size: LongInt):LongInt; override;
\r
141 tsocket=longint; // for compatibility with twsocket
\r
143 twsocket=tlsocket; {easy}
\r
146 {!!!function longipdns(s:string):longint;}
\r
153 {$include unixstuff.inc}
\r
156 function tlsocket.getaddrsize:integer;
\r
158 result := inaddrsize(inaddr);
\r
162 procedure tlsocket.realconnect;
\r
167 // writeln('trying to connect to ',ipbintostr(biniplist_get(biniplist,currentip)),'#',port);
\r
168 makeinaddrv(biniplist_get(biniplist,currentip),port,inaddr);
\r
170 if (currentip >= biniplist_getcount(biniplist)) then trymoreips := false;
\r
171 udp := uppercase(proto) = 'UDP';
\r
172 if udp then a := SOCK_DGRAM else a := SOCK_STREAM;
\r
173 a := Socket(inaddr.inaddr.family,a,0);
\r
174 //writeln(ord(inaddr.inaddr.family));
\r
175 if a = -1 then begin
\r
176 lasterror := {$ifdef win32}getlasterror{$else}socketerror{$endif};
\r
177 raise esocketexception.create('unable to create socket');
\r
184 SetSocketOptions(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
186 state := wsconnected;
\r
187 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
189 eventcore.rmasterset(fdhandlein,false);
\r
190 eventcore.wmasterclr(fdhandleout);
\r
192 state :=wsconnecting;
\r
194 //writeln(inaddr.inaddr.port);
\r
195 winsock.Connect(fdhandlein,winsock.psockaddr(@inADDR)^,getaddrsize);
\r
197 sockets.Connect(fdhandlein,inADDR,getaddrsize);
\r
199 eventcore.rmasterset(fdhandlein,false);
\r
200 eventcore.wmasterset(fdhandleout);
\r
201 if trymoreips then connecttimeout.enabled := true;
\r
205 on e: exception do begin
\r
207 raise; //reraise the exception
\r
213 procedure tlsocket.connecttimeouthandler(sender:tobject);
\r
215 connecttimeout.enabled := false;
\r
216 destroying := true; //hack to not cause handler to trigger
\r
218 destroying := false;
\r
222 procedure tlsocket.connect;
\r
227 if state <> wsclosed then close;
\r
229 if isbiniplist(addr) then biniplist := addr else biniplist := forwardlookuplist(addr,0);
\r
230 if biniplist_getcount(biniplist) = 0 then raise exception.create('unable to resolve '+addr);
\r
232 //makeinaddrv(addr,port,inaddr);
\r
235 if not assigned(connecttimeout) then begin
\r
236 connecttimeout := tltimer.create(self);
\r
237 connecttimeout.Tag := integer(self);
\r
238 connecttimeout.ontimer := connecttimeouthandler;
\r
239 connecttimeout.interval := 2500;
\r
240 connecttimeout.enabled := false;
\r
245 procedure tlsocket.sendstr(const str : string);
\r
248 send(@str[1],length(str))
\r
250 inherited sendstr(str);
\r
254 function tlsocket.send(data:pointer;len:integer):integer;
\r
257 // writeln('sending to '+ipbintostr(inaddrvtobinip(inaddr)),' ',htons(inaddr.inaddr.port),' ',len,' bytes');
\r
258 result := sendto(inaddr,getaddrsize,data,len);
\r
260 // writeln('send result ',result);
\r
261 // writeln('errno',errno);
\r
263 result := inherited send(data,len);
\r
268 function tlsocket.receive(Buf:Pointer;BufSize:integer):integer;
\r
271 {$ifdef secondlistener}
\r
272 if lastsessionfromsecond then begin
\r
273 result := secondlistener.receive(buf,bufsize);
\r
274 lastsessionfromsecond := false;
\r
277 result := myfdread(self.fdhandlein,buf^,bufsize);
\r
279 result := inherited receive(buf,bufsize);
\r
283 procedure tlsocket.bindsocket;
\r
286 inAddrtemp:TInetSockAddrV;
\r
287 inAddrtempx:{$ifdef win32}winsock.TSockaddr{$else}TInetSockAddrV{$endif} absolute inaddrtemp;
\r
288 inaddrtempsize:integer;
\r
291 if (localaddr <> '') or (localport <> '') then begin
\r
292 if localaddr = '' then begin
\r
294 if inaddr.inaddr.family = AF_INET6 then localaddr := '::' else
\r
296 localaddr := '0.0.0.0';
\r
298 //gethostbyname(localaddr,host);
\r
300 inaddrtempsize := makeinaddrv(forwardlookup(localaddr,0),localport,inaddrtemp);
\r
302 If Bind(fdhandlein,inaddrtempx,inaddrtempsize)<> {$ifdef win32}0{$else}true{$endif} Then begin
\r
304 lasterror := {$ifdef win32}getlasterror{$else}socketerror{$endif};
\r
305 raise ESocketException.create('unable to bind, error '+inttostr(lasterror));
\r
310 on e: exception do begin
\r
312 raise; //reraise the exception
\r
317 procedure tlsocket.listen;
\r
324 if state <> wsclosed then close;
\r
325 udp := uppercase(proto) = 'UDP';
\r
326 if udp then socktype := SOCK_DGRAM else socktype := SOCK_STREAM;
\r
329 if addr = '' then begin
\r
331 if not v4listendefault then begin
\r
337 if isbiniplist(addr) then biniptemp := biniplist_get(addr,0) else biniptemp := forwardlookup(addr,10);
\r
338 addr := ipbintostr(biniptemp);
\r
339 fdhandlein := socket(biniptemp.family,socktype,0);
\r
341 if (addr = '::') and (origaddr = '') and (fdhandlein < 0) then begin
\r
343 fdhandlein := socket(AF_INET,socktype,0);
\r
347 if fdhandlein = -1 then raise ESocketException.create('unable to create socket');
\r
348 dupnowatch(fdhandlein); // sets up maxs and copies handle to fdhandleout among other things
\r
349 //eventcore.setfdreverse(fdhandlein,self); //already taken care of by dup
\r
350 state := wsclosed; // then set this back as it was an undesired side effect of dup
\r
353 yes := $01010101; {Copied this from existing code. Value is empiric,
\r
354 but works. (yes=true<>0) }
\r
356 if SetSocketOptions(fdhandlein, SOL_SOCKET, SO_REUSEADDR,yes,sizeof(yes))=-1 then begin
\r
357 raise ESocketException.create('unable to set socket options');
\r
364 if not udp then begin
\r
365 {!!! allow custom queue length? default 5}
\r
366 if listenqueue = 0 then listenqueue := 5;
\r
367 If {$ifdef win32}winsock{$else}sockets{$endif}.Listen(fdhandlein,listenqueue)<>{$ifdef win32}0{$else}true{$endif} Then raise esocketexception.create('unable to listen');
\r
368 state := wsListening;
\r
371 SetSocketOptions(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
373 state := wsconnected;
\r
376 {$ifdef secondlistener}
\r
377 //listening on ::. try to listen on 0.0.0.0 as well for platforms which don't already do that
\r
378 if addr = '::' then begin
\r
379 secondlistener := tlsocket.create(nil);
\r
380 secondlistener.proto := proto;
\r
381 secondlistener.addr := '0.0.0.0';
\r
382 secondlistener.port := port;
\r
384 secondlistener.ondataavailable := secondaccepthandler;
\r
386 secondlistener.onsessionAvailable := secondaccepthandler;
\r
388 secondlistener.listen;
\r
392 if state = wsclosed then begin
\r
393 if fdhandlein >= 0 then begin
\r
394 {one *can* get here without fd -beware}
\r
395 eventcore.rmasterclr(fdhandlein);
\r
396 myfdclose(fdhandlein); // we musnt leak file discriptors
\r
397 eventcore.setfdreverse(fdhandlein,nil);
\r
401 eventcore.rmasterset(fdhandlein,not udp);
\r
403 if fdhandleout >= 0 then eventcore.wmasterclr(fdhandleout);
\r
405 //writeln('listened on addr '+addr+':'+port+' '+proto+' using socket number ',fdhandlein);
\r
408 {$ifdef secondlistener}
\r
409 procedure tlsocket.internalclose(error:word);
\r
411 if assigned(secondlistener) then secondlistener.destroy;
\r
412 inherited internalclose(error);
\r
415 procedure tlsocket.secondaccepthandler;
\r
417 lastsessionfromsecond := true;
\r
419 ondataavailable(self,error);
\r
421 if assigned(onsessionavailable) then onsessionavailable(self,error);
\r
426 function tlsocket.accept : longint;
\r
428 FromAddrSize : LongInt; // i don't realy know what to do with these at this
\r
429 FromAddr : TInetSockAddrV; // at this point time will tell :)
\r
432 {$ifdef secondlistener}
\r
433 if (lastsessionfromsecond) then begin
\r
434 lastsessionfromsecond := false;
\r
435 result := secondlistener.accept;
\r
440 FromAddrSize := Sizeof(FromAddr);
\r
442 result := winsock.accept(fdhandlein,@fromaddr,@fromaddrsize);
\r
444 result := sockets.accept(fdhandlein,fromaddr,fromaddrsize);
\r
446 //now we have accepted one request start monitoring for more again
\r
447 eventcore.rmasterset(fdhandlein,true);
\r
449 if result = -1 then begin
\r
450 raise esocketexception.create('error '+inttostr({$ifdef win32}getlasterror{$else}socketerror{$endif})+' while accepting');
\r
452 if result > absoloutemaxs then begin
\r
456 raise esocketexception.create('file discriptor out of range: '+inttostr(a));
\r
460 function tlsocket.sendto(dest:TInetSockAddrV;destlen:integer;data:pointer;len:integer):integer;
\r
462 destx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute dest;
\r
464 {$ifdef secondlistener}
\r
465 if assigned(secondlistener) then if (dest.inaddr.family = AF_INET) then begin
\r
466 result := secondlistener.sendto(dest,destlen,data,len);
\r
470 result := {$ifdef win32}winsock{$else}sockets{$endif}.sendto(self.fdhandleout,data^,len,0,destx,destlen);
\r
473 function tlsocket.receivefrom(data:pointer;len:integer;var src:TInetSockAddrV;var srclen:integer):integer;
\r
475 srcx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute src;
\r
477 {$ifdef secondlistener}
\r
478 if assigned(secondlistener) then if lastsessionfromsecond then begin
\r
479 lastsessionfromsecond := false;
\r
480 result := secondlistener.receivefrom(data,len,src,srclen);
\r
484 result := {$ifdef win32}winsock{$else}sockets{$endif}.recvfrom(self.fdhandlein,data^,len,0,srcx,srclen);
\r
487 procedure tlsocket.connectionfailedhandler(error:word);
\r
489 if trymoreips then begin
\r
490 // writeln('failed with error ',error);
\r
491 connecttimeout.enabled := false;
\r
492 destroying := true;
\r
493 state := wsconnected;
\r
494 self.internalclose(0);
\r
495 destroying := false;
\r
498 state := wsconnected;
\r
499 if assigned(onsessionconnected) then onsessionconnected(self,error);
\r
500 self.internalclose(0);
\r
501 recvq.del(maxlongint);
\r
505 procedure tlsocket.connectsuccesshandler;
\r
507 trymoreips := false;
\r
508 connecttimeout.enabled := false;
\r
509 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
513 procedure tlsocket.handlefdtrigger(readtrigger,writetrigger:boolean);
\r
515 tempbuf:array[0..receivebufsize-1] of byte;
\r
517 // writeln('got a fd trigger, readtrigger=',readtrigger,' writetrigger=',writetrigger,' state=',integer(state));
\r
518 if (state =wslistening) and readtrigger then begin
\r
519 { debugout('listening socket triggered on read');}
\r
520 eventcore.rmasterclr(fdhandlein);
\r
521 if assigned(onsessionAvailable) then onsessionAvailable(self,0);
\r
523 if udp and readtrigger then begin
\r
524 if assigned(ondataAvailable) then ondataAvailable(self,0);
\r
528 if (state =wsconnecting) and writetrigger then begin
\r
529 // code for dealing with the reults of a non-blocking connect is
\r
531 // if just write is triggered it means connect suceeded
\r
532 // if both read and write are triggered it can mean 2 things
\r
533 // 1: connect ok and data availible
\r
535 // to find out which you must read from the socket and look for errors
\r
536 // there if we read successfully we drop through into the code for fireing
\r
538 if not readtrigger then begin
\r
539 state := wsconnected;
\r
540 connectsuccesshandler;
\r
542 numread := myfdread(fdhandlein,tempbuf,sizeof(tempbuf));
\r
543 if numread <> -1 then begin
\r
544 state := wsconnected;
\r
545 connectsuccesshandler;
\r
546 //connectread := true;
\r
547 recvq.add(@tempbuf,numread);
\r
549 connectionfailedhandler({$ifdef win32}wsagetlasterror{$else}linuxerror{$endif});
\r
552 // if things went well here we are now in the state wsconnected with data sitting in our receive buffer
\r
553 // so we drop down into the processing for data availible
\r
555 if fdhandlein >= 0 then begin
\r
556 if state = wsconnected then begin
\r
557 eventcore.rmasterset(fdhandlein,false);
\r
559 eventcore.rmasterclr(fdhandlein);
\r
562 if fdhandleout >= 0 then begin
\r
563 if sendq.size = 0 then begin
\r
564 //don't clear the bit in fdswmaster if data is in the sendq
\r
565 eventcore.wmasterclr(fdhandleout);
\r
570 inherited handlefdtrigger(readtrigger,writetrigger);
\r
573 constructor tlsocket.Create(AOwner: TComponent);
\r
575 inherited create(aowner);
\r
576 closehandles := true;
\r
577 trymoreips := true;
\r
581 function tlsocket.getpeername(var addr:tsockaddrin;addrlen:integer):integer;
\r
583 addrx : {$ifdef win32}winsock.tsockaddr{$else}tsockaddrin{$endif} absolute addr;
\r
585 result := {$ifdef win32}winsock{$else}sockets{$endif}.getpeername(self.fdhandlein,addrx,addrlen);
\r
588 procedure tlsocket.getxaddrbin(var binip:tbinip);
\r
590 addr:tinetsockaddrv;
\r
594 fillchar(addr,sizeof(addr),0);
\r
597 winsock.getsockname(self.fdhandlein,psockaddr(@addr)^,i);
\r
599 sockets.getsocketname(self.fdhandlein,addr,i);
\r
601 binip.family := addr.inaddr.family;
\r
603 if addr.inaddr6.sin6_family = AF_INET6 then begin
\r
604 binip.ip6 := addr.inaddr6.sin6_addr;
\r
608 binip.ip := addr.inaddr.addr;
\r
610 converttov4(binip);
\r
613 procedure tlsocket.getpeeraddrbin(var binip:tbinip);
\r
615 addr:tinetsockaddrv;
\r
619 fillchar(addr,sizeof(addr),0);
\r
621 winsock.getpeername(self.fdhandlein,psockaddr(@addr)^,i);
\r
623 sockets.getpeername(self.fdhandlein,addr,i);
\r
626 binip.family := addr.inaddr.family;
\r
628 if addr.inaddr6.sin6_family = AF_INET6 then begin
\r
629 binip.ip6 := addr.inaddr6.sin6_addr;
\r
633 binip.ip := addr.inaddr.addr;
\r
635 converttov4(binip);
\r
638 function tlsocket.getXaddr:string;
\r
642 getxaddrbin(biniptemp);
\r
643 result := ipbintostr(biniptemp);
\r
644 if result = '' then result := 'error';
\r
647 function tlsocket.getpeeraddr:string;
\r
651 getpeeraddrbin(biniptemp);
\r
652 result := ipbintostr(biniptemp);
\r
653 if result = '' then result := 'error';
\r
656 function tlsocket.getXport:string;
\r
658 addr:tinetsockaddrv;
\r
663 winsock.getsockname(self.fdhandlein,psockaddrin(@addr)^,i);
\r
666 sockets.getsocketname(self.fdhandlein,addr,i);
\r
669 result := inttostr(htons(addr.InAddr.port));
\r
672 function tlsocket.getpeerport:string;
\r
674 addr:tinetsockaddrv;
\r
679 winsock.getpeername(self.fdhandlein,psockaddrin(@addr)^,i);
\r
682 sockets.getpeername(self.fdhandlein,addr,i);
\r
685 result := inttostr(htons(addr.InAddr.port));
\r
689 procedure tlsocket.myfdclose(fd : integer);
\r
693 function tlsocket.myfdwrite(fd: LongInt;const buf;size: LongInt):LongInt;
\r
695 result := winsock.send(fd,(@buf)^,size,0);
\r
697 function tlsocket.myfdread(fd: LongInt;var buf;size: LongInt):LongInt;
\r
699 result := winsock.recv(fd,buf,size,0);
\r