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
164 procedure tlsocket.realconnect;
\r
168 //writeln('trying to connect to ',ipbintostr(biniplist_get(biniplist,currentip)),'#',port);
\r
169 makeinaddrv(biniplist_get(biniplist,currentip),port,inaddr);
\r
171 if (currentip >= biniplist_getcount(biniplist)) then trymoreips := false;
\r
174 if (uppercase(proto) = 'UDP') then begin
\r
179 end else if (uppercase(proto) = 'TCP') or (uppercase(proto) = '') then begin
\r
183 end else if (uppercase(proto) = 'ICMP') or (strtointdef(proto,256) < 256) then begin
\r
184 b := strtointdef(proto,IPPROTO_ICMP);
\r
188 raise ESocketException.create('unrecognised protocol');
\r
191 a := Socket(inaddr.inaddr.family,a,b);
\r
192 //writeln(ord(inaddr.inaddr.family));
\r
193 if a = -1 then begin
\r
194 //unable to create socket, fire an error event (better to use an error event
\r
195 //to avoid poor interaction with multilistener stuff.
\r
196 //a socket value of -2 is a special value to say there is no socket but
\r
197 //we want internalclose to act as if there was
\r
200 tltask.create(taskcallconnectionfailedhandler,self,{$ifdef win32}wsagetlasterror{$else}socketerror{$endif},0);
\r
206 if dgram then begin
\r
208 SetSocketOptions(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
210 SetSockOpt(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
212 state := wsconnected;
\r
213 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
215 eventcore.rmasterset(fdhandlein,false);
\r
216 eventcore.wmasterclr(fdhandleout);
\r
218 state :=wsconnecting;
\r
220 //writeln(inaddr.inaddr.port);
\r
221 winsock.Connect(fdhandlein,winsock.psockaddr(@inADDR)^,getaddrsize);
\r
223 sockets.Connect(fdhandlein,inADDR,getaddrsize);
\r
225 eventcore.rmasterset(fdhandlein,false);
\r
226 eventcore.wmasterset(fdhandleout);
\r
227 if trymoreips then connecttimeout.enabled := true;
\r
231 on e: exception do begin
\r
233 raise; //reraise the exception
\r
239 procedure tlsocket.connecttimeouthandler(sender:tobject);
\r
241 connecttimeout.enabled := false;
\r
242 destroying := true; //hack to not cause handler to trigger
\r
244 destroying := false;
\r
248 procedure tlsocket.connect;
\r
253 if state <> wsclosed then close;
\r
255 if isbiniplist(addr) then biniplist := addr else biniplist := forwardlookuplist(addr,0);
\r
256 if biniplist_getcount(biniplist) = 0 then raise exception.create('unable to resolve '+addr);
\r
258 //makeinaddrv(addr,port,inaddr);
\r
261 if not assigned(connecttimeout) then begin
\r
262 connecttimeout := tltimer.create(self);
\r
263 connecttimeout.ontimer := connecttimeouthandler;
\r
264 connecttimeout.interval := 2500;
\r
265 connecttimeout.enabled := false;
\r
270 procedure tlsocket.sendstr(const str : string);
\r
272 if dgram then begin
\r
273 send(@str[1],length(str))
\r
275 inherited sendstr(str);
\r
279 function tlsocket.send(data:pointer;len:integer):integer;
\r
281 if dgram then begin
\r
282 // writeln('sending to '+ipbintostr(inaddrvtobinip(inaddr)),' ',htons(inaddr.inaddr.port),' ',len,' bytes');
\r
283 result := sendto(inaddr,getaddrsize,data,len);
\r
285 // writeln('send result ',result);
\r
286 // writeln('errno',errno);
\r
288 result := inherited send(data,len);
\r
293 function tlsocket.receive(Buf:Pointer;BufSize:integer):integer;
\r
295 if dgram then begin
\r
296 {$ifdef secondlistener}
\r
297 if lastsessionfromsecond then begin
\r
298 result := secondlistener.receive(buf,bufsize);
\r
299 lastsessionfromsecond := false;
\r
302 result := myfdread(self.fdhandlein,buf^,bufsize);
\r
304 result := inherited receive(buf,bufsize);
\r
308 procedure tlsocket.bindsocket;
\r
311 inAddrtemp:TInetSockAddrV;
\r
312 inAddrtempx:{$ifdef win32}winsock.TSockaddr{$else}TInetSockAddrV{$endif} absolute inaddrtemp;
\r
313 inaddrtempsize:integer;
\r
316 if (localaddr <> '') or (localport <> '') then begin
\r
317 if localaddr = '' then begin
\r
319 if inaddr.inaddr.family = AF_INET6 then localaddr := '::' else
\r
321 localaddr := '0.0.0.0';
\r
323 //gethostbyname(localaddr,host);
\r
324 inaddrtempsize := makeinaddrv(forwardlookup(localaddr,0),localport,inaddrtemp);
\r
326 If Bind(fdhandlein,inaddrtempx,inaddrtempsize)<> {$ifdef win32}0{$else}true{$endif} Then begin
\r
328 lasterror := {$ifdef win32}getlasterror{$else}socketerror{$endif};
\r
329 raise ESocketException.create('unable to bind on address '+localaddr+'#'+localport+', error '+inttostr(lasterror));
\r
334 on e: exception do begin
\r
336 raise; //reraise the exception
\r
341 procedure tlsocket.listen;
\r
348 if state <> wsclosed then close;
\r
349 udp := uppercase(proto) = 'UDP';
\r
351 socktype := SOCK_DGRAM;
\r
353 end else socktype := SOCK_STREAM;
\r
356 if addr = '' then begin
\r
358 if not v4listendefault then begin
\r
364 if isbiniplist(addr) then biniptemp := biniplist_get(addr,0) else biniptemp := forwardlookup(addr,10);
\r
365 addr := ipbintostr(biniptemp);
\r
366 fdhandlein := socket(biniptemp.family,socktype,0);
\r
368 if (addr = '::') and (origaddr = '') and (fdhandlein < 0) then begin
\r
370 fdhandlein := socket(AF_INET,socktype,0);
\r
374 if fdhandlein = -1 then raise ESocketException.create('unable to create socket'{$ifdef win32}+' error='+inttostr(wsagetlasterror){$endif});
\r
375 dupnowatch(fdhandlein); // sets up maxs and copies handle to fdhandleout among other things
\r
376 //eventcore.setfdreverse(fdhandlein,self); //already taken care of by dup
\r
377 state := wsclosed; // then set this back as it was an undesired side effect of dup
\r
380 yes := $01010101; {Copied this from existing code. Value is empiric,
\r
381 but works. (yes=true<>0) }
\r
383 if SetSocketOptions(fdhandlein, SOL_SOCKET, SO_REUSEADDR,yes,sizeof(yes))=-1 then begin
\r
384 raise ESocketException.create('unable to set socket options');
\r
391 if not udp then begin
\r
392 {!!! allow custom queue length? default 5}
\r
393 if listenqueue = 0 then listenqueue := 5;
\r
394 If {$ifdef win32}winsock{$else}sockets{$endif}.Listen(fdhandlein,listenqueue)<>{$ifdef win32}0{$else}true{$endif} Then raise
\r
395 esocketexception.create('unable to listen');
\r
396 state := wsListening;
\r
399 SetSocketOptions(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
401 SetSockOpt(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
403 state := wsconnected;
\r
406 {$ifdef secondlistener}
\r
407 //listening on ::. try to listen on 0.0.0.0 as well for platforms which don't already do that
\r
408 if addr = '::' then begin
\r
409 secondlistener := tlsocket.create(nil);
\r
410 secondlistener.proto := proto;
\r
411 secondlistener.addr := '0.0.0.0';
\r
412 secondlistener.port := port;
\r
414 secondlistener.ondataavailable := secondaccepthandler;
\r
416 secondlistener.onsessionAvailable := secondaccepthandler;
\r
419 secondlistener.listen;
\r
421 secondlistener.destroy;
\r
422 secondlistener := nil;
\r
427 if state = wsclosed then begin
\r
428 if fdhandlein >= 0 then begin
\r
429 {one *can* get here without fd -beware}
\r
430 eventcore.rmasterclr(fdhandlein);
\r
431 myfdclose(fdhandlein); // we musnt leak file discriptors
\r
432 eventcore.setfdreverse(fdhandlein,nil);
\r
436 eventcore.rmasterset(fdhandlein,not udp);
\r
438 if fdhandleout >= 0 then eventcore.wmasterclr(fdhandleout);
\r
440 //writeln('listened on addr '+addr+':'+port+' '+proto+' using socket number ',fdhandlein);
\r
443 {$ifdef secondlistener}
\r
444 procedure tlsocket.internalclose(error:word);
\r
446 if assigned(secondlistener) then begin
\r
447 secondlistener.destroy;
\r
448 secondlistener := nil;
\r
450 inherited internalclose(error);
\r
453 procedure tlsocket.secondaccepthandler;
\r
455 lastsessionfromsecond := true;
\r
457 ondataavailable(self,error);
\r
459 if assigned(onsessionavailable) then onsessionavailable(self,error);
\r
464 function tlsocket.accept : longint;
\r
466 FromAddrSize : LongInt; // i don't realy know what to do with these at this
\r
467 FromAddr : TInetSockAddrV; // at this point time will tell :)
\r
470 {$ifdef secondlistener}
\r
471 if (lastsessionfromsecond) then begin
\r
472 lastsessionfromsecond := false;
\r
473 result := secondlistener.accept;
\r
478 FromAddrSize := Sizeof(FromAddr);
\r
480 result := winsock.accept(fdhandlein,@fromaddr,@fromaddrsize);
\r
482 result := sockets.accept(fdhandlein,fromaddr,fromaddrsize);
\r
484 //now we have accepted one request start monitoring for more again
\r
485 eventcore.rmasterset(fdhandlein,true);
\r
487 if result = -1 then begin
\r
488 raise esocketexception.create('error '+inttostr({$ifdef win32}getlasterror{$else}socketerror{$endif})+' while accepting');
\r
490 if result > absoloutemaxs then begin
\r
494 raise esocketexception.create('file discriptor out of range: '+inttostr(a));
\r
498 function tlsocket.sendto(dest:TInetSockAddrV;destlen:integer;data:pointer;len:integer):integer;
\r
500 destx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute dest;
\r
502 {$ifdef secondlistener}
\r
503 if assigned(secondlistener) then if (dest.inaddr.family = AF_INET) then begin
\r
504 result := secondlistener.sendto(dest,destlen,data,len);
\r
508 result := {$ifdef win32}winsock{$else}sockets{$endif}.sendto(self.fdhandleout,data^,len,0,destx,destlen);
\r
511 function tlsocket.receivefrom(data:pointer;len:integer;var src:TInetSockAddrV;var srclen:integer):integer;
\r
513 tempsrc:TInetSockAddrV;
\r
514 tempsrclen:integer;
\r
515 srcx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute tempsrc;
\r
518 {$ifdef secondlistener}
\r
519 if assigned(secondlistener) then if lastsessionfromsecond then begin
\r
520 lastsessionfromsecond := false;
\r
521 result := secondlistener.receivefrom(data,len,src,srclen);
\r
525 tempsrclen := sizeof(tempsrc);
\r
526 result := {$ifdef win32}winsock{$else}sockets{$endif}.recvfrom(self.fdhandlein,data^,len,0,srcx,tempsrclen);
\r
529 biniptemp := inaddrvtobinip(tempsrc);
\r
530 if needconverttov4(biniptemp) then begin
\r
531 converttov4(biniptemp);
\r
532 tempsrclen := makeinaddrv(biniptemp,inttostr(ntohs(tempsrc.InAddr.port)),tempsrc);
\r
536 move(tempsrc,src,srclen);
\r
537 srclen := tempsrclen;
\r
540 procedure tlsocket.taskcallconnectionfailedhandler(wparam,lparam : longint);
\r
542 connectionfailedhandler(wparam);
\r
545 procedure tlsocket.connectionfailedhandler(error:word);
\r
547 if trymoreips then begin
\r
548 // writeln('failed with error ',error);
\r
549 connecttimeout.enabled := false;
\r
550 destroying := true;
\r
551 state := wsconnected;
\r
552 self.internalclose(0);
\r
553 destroying := false;
\r
556 state := wsconnected;
\r
557 if assigned(onsessionconnected) then onsessionconnected(self,error);
\r
558 self.internalclose(0);
\r
559 recvq.del(maxlongint);
\r
563 procedure tlsocket.connectsuccesshandler;
\r
565 trymoreips := false;
\r
566 connecttimeout.enabled := false;
\r
567 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
571 procedure tlsocket.handlefdtrigger(readtrigger,writetrigger:boolean);
\r
573 tempbuf:array[0..receivebufsize-1] of byte;
\r
575 // writeln('got a fd trigger, readtrigger=',readtrigger,' writetrigger=',writetrigger,' state=',integer(state));
\r
576 if (state =wslistening) and readtrigger then begin
\r
577 { debugout('listening socket triggered on read');}
\r
578 eventcore.rmasterclr(fdhandlein);
\r
579 if assigned(onsessionAvailable) then onsessionAvailable(self,0);
\r
581 if dgram and readtrigger then begin
\r
582 if assigned(ondataAvailable) then ondataAvailable(self,0);
\r
586 if (state =wsconnecting) and writetrigger then begin
\r
587 // code for dealing with the reults of a non-blocking connect is
\r
589 // if just write is triggered it means connect suceeded
\r
590 // if both read and write are triggered it can mean 2 things
\r
591 // 1: connect ok and data availible
\r
593 // to find out which you must read from the socket and look for errors
\r
594 // there if we read successfully we drop through into the code for fireing
\r
596 if not readtrigger then begin
\r
597 state := wsconnected;
\r
598 connectsuccesshandler;
\r
600 numread := myfdread(fdhandlein,tempbuf,sizeof(tempbuf));
\r
601 if numread <> -1 then begin
\r
602 state := wsconnected;
\r
603 connectsuccesshandler;
\r
604 //connectread := true;
\r
605 recvq.add(@tempbuf,numread);
\r
607 connectionfailedhandler({$ifdef win32}wsagetlasterror{$else}linuxerror{$endif});
\r
610 // if things went well here we are now in the state wsconnected with data sitting in our receive buffer
\r
611 // so we drop down into the processing for data availible
\r
613 if fdhandlein >= 0 then begin
\r
614 if state = wsconnected then begin
\r
615 eventcore.rmasterset(fdhandlein,false);
\r
617 eventcore.rmasterclr(fdhandlein);
\r
620 if fdhandleout >= 0 then begin
\r
621 if sendq.size = 0 then begin
\r
622 //don't clear the bit in fdswmaster if data is in the sendq
\r
623 eventcore.wmasterclr(fdhandleout);
\r
628 inherited handlefdtrigger(readtrigger,writetrigger);
\r
631 constructor tlsocket.Create(AOwner: TComponent);
\r
633 inherited create(aowner);
\r
634 closehandles := true;
\r
635 trymoreips := true;
\r
639 function tlsocket.getpeername(var addr:tsockaddrin;addrlen:integer):integer;
\r
641 addrx : {$ifdef win32}winsock.tsockaddr{$else}tsockaddrin{$endif} absolute addr;
\r
643 result := {$ifdef win32}winsock{$else}sockets{$endif}.getpeername(self.fdhandlein,addrx,addrlen);
\r
646 procedure tlsocket.getxaddrbin(var binip:tbinip);
\r
648 addr:tinetsockaddrv;
\r
652 fillchar(addr,sizeof(addr),0);
\r
655 winsock.getsockname(self.fdhandlein,psockaddr(@addr)^,i);
\r
657 sockets.getsocketname(self.fdhandlein,addr,i);
\r
659 binip := inaddrvtobinip(addr);
\r
660 converttov4(binip);
\r
663 procedure tlsocket.getpeeraddrbin(var binip:tbinip);
\r
665 addr:tinetsockaddrv;
\r
669 fillchar(addr,sizeof(addr),0);
\r
671 winsock.getpeername(self.fdhandlein,psockaddr(@addr)^,i);
\r
673 sockets.getpeername(self.fdhandlein,addr,i);
\r
676 binip := inaddrvtobinip(addr);
\r
677 converttov4(binip);
\r
680 function tlsocket.getXaddr:string;
\r
684 getxaddrbin(biniptemp);
\r
685 result := ipbintostr(biniptemp);
\r
686 if result = '' then result := 'error';
\r
689 function tlsocket.getpeeraddr:string;
\r
693 getpeeraddrbin(biniptemp);
\r
694 result := ipbintostr(biniptemp);
\r
695 if result = '' then result := 'error';
\r
698 function tlsocket.getXport:string;
\r
700 addr:tinetsockaddrv;
\r
705 winsock.getsockname(self.fdhandlein,psockaddrin(@addr)^,i);
\r
708 sockets.getsocketname(self.fdhandlein,addr,i);
\r
711 result := inttostr(htons(addr.InAddr.port));
\r
714 function tlsocket.getpeerport:string;
\r
716 addr:tinetsockaddrv;
\r
721 winsock.getpeername(self.fdhandlein,psockaddrin(@addr)^,i);
\r
724 sockets.getpeername(self.fdhandlein,addr,i);
\r
727 result := inttostr(htons(addr.InAddr.port));
\r
731 procedure tlsocket.myfdclose(fd : integer);
\r
735 function tlsocket.myfdwrite(fd: LongInt;const buf;size: LongInt):LongInt;
\r
737 result := winsock.send(fd,(@buf)^,size,0);
\r
739 function tlsocket.myfdread(fd: LongInt;var buf;size: LongInt):LongInt;
\r
741 result := winsock.recv(fd,buf,size,0);
\r