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
58 sunB = packed record
\r
59 s_b1, s_b2, s_b3, s_b4: byte;
\r
62 SunW = packed record
\r
66 TInAddr = packed record
\r
70 2: (S_addr: cardinal);
\r
74 TLsocket = class(tlasio)
\r
78 inAddr : TInetSockAddrV;
\r
80 biniplist:tbiniplist;
\r
83 connecttimeout:tltimer;
\r
85 { inAddrSize:integer;}
\r
87 //host : THostentry ;
\r
89 //mainthread : boolean ; //for debuggin only
\r
96 listenqueue:integer;
\r
97 procedure connectionfailedhandler(error:word);
\r
98 procedure connecttimeouthandler(sender:tobject);
\r
99 procedure connectsuccesshandler;
\r
100 function getaddrsize:integer;
\r
101 procedure connect; virtual;
\r
102 procedure realconnect;
\r
103 procedure bindsocket;
\r
105 function accept : longint;
\r
106 function sendto(dest:TInetSockAddrV;destlen:integer;data:pointer;len:integer):integer; virtual;
\r
107 function receivefrom(data:pointer;len:integer;var src:TInetSockAddrV;var srclen:integer):integer; virtual;
\r
108 //procedure internalclose(error:word);override;
\r
109 procedure handlefdtrigger(readtrigger,writetrigger:boolean); override;
\r
110 function send(data:pointer;len:integer):integer;override;
\r
111 procedure sendstr(const str : string);override;
\r
112 function Receive(Buf:Pointer;BufSize:integer):integer; override;
\r
113 function getpeername(var addr:tsockaddrin;addrlen:integer):integer; virtual;
\r
114 procedure getXaddrbin(var binip:tbinip); virtual;
\r
115 procedure getpeeraddrbin(var binip:tbinip); virtual;
\r
116 function getXaddr:string; virtual;
\r
117 function getpeeraddr:string; virtual;
\r
118 function getXport:string; virtual;
\r
119 function getpeerport:string; virtual;
\r
120 constructor Create(AOwner: TComponent); override;
\r
122 procedure myfdclose(fd : integer); override;
\r
123 function myfdwrite(fd: LongInt;const buf;size: LongInt):LongInt; override;
\r
124 function myfdread(fd: LongInt;var buf;size: LongInt):LongInt; override;
\r
127 tsocket=longint; // for compatibility with twsocket
\r
129 twsocket=tlsocket; {easy}
\r
132 {!!!function longipdns(s:string):longint;}
\r
136 v4listendefault:boolean=false;
\r
145 {$include unixstuff.inc}
\r
148 function tlsocket.getaddrsize:integer;
\r
150 result := inaddrsize(inaddr);
\r
154 procedure tlsocket.realconnect;
\r
159 // writeln('trying to connect to ',ipbintostr(biniplist_get(biniplist,currentip)),'#',port);
\r
160 makeinaddrv(biniplist_get(biniplist,currentip),port,inaddr);
\r
162 if (currentip >= biniplist_getcount(biniplist)) then trymoreips := false;
\r
163 udp := uppercase(proto) = 'UDP';
\r
164 if udp then a := SOCK_DGRAM else a := SOCK_STREAM;
\r
165 a := Socket(inaddr.inaddr.family,a,0);
\r
166 //writeln(ord(inaddr.inaddr.family));
\r
167 if a = -1 then begin
\r
168 lasterror := {$ifdef win32}getlasterror{$else}socketerror{$endif};
\r
169 raise esocketexception.create('unable to create socket');
\r
176 SetSocketOptions(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
178 state := wsconnected;
\r
179 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
181 eventcore.rmasterset(fdhandlein,false);
\r
182 eventcore.wmasterclr(fdhandleout);
\r
184 state :=wsconnecting;
\r
186 //writeln(inaddr.inaddr.port);
\r
187 winsock.Connect(fdhandlein,winsock.psockaddr(@inADDR)^,getaddrsize);
\r
189 sockets.Connect(fdhandlein,inADDR,getaddrsize);
\r
191 eventcore.rmasterset(fdhandlein,false);
\r
192 eventcore.wmasterset(fdhandleout);
\r
193 if trymoreips then connecttimeout.enabled := true;
\r
197 on e: exception do begin
\r
199 raise; //reraise the exception
\r
205 procedure tlsocket.connecttimeouthandler(sender:tobject);
\r
207 connecttimeout.enabled := false;
\r
208 destroying := true; //hack to not cause handler to trigger
\r
210 destroying := false;
\r
214 procedure tlsocket.connect;
\r
219 if state <> wsclosed then close;
\r
221 if isbiniplist(addr) then biniplist := addr else biniplist := forwardlookuplist(addr,0);
\r
222 if biniplist_getcount(biniplist) = 0 then raise exception.create('unable to resolve '+addr);
\r
224 //makeinaddrv(addr,port,inaddr);
\r
227 if not assigned(connecttimeout) then begin
\r
228 connecttimeout := tltimer.create(self);
\r
229 connecttimeout.Tag := integer(self);
\r
230 connecttimeout.ontimer := connecttimeouthandler;
\r
231 connecttimeout.interval := 2500;
\r
232 connecttimeout.enabled := false;
\r
237 procedure tlsocket.sendstr(const str : string);
\r
240 send(@str[1],length(str))
\r
242 inherited sendstr(str);
\r
246 function tlsocket.send(data:pointer;len:integer):integer;
\r
249 // writeln('sending to '+ipbintostr(inaddrvtobinip(inaddr)),' ',htons(inaddr.inaddr.port),' ',len,' bytes');
\r
250 result := sendto(inaddr,getaddrsize,data,len);
\r
252 // writeln('send result ',result);
\r
253 // writeln('errno',errno);
\r
255 result := inherited send(data,len);
\r
260 function tlsocket.receive(Buf:Pointer;BufSize:integer):integer;
\r
263 result := myfdread(self.fdhandlein,buf^,bufsize);
\r
265 result := inherited receive(buf,bufsize);
\r
269 procedure tlsocket.bindsocket;
\r
272 inAddrtemp:TInetSockAddrV;
\r
273 inAddrtempx:{$ifdef win32}winsock.TSockaddr{$else}TInetSockAddrV{$endif} absolute inaddrtemp;
\r
274 inaddrtempsize:integer;
\r
277 if (localaddr <> '') or (localport <> '') then begin
\r
278 if localaddr = '' then begin
\r
280 if inaddr.inaddr.family = AF_INET6 then localaddr := '::' else
\r
282 localaddr := '0.0.0.0';
\r
284 //gethostbyname(localaddr,host);
\r
286 inaddrtempsize := makeinaddrv(forwardlookup(localaddr,0),localport,inaddrtemp);
\r
288 If Bind(fdhandlein,inaddrtempx,inaddrtempsize)<> {$ifdef win32}0{$else}true{$endif} Then begin
\r
290 lasterror := {$ifdef win32}getlasterror{$else}socketerror{$endif};
\r
291 raise ESocketException.create('unable to bind, error '+inttostr(lasterror));
\r
296 on e: exception do begin
\r
298 raise; //reraise the exception
\r
303 procedure tlsocket.listen;
\r
310 if state <> wsclosed then close;
\r
311 udp := uppercase(proto) = 'UDP';
\r
312 if udp then socktype := SOCK_DGRAM else socktype := SOCK_STREAM;
\r
315 if addr = '' then begin
\r
317 if not v4listendefault then begin
\r
323 if isbiniplist(addr) then biniptemp := biniplist_get(addr,0) else biniptemp := forwardlookup(addr,10);
\r
324 addr := ipbintostr(biniptemp);
\r
325 fdhandlein := socket(biniptemp.family,socktype,0);
\r
327 if (addr = '::') and (origaddr = '') and (fdhandlein < 0) then begin
\r
329 fdhandlein := socket(AF_INET,socktype,0);
\r
332 if fdhandlein = -1 then raise ESocketException.create('unable to create socket');
\r
333 dupnowatch(fdhandlein); // sets up maxs and copies handle to fdhandleout among other things
\r
334 //eventcore.setfdreverse(fdhandlein,self); //already taken care of by dup
\r
335 state := wsclosed; // then set this back as it was an undesired side effect of dup
\r
338 yes := $01010101; {Copied this from existing code. Value is empiric,
\r
339 but works. (yes=true<>0) }
\r
341 if SetSocketOptions(fdhandlein, SOL_SOCKET, SO_REUSEADDR,yes,sizeof(yes))=-1 then begin
\r
342 raise ESocketException.create('unable to set socket options');
\r
349 if not udp then begin
\r
350 {!!! allow custom queue length? default 5}
\r
351 if listenqueue = 0 then listenqueue := 5;
\r
352 If {$ifdef win32}winsock{$else}sockets{$endif}.Listen(fdhandlein,listenqueue)<>{$ifdef win32}0{$else}true{$endif} Then raise esocketexception.create('unable to listen');
\r
353 state := wsListening;
\r
356 SetSocketOptions(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
358 state := wsconnected;
\r
361 if state = wsclosed then begin
\r
362 if fdhandlein >= 0 then begin
\r
363 {one *can* get here without fd -beware}
\r
364 eventcore.rmasterclr(fdhandlein);
\r
365 myfdclose(fdhandlein); // we musnt leak file discriptors
\r
366 eventcore.setfdreverse(fdhandlein,nil);
\r
370 eventcore.rmasterset(fdhandlein,not udp);
\r
372 if fdhandleout >= 0 then eventcore.wmasterclr(fdhandleout);
\r
374 //writeln('listened on addr '+addr+':'+port+' '+proto+' using socket number ',fdhandlein);
\r
377 function tlsocket.accept : longint;
\r
379 FromAddrSize : LongInt; // i don't realy know what to do with these at this
\r
380 FromAddr : TInetSockAddrV; // at this point time will tell :)
\r
384 FromAddrSize := Sizeof(FromAddr);
\r
386 result := winsock.accept(fdhandlein,@fromaddr,@fromaddrsize);
\r
388 result := sockets.accept(fdhandlein,fromaddr,fromaddrsize);
\r
390 //now we have accepted one request start monitoring for more again
\r
391 eventcore.rmasterset(fdhandlein,true);
\r
393 if result = -1 then begin
\r
394 raise esocketexception.create('error '+inttostr({$ifdef win32}getlasterror{$else}socketerror{$endif})+' while accepting');
\r
396 if result > absoloutemaxs then begin
\r
400 raise esocketexception.create('file discriptor out of range: '+inttostr(a));
\r
404 function tlsocket.sendto(dest:TInetSockAddrV;destlen:integer;data:pointer;len:integer):integer;
\r
406 destx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute dest;
\r
408 result := {$ifdef win32}winsock{$else}sockets{$endif}.sendto(self.fdhandleout,data^,len,0,destx,destlen);
\r
411 function tlsocket.receivefrom(data:pointer;len:integer;var src:TInetSockAddrV;var srclen:integer):integer;
\r
413 srcx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute src;
\r
415 result := {$ifdef win32}winsock{$else}sockets{$endif}.recvfrom(self.fdhandlein,data^,len,0,srcx,srclen);
\r
418 procedure tlsocket.connectionfailedhandler(error:word);
\r
420 if trymoreips then begin
\r
421 // writeln('failed with error ',error);
\r
422 connecttimeout.enabled := false;
\r
423 destroying := true;
\r
424 state := wsconnected;
\r
425 self.internalclose(0);
\r
426 destroying := false;
\r
429 state := wsconnected;
\r
430 if assigned(onsessionconnected) then onsessionconnected(self,error);
\r
431 self.internalclose(0);
\r
432 recvq.del(maxlongint);
\r
436 procedure tlsocket.connectsuccesshandler;
\r
438 trymoreips := false;
\r
439 connecttimeout.enabled := false;
\r
440 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
444 procedure tlsocket.handlefdtrigger(readtrigger,writetrigger:boolean);
\r
446 tempbuf:array[0..receivebufsize-1] of byte;
\r
448 // writeln('got a fd trigger, readtrigger=',readtrigger,' writetrigger=',writetrigger,' state=',integer(state));
\r
449 if (state =wslistening) and readtrigger then begin
\r
450 { debugout('listening socket triggered on read');}
\r
451 eventcore.rmasterclr(fdhandlein);
\r
452 if assigned(onsessionAvailable) then onsessionAvailable(self,0);
\r
454 if udp and readtrigger then begin
\r
455 if assigned(ondataAvailable) then ondataAvailable(self,0);
\r
459 if (state =wsconnecting) and writetrigger then begin
\r
460 // code for dealing with the reults of a non-blocking connect is
\r
462 // if just write is triggered it means connect suceeded
\r
463 // if both read and write are triggered it can mean 2 things
\r
464 // 1: connect ok and data availible
\r
466 // to find out which you must read from the socket and look for errors
\r
467 // there if we read successfully we drop through into the code for fireing
\r
469 if not readtrigger then begin
\r
470 state := wsconnected;
\r
471 connectsuccesshandler;
\r
473 numread := myfdread(fdhandlein,tempbuf,sizeof(tempbuf));
\r
474 if numread <> -1 then begin
\r
475 state := wsconnected;
\r
476 connectsuccesshandler;
\r
477 //connectread := true;
\r
478 recvq.add(@tempbuf,numread);
\r
480 connectionfailedhandler({$ifdef win32}wsagetlasterror{$else}linuxerror{$endif});
\r
483 // if things went well here we are now in the state wsconnected with data sitting in our receive buffer
\r
484 // so we drop down into the processing for data availible
\r
486 if fdhandlein >= 0 then begin
\r
487 if state = wsconnected then begin
\r
488 eventcore.rmasterset(fdhandlein,false);
\r
490 eventcore.rmasterclr(fdhandlein);
\r
493 if fdhandleout >= 0 then begin
\r
494 if sendq.size = 0 then begin
\r
495 //don't clear the bit in fdswmaster if data is in the sendq
\r
496 eventcore.wmasterclr(fdhandleout);
\r
501 inherited handlefdtrigger(readtrigger,writetrigger);
\r
504 constructor tlsocket.Create(AOwner: TComponent);
\r
506 inherited create(aowner);
\r
507 closehandles := true;
\r
508 trymoreips := true;
\r
512 function tlsocket.getpeername(var addr:tsockaddrin;addrlen:integer):integer;
\r
514 addrx : {$ifdef win32}winsock.tsockaddr{$else}tsockaddrin{$endif} absolute addr;
\r
516 result := {$ifdef win32}winsock{$else}sockets{$endif}.getpeername(self.fdhandlein,addrx,addrlen);
\r
519 procedure tlsocket.getxaddrbin(var binip:tbinip);
\r
521 addr:tinetsockaddrv;
\r
525 fillchar(addr,sizeof(addr),0);
\r
528 winsock.getsockname(self.fdhandlein,psockaddr(@addr)^,i);
\r
530 sockets.getsocketname(self.fdhandlein,addr,i);
\r
532 binip.family := addr.inaddr.family;
\r
534 if addr.inaddr6.sin6_family = AF_INET6 then begin
\r
535 binip.ip6 := addr.inaddr6.sin6_addr;
\r
539 binip.ip := addr.inaddr.addr;
\r
541 converttov4(binip);
\r
544 procedure tlsocket.getpeeraddrbin(var binip:tbinip);
\r
546 addr:tinetsockaddrv;
\r
550 fillchar(addr,sizeof(addr),0);
\r
552 winsock.getpeername(self.fdhandlein,psockaddr(@addr)^,i);
\r
554 sockets.getpeername(self.fdhandlein,addr,i);
\r
557 binip.family := addr.inaddr.family;
\r
559 if addr.inaddr6.sin6_family = AF_INET6 then begin
\r
560 binip.ip6 := addr.inaddr6.sin6_addr;
\r
564 binip.ip := addr.inaddr.addr;
\r
566 converttov4(binip);
\r
569 function tlsocket.getXaddr:string;
\r
573 getxaddrbin(biniptemp);
\r
574 result := ipbintostr(biniptemp);
\r
575 if result = '' then result := 'error';
\r
578 function tlsocket.getpeeraddr:string;
\r
582 getpeeraddrbin(biniptemp);
\r
583 result := ipbintostr(biniptemp);
\r
584 if result = '' then result := 'error';
\r
587 function tlsocket.getXport:string;
\r
589 addr:tinetsockaddrv;
\r
594 winsock.getsockname(self.fdhandlein,psockaddrin(@addr)^,i);
\r
597 sockets.getsocketname(self.fdhandlein,addr,i);
\r
600 result := inttostr(htons(addr.InAddr.port));
\r
603 function tlsocket.getpeerport:string;
\r
605 addr:tinetsockaddrv;
\r
610 winsock.getpeername(self.fdhandlein,psockaddrin(@addr)^,i);
\r
613 sockets.getpeername(self.fdhandlein,addr,i);
\r
616 result := inttostr(htons(addr.InAddr.port));
\r
620 procedure tlsocket.myfdclose(fd : integer);
\r
624 function tlsocket.myfdwrite(fd: LongInt;const buf;size: LongInt):LongInt;
\r
626 result := winsock.send(fd,(@buf)^,size,0);
\r
628 function tlsocket.myfdread(fd: LongInt;var buf;size: LongInt):LongInt;
\r
630 result := winsock.recv(fd,buf,size,0);
\r