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
337 socktype := SOCK_DGRAM;
\r
339 end else socktype := SOCK_STREAM;
\r
342 if addr = '' then begin
\r
344 if not v4listendefault then begin
\r
350 if isbiniplist(addr) then biniptemp := biniplist_get(addr,0) else biniptemp := forwardlookup(addr,10);
\r
351 addr := ipbintostr(biniptemp);
\r
352 fdhandlein := socket(biniptemp.family,socktype,0);
\r
354 if (addr = '::') and (origaddr = '') and (fdhandlein < 0) then begin
\r
356 fdhandlein := socket(AF_INET,socktype,0);
\r
360 if fdhandlein = -1 then raise ESocketException.create('unable to create socket');
\r
361 dupnowatch(fdhandlein); // sets up maxs and copies handle to fdhandleout among other things
\r
362 //eventcore.setfdreverse(fdhandlein,self); //already taken care of by dup
\r
363 state := wsclosed; // then set this back as it was an undesired side effect of dup
\r
366 yes := $01010101; {Copied this from existing code. Value is empiric,
\r
367 but works. (yes=true<>0) }
\r
369 if SetSocketOptions(fdhandlein, SOL_SOCKET, SO_REUSEADDR,yes,sizeof(yes))=-1 then begin
\r
370 raise ESocketException.create('unable to set socket options');
\r
377 if not udp then begin
\r
378 {!!! allow custom queue length? default 5}
\r
379 if listenqueue = 0 then listenqueue := 5;
\r
380 If {$ifdef win32}winsock{$else}sockets{$endif}.Listen(fdhandlein,listenqueue)<>{$ifdef win32}0{$else}true{$endif} Then raise esocketexception.create('unable to listen');
\r
381 state := wsListening;
\r
384 SetSocketOptions(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
386 state := wsconnected;
\r
389 {$ifdef secondlistener}
\r
390 //listening on ::. try to listen on 0.0.0.0 as well for platforms which don't already do that
\r
391 if addr = '::' then begin
\r
392 secondlistener := tlsocket.create(nil);
\r
393 secondlistener.proto := proto;
\r
394 secondlistener.addr := '0.0.0.0';
\r
395 secondlistener.port := port;
\r
397 secondlistener.ondataavailable := secondaccepthandler;
\r
399 secondlistener.onsessionAvailable := secondaccepthandler;
\r
402 secondlistener.listen;
\r
404 secondlistener.destroy;
\r
405 secondlistener := nil;
\r
410 if state = wsclosed then begin
\r
411 if fdhandlein >= 0 then begin
\r
412 {one *can* get here without fd -beware}
\r
413 eventcore.rmasterclr(fdhandlein);
\r
414 myfdclose(fdhandlein); // we musnt leak file discriptors
\r
415 eventcore.setfdreverse(fdhandlein,nil);
\r
419 eventcore.rmasterset(fdhandlein,not udp);
\r
421 if fdhandleout >= 0 then eventcore.wmasterclr(fdhandleout);
\r
423 //writeln('listened on addr '+addr+':'+port+' '+proto+' using socket number ',fdhandlein);
\r
426 {$ifdef secondlistener}
\r
427 procedure tlsocket.internalclose(error:word);
\r
429 if assigned(secondlistener) then begin
\r
430 secondlistener.destroy;
\r
431 secondlistener := nil;
\r
433 inherited internalclose(error);
\r
436 procedure tlsocket.secondaccepthandler;
\r
438 lastsessionfromsecond := true;
\r
440 ondataavailable(self,error);
\r
442 if assigned(onsessionavailable) then onsessionavailable(self,error);
\r
447 function tlsocket.accept : longint;
\r
449 FromAddrSize : LongInt; // i don't realy know what to do with these at this
\r
450 FromAddr : TInetSockAddrV; // at this point time will tell :)
\r
453 {$ifdef secondlistener}
\r
454 if (lastsessionfromsecond) then begin
\r
455 lastsessionfromsecond := false;
\r
456 result := secondlistener.accept;
\r
461 FromAddrSize := Sizeof(FromAddr);
\r
463 result := winsock.accept(fdhandlein,@fromaddr,@fromaddrsize);
\r
465 result := sockets.accept(fdhandlein,fromaddr,fromaddrsize);
\r
467 //now we have accepted one request start monitoring for more again
\r
468 eventcore.rmasterset(fdhandlein,true);
\r
470 if result = -1 then begin
\r
471 raise esocketexception.create('error '+inttostr({$ifdef win32}getlasterror{$else}socketerror{$endif})+' while accepting');
\r
473 if result > absoloutemaxs then begin
\r
477 raise esocketexception.create('file discriptor out of range: '+inttostr(a));
\r
481 function tlsocket.sendto(dest:TInetSockAddrV;destlen:integer;data:pointer;len:integer):integer;
\r
483 destx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute dest;
\r
485 {$ifdef secondlistener}
\r
486 if assigned(secondlistener) then if (dest.inaddr.family = AF_INET) then begin
\r
487 result := secondlistener.sendto(dest,destlen,data,len);
\r
491 result := {$ifdef win32}winsock{$else}sockets{$endif}.sendto(self.fdhandleout,data^,len,0,destx,destlen);
\r
494 function tlsocket.receivefrom(data:pointer;len:integer;var src:TInetSockAddrV;var srclen:integer):integer;
\r
496 tempsrc:TInetSockAddrV;
\r
497 tempsrclen:integer;
\r
498 srcx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute tempsrc;
\r
501 {$ifdef secondlistener}
\r
502 if assigned(secondlistener) then if lastsessionfromsecond then begin
\r
503 lastsessionfromsecond := false;
\r
504 result := secondlistener.receivefrom(data,len,src,srclen);
\r
508 tempsrclen := sizeof(tempsrc);
\r
509 result := {$ifdef win32}winsock{$else}sockets{$endif}.recvfrom(self.fdhandlein,data^,len,0,srcx,tempsrclen);
\r
512 biniptemp := inaddrvtobinip(tempsrc);
\r
513 if needconverttov4(biniptemp) then begin
\r
514 converttov4(biniptemp);
\r
515 tempsrclen := makeinaddrv(biniptemp,inttostr(ntohs(tempsrc.InAddr.port)),tempsrc);
\r
519 move(tempsrc,src,srclen);
\r
520 srclen := tempsrclen;
\r
523 procedure tlsocket.connectionfailedhandler(error:word);
\r
525 if trymoreips then begin
\r
526 // writeln('failed with error ',error);
\r
527 connecttimeout.enabled := false;
\r
528 destroying := true;
\r
529 state := wsconnected;
\r
530 self.internalclose(0);
\r
531 destroying := false;
\r
534 state := wsconnected;
\r
535 if assigned(onsessionconnected) then onsessionconnected(self,error);
\r
536 self.internalclose(0);
\r
537 recvq.del(maxlongint);
\r
541 procedure tlsocket.connectsuccesshandler;
\r
543 trymoreips := false;
\r
544 connecttimeout.enabled := false;
\r
545 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
549 procedure tlsocket.handlefdtrigger(readtrigger,writetrigger:boolean);
\r
551 tempbuf:array[0..receivebufsize-1] of byte;
\r
553 // writeln('got a fd trigger, readtrigger=',readtrigger,' writetrigger=',writetrigger,' state=',integer(state));
\r
554 if (state =wslistening) and readtrigger then begin
\r
555 { debugout('listening socket triggered on read');}
\r
556 eventcore.rmasterclr(fdhandlein);
\r
557 if assigned(onsessionAvailable) then onsessionAvailable(self,0);
\r
559 if dgram and readtrigger then begin
\r
560 if assigned(ondataAvailable) then ondataAvailable(self,0);
\r
564 if (state =wsconnecting) and writetrigger then begin
\r
565 // code for dealing with the reults of a non-blocking connect is
\r
567 // if just write is triggered it means connect suceeded
\r
568 // if both read and write are triggered it can mean 2 things
\r
569 // 1: connect ok and data availible
\r
571 // to find out which you must read from the socket and look for errors
\r
572 // there if we read successfully we drop through into the code for fireing
\r
574 if not readtrigger then begin
\r
575 state := wsconnected;
\r
576 connectsuccesshandler;
\r
578 numread := myfdread(fdhandlein,tempbuf,sizeof(tempbuf));
\r
579 if numread <> -1 then begin
\r
580 state := wsconnected;
\r
581 connectsuccesshandler;
\r
582 //connectread := true;
\r
583 recvq.add(@tempbuf,numread);
\r
585 connectionfailedhandler({$ifdef win32}wsagetlasterror{$else}linuxerror{$endif});
\r
588 // if things went well here we are now in the state wsconnected with data sitting in our receive buffer
\r
589 // so we drop down into the processing for data availible
\r
591 if fdhandlein >= 0 then begin
\r
592 if state = wsconnected then begin
\r
593 eventcore.rmasterset(fdhandlein,false);
\r
595 eventcore.rmasterclr(fdhandlein);
\r
598 if fdhandleout >= 0 then begin
\r
599 if sendq.size = 0 then begin
\r
600 //don't clear the bit in fdswmaster if data is in the sendq
\r
601 eventcore.wmasterclr(fdhandleout);
\r
606 inherited handlefdtrigger(readtrigger,writetrigger);
\r
609 constructor tlsocket.Create(AOwner: TComponent);
\r
611 inherited create(aowner);
\r
612 closehandles := true;
\r
613 trymoreips := true;
\r
617 function tlsocket.getpeername(var addr:tsockaddrin;addrlen:integer):integer;
\r
619 addrx : {$ifdef win32}winsock.tsockaddr{$else}tsockaddrin{$endif} absolute addr;
\r
621 result := {$ifdef win32}winsock{$else}sockets{$endif}.getpeername(self.fdhandlein,addrx,addrlen);
\r
624 procedure tlsocket.getxaddrbin(var binip:tbinip);
\r
626 addr:tinetsockaddrv;
\r
630 fillchar(addr,sizeof(addr),0);
\r
633 winsock.getsockname(self.fdhandlein,psockaddr(@addr)^,i);
\r
635 sockets.getsocketname(self.fdhandlein,addr,i);
\r
637 binip := inaddrvtobinip(addr);
\r
638 converttov4(binip);
\r
641 procedure tlsocket.getpeeraddrbin(var binip:tbinip);
\r
643 addr:tinetsockaddrv;
\r
647 fillchar(addr,sizeof(addr),0);
\r
649 winsock.getpeername(self.fdhandlein,psockaddr(@addr)^,i);
\r
651 sockets.getpeername(self.fdhandlein,addr,i);
\r
654 binip := inaddrvtobinip(addr);
\r
655 converttov4(binip);
\r
658 function tlsocket.getXaddr:string;
\r
662 getxaddrbin(biniptemp);
\r
663 result := ipbintostr(biniptemp);
\r
664 if result = '' then result := 'error';
\r
667 function tlsocket.getpeeraddr:string;
\r
671 getpeeraddrbin(biniptemp);
\r
672 result := ipbintostr(biniptemp);
\r
673 if result = '' then result := 'error';
\r
676 function tlsocket.getXport:string;
\r
678 addr:tinetsockaddrv;
\r
683 winsock.getsockname(self.fdhandlein,psockaddrin(@addr)^,i);
\r
686 sockets.getsocketname(self.fdhandlein,addr,i);
\r
689 result := inttostr(htons(addr.InAddr.port));
\r
692 function tlsocket.getpeerport:string;
\r
694 addr:tinetsockaddrv;
\r
699 winsock.getpeername(self.fdhandlein,psockaddrin(@addr)^,i);
\r
702 sockets.getpeername(self.fdhandlein,addr,i);
\r
705 result := inttostr(htons(addr.InAddr.port));
\r
709 procedure tlsocket.myfdclose(fd : integer);
\r
713 function tlsocket.myfdwrite(fd: LongInt;const buf;size: LongInt):LongInt;
\r
715 result := winsock.send(fd,(@buf)^,size,0);
\r
717 function tlsocket.myfdread(fd: LongInt;var buf;size: LongInt):LongInt;
\r
719 result := winsock.recv(fd,buf,size,0);
\r