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
164 // writeln('trying to connect to ',ipbintostr(biniplist_get(biniplist,currentip)),'#',port);
\r
165 makeinaddrv(biniplist_get(biniplist,currentip),port,inaddr);
\r
167 if (currentip >= biniplist_getcount(biniplist)) then trymoreips := false;
\r
168 udp := uppercase(proto) = 'UDP';
\r
169 if udp then a := SOCK_DGRAM else a := SOCK_STREAM;
\r
170 a := Socket(inaddr.inaddr.family,a,0);
\r
171 //writeln(ord(inaddr.inaddr.family));
\r
172 if a = -1 then begin
\r
173 lasterror := {$ifdef win32}getlasterror{$else}socketerror{$endif};
\r
174 raise esocketexception.create('unable to create socket');
\r
181 SetSocketOptions(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
183 state := wsconnected;
\r
184 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
186 eventcore.rmasterset(fdhandlein,false);
\r
187 eventcore.wmasterclr(fdhandleout);
\r
189 state :=wsconnecting;
\r
191 //writeln(inaddr.inaddr.port);
\r
192 winsock.Connect(fdhandlein,winsock.psockaddr(@inADDR)^,getaddrsize);
\r
194 sockets.Connect(fdhandlein,inADDR,getaddrsize);
\r
196 eventcore.rmasterset(fdhandlein,false);
\r
197 eventcore.wmasterset(fdhandleout);
\r
198 if trymoreips then connecttimeout.enabled := true;
\r
202 on e: exception do begin
\r
204 raise; //reraise the exception
\r
210 procedure tlsocket.connecttimeouthandler(sender:tobject);
\r
212 connecttimeout.enabled := false;
\r
213 destroying := true; //hack to not cause handler to trigger
\r
215 destroying := false;
\r
219 procedure tlsocket.connect;
\r
224 if state <> wsclosed then close;
\r
226 if isbiniplist(addr) then biniplist := addr else biniplist := forwardlookuplist(addr,0);
\r
227 if biniplist_getcount(biniplist) = 0 then raise exception.create('unable to resolve '+addr);
\r
229 //makeinaddrv(addr,port,inaddr);
\r
232 if not assigned(connecttimeout) then begin
\r
233 connecttimeout := tltimer.create(self);
\r
234 connecttimeout.Tag := integer(self);
\r
235 connecttimeout.ontimer := connecttimeouthandler;
\r
236 connecttimeout.interval := 2500;
\r
237 connecttimeout.enabled := false;
\r
242 procedure tlsocket.sendstr(const str : string);
\r
245 send(@str[1],length(str))
\r
247 inherited sendstr(str);
\r
251 function tlsocket.send(data:pointer;len:integer):integer;
\r
254 // writeln('sending to '+ipbintostr(inaddrvtobinip(inaddr)),' ',htons(inaddr.inaddr.port),' ',len,' bytes');
\r
255 result := sendto(inaddr,getaddrsize,data,len);
\r
257 // writeln('send result ',result);
\r
258 // writeln('errno',errno);
\r
260 result := inherited send(data,len);
\r
265 function tlsocket.receive(Buf:Pointer;BufSize:integer):integer;
\r
268 {$ifdef secondlistener}
\r
269 if lastsessionfromsecond then begin
\r
270 result := secondlistener.receive(buf,bufsize);
\r
271 lastsessionfromsecond := false;
\r
274 result := myfdread(self.fdhandlein,buf^,bufsize);
\r
276 result := inherited receive(buf,bufsize);
\r
280 procedure tlsocket.bindsocket;
\r
283 inAddrtemp:TInetSockAddrV;
\r
284 inAddrtempx:{$ifdef win32}winsock.TSockaddr{$else}TInetSockAddrV{$endif} absolute inaddrtemp;
\r
285 inaddrtempsize:integer;
\r
288 if (localaddr <> '') or (localport <> '') then begin
\r
289 if localaddr = '' then begin
\r
291 if inaddr.inaddr.family = AF_INET6 then localaddr := '::' else
\r
293 localaddr := '0.0.0.0';
\r
295 //gethostbyname(localaddr,host);
\r
297 inaddrtempsize := makeinaddrv(forwardlookup(localaddr,0),localport,inaddrtemp);
\r
299 If Bind(fdhandlein,inaddrtempx,inaddrtempsize)<> {$ifdef win32}0{$else}true{$endif} Then begin
\r
301 lasterror := {$ifdef win32}getlasterror{$else}socketerror{$endif};
\r
302 raise ESocketException.create('unable to bind on address '+localaddr+'#'+localport+', error '+inttostr(lasterror));
\r
307 on e: exception do begin
\r
309 raise; //reraise the exception
\r
314 procedure tlsocket.listen;
\r
321 if state <> wsclosed then close;
\r
322 udp := uppercase(proto) = 'UDP';
\r
323 if udp then socktype := SOCK_DGRAM else socktype := SOCK_STREAM;
\r
326 if addr = '' then begin
\r
328 if not v4listendefault then begin
\r
334 if isbiniplist(addr) then biniptemp := biniplist_get(addr,0) else biniptemp := forwardlookup(addr,10);
\r
335 addr := ipbintostr(biniptemp);
\r
336 fdhandlein := socket(biniptemp.family,socktype,0);
\r
338 if (addr = '::') and (origaddr = '') and (fdhandlein < 0) then begin
\r
340 fdhandlein := socket(AF_INET,socktype,0);
\r
344 if fdhandlein = -1 then raise ESocketException.create('unable to create socket');
\r
345 dupnowatch(fdhandlein); // sets up maxs and copies handle to fdhandleout among other things
\r
346 //eventcore.setfdreverse(fdhandlein,self); //already taken care of by dup
\r
347 state := wsclosed; // then set this back as it was an undesired side effect of dup
\r
350 yes := $01010101; {Copied this from existing code. Value is empiric,
\r
351 but works. (yes=true<>0) }
\r
353 if SetSocketOptions(fdhandlein, SOL_SOCKET, SO_REUSEADDR,yes,sizeof(yes))=-1 then begin
\r
354 raise ESocketException.create('unable to set socket options');
\r
361 if not udp then begin
\r
362 {!!! allow custom queue length? default 5}
\r
363 if listenqueue = 0 then listenqueue := 5;
\r
364 If {$ifdef win32}winsock{$else}sockets{$endif}.Listen(fdhandlein,listenqueue)<>{$ifdef win32}0{$else}true{$endif} Then raise esocketexception.create('unable to listen');
\r
365 state := wsListening;
\r
368 SetSocketOptions(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
370 state := wsconnected;
\r
373 {$ifdef secondlistener}
\r
374 //listening on ::. try to listen on 0.0.0.0 as well for platforms which don't already do that
\r
375 if addr = '::' then begin
\r
376 secondlistener := tlsocket.create(nil);
\r
377 secondlistener.proto := proto;
\r
378 secondlistener.addr := '0.0.0.0';
\r
379 secondlistener.port := port;
\r
381 secondlistener.ondataavailable := secondaccepthandler;
\r
383 secondlistener.onsessionAvailable := secondaccepthandler;
\r
386 secondlistener.listen;
\r
388 secondlistener.destroy;
\r
389 secondlistener := nil;
\r
394 if state = wsclosed then begin
\r
395 if fdhandlein >= 0 then begin
\r
396 {one *can* get here without fd -beware}
\r
397 eventcore.rmasterclr(fdhandlein);
\r
398 myfdclose(fdhandlein); // we musnt leak file discriptors
\r
399 eventcore.setfdreverse(fdhandlein,nil);
\r
403 eventcore.rmasterset(fdhandlein,not udp);
\r
405 if fdhandleout >= 0 then eventcore.wmasterclr(fdhandleout);
\r
407 //writeln('listened on addr '+addr+':'+port+' '+proto+' using socket number ',fdhandlein);
\r
410 {$ifdef secondlistener}
\r
411 procedure tlsocket.internalclose(error:word);
\r
413 if assigned(secondlistener) then begin
\r
414 secondlistener.destroy;
\r
415 secondlistener := nil;
\r
417 inherited internalclose(error);
\r
420 procedure tlsocket.secondaccepthandler;
\r
422 lastsessionfromsecond := true;
\r
424 ondataavailable(self,error);
\r
426 if assigned(onsessionavailable) then onsessionavailable(self,error);
\r
431 function tlsocket.accept : longint;
\r
433 FromAddrSize : LongInt; // i don't realy know what to do with these at this
\r
434 FromAddr : TInetSockAddrV; // at this point time will tell :)
\r
437 {$ifdef secondlistener}
\r
438 if (lastsessionfromsecond) then begin
\r
439 lastsessionfromsecond := false;
\r
440 result := secondlistener.accept;
\r
445 FromAddrSize := Sizeof(FromAddr);
\r
447 result := winsock.accept(fdhandlein,@fromaddr,@fromaddrsize);
\r
449 result := sockets.accept(fdhandlein,fromaddr,fromaddrsize);
\r
451 //now we have accepted one request start monitoring for more again
\r
452 eventcore.rmasterset(fdhandlein,true);
\r
454 if result = -1 then begin
\r
455 raise esocketexception.create('error '+inttostr({$ifdef win32}getlasterror{$else}socketerror{$endif})+' while accepting');
\r
457 if result > absoloutemaxs then begin
\r
461 raise esocketexception.create('file discriptor out of range: '+inttostr(a));
\r
465 function tlsocket.sendto(dest:TInetSockAddrV;destlen:integer;data:pointer;len:integer):integer;
\r
467 destx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute dest;
\r
469 {$ifdef secondlistener}
\r
470 if assigned(secondlistener) then if (dest.inaddr.family = AF_INET) then begin
\r
471 result := secondlistener.sendto(dest,destlen,data,len);
\r
475 result := {$ifdef win32}winsock{$else}sockets{$endif}.sendto(self.fdhandleout,data^,len,0,destx,destlen);
\r
478 function tlsocket.receivefrom(data:pointer;len:integer;var src:TInetSockAddrV;var srclen:integer):integer;
\r
480 tempsrc:TInetSockAddrV;
\r
481 tempsrclen:integer;
\r
482 srcx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute tempsrc;
\r
485 {$ifdef secondlistener}
\r
486 if assigned(secondlistener) then if lastsessionfromsecond then begin
\r
487 lastsessionfromsecond := false;
\r
488 result := secondlistener.receivefrom(data,len,src,srclen);
\r
492 tempsrclen := sizeof(tempsrc);
\r
493 result := {$ifdef win32}winsock{$else}sockets{$endif}.recvfrom(self.fdhandlein,data^,len,0,srcx,tempsrclen);
\r
496 biniptemp := inaddrvtobinip(tempsrc);
\r
497 if needconverttov4(biniptemp) then begin
\r
498 converttov4(biniptemp);
\r
499 tempsrclen := makeinaddrv(biniptemp,inttostr(ntohs(tempsrc.InAddr.port)),tempsrc);
\r
503 move(tempsrc,src,srclen);
\r
504 srclen := tempsrclen;
\r
507 procedure tlsocket.connectionfailedhandler(error:word);
\r
509 if trymoreips then begin
\r
510 // writeln('failed with error ',error);
\r
511 connecttimeout.enabled := false;
\r
512 destroying := true;
\r
513 state := wsconnected;
\r
514 self.internalclose(0);
\r
515 destroying := false;
\r
518 state := wsconnected;
\r
519 if assigned(onsessionconnected) then onsessionconnected(self,error);
\r
520 self.internalclose(0);
\r
521 recvq.del(maxlongint);
\r
525 procedure tlsocket.connectsuccesshandler;
\r
527 trymoreips := false;
\r
528 connecttimeout.enabled := false;
\r
529 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
533 procedure tlsocket.handlefdtrigger(readtrigger,writetrigger:boolean);
\r
535 tempbuf:array[0..receivebufsize-1] of byte;
\r
537 // writeln('got a fd trigger, readtrigger=',readtrigger,' writetrigger=',writetrigger,' state=',integer(state));
\r
538 if (state =wslistening) and readtrigger then begin
\r
539 { debugout('listening socket triggered on read');}
\r
540 eventcore.rmasterclr(fdhandlein);
\r
541 if assigned(onsessionAvailable) then onsessionAvailable(self,0);
\r
543 if udp and readtrigger then begin
\r
544 if assigned(ondataAvailable) then ondataAvailable(self,0);
\r
548 if (state =wsconnecting) and writetrigger then begin
\r
549 // code for dealing with the reults of a non-blocking connect is
\r
551 // if just write is triggered it means connect suceeded
\r
552 // if both read and write are triggered it can mean 2 things
\r
553 // 1: connect ok and data availible
\r
555 // to find out which you must read from the socket and look for errors
\r
556 // there if we read successfully we drop through into the code for fireing
\r
558 if not readtrigger then begin
\r
559 state := wsconnected;
\r
560 connectsuccesshandler;
\r
562 numread := myfdread(fdhandlein,tempbuf,sizeof(tempbuf));
\r
563 if numread <> -1 then begin
\r
564 state := wsconnected;
\r
565 connectsuccesshandler;
\r
566 //connectread := true;
\r
567 recvq.add(@tempbuf,numread);
\r
569 connectionfailedhandler({$ifdef win32}wsagetlasterror{$else}linuxerror{$endif});
\r
572 // if things went well here we are now in the state wsconnected with data sitting in our receive buffer
\r
573 // so we drop down into the processing for data availible
\r
575 if fdhandlein >= 0 then begin
\r
576 if state = wsconnected then begin
\r
577 eventcore.rmasterset(fdhandlein,false);
\r
579 eventcore.rmasterclr(fdhandlein);
\r
582 if fdhandleout >= 0 then begin
\r
583 if sendq.size = 0 then begin
\r
584 //don't clear the bit in fdswmaster if data is in the sendq
\r
585 eventcore.wmasterclr(fdhandleout);
\r
590 inherited handlefdtrigger(readtrigger,writetrigger);
\r
593 constructor tlsocket.Create(AOwner: TComponent);
\r
595 inherited create(aowner);
\r
596 closehandles := true;
\r
597 trymoreips := true;
\r
601 function tlsocket.getpeername(var addr:tsockaddrin;addrlen:integer):integer;
\r
603 addrx : {$ifdef win32}winsock.tsockaddr{$else}tsockaddrin{$endif} absolute addr;
\r
605 result := {$ifdef win32}winsock{$else}sockets{$endif}.getpeername(self.fdhandlein,addrx,addrlen);
\r
608 procedure tlsocket.getxaddrbin(var binip:tbinip);
\r
610 addr:tinetsockaddrv;
\r
614 fillchar(addr,sizeof(addr),0);
\r
617 winsock.getsockname(self.fdhandlein,psockaddr(@addr)^,i);
\r
619 sockets.getsocketname(self.fdhandlein,addr,i);
\r
621 binip := inaddrvtobinip(addr);
\r
622 converttov4(binip);
\r
625 procedure tlsocket.getpeeraddrbin(var binip:tbinip);
\r
627 addr:tinetsockaddrv;
\r
631 fillchar(addr,sizeof(addr),0);
\r
633 winsock.getpeername(self.fdhandlein,psockaddr(@addr)^,i);
\r
635 sockets.getpeername(self.fdhandlein,addr,i);
\r
638 binip := inaddrvtobinip(addr);
\r
639 converttov4(binip);
\r
642 function tlsocket.getXaddr:string;
\r
646 getxaddrbin(biniptemp);
\r
647 result := ipbintostr(biniptemp);
\r
648 if result = '' then result := 'error';
\r
651 function tlsocket.getpeeraddr:string;
\r
655 getpeeraddrbin(biniptemp);
\r
656 result := ipbintostr(biniptemp);
\r
657 if result = '' then result := 'error';
\r
660 function tlsocket.getXport:string;
\r
662 addr:tinetsockaddrv;
\r
667 winsock.getsockname(self.fdhandlein,psockaddrin(@addr)^,i);
\r
670 sockets.getsocketname(self.fdhandlein,addr,i);
\r
673 result := inttostr(htons(addr.InAddr.port));
\r
676 function tlsocket.getpeerport:string;
\r
678 addr:tinetsockaddrv;
\r
683 winsock.getpeername(self.fdhandlein,psockaddrin(@addr)^,i);
\r
686 sockets.getpeername(self.fdhandlein,addr,i);
\r
689 result := inttostr(htons(addr.InAddr.port));
\r
693 procedure tlsocket.myfdclose(fd : integer);
\r
697 function tlsocket.myfdwrite(fd: LongInt;const buf;size: LongInt):LongInt;
\r
699 result := winsock.send(fd,(@buf)^,size,0);
\r
701 function tlsocket.myfdread(fd: LongInt;var buf;size: LongInt):LongInt;
\r
703 result := winsock.recv(fd,buf,size,0);
\r