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_listen(Sock: LongInt; MaxConnect: LongInt):Boolean;
\r
182 result := listen(sock,maxconnect);
\r
184 function system_Accept(Sock: LongInt;var Addr;var Addrlen: LongInt):LongInt;
\r
186 result := accept(sock,addr,addrlen);
\r
190 procedure tlsocket.realconnect;
\r
194 //writeln('trying to connect to ',ipbintostr(biniplist_get(biniplist,currentip)),'#',port);
\r
195 makeinaddrv(biniplist_get(biniplist,currentip),port,inaddr);
\r
197 if (currentip >= biniplist_getcount(biniplist)) then trymoreips := false;
\r
200 if (uppercase(proto) = 'UDP') then begin
\r
205 end else if (uppercase(proto) = 'TCP') or (uppercase(proto) = '') then begin
\r
209 end else if (uppercase(proto) = 'ICMP') or (strtointdef(proto,256) < 256) then begin
\r
210 b := strtointdef(proto,IPPROTO_ICMP);
\r
214 raise ESocketException.create('unrecognised protocol');
\r
217 a := Socket(inaddr.inaddr.family,a,b);
\r
218 //writeln(ord(inaddr.inaddr.family));
\r
219 if a = -1 then begin
\r
220 //unable to create socket, fire an error event (better to use an error event
\r
221 //to avoid poor interaction with multilistener stuff.
\r
222 //a socket value of -2 is a special value to say there is no socket but
\r
223 //we want internalclose to act as if there was
\r
226 tltask.create(taskcallconnectionfailedhandler,self,{$ifdef win32}wsagetlasterror{$else}socketerror{$endif},0);
\r
232 if dgram then begin
\r
234 SetSocketOptions(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
236 SetSockOpt(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
238 state := wsconnected;
\r
239 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
241 eventcore.rmasterset(fdhandlein,false);
\r
242 eventcore.wmasterclr(fdhandleout);
\r
244 state :=wsconnecting;
\r
246 //writeln(inaddr.inaddr.port);
\r
247 winsock.Connect(fdhandlein,winsock.psockaddr(@inADDR)^,getaddrsize);
\r
249 system_Connect(fdhandlein,inADDR,getaddrsize);
\r
251 eventcore.rmasterset(fdhandlein,false);
\r
252 eventcore.wmasterset(fdhandleout);
\r
253 if trymoreips then connecttimeout.enabled := true;
\r
257 on e: exception do begin
\r
259 raise; //reraise the exception
\r
265 procedure tlsocket.connecttimeouthandler(sender:tobject);
\r
267 connecttimeout.enabled := false;
\r
268 destroying := true; //hack to not cause handler to trigger
\r
270 destroying := false;
\r
277 procedure tlsocket.connect;
\r
282 if state <> wsclosed then close;
\r
284 if isbiniplist(addr) then biniplist := addr else biniplist := forwardlookuplist(addr,0);
\r
285 if biniplist_getcount(biniplist) = 0 then raise exception.create('unable to resolve '+addr);
\r
287 //makeinaddrv(addr,port,inaddr);
\r
290 if not assigned(connecttimeout) then begin
\r
291 connecttimeout := tltimer.create(self);
\r
292 connecttimeout.ontimer := connecttimeouthandler;
\r
293 connecttimeout.interval := 2500;
\r
294 connecttimeout.enabled := false;
\r
299 procedure tlsocket.sendstr(const str : string);
\r
301 if dgram then begin
\r
302 send(@str[1],length(str))
\r
304 inherited sendstr(str);
\r
308 function tlsocket.send(data:pointer;len:integer):integer;
\r
310 if dgram then begin
\r
311 // writeln('sending to '+ipbintostr(inaddrvtobinip(inaddr)),' ',htons(inaddr.inaddr.port),' ',len,' bytes');
\r
312 result := sendto(inaddr,getaddrsize,data,len);
\r
314 // writeln('send result ',result);
\r
315 // writeln('errno',errno);
\r
317 result := inherited send(data,len);
\r
322 function tlsocket.receive(Buf:Pointer;BufSize:integer):integer;
\r
324 if dgram then begin
\r
325 {$ifdef secondlistener}
\r
326 if lastsessionfromsecond then begin
\r
327 result := secondlistener.receive(buf,bufsize);
\r
328 lastsessionfromsecond := false;
\r
331 result := myfdread(self.fdhandlein,buf^,bufsize);
\r
333 result := inherited receive(buf,bufsize);
\r
337 procedure tlsocket.bindsocket;
\r
340 inAddrtemp:TInetSockAddrV;
\r
341 inAddrtempx:{$ifdef win32}winsock.TSockaddr{$else}TInetSockAddrV{$endif} absolute inaddrtemp;
\r
342 inaddrtempsize:integer;
\r
345 if (localaddr <> '') or (localport <> '') then begin
\r
346 if localaddr = '' then begin
\r
348 if inaddr.inaddr.family = AF_INET6 then localaddr := '::' else
\r
350 localaddr := '0.0.0.0';
\r
352 //gethostbyname(localaddr,host);
\r
353 inaddrtempsize := makeinaddrv(forwardlookup(localaddr,0),localport,inaddrtemp);
\r
355 If Bind(fdhandlein,inaddrtempx,inaddrtempsize)<> {$ifdef win32}0{$else}true{$endif} Then begin
\r
357 lasterror := {$ifdef win32}getlasterror{$else}socketerror{$endif};
\r
358 raise ESocketException.create('unable to bind on address '+localaddr+'#'+localport+', error '+inttostr(lasterror));
\r
363 on e: exception do begin
\r
365 raise; //reraise the exception
\r
370 procedure tlsocket.listen;
\r
377 if state <> wsclosed then close;
\r
378 udp := uppercase(proto) = 'UDP';
\r
380 socktype := SOCK_DGRAM;
\r
382 end else socktype := SOCK_STREAM;
\r
385 if addr = '' then begin
\r
387 if not v4listendefault then begin
\r
393 if isbiniplist(addr) then biniptemp := biniplist_get(addr,0) else biniptemp := forwardlookup(addr,10);
\r
394 addr := ipbintostr(biniptemp);
\r
395 fdhandlein := socket(biniptemp.family,socktype,0);
\r
397 if (addr = '::') and (origaddr = '') and (fdhandlein < 0) then begin
\r
399 fdhandlein := socket(AF_INET,socktype,0);
\r
403 if fdhandlein = -1 then raise ESocketException.create('unable to create socket'{$ifdef win32}+' error='+inttostr(wsagetlasterror){$endif});
\r
404 dupnowatch(fdhandlein); // sets up maxs and copies handle to fdhandleout among other things
\r
405 //eventcore.setfdreverse(fdhandlein,self); //already taken care of by dup
\r
406 state := wsclosed; // then set this back as it was an undesired side effect of dup
\r
409 yes := $01010101; {Copied this from existing code. Value is empiric,
\r
410 but works. (yes=true<>0) }
\r
412 if SetSocketOptions(fdhandlein, SOL_SOCKET, SO_REUSEADDR,yes,sizeof(yes))=-1 then begin
\r
413 raise ESocketException.create('unable to set socket options');
\r
420 if not udp then begin
\r
421 {!!! allow custom queue length? default 5}
\r
422 if listenqueue = 0 then listenqueue := 5;
\r
423 If {$ifdef win32}winsock.listen{$else}system_listen{$endif}(fdhandlein,listenqueue)<>{$ifdef win32}0{$else}true{$endif} Then raise
\r
424 esocketexception.create('unable to listen');
\r
425 state := wsListening;
\r
428 SetSocketOptions(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
430 SetSockOpt(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
432 state := wsconnected;
\r
435 {$ifdef secondlistener}
\r
436 //listening on ::. try to listen on 0.0.0.0 as well for platforms which don't already do that
\r
437 if addr = '::' then begin
\r
438 secondlistener := tlsocket.create(nil);
\r
439 secondlistener.proto := proto;
\r
440 secondlistener.addr := '0.0.0.0';
\r
441 secondlistener.port := port;
\r
443 secondlistener.ondataavailable := secondaccepthandler;
\r
445 secondlistener.onsessionAvailable := secondaccepthandler;
\r
448 secondlistener.listen;
\r
450 secondlistener.destroy;
\r
451 secondlistener := nil;
\r
456 if state = wsclosed then begin
\r
457 if fdhandlein >= 0 then begin
\r
458 {one *can* get here without fd -beware}
\r
459 eventcore.rmasterclr(fdhandlein);
\r
460 myfdclose(fdhandlein); // we musnt leak file discriptors
\r
461 eventcore.setfdreverse(fdhandlein,nil);
\r
465 eventcore.rmasterset(fdhandlein,not udp);
\r
467 if fdhandleout >= 0 then eventcore.wmasterclr(fdhandleout);
\r
469 //writeln('listened on addr '+addr+':'+port+' '+proto+' using socket number ',fdhandlein);
\r
472 {$ifdef secondlistener}
\r
473 procedure tlsocket.internalclose(error:word);
\r
475 if assigned(secondlistener) then begin
\r
476 secondlistener.destroy;
\r
477 secondlistener := nil;
\r
479 inherited internalclose(error);
\r
482 procedure tlsocket.secondaccepthandler;
\r
484 lastsessionfromsecond := true;
\r
486 ondataavailable(self,error);
\r
488 if assigned(onsessionavailable) then onsessionavailable(self,error);
\r
493 function tlsocket.accept : longint;
\r
495 FromAddrSize : LongInt; // i don't realy know what to do with these at this
\r
496 FromAddr : TInetSockAddrV; // at this point time will tell :)
\r
499 {$ifdef secondlistener}
\r
500 if (lastsessionfromsecond) then begin
\r
501 lastsessionfromsecond := false;
\r
502 result := secondlistener.accept;
\r
507 FromAddrSize := Sizeof(FromAddr);
\r
509 result := winsock.accept(fdhandlein,@fromaddr,@fromaddrsize);
\r
511 result := system_accept(fdhandlein,fromaddr,fromaddrsize);
\r
513 //now we have accepted one request start monitoring for more again
\r
514 eventcore.rmasterset(fdhandlein,true);
\r
516 if result = -1 then begin
\r
517 raise esocketexception.create('error '+inttostr({$ifdef win32}getlasterror{$else}socketerror{$endif})+' while accepting');
\r
519 if result > absoloutemaxs then begin
\r
523 raise esocketexception.create('file discriptor out of range: '+inttostr(a));
\r
528 function tlsocket.sendto(dest:TInetSockAddrV;destlen:integer;data:pointer;len:integer):integer;
\r
530 destx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute dest;
\r
532 {$ifdef secondlistener}
\r
533 if assigned(secondlistener) then if (dest.inaddr.family = AF_INET) then begin
\r
534 result := secondlistener.sendto(dest,destlen,data,len);
\r
538 result := {$ifdef win32}winsock.sendto{$else}system_sendto{$endif}(self.fdhandleout,data^,len,0,destx,destlen);
\r
542 function tlsocket.receivefrom(data:pointer;len:integer;var src:TInetSockAddrV;var srclen:integer):integer;
\r
544 tempsrc:TInetSockAddrV;
\r
545 tempsrclen:integer;
\r
546 srcx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute tempsrc;
\r
549 {$ifdef secondlistener}
\r
550 if assigned(secondlistener) then if lastsessionfromsecond then begin
\r
551 lastsessionfromsecond := false;
\r
552 result := secondlistener.receivefrom(data,len,src,srclen);
\r
556 tempsrclen := sizeof(tempsrc);
\r
557 result := recvfrom(self.fdhandlein,data^,len,0,srcx,tempsrclen);
\r
560 biniptemp := inaddrvtobinip(tempsrc);
\r
561 if needconverttov4(biniptemp) then begin
\r
562 converttov4(biniptemp);
\r
563 tempsrclen := makeinaddrv(biniptemp,inttostr(ntohs(tempsrc.InAddr.port)),tempsrc);
\r
567 move(tempsrc,src,srclen);
\r
568 srclen := tempsrclen;
\r
571 procedure tlsocket.taskcallconnectionfailedhandler(wparam,lparam : longint);
\r
573 connectionfailedhandler(wparam);
\r
576 procedure tlsocket.connectionfailedhandler(error:word);
\r
578 if trymoreips then begin
\r
579 // writeln('failed with error ',error);
\r
580 connecttimeout.enabled := false;
\r
581 destroying := true;
\r
582 state := wsconnected;
\r
583 self.internalclose(0);
\r
584 destroying := false;
\r
587 state := wsconnected;
\r
588 if assigned(onsessionconnected) then onsessionconnected(self,error);
\r
589 self.internalclose(0);
\r
590 recvq.del(maxlongint);
\r
594 procedure tlsocket.connectsuccesshandler;
\r
596 trymoreips := false;
\r
597 connecttimeout.enabled := false;
\r
598 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
602 procedure tlsocket.handlefdtrigger(readtrigger,writetrigger:boolean);
\r
604 tempbuf:array[0..receivebufsize-1] of byte;
\r
606 // writeln('got a fd trigger, readtrigger=',readtrigger,' writetrigger=',writetrigger,' state=',integer(state));
\r
607 if (state =wslistening) and readtrigger then begin
\r
608 { debugout('listening socket triggered on read');}
\r
609 eventcore.rmasterclr(fdhandlein);
\r
610 if assigned(onsessionAvailable) then onsessionAvailable(self,0);
\r
612 if dgram and readtrigger then begin
\r
613 if assigned(ondataAvailable) then ondataAvailable(self,0);
\r
617 if (state =wsconnecting) and writetrigger then begin
\r
618 // code for dealing with the reults of a non-blocking connect is
\r
620 // if just write is triggered it means connect suceeded
\r
621 // if both read and write are triggered it can mean 2 things
\r
622 // 1: connect ok and data availible
\r
624 // to find out which you must read from the socket and look for errors
\r
625 // there if we read successfully we drop through into the code for fireing
\r
627 if not readtrigger then begin
\r
628 state := wsconnected;
\r
629 connectsuccesshandler;
\r
631 numread := myfdread(fdhandlein,tempbuf,sizeof(tempbuf));
\r
632 if numread <> -1 then begin
\r
633 state := wsconnected;
\r
634 connectsuccesshandler;
\r
635 //connectread := true;
\r
636 recvq.add(@tempbuf,numread);
\r
638 connectionfailedhandler({$ifdef win32}wsagetlasterror{$else}linuxerror{$endif});
\r
641 // if things went well here we are now in the state wsconnected with data sitting in our receive buffer
\r
642 // so we drop down into the processing for data availible
\r
644 if fdhandlein >= 0 then begin
\r
645 if state = wsconnected then begin
\r
646 eventcore.rmasterset(fdhandlein,false);
\r
648 eventcore.rmasterclr(fdhandlein);
\r
651 if fdhandleout >= 0 then begin
\r
652 if sendq.size = 0 then begin
\r
653 //don't clear the bit in fdswmaster if data is in the sendq
\r
654 eventcore.wmasterclr(fdhandleout);
\r
659 inherited handlefdtrigger(readtrigger,writetrigger);
\r
662 constructor tlsocket.Create(AOwner: TComponent);
\r
664 inherited create(aowner);
\r
665 closehandles := true;
\r
666 trymoreips := true;
\r
671 function tlsocket.getpeername(var addr:tsockaddrin;addrlen:integer):integer;
\r
673 addrx : {$ifdef win32}winsock.tsockaddr{$else}tsockaddrin{$endif} absolute addr;
\r
675 result := {$ifdef win32}winsock.getpeername{$else}system_getpeername{$endif}(self.fdhandlein,addrx,addrlen);
\r
678 procedure tlsocket.getxaddrbin(var binip:tbinip);
\r
680 addr:tinetsockaddrv;
\r
684 fillchar(addr,sizeof(addr),0);
\r
687 winsock.getsockname(self.fdhandlein,psockaddr(@addr)^,i);
\r
689 getsocketname(self.fdhandlein,addr,i);
\r
691 binip := inaddrvtobinip(addr);
\r
692 converttov4(binip);
\r
695 procedure tlsocket.getpeeraddrbin(var binip:tbinip);
\r
697 addr:tinetsockaddrv;
\r
701 fillchar(addr,sizeof(addr),0);
\r
703 winsock.getpeername(self.fdhandlein,psockaddr(@addr)^,i);
\r
705 system_getpeername(self.fdhandlein,addr,i);
\r
708 binip := inaddrvtobinip(addr);
\r
709 converttov4(binip);
\r
712 function tlsocket.getXaddr:string;
\r
716 getxaddrbin(biniptemp);
\r
717 result := ipbintostr(biniptemp);
\r
718 if result = '' then result := 'error';
\r
721 function tlsocket.getpeeraddr:string;
\r
725 getpeeraddrbin(biniptemp);
\r
726 result := ipbintostr(biniptemp);
\r
727 if result = '' then result := 'error';
\r
730 function tlsocket.getXport:string;
\r
732 addr:tinetsockaddrv;
\r
737 winsock.getsockname(self.fdhandlein,psockaddrin(@addr)^,i);
\r
740 getsocketname(self.fdhandlein,addr,i);
\r
743 result := inttostr(htons(addr.InAddr.port));
\r
746 function tlsocket.getpeerport:string;
\r
748 addr:tinetsockaddrv;
\r
753 winsock.getpeername(self.fdhandlein,psockaddrin(@addr)^,i);
\r
756 system_getpeername(self.fdhandlein,addr,i);
\r
759 result := inttostr(htons(addr.InAddr.port));
\r
763 procedure tlsocket.myfdclose(fd : integer);
\r
767 function tlsocket.myfdwrite(fd: LongInt;const buf;size: LongInt):LongInt;
\r
769 result := winsock.send(fd,(@buf)^,size,0);
\r
771 function tlsocket.myfdread(fd: LongInt;var buf;size: LongInt):LongInt;
\r
773 result := winsock.recv(fd,buf,size,0);
\r