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 SetSockOpt(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
199 state := wsconnected;
\r
200 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
202 eventcore.rmasterset(fdhandlein,false);
\r
203 eventcore.wmasterclr(fdhandleout);
\r
205 state :=wsconnecting;
\r
207 //writeln(inaddr.inaddr.port);
\r
208 winsock.Connect(fdhandlein,winsock.psockaddr(@inADDR)^,getaddrsize);
\r
210 sockets.Connect(fdhandlein,inADDR,getaddrsize);
\r
212 eventcore.rmasterset(fdhandlein,false);
\r
213 eventcore.wmasterset(fdhandleout);
\r
214 if trymoreips then connecttimeout.enabled := true;
\r
218 on e: exception do begin
\r
220 raise; //reraise the exception
\r
226 procedure tlsocket.connecttimeouthandler(sender:tobject);
\r
228 connecttimeout.enabled := false;
\r
229 destroying := true; //hack to not cause handler to trigger
\r
231 destroying := false;
\r
235 procedure tlsocket.connect;
\r
240 if state <> wsclosed then close;
\r
242 if isbiniplist(addr) then biniplist := addr else biniplist := forwardlookuplist(addr,0);
\r
243 if biniplist_getcount(biniplist) = 0 then raise exception.create('unable to resolve '+addr);
\r
245 //makeinaddrv(addr,port,inaddr);
\r
248 if not assigned(connecttimeout) then begin
\r
249 connecttimeout := tltimer.create(self);
\r
250 connecttimeout.Tag := integer(self);
\r
251 connecttimeout.ontimer := connecttimeouthandler;
\r
252 connecttimeout.interval := 2500;
\r
253 connecttimeout.enabled := false;
\r
258 procedure tlsocket.sendstr(const str : string);
\r
260 if dgram then begin
\r
261 send(@str[1],length(str))
\r
263 inherited sendstr(str);
\r
267 function tlsocket.send(data:pointer;len:integer):integer;
\r
269 if dgram then begin
\r
270 // writeln('sending to '+ipbintostr(inaddrvtobinip(inaddr)),' ',htons(inaddr.inaddr.port),' ',len,' bytes');
\r
271 result := sendto(inaddr,getaddrsize,data,len);
\r
273 // writeln('send result ',result);
\r
274 // writeln('errno',errno);
\r
276 result := inherited send(data,len);
\r
281 function tlsocket.receive(Buf:Pointer;BufSize:integer):integer;
\r
283 if dgram then begin
\r
284 {$ifdef secondlistener}
\r
285 if lastsessionfromsecond then begin
\r
286 result := secondlistener.receive(buf,bufsize);
\r
287 lastsessionfromsecond := false;
\r
290 result := myfdread(self.fdhandlein,buf^,bufsize);
\r
292 result := inherited receive(buf,bufsize);
\r
296 procedure tlsocket.bindsocket;
\r
299 inAddrtemp:TInetSockAddrV;
\r
300 inAddrtempx:{$ifdef win32}winsock.TSockaddr{$else}TInetSockAddrV{$endif} absolute inaddrtemp;
\r
301 inaddrtempsize:integer;
\r
304 if (localaddr <> '') or (localport <> '') then begin
\r
305 if localaddr = '' then begin
\r
307 if inaddr.inaddr.family = AF_INET6 then localaddr := '::' else
\r
309 localaddr := '0.0.0.0';
\r
311 //gethostbyname(localaddr,host);
\r
312 inaddrtempsize := makeinaddrv(forwardlookup(localaddr,0),localport,inaddrtemp);
\r
314 If Bind(fdhandlein,inaddrtempx,inaddrtempsize)<> {$ifdef win32}0{$else}true{$endif} Then begin
\r
316 lasterror := {$ifdef win32}getlasterror{$else}socketerror{$endif};
\r
317 raise ESocketException.create('unable to bind on address '+localaddr+'#'+localport+', error '+inttostr(lasterror));
\r
322 on e: exception do begin
\r
324 raise; //reraise the exception
\r
329 procedure tlsocket.listen;
\r
336 if state <> wsclosed then close;
\r
337 udp := uppercase(proto) = 'UDP';
\r
339 socktype := SOCK_DGRAM;
\r
341 end else socktype := SOCK_STREAM;
\r
344 if addr = '' then begin
\r
346 if not v4listendefault then begin
\r
352 if isbiniplist(addr) then biniptemp := biniplist_get(addr,0) else biniptemp := forwardlookup(addr,10);
\r
353 addr := ipbintostr(biniptemp);
\r
354 fdhandlein := socket(biniptemp.family,socktype,0);
\r
356 if (addr = '::') and (origaddr = '') and (fdhandlein < 0) then begin
\r
358 fdhandlein := socket(AF_INET,socktype,0);
\r
362 if fdhandlein = -1 then raise ESocketException.create('unable to create socket');
\r
363 dupnowatch(fdhandlein); // sets up maxs and copies handle to fdhandleout among other things
\r
364 //eventcore.setfdreverse(fdhandlein,self); //already taken care of by dup
\r
365 state := wsclosed; // then set this back as it was an undesired side effect of dup
\r
368 yes := $01010101; {Copied this from existing code. Value is empiric,
\r
369 but works. (yes=true<>0) }
\r
371 if SetSocketOptions(fdhandlein, SOL_SOCKET, SO_REUSEADDR,yes,sizeof(yes))=-1 then begin
\r
372 raise ESocketException.create('unable to set socket options');
\r
379 if not udp then begin
\r
380 {!!! allow custom queue length? default 5}
\r
381 if listenqueue = 0 then listenqueue := 5;
\r
382 If {$ifdef win32}winsock{$else}sockets{$endif}.Listen(fdhandlein,listenqueue)<>{$ifdef win32}0{$else}true{$endif} Then raise
\r
383 esocketexception.create('unable to listen');
\r
384 state := wsListening;
\r
387 SetSocketOptions(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
389 SetSockOpt(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
391 state := wsconnected;
\r
394 {$ifdef secondlistener}
\r
395 //listening on ::. try to listen on 0.0.0.0 as well for platforms which don't already do that
\r
396 if addr = '::' then begin
\r
397 secondlistener := tlsocket.create(nil);
\r
398 secondlistener.proto := proto;
\r
399 secondlistener.addr := '0.0.0.0';
\r
400 secondlistener.port := port;
\r
402 secondlistener.ondataavailable := secondaccepthandler;
\r
404 secondlistener.onsessionAvailable := secondaccepthandler;
\r
407 secondlistener.listen;
\r
409 secondlistener.destroy;
\r
410 secondlistener := nil;
\r
415 if state = wsclosed then begin
\r
416 if fdhandlein >= 0 then begin
\r
417 {one *can* get here without fd -beware}
\r
418 eventcore.rmasterclr(fdhandlein);
\r
419 myfdclose(fdhandlein); // we musnt leak file discriptors
\r
420 eventcore.setfdreverse(fdhandlein,nil);
\r
424 eventcore.rmasterset(fdhandlein,not udp);
\r
426 if fdhandleout >= 0 then eventcore.wmasterclr(fdhandleout);
\r
428 //writeln('listened on addr '+addr+':'+port+' '+proto+' using socket number ',fdhandlein);
\r
431 {$ifdef secondlistener}
\r
432 procedure tlsocket.internalclose(error:word);
\r
434 if assigned(secondlistener) then begin
\r
435 secondlistener.destroy;
\r
436 secondlistener := nil;
\r
438 inherited internalclose(error);
\r
441 procedure tlsocket.secondaccepthandler;
\r
443 lastsessionfromsecond := true;
\r
445 ondataavailable(self,error);
\r
447 if assigned(onsessionavailable) then onsessionavailable(self,error);
\r
452 function tlsocket.accept : longint;
\r
454 FromAddrSize : LongInt; // i don't realy know what to do with these at this
\r
455 FromAddr : TInetSockAddrV; // at this point time will tell :)
\r
458 {$ifdef secondlistener}
\r
459 if (lastsessionfromsecond) then begin
\r
460 lastsessionfromsecond := false;
\r
461 result := secondlistener.accept;
\r
466 FromAddrSize := Sizeof(FromAddr);
\r
468 result := winsock.accept(fdhandlein,@fromaddr,@fromaddrsize);
\r
470 result := sockets.accept(fdhandlein,fromaddr,fromaddrsize);
\r
472 //now we have accepted one request start monitoring for more again
\r
473 eventcore.rmasterset(fdhandlein,true);
\r
475 if result = -1 then begin
\r
476 raise esocketexception.create('error '+inttostr({$ifdef win32}getlasterror{$else}socketerror{$endif})+' while accepting');
\r
478 if result > absoloutemaxs then begin
\r
482 raise esocketexception.create('file discriptor out of range: '+inttostr(a));
\r
486 function tlsocket.sendto(dest:TInetSockAddrV;destlen:integer;data:pointer;len:integer):integer;
\r
488 destx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute dest;
\r
490 {$ifdef secondlistener}
\r
491 if assigned(secondlistener) then if (dest.inaddr.family = AF_INET) then begin
\r
492 result := secondlistener.sendto(dest,destlen,data,len);
\r
496 result := {$ifdef win32}winsock{$else}sockets{$endif}.sendto(self.fdhandleout,data^,len,0,destx,destlen);
\r
499 function tlsocket.receivefrom(data:pointer;len:integer;var src:TInetSockAddrV;var srclen:integer):integer;
\r
501 tempsrc:TInetSockAddrV;
\r
502 tempsrclen:integer;
\r
503 srcx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute tempsrc;
\r
506 {$ifdef secondlistener}
\r
507 if assigned(secondlistener) then if lastsessionfromsecond then begin
\r
508 lastsessionfromsecond := false;
\r
509 result := secondlistener.receivefrom(data,len,src,srclen);
\r
513 tempsrclen := sizeof(tempsrc);
\r
514 result := {$ifdef win32}winsock{$else}sockets{$endif}.recvfrom(self.fdhandlein,data^,len,0,srcx,tempsrclen);
\r
517 biniptemp := inaddrvtobinip(tempsrc);
\r
518 if needconverttov4(biniptemp) then begin
\r
519 converttov4(biniptemp);
\r
520 tempsrclen := makeinaddrv(biniptemp,inttostr(ntohs(tempsrc.InAddr.port)),tempsrc);
\r
524 move(tempsrc,src,srclen);
\r
525 srclen := tempsrclen;
\r
528 procedure tlsocket.connectionfailedhandler(error:word);
\r
530 if trymoreips then begin
\r
531 // writeln('failed with error ',error);
\r
532 connecttimeout.enabled := false;
\r
533 destroying := true;
\r
534 state := wsconnected;
\r
535 self.internalclose(0);
\r
536 destroying := false;
\r
539 state := wsconnected;
\r
540 if assigned(onsessionconnected) then onsessionconnected(self,error);
\r
541 self.internalclose(0);
\r
542 recvq.del(maxlongint);
\r
546 procedure tlsocket.connectsuccesshandler;
\r
548 trymoreips := false;
\r
549 connecttimeout.enabled := false;
\r
550 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
554 procedure tlsocket.handlefdtrigger(readtrigger,writetrigger:boolean);
\r
556 tempbuf:array[0..receivebufsize-1] of byte;
\r
558 // writeln('got a fd trigger, readtrigger=',readtrigger,' writetrigger=',writetrigger,' state=',integer(state));
\r
559 if (state =wslistening) and readtrigger then begin
\r
560 { debugout('listening socket triggered on read');}
\r
561 eventcore.rmasterclr(fdhandlein);
\r
562 if assigned(onsessionAvailable) then onsessionAvailable(self,0);
\r
564 if dgram and readtrigger then begin
\r
565 if assigned(ondataAvailable) then ondataAvailable(self,0);
\r
569 if (state =wsconnecting) and writetrigger then begin
\r
570 // code for dealing with the reults of a non-blocking connect is
\r
572 // if just write is triggered it means connect suceeded
\r
573 // if both read and write are triggered it can mean 2 things
\r
574 // 1: connect ok and data availible
\r
576 // to find out which you must read from the socket and look for errors
\r
577 // there if we read successfully we drop through into the code for fireing
\r
579 if not readtrigger then begin
\r
580 state := wsconnected;
\r
581 connectsuccesshandler;
\r
583 numread := myfdread(fdhandlein,tempbuf,sizeof(tempbuf));
\r
584 if numread <> -1 then begin
\r
585 state := wsconnected;
\r
586 connectsuccesshandler;
\r
587 //connectread := true;
\r
588 recvq.add(@tempbuf,numread);
\r
590 connectionfailedhandler({$ifdef win32}wsagetlasterror{$else}linuxerror{$endif});
\r
593 // if things went well here we are now in the state wsconnected with data sitting in our receive buffer
\r
594 // so we drop down into the processing for data availible
\r
596 if fdhandlein >= 0 then begin
\r
597 if state = wsconnected then begin
\r
598 eventcore.rmasterset(fdhandlein,false);
\r
600 eventcore.rmasterclr(fdhandlein);
\r
603 if fdhandleout >= 0 then begin
\r
604 if sendq.size = 0 then begin
\r
605 //don't clear the bit in fdswmaster if data is in the sendq
\r
606 eventcore.wmasterclr(fdhandleout);
\r
611 inherited handlefdtrigger(readtrigger,writetrigger);
\r
614 constructor tlsocket.Create(AOwner: TComponent);
\r
616 inherited create(aowner);
\r
617 closehandles := true;
\r
618 trymoreips := true;
\r
622 function tlsocket.getpeername(var addr:tsockaddrin;addrlen:integer):integer;
\r
624 addrx : {$ifdef win32}winsock.tsockaddr{$else}tsockaddrin{$endif} absolute addr;
\r
626 result := {$ifdef win32}winsock{$else}sockets{$endif}.getpeername(self.fdhandlein,addrx,addrlen);
\r
629 procedure tlsocket.getxaddrbin(var binip:tbinip);
\r
631 addr:tinetsockaddrv;
\r
635 fillchar(addr,sizeof(addr),0);
\r
638 winsock.getsockname(self.fdhandlein,psockaddr(@addr)^,i);
\r
640 sockets.getsocketname(self.fdhandlein,addr,i);
\r
642 binip := inaddrvtobinip(addr);
\r
643 converttov4(binip);
\r
646 procedure tlsocket.getpeeraddrbin(var binip:tbinip);
\r
648 addr:tinetsockaddrv;
\r
652 fillchar(addr,sizeof(addr),0);
\r
654 winsock.getpeername(self.fdhandlein,psockaddr(@addr)^,i);
\r
656 sockets.getpeername(self.fdhandlein,addr,i);
\r
659 binip := inaddrvtobinip(addr);
\r
660 converttov4(binip);
\r
663 function tlsocket.getXaddr:string;
\r
667 getxaddrbin(biniptemp);
\r
668 result := ipbintostr(biniptemp);
\r
669 if result = '' then result := 'error';
\r
672 function tlsocket.getpeeraddr:string;
\r
676 getpeeraddrbin(biniptemp);
\r
677 result := ipbintostr(biniptemp);
\r
678 if result = '' then result := 'error';
\r
681 function tlsocket.getXport:string;
\r
683 addr:tinetsockaddrv;
\r
688 winsock.getsockname(self.fdhandlein,psockaddrin(@addr)^,i);
\r
691 sockets.getsocketname(self.fdhandlein,addr,i);
\r
694 result := inttostr(htons(addr.InAddr.port));
\r
697 function tlsocket.getpeerport:string;
\r
699 addr:tinetsockaddrv;
\r
704 winsock.getpeername(self.fdhandlein,psockaddrin(@addr)^,i);
\r
707 sockets.getpeername(self.fdhandlein,addr,i);
\r
710 result := inttostr(htons(addr.InAddr.port));
\r
714 procedure tlsocket.myfdclose(fd : integer);
\r
718 function tlsocket.myfdwrite(fd: LongInt;const buf;size: LongInt):LongInt;
\r
720 result := winsock.send(fd,(@buf)^,size,0);
\r
722 function tlsocket.myfdread(fd: LongInt;var buf;size: LongInt):LongInt;
\r
724 result := winsock.recv(fd,buf,size,0);
\r