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
60 v4listendefault:boolean=false;
\r
65 sunB = packed record
\r
66 s_b1, s_b2, s_b3, s_b4: byte;
\r
69 SunW = packed record
\r
73 TInAddr = packed record
\r
77 2: (S_addr: cardinal);
\r
81 TLsocket = class(tlasio)
\r
85 inAddr : TInetSockAddrV;
\r
87 biniplist:tbiniplist;
\r
90 connecttimeout:tltimer;
\r
92 { inAddrSize:integer;}
\r
94 //host : THostentry ;
\r
96 //mainthread : boolean ; //for debuggin only
\r
103 listenqueue:integer;
\r
104 {$ifdef secondlistener}
\r
105 secondlistener:tlsocket;
\r
106 lastsessionfromsecond:boolean;
\r
107 procedure secondaccepthandler(sender:tobject;error:word);
\r
108 procedure internalclose(error:word);override;
\r
110 procedure connectionfailedhandler(error:word);
\r
111 procedure connecttimeouthandler(sender:tobject);
\r
112 procedure connectsuccesshandler;
\r
113 function getaddrsize:integer;
\r
114 procedure connect; virtual;
\r
115 procedure realconnect;
\r
116 procedure bindsocket;
\r
118 function accept : longint;
\r
119 function sendto(dest:TInetSockAddrV;destlen:integer;data:pointer;len:integer):integer; virtual;
\r
120 function receivefrom(data:pointer;len:integer;var src:TInetSockAddrV;var srclen:integer):integer; virtual;
\r
122 procedure handlefdtrigger(readtrigger,writetrigger:boolean); override;
\r
123 function send(data:pointer;len:integer):integer;override;
\r
124 procedure sendstr(const str : string);override;
\r
125 function Receive(Buf:Pointer;BufSize:integer):integer; override;
\r
126 function getpeername(var addr:tsockaddrin;addrlen:integer):integer; virtual;
\r
127 procedure getXaddrbin(var binip:tbinip); virtual;
\r
128 procedure getpeeraddrbin(var binip:tbinip); virtual;
\r
129 function getXaddr:string; virtual;
\r
130 function getpeeraddr:string; virtual;
\r
131 function getXport:string; virtual;
\r
132 function getpeerport:string; virtual;
\r
133 constructor Create(AOwner: TComponent); override;
\r
135 procedure myfdclose(fd : integer); override;
\r
136 function myfdwrite(fd: LongInt;const buf;size: LongInt):LongInt; override;
\r
137 function myfdread(fd: LongInt;var buf;size: LongInt):LongInt; override;
\r
140 tsocket=longint; // for compatibility with twsocket
\r
142 twsocket=tlsocket; {easy}
\r
150 {$include unixstuff.inc}
\r
153 function tlsocket.getaddrsize:integer;
\r
155 result := inaddrsize(inaddr);
\r
159 procedure tlsocket.realconnect;
\r
163 // writeln('trying to connect to ',ipbintostr(biniplist_get(biniplist,currentip)),'#',port);
\r
164 makeinaddrv(biniplist_get(biniplist,currentip),port,inaddr);
\r
166 if (currentip >= biniplist_getcount(biniplist)) then trymoreips := false;
\r
169 if (uppercase(proto) = 'UDP') then begin
\r
174 end else if (uppercase(proto) = 'TCP') then begin
\r
179 b := strtointdef(proto,IPPROTO_ICMP);
\r
184 a := Socket(inaddr.inaddr.family,a,b);
\r
185 //writeln(ord(inaddr.inaddr.family));
\r
186 if a = -1 then begin
\r
187 lasterror := {$ifdef win32}getlasterror{$else}socketerror{$endif};
\r
188 raise esocketexception.create('unable to create socket');
\r
193 if dgram then begin
\r
195 SetSocketOptions(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
197 state := wsconnected;
\r
198 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
200 eventcore.rmasterset(fdhandlein,false);
\r
201 eventcore.wmasterclr(fdhandleout);
\r
203 state :=wsconnecting;
\r
205 //writeln(inaddr.inaddr.port);
\r
206 winsock.Connect(fdhandlein,winsock.psockaddr(@inADDR)^,getaddrsize);
\r
208 sockets.Connect(fdhandlein,inADDR,getaddrsize);
\r
210 eventcore.rmasterset(fdhandlein,false);
\r
211 eventcore.wmasterset(fdhandleout);
\r
212 if trymoreips then connecttimeout.enabled := true;
\r
216 on e: exception do begin
\r
218 raise; //reraise the exception
\r
224 procedure tlsocket.connecttimeouthandler(sender:tobject);
\r
226 connecttimeout.enabled := false;
\r
227 destroying := true; //hack to not cause handler to trigger
\r
229 destroying := false;
\r
233 procedure tlsocket.connect;
\r
238 if state <> wsclosed then close;
\r
240 if isbiniplist(addr) then biniplist := addr else biniplist := forwardlookuplist(addr,0);
\r
241 if biniplist_getcount(biniplist) = 0 then raise exception.create('unable to resolve '+addr);
\r
243 //makeinaddrv(addr,port,inaddr);
\r
246 if not assigned(connecttimeout) then begin
\r
247 connecttimeout := tltimer.create(self);
\r
248 connecttimeout.Tag := integer(self);
\r
249 connecttimeout.ontimer := connecttimeouthandler;
\r
250 connecttimeout.interval := 2500;
\r
251 connecttimeout.enabled := false;
\r
256 procedure tlsocket.sendstr(const str : string);
\r
258 if dgram then begin
\r
259 send(@str[1],length(str))
\r
261 inherited sendstr(str);
\r
265 function tlsocket.send(data:pointer;len:integer):integer;
\r
267 if dgram then begin
\r
268 // writeln('sending to '+ipbintostr(inaddrvtobinip(inaddr)),' ',htons(inaddr.inaddr.port),' ',len,' bytes');
\r
269 result := sendto(inaddr,getaddrsize,data,len);
\r
271 // writeln('send result ',result);
\r
272 // writeln('errno',errno);
\r
274 result := inherited send(data,len);
\r
279 function tlsocket.receive(Buf:Pointer;BufSize:integer):integer;
\r
281 if dgram then begin
\r
282 {$ifdef secondlistener}
\r
283 if lastsessionfromsecond then begin
\r
284 result := secondlistener.receive(buf,bufsize);
\r
285 lastsessionfromsecond := false;
\r
288 result := myfdread(self.fdhandlein,buf^,bufsize);
\r
290 result := inherited receive(buf,bufsize);
\r
294 procedure tlsocket.bindsocket;
\r
297 inAddrtemp:TInetSockAddrV;
\r
298 inAddrtempx:{$ifdef win32}winsock.TSockaddr{$else}TInetSockAddrV{$endif} absolute inaddrtemp;
\r
299 inaddrtempsize:integer;
\r
302 if (localaddr <> '') or (localport <> '') then begin
\r
303 if localaddr = '' then begin
\r
305 if inaddr.inaddr.family = AF_INET6 then localaddr := '::' else
\r
307 localaddr := '0.0.0.0';
\r
309 //gethostbyname(localaddr,host);
\r
310 inaddrtempsize := makeinaddrv(forwardlookup(localaddr,0),localport,inaddrtemp);
\r
312 If Bind(fdhandlein,inaddrtempx,inaddrtempsize)<> {$ifdef win32}0{$else}true{$endif} Then begin
\r
314 lasterror := {$ifdef win32}getlasterror{$else}socketerror{$endif};
\r
315 raise ESocketException.create('unable to bind on address '+localaddr+'#'+localport+', error '+inttostr(lasterror));
\r
320 on e: exception do begin
\r
322 raise; //reraise the exception
\r
327 procedure tlsocket.listen;
\r
334 if state <> wsclosed then close;
\r
335 udp := uppercase(proto) = 'UDP';
\r
336 if udp then socktype := SOCK_DGRAM else socktype := SOCK_STREAM;
\r
339 if addr = '' then begin
\r
341 if not v4listendefault then begin
\r
347 if isbiniplist(addr) then biniptemp := biniplist_get(addr,0) else biniptemp := forwardlookup(addr,10);
\r
348 addr := ipbintostr(biniptemp);
\r
349 fdhandlein := socket(biniptemp.family,socktype,0);
\r
351 if (addr = '::') and (origaddr = '') and (fdhandlein < 0) then begin
\r
353 fdhandlein := socket(AF_INET,socktype,0);
\r
357 if fdhandlein = -1 then raise ESocketException.create('unable to create socket');
\r
358 dupnowatch(fdhandlein); // sets up maxs and copies handle to fdhandleout among other things
\r
359 //eventcore.setfdreverse(fdhandlein,self); //already taken care of by dup
\r
360 state := wsclosed; // then set this back as it was an undesired side effect of dup
\r
363 yes := $01010101; {Copied this from existing code. Value is empiric,
\r
364 but works. (yes=true<>0) }
\r
366 if SetSocketOptions(fdhandlein, SOL_SOCKET, SO_REUSEADDR,yes,sizeof(yes))=-1 then begin
\r
367 raise ESocketException.create('unable to set socket options');
\r
374 if not udp then begin
\r
375 {!!! allow custom queue length? default 5}
\r
376 if listenqueue = 0 then listenqueue := 5;
\r
377 If {$ifdef win32}winsock{$else}sockets{$endif}.Listen(fdhandlein,listenqueue)<>{$ifdef win32}0{$else}true{$endif} Then raise esocketexception.create('unable to listen');
\r
378 state := wsListening;
\r
381 SetSocketOptions(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
383 state := wsconnected;
\r
386 {$ifdef secondlistener}
\r
387 //listening on ::. try to listen on 0.0.0.0 as well for platforms which don't already do that
\r
388 if addr = '::' then begin
\r
389 secondlistener := tlsocket.create(nil);
\r
390 secondlistener.proto := proto;
\r
391 secondlistener.addr := '0.0.0.0';
\r
392 secondlistener.port := port;
\r
394 secondlistener.ondataavailable := secondaccepthandler;
\r
396 secondlistener.onsessionAvailable := secondaccepthandler;
\r
399 secondlistener.listen;
\r
401 secondlistener.destroy;
\r
402 secondlistener := nil;
\r
407 if state = wsclosed then begin
\r
408 if fdhandlein >= 0 then begin
\r
409 {one *can* get here without fd -beware}
\r
410 eventcore.rmasterclr(fdhandlein);
\r
411 myfdclose(fdhandlein); // we musnt leak file discriptors
\r
412 eventcore.setfdreverse(fdhandlein,nil);
\r
416 eventcore.rmasterset(fdhandlein,not udp);
\r
418 if fdhandleout >= 0 then eventcore.wmasterclr(fdhandleout);
\r
420 //writeln('listened on addr '+addr+':'+port+' '+proto+' using socket number ',fdhandlein);
\r
423 {$ifdef secondlistener}
\r
424 procedure tlsocket.internalclose(error:word);
\r
426 if assigned(secondlistener) then begin
\r
427 secondlistener.destroy;
\r
428 secondlistener := nil;
\r
430 inherited internalclose(error);
\r
433 procedure tlsocket.secondaccepthandler;
\r
435 lastsessionfromsecond := true;
\r
437 ondataavailable(self,error);
\r
439 if assigned(onsessionavailable) then onsessionavailable(self,error);
\r
444 function tlsocket.accept : longint;
\r
446 FromAddrSize : LongInt; // i don't realy know what to do with these at this
\r
447 FromAddr : TInetSockAddrV; // at this point time will tell :)
\r
450 {$ifdef secondlistener}
\r
451 if (lastsessionfromsecond) then begin
\r
452 lastsessionfromsecond := false;
\r
453 result := secondlistener.accept;
\r
458 FromAddrSize := Sizeof(FromAddr);
\r
460 result := winsock.accept(fdhandlein,@fromaddr,@fromaddrsize);
\r
462 result := sockets.accept(fdhandlein,fromaddr,fromaddrsize);
\r
464 //now we have accepted one request start monitoring for more again
\r
465 eventcore.rmasterset(fdhandlein,true);
\r
467 if result = -1 then begin
\r
468 raise esocketexception.create('error '+inttostr({$ifdef win32}getlasterror{$else}socketerror{$endif})+' while accepting');
\r
470 if result > absoloutemaxs then begin
\r
474 raise esocketexception.create('file discriptor out of range: '+inttostr(a));
\r
478 function tlsocket.sendto(dest:TInetSockAddrV;destlen:integer;data:pointer;len:integer):integer;
\r
480 destx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute dest;
\r
482 {$ifdef secondlistener}
\r
483 if assigned(secondlistener) then if (dest.inaddr.family = AF_INET) then begin
\r
484 result := secondlistener.sendto(dest,destlen,data,len);
\r
488 result := {$ifdef win32}winsock{$else}sockets{$endif}.sendto(self.fdhandleout,data^,len,0,destx,destlen);
\r
491 function tlsocket.receivefrom(data:pointer;len:integer;var src:TInetSockAddrV;var srclen:integer):integer;
\r
493 tempsrc:TInetSockAddrV;
\r
494 tempsrclen:integer;
\r
495 srcx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute tempsrc;
\r
498 {$ifdef secondlistener}
\r
499 if assigned(secondlistener) then if lastsessionfromsecond then begin
\r
500 lastsessionfromsecond := false;
\r
501 result := secondlistener.receivefrom(data,len,src,srclen);
\r
505 tempsrclen := sizeof(tempsrc);
\r
506 result := {$ifdef win32}winsock{$else}sockets{$endif}.recvfrom(self.fdhandlein,data^,len,0,srcx,tempsrclen);
\r
509 biniptemp := inaddrvtobinip(tempsrc);
\r
510 if needconverttov4(biniptemp) then begin
\r
511 converttov4(biniptemp);
\r
512 tempsrclen := makeinaddrv(biniptemp,inttostr(ntohs(tempsrc.InAddr.port)),tempsrc);
\r
516 move(tempsrc,src,srclen);
\r
517 srclen := tempsrclen;
\r
520 procedure tlsocket.connectionfailedhandler(error:word);
\r
522 if trymoreips then begin
\r
523 // writeln('failed with error ',error);
\r
524 connecttimeout.enabled := false;
\r
525 destroying := true;
\r
526 state := wsconnected;
\r
527 self.internalclose(0);
\r
528 destroying := false;
\r
531 state := wsconnected;
\r
532 if assigned(onsessionconnected) then onsessionconnected(self,error);
\r
533 self.internalclose(0);
\r
534 recvq.del(maxlongint);
\r
538 procedure tlsocket.connectsuccesshandler;
\r
540 trymoreips := false;
\r
541 connecttimeout.enabled := false;
\r
542 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
546 procedure tlsocket.handlefdtrigger(readtrigger,writetrigger:boolean);
\r
548 tempbuf:array[0..receivebufsize-1] of byte;
\r
550 // writeln('got a fd trigger, readtrigger=',readtrigger,' writetrigger=',writetrigger,' state=',integer(state));
\r
551 if (state =wslistening) and readtrigger then begin
\r
552 { debugout('listening socket triggered on read');}
\r
553 eventcore.rmasterclr(fdhandlein);
\r
554 if assigned(onsessionAvailable) then onsessionAvailable(self,0);
\r
556 if dgram and readtrigger then begin
\r
557 if assigned(ondataAvailable) then ondataAvailable(self,0);
\r
561 if (state =wsconnecting) and writetrigger then begin
\r
562 // code for dealing with the reults of a non-blocking connect is
\r
564 // if just write is triggered it means connect suceeded
\r
565 // if both read and write are triggered it can mean 2 things
\r
566 // 1: connect ok and data availible
\r
568 // to find out which you must read from the socket and look for errors
\r
569 // there if we read successfully we drop through into the code for fireing
\r
571 if not readtrigger then begin
\r
572 state := wsconnected;
\r
573 connectsuccesshandler;
\r
575 numread := myfdread(fdhandlein,tempbuf,sizeof(tempbuf));
\r
576 if numread <> -1 then begin
\r
577 state := wsconnected;
\r
578 connectsuccesshandler;
\r
579 //connectread := true;
\r
580 recvq.add(@tempbuf,numread);
\r
582 connectionfailedhandler({$ifdef win32}wsagetlasterror{$else}linuxerror{$endif});
\r
585 // if things went well here we are now in the state wsconnected with data sitting in our receive buffer
\r
586 // so we drop down into the processing for data availible
\r
588 if fdhandlein >= 0 then begin
\r
589 if state = wsconnected then begin
\r
590 eventcore.rmasterset(fdhandlein,false);
\r
592 eventcore.rmasterclr(fdhandlein);
\r
595 if fdhandleout >= 0 then begin
\r
596 if sendq.size = 0 then begin
\r
597 //don't clear the bit in fdswmaster if data is in the sendq
\r
598 eventcore.wmasterclr(fdhandleout);
\r
603 inherited handlefdtrigger(readtrigger,writetrigger);
\r
606 constructor tlsocket.Create(AOwner: TComponent);
\r
608 inherited create(aowner);
\r
609 closehandles := true;
\r
610 trymoreips := true;
\r
614 function tlsocket.getpeername(var addr:tsockaddrin;addrlen:integer):integer;
\r
616 addrx : {$ifdef win32}winsock.tsockaddr{$else}tsockaddrin{$endif} absolute addr;
\r
618 result := {$ifdef win32}winsock{$else}sockets{$endif}.getpeername(self.fdhandlein,addrx,addrlen);
\r
621 procedure tlsocket.getxaddrbin(var binip:tbinip);
\r
623 addr:tinetsockaddrv;
\r
627 fillchar(addr,sizeof(addr),0);
\r
630 winsock.getsockname(self.fdhandlein,psockaddr(@addr)^,i);
\r
632 sockets.getsocketname(self.fdhandlein,addr,i);
\r
634 binip := inaddrvtobinip(addr);
\r
635 converttov4(binip);
\r
638 procedure tlsocket.getpeeraddrbin(var binip:tbinip);
\r
640 addr:tinetsockaddrv;
\r
644 fillchar(addr,sizeof(addr),0);
\r
646 winsock.getpeername(self.fdhandlein,psockaddr(@addr)^,i);
\r
648 sockets.getpeername(self.fdhandlein,addr,i);
\r
651 binip := inaddrvtobinip(addr);
\r
652 converttov4(binip);
\r
655 function tlsocket.getXaddr:string;
\r
659 getxaddrbin(biniptemp);
\r
660 result := ipbintostr(biniptemp);
\r
661 if result = '' then result := 'error';
\r
664 function tlsocket.getpeeraddr:string;
\r
668 getpeeraddrbin(biniptemp);
\r
669 result := ipbintostr(biniptemp);
\r
670 if result = '' then result := 'error';
\r
673 function tlsocket.getXport:string;
\r
675 addr:tinetsockaddrv;
\r
680 winsock.getsockname(self.fdhandlein,psockaddrin(@addr)^,i);
\r
683 sockets.getsocketname(self.fdhandlein,addr,i);
\r
686 result := inttostr(htons(addr.InAddr.port));
\r
689 function tlsocket.getpeerport:string;
\r
691 addr:tinetsockaddrv;
\r
696 winsock.getpeername(self.fdhandlein,psockaddrin(@addr)^,i);
\r
699 sockets.getpeername(self.fdhandlein,addr,i);
\r
702 result := inttostr(htons(addr.InAddr.port));
\r
706 procedure tlsocket.myfdclose(fd : integer);
\r
710 function tlsocket.myfdwrite(fd: LongInt;const buf;size: LongInt):LongInt;
\r
712 result := winsock.send(fd,(@buf)^,size,0);
\r
714 function tlsocket.myfdread(fd: LongInt;var buf;size: LongInt):LongInt;
\r
716 result := winsock.recv(fd,buf,size,0);
\r