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 function getaddrsize:integer;
\r
111 procedure connect; virtual;
\r
112 procedure realconnect;
\r
113 procedure bindsocket;
\r
115 function accept : longint;
\r
116 function sendto(dest:TInetSockAddrV;destlen:integer;data:pointer;len:integer):integer; virtual;
\r
117 function receivefrom(data:pointer;len:integer;var src:TInetSockAddrV;var srclen:integer):integer; virtual;
\r
119 procedure handlefdtrigger(readtrigger,writetrigger:boolean); override;
\r
120 function send(data:pointer;len:integer):integer;override;
\r
121 procedure sendstr(const str : string);override;
\r
122 function Receive(Buf:Pointer;BufSize:integer):integer; override;
\r
123 function getpeername(var addr:tsockaddrin;addrlen:integer):integer; virtual;
\r
124 procedure getXaddrbin(var binip:tbinip); virtual;
\r
125 procedure getpeeraddrbin(var binip:tbinip); virtual;
\r
126 function getXaddr:string; virtual;
\r
127 function getpeeraddr:string; virtual;
\r
128 function getXport:string; virtual;
\r
129 function getpeerport:string; virtual;
\r
130 constructor Create(AOwner: TComponent); override;
\r
132 //this one has to be kept public for now because lcorewsaasyncselect calls it
\r
133 procedure connectionfailedhandler(error:word);
\r
135 procedure taskcallconnectionfailedhandler(wparam,lparam : longint);
\r
137 procedure connecttimeouthandler(sender:tobject);
\r
138 procedure connectsuccesshandler;
\r
140 procedure myfdclose(fd : integer); override;
\r
141 function myfdwrite(fd: LongInt;const buf;size: LongInt):LongInt; override;
\r
142 function myfdread(fd: LongInt;var buf;size: LongInt):LongInt; override;
\r
145 tsocket=longint; // for compatibility with twsocket
\r
147 twsocket=tlsocket; {easy}
\r
155 {$include unixstuff.inc}
\r
158 function tlsocket.getaddrsize:integer;
\r
160 result := inaddrsize(inaddr);
\r
163 //I used to use the system versions of these from within lsocket (which has
\r
164 //functions whose name clashes with them) by using sockets.* and but I can't do
\r
165 //that anymore since in some cases connect is now provided by unixstuff.inc
\r
166 //hence these wrapper functions --plugwash
\r
168 function system_Connect(Sock: LongInt;const Addr;Addrlen: LongInt):Boolean;
\r
170 result := connect(sock,addr,addrlen);
\r
172 function system_SendTo(Sock: LongInt; const Buf;BufLen: LongInt;Flags: LongInt;var Addr;AddrLen: LongInt):LongInt;
\r
174 result := sendto(sock,buf,buflen,flags,addr,addrlen);
\r
176 function system_getpeername(Sock: LongInt;var Addr;var Addrlen: LongInt):LongInt;
\r
178 result := getpeername(sock,addr,addrlen);
\r
180 function system_getsocketname(Sock: LongInt;var Addr;var Addrlen: LongInt):LongInt;
\r
182 result := getsocketname(sock,addr,addrlen);
\r
184 function system_listen(Sock: LongInt; MaxConnect: LongInt):Boolean;
\r
186 result := listen(sock,maxconnect);
\r
188 function system_Accept(Sock: LongInt;var Addr;var Addrlen: LongInt):LongInt;
\r
190 result := accept(sock,addr,addrlen);
\r
194 procedure tlsocket.realconnect;
\r
198 //writeln('trying to connect to ',ipbintostr(biniplist_get(biniplist,currentip)),'#',port);
\r
199 makeinaddrv(biniplist_get(biniplist,currentip),port,inaddr);
\r
201 if (currentip >= biniplist_getcount(biniplist)) then trymoreips := false;
\r
204 if (uppercase(proto) = 'UDP') then begin
\r
209 end else if (uppercase(proto) = 'TCP') or (uppercase(proto) = '') then begin
\r
213 end else if (uppercase(proto) = 'ICMP') or (strtointdef(proto,256) < 256) then begin
\r
214 b := strtointdef(proto,IPPROTO_ICMP);
\r
218 raise ESocketException.create('unrecognised protocol');
\r
221 a := Socket(inaddr.inaddr.family,a,b);
\r
222 //writeln(ord(inaddr.inaddr.family));
\r
223 if a = -1 then begin
\r
224 //unable to create socket, fire an error event (better to use an error event
\r
225 //to avoid poor interaction with multilistener stuff.
\r
226 //a socket value of -2 is a special value to say there is no socket but
\r
227 //we want internalclose to act as if there was
\r
230 tltask.create(taskcallconnectionfailedhandler,self,{$ifdef win32}wsagetlasterror{$else}socketerror{$endif},0);
\r
236 if dgram then begin
\r
238 SetSocketOptions(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
240 SetSockOpt(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
242 state := wsconnected;
\r
243 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
245 eventcore.rmasterset(fdhandlein,false);
\r
246 eventcore.wmasterclr(fdhandleout);
\r
248 state :=wsconnecting;
\r
250 //writeln(inaddr.inaddr.port);
\r
251 winsock.Connect(fdhandlein,winsock.psockaddr(@inADDR)^,getaddrsize);
\r
253 system_Connect(fdhandlein,inADDR,getaddrsize);
\r
255 eventcore.rmasterset(fdhandlein,false);
\r
256 eventcore.wmasterset(fdhandleout);
\r
257 if trymoreips then connecttimeout.enabled := true;
\r
261 on e: exception do begin
\r
263 raise; //reraise the exception
\r
269 procedure tlsocket.connecttimeouthandler(sender:tobject);
\r
271 connecttimeout.enabled := false;
\r
272 destroying := true; //hack to not cause handler to trigger
\r
274 destroying := false;
\r
281 procedure tlsocket.connect;
\r
286 if state <> wsclosed then close;
\r
288 if isbiniplist(addr) then biniplist := addr else biniplist := forwardlookuplist(addr,0);
\r
289 if biniplist_getcount(biniplist) = 0 then raise exception.create('unable to resolve '+addr);
\r
291 //makeinaddrv(addr,port,inaddr);
\r
294 if not assigned(connecttimeout) then begin
\r
295 connecttimeout := tltimer.create(self);
\r
296 connecttimeout.ontimer := connecttimeouthandler;
\r
297 connecttimeout.interval := 2500;
\r
298 connecttimeout.enabled := false;
\r
303 procedure tlsocket.sendstr(const str : string);
\r
305 if dgram then begin
\r
306 send(@str[1],length(str))
\r
308 inherited sendstr(str);
\r
312 function tlsocket.send(data:pointer;len:integer):integer;
\r
314 if dgram then begin
\r
315 // writeln('sending to '+ipbintostr(inaddrvtobinip(inaddr)),' ',htons(inaddr.inaddr.port),' ',len,' bytes');
\r
316 result := sendto(inaddr,getaddrsize,data,len);
\r
318 // writeln('send result ',result);
\r
319 // writeln('errno',errno);
\r
321 result := inherited send(data,len);
\r
326 function tlsocket.receive(Buf:Pointer;BufSize:integer):integer;
\r
328 if dgram then begin
\r
329 {$ifdef secondlistener}
\r
330 if lastsessionfromsecond then begin
\r
331 result := secondlistener.receive(buf,bufsize);
\r
332 lastsessionfromsecond := false;
\r
335 result := myfdread(self.fdhandlein,buf^,bufsize);
\r
337 result := inherited receive(buf,bufsize);
\r
341 procedure tlsocket.bindsocket;
\r
344 inAddrtemp:TInetSockAddrV;
\r
345 inAddrtempx:{$ifdef win32}winsock.TSockaddr{$else}TInetSockAddrV{$endif} absolute inaddrtemp;
\r
346 inaddrtempsize:integer;
\r
349 if (localaddr <> '') or (localport <> '') then begin
\r
350 if localaddr = '' then begin
\r
352 if inaddr.inaddr.family = AF_INET6 then localaddr := '::' else
\r
354 localaddr := '0.0.0.0';
\r
356 //gethostbyname(localaddr,host);
\r
357 inaddrtempsize := makeinaddrv(forwardlookup(localaddr,0),localport,inaddrtemp);
\r
359 If Bind(fdhandlein,inaddrtempx,inaddrtempsize)<> {$ifdef win32}0{$else}true{$endif} Then begin
\r
361 lasterror := {$ifdef win32}getlasterror{$else}socketerror{$endif};
\r
362 raise ESocketException.create('unable to bind on address '+localaddr+'#'+localport+', error '+inttostr(lasterror));
\r
367 on e: exception do begin
\r
369 raise; //reraise the exception
\r
374 procedure tlsocket.listen;
\r
381 if state <> wsclosed then close;
\r
382 udp := uppercase(proto) = 'UDP';
\r
384 socktype := SOCK_DGRAM;
\r
386 end else socktype := SOCK_STREAM;
\r
389 if addr = '' then begin
\r
391 if not v4listendefault then begin
\r
397 if isbiniplist(addr) then biniptemp := biniplist_get(addr,0) else biniptemp := forwardlookup(addr,10);
\r
398 addr := ipbintostr(biniptemp);
\r
399 fdhandlein := socket(biniptemp.family,socktype,0);
\r
401 if (addr = '::') and (origaddr = '') and (fdhandlein < 0) then begin
\r
403 fdhandlein := socket(AF_INET,socktype,0);
\r
407 if fdhandlein = -1 then raise ESocketException.create('unable to create socket'{$ifdef win32}+' error='+inttostr(wsagetlasterror){$endif});
\r
408 dupnowatch(fdhandlein); // sets up maxs and copies handle to fdhandleout among other things
\r
409 //eventcore.setfdreverse(fdhandlein,self); //already taken care of by dup
\r
410 state := wsclosed; // then set this back as it was an undesired side effect of dup
\r
413 yes := $01010101; {Copied this from existing code. Value is empiric,
\r
414 but works. (yes=true<>0) }
\r
416 if SetSocketOptions(fdhandlein, SOL_SOCKET, SO_REUSEADDR,yes,sizeof(yes))=-1 then begin
\r
417 raise ESocketException.create('unable to set socket options');
\r
424 if not udp then begin
\r
425 {!!! allow custom queue length? default 5}
\r
426 if listenqueue = 0 then listenqueue := 5;
\r
427 If {$ifdef win32}winsock.listen{$else}system_listen{$endif}(fdhandlein,listenqueue)<>{$ifdef win32}0{$else}true{$endif} Then raise
\r
428 esocketexception.create('unable to listen');
\r
429 state := wsListening;
\r
432 SetSocketOptions(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
434 SetSockOpt(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
436 state := wsconnected;
\r
439 {$ifdef secondlistener}
\r
440 //listening on ::. try to listen on 0.0.0.0 as well for platforms which don't already do that
\r
441 if addr = '::' then begin
\r
442 secondlistener := tlsocket.create(nil);
\r
443 secondlistener.proto := proto;
\r
444 secondlistener.addr := '0.0.0.0';
\r
445 secondlistener.port := port;
\r
447 secondlistener.ondataavailable := secondaccepthandler;
\r
449 secondlistener.onsessionAvailable := secondaccepthandler;
\r
452 secondlistener.listen;
\r
454 secondlistener.destroy;
\r
455 secondlistener := nil;
\r
460 if state = wsclosed then begin
\r
461 if fdhandlein >= 0 then begin
\r
462 {one *can* get here without fd -beware}
\r
463 eventcore.rmasterclr(fdhandlein);
\r
464 myfdclose(fdhandlein); // we musnt leak file discriptors
\r
465 eventcore.setfdreverse(fdhandlein,nil);
\r
469 eventcore.rmasterset(fdhandlein,not udp);
\r
471 if fdhandleout >= 0 then eventcore.wmasterclr(fdhandleout);
\r
473 //writeln('listened on addr '+addr+':'+port+' '+proto+' using socket number ',fdhandlein);
\r
476 {$ifdef secondlistener}
\r
477 procedure tlsocket.internalclose(error:word);
\r
479 if assigned(secondlistener) then begin
\r
480 secondlistener.destroy;
\r
481 secondlistener := nil;
\r
483 inherited internalclose(error);
\r
486 procedure tlsocket.secondaccepthandler;
\r
488 lastsessionfromsecond := true;
\r
490 ondataavailable(self,error);
\r
492 if assigned(onsessionavailable) then onsessionavailable(self,error);
\r
497 function tlsocket.accept : longint;
\r
499 FromAddrSize : LongInt; // i don't realy know what to do with these at this
\r
500 FromAddr : TInetSockAddrV; // at this point time will tell :)
\r
503 {$ifdef secondlistener}
\r
504 if (lastsessionfromsecond) then begin
\r
505 lastsessionfromsecond := false;
\r
506 result := secondlistener.accept;
\r
511 FromAddrSize := Sizeof(FromAddr);
\r
513 result := winsock.accept(fdhandlein,@fromaddr,@fromaddrsize);
\r
515 result := system_accept(fdhandlein,fromaddr,fromaddrsize);
\r
517 //now we have accepted one request start monitoring for more again
\r
518 eventcore.rmasterset(fdhandlein,true);
\r
520 if result = -1 then begin
\r
521 raise esocketexception.create('error '+inttostr({$ifdef win32}getlasterror{$else}socketerror{$endif})+' while accepting');
\r
523 if result > absoloutemaxs then begin
\r
527 raise esocketexception.create('file discriptor out of range: '+inttostr(a));
\r
532 function tlsocket.sendto(dest:TInetSockAddrV;destlen:integer;data:pointer;len:integer):integer;
\r
534 destx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute dest;
\r
536 {$ifdef secondlistener}
\r
537 if assigned(secondlistener) then if (dest.inaddr.family = AF_INET) then begin
\r
538 result := secondlistener.sendto(dest,destlen,data,len);
\r
542 result := {$ifdef win32}winsock.sendto{$else}system_sendto{$endif}(self.fdhandleout,data^,len,0,destx,destlen);
\r
546 function tlsocket.receivefrom(data:pointer;len:integer;var src:TInetSockAddrV;var srclen:integer):integer;
\r
548 tempsrc:TInetSockAddrV;
\r
549 tempsrclen:integer;
\r
550 srcx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute tempsrc;
\r
553 {$ifdef secondlistener}
\r
554 if assigned(secondlistener) then if lastsessionfromsecond then begin
\r
555 lastsessionfromsecond := false;
\r
556 result := secondlistener.receivefrom(data,len,src,srclen);
\r
560 tempsrclen := sizeof(tempsrc);
\r
561 result := recvfrom(self.fdhandlein,data^,len,0,srcx,tempsrclen);
\r
564 biniptemp := inaddrvtobinip(tempsrc);
\r
565 if needconverttov4(biniptemp) then begin
\r
566 converttov4(biniptemp);
\r
567 tempsrclen := makeinaddrv(biniptemp,inttostr(ntohs(tempsrc.InAddr.port)),tempsrc);
\r
571 move(tempsrc,src,srclen);
\r
572 srclen := tempsrclen;
\r
575 procedure tlsocket.taskcallconnectionfailedhandler(wparam,lparam : longint);
\r
577 connectionfailedhandler(wparam);
\r
580 procedure tlsocket.connectionfailedhandler(error:word);
\r
582 if trymoreips then begin
\r
583 // writeln('failed with error ',error);
\r
584 connecttimeout.enabled := false;
\r
585 destroying := true;
\r
586 state := wsconnected;
\r
587 self.internalclose(0);
\r
588 destroying := false;
\r
591 state := wsconnected;
\r
592 if assigned(onsessionconnected) then onsessionconnected(self,error);
\r
593 self.internalclose(0);
\r
594 recvq.del(maxlongint);
\r
598 procedure tlsocket.connectsuccesshandler;
\r
600 trymoreips := false;
\r
601 connecttimeout.enabled := false;
\r
602 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
606 procedure tlsocket.handlefdtrigger(readtrigger,writetrigger:boolean);
\r
608 tempbuf:array[0..receivebufsize-1] of byte;
\r
610 // writeln('got a fd trigger, readtrigger=',readtrigger,' writetrigger=',writetrigger,' state=',integer(state));
\r
611 if (state =wslistening) and readtrigger then begin
\r
612 { debugout('listening socket triggered on read');}
\r
613 eventcore.rmasterclr(fdhandlein);
\r
614 if assigned(onsessionAvailable) then onsessionAvailable(self,0);
\r
616 if dgram and readtrigger then begin
\r
617 if assigned(ondataAvailable) then ondataAvailable(self,0);
\r
621 if (state =wsconnecting) and writetrigger then begin
\r
622 // code for dealing with the reults of a non-blocking connect is
\r
624 // if just write is triggered it means connect suceeded
\r
625 // if both read and write are triggered it can mean 2 things
\r
626 // 1: connect ok and data availible
\r
628 // to find out which you must read from the socket and look for errors
\r
629 // there if we read successfully we drop through into the code for fireing
\r
631 if not readtrigger then begin
\r
632 state := wsconnected;
\r
633 connectsuccesshandler;
\r
635 numread := myfdread(fdhandlein,tempbuf,sizeof(tempbuf));
\r
636 if numread <> -1 then begin
\r
637 state := wsconnected;
\r
638 connectsuccesshandler;
\r
639 //connectread := true;
\r
640 recvq.add(@tempbuf,numread);
\r
642 connectionfailedhandler({$ifdef win32}wsagetlasterror{$else}linuxerror{$endif});
\r
645 // if things went well here we are now in the state wsconnected with data sitting in our receive buffer
\r
646 // so we drop down into the processing for data availible
\r
648 if fdhandlein >= 0 then begin
\r
649 if state = wsconnected then begin
\r
650 eventcore.rmasterset(fdhandlein,false);
\r
652 eventcore.rmasterclr(fdhandlein);
\r
655 if fdhandleout >= 0 then begin
\r
656 if sendq.size = 0 then begin
\r
657 //don't clear the bit in fdswmaster if data is in the sendq
\r
658 eventcore.wmasterclr(fdhandleout);
\r
663 inherited handlefdtrigger(readtrigger,writetrigger);
\r
666 constructor tlsocket.Create(AOwner: TComponent);
\r
668 inherited create(aowner);
\r
669 closehandles := true;
\r
670 trymoreips := true;
\r
675 function tlsocket.getpeername(var addr:tsockaddrin;addrlen:integer):integer;
\r
677 addrx : {$ifdef win32}winsock.tsockaddr{$else}tsockaddrin{$endif} absolute addr;
\r
679 result := {$ifdef win32}winsock.getpeername{$else}system_getpeername{$endif}(self.fdhandlein,addrx,addrlen);
\r
682 procedure tlsocket.getxaddrbin(var binip:tbinip);
\r
684 addr:tinetsockaddrv;
\r
688 fillchar(addr,sizeof(addr),0);
\r
691 winsock.getsockname(self.fdhandlein,psockaddr(@addr)^,i);
\r
693 system_getsocketname(self.fdhandlein,addr,i);
\r
695 binip := inaddrvtobinip(addr);
\r
696 converttov4(binip);
\r
699 procedure tlsocket.getpeeraddrbin(var binip:tbinip);
\r
701 addr:tinetsockaddrv;
\r
705 fillchar(addr,sizeof(addr),0);
\r
707 winsock.getpeername(self.fdhandlein,psockaddr(@addr)^,i);
\r
709 system_getpeername(self.fdhandlein,addr,i);
\r
712 binip := inaddrvtobinip(addr);
\r
713 converttov4(binip);
\r
716 function tlsocket.getXaddr:string;
\r
720 getxaddrbin(biniptemp);
\r
721 result := ipbintostr(biniptemp);
\r
722 if result = '' then result := 'error';
\r
725 function tlsocket.getpeeraddr:string;
\r
729 getpeeraddrbin(biniptemp);
\r
730 result := ipbintostr(biniptemp);
\r
731 if result = '' then result := 'error';
\r
734 function tlsocket.getXport:string;
\r
736 addr:tinetsockaddrv;
\r
741 winsock.getsockname(self.fdhandlein,psockaddrin(@addr)^,i);
\r
744 system_getsocketname(self.fdhandlein,addr,i);
\r
747 result := inttostr(htons(addr.InAddr.port));
\r
750 function tlsocket.getpeerport:string;
\r
752 addr:tinetsockaddrv;
\r
757 winsock.getpeername(self.fdhandlein,psockaddrin(@addr)^,i);
\r
760 system_getpeername(self.fdhandlein,addr,i);
\r
763 result := inttostr(htons(addr.InAddr.port));
\r
767 procedure tlsocket.myfdclose(fd : integer);
\r
771 function tlsocket.myfdwrite(fd: LongInt;const buf;size: LongInt):LongInt;
\r
773 result := winsock.send(fd,(@buf)^,size,0);
\r
775 function tlsocket.myfdread(fd: LongInt;var buf;size: LongInt):LongInt;
\r
777 result := winsock.recv(fd,buf,size,0);
\r