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
222 biniplist := forwardlookuplist(addr,0);
\r
223 if biniplist_getcount(biniplist) = 0 then raise exception.create('unable to resolve '+addr);
\r
225 //makeinaddrv(addr,port,inaddr);
\r
228 if not assigned(connecttimeout) then begin
\r
229 connecttimeout := tltimer.create(self);
\r
230 connecttimeout.Tag := integer(self);
\r
231 connecttimeout.ontimer := connecttimeouthandler;
\r
232 connecttimeout.interval := 2500;
\r
233 connecttimeout.enabled := false;
\r
238 procedure tlsocket.sendstr(const str : string);
\r
241 send(@str[1],length(str))
\r
243 inherited sendstr(str);
\r
247 function tlsocket.send(data:pointer;len:integer):integer;
\r
250 // writeln('sending to '+ipbintostr(inaddrvtobinip(inaddr)),' ',htons(inaddr.inaddr.port),' ',len,' bytes');
\r
251 result := sendto(inaddr,getaddrsize,data,len);
\r
253 // writeln('send result ',result);
\r
254 // writeln('errno',errno);
\r
256 result := inherited send(data,len);
\r
261 function tlsocket.receive(Buf:Pointer;BufSize:integer):integer;
\r
264 result := myfdread(self.fdhandlein,buf^,bufsize);
\r
266 result := inherited receive(buf,bufsize);
\r
270 procedure tlsocket.bindsocket;
\r
273 inAddrtemp:TInetSockAddrV;
\r
274 inAddrtempx:{$ifdef win32}winsock.TSockaddr{$else}TInetSockAddrV{$endif} absolute inaddrtemp;
\r
275 inaddrtempsize:integer;
\r
278 if (localaddr <> '') or (localport <> '') then begin
\r
279 if localaddr = '' then begin
\r
281 if inaddr.inaddr.family = AF_INET6 then localaddr := '::' else
\r
283 localaddr := '0.0.0.0';
\r
285 //gethostbyname(localaddr,host);
\r
287 inaddrtempsize := makeinaddrv(forwardlookup(localaddr,0),localport,inaddrtemp);
\r
289 If Bind(fdhandlein,inaddrtempx,inaddrtempsize)<> {$ifdef win32}0{$else}true{$endif} Then begin
\r
291 lasterror := {$ifdef win32}getlasterror{$else}socketerror{$endif};
\r
292 raise ESocketException.create('unable to bind, error '+inttostr(lasterror));
\r
297 on e: exception do begin
\r
299 raise; //reraise the exception
\r
304 procedure tlsocket.listen;
\r
311 if state <> wsclosed then close;
\r
312 udp := uppercase(proto) = 'UDP';
\r
313 if udp then socktype := SOCK_DGRAM else socktype := SOCK_STREAM;
\r
316 if addr = '' then begin
\r
318 if not v4listendefault then begin
\r
324 biniptemp := forwardlookup(addr,10);
\r
325 addr := ipbintostr(biniptemp);
\r
326 fdhandlein := socket(biniptemp.family,socktype,0);
\r
328 if (addr = '::') and (origaddr = '') and (fdhandlein < 0) then begin
\r
330 fdhandlein := socket(AF_INET,socktype,0);
\r
333 if fdhandlein = -1 then raise ESocketException.create('unable to create socket');
\r
334 dupnowatch(fdhandlein); // sets up maxs and copies handle to fdhandleout among other things
\r
335 //eventcore.setfdreverse(fdhandlein,self); //already taken care of by dup
\r
336 state := wsclosed; // then set this back as it was an undesired side effect of dup
\r
339 yes := $01010101; {Copied this from existing code. Value is empiric,
\r
340 but works. (yes=true<>0) }
\r
342 if SetSocketOptions(fdhandlein, SOL_SOCKET, SO_REUSEADDR,yes,sizeof(yes))=-1 then begin
\r
343 raise ESocketException.create('unable to set socket options');
\r
350 if not udp then begin
\r
351 {!!! allow custom queue length? default 5}
\r
352 if listenqueue = 0 then listenqueue := 5;
\r
353 If {$ifdef win32}winsock{$else}sockets{$endif}.Listen(fdhandlein,listenqueue)<>{$ifdef win32}0{$else}true{$endif} Then raise esocketexception.create('unable to listen');
\r
354 state := wsListening;
\r
357 SetSocketOptions(fdhandleout, SOL_SOCKET, SO_BROADCAST, 'TRUE', Length('TRUE'));
\r
359 state := wsconnected;
\r
362 if state = wsclosed then begin
\r
363 if fdhandlein >= 0 then begin
\r
364 {one *can* get here without fd -beware}
\r
365 eventcore.rmasterclr(fdhandlein);
\r
366 myfdclose(fdhandlein); // we musnt leak file discriptors
\r
367 eventcore.setfdreverse(fdhandlein,nil);
\r
371 eventcore.rmasterset(fdhandlein,not udp);
\r
373 if fdhandleout >= 0 then eventcore.wmasterclr(fdhandleout);
\r
375 //writeln('listened on addr '+addr+':'+port+' '+proto+' using socket number ',fdhandlein);
\r
378 function tlsocket.accept : longint;
\r
380 FromAddrSize : LongInt; // i don't realy know what to do with these at this
\r
381 FromAddr : TInetSockAddrV; // at this point time will tell :)
\r
385 FromAddrSize := Sizeof(FromAddr);
\r
387 result := winsock.accept(fdhandlein,@fromaddr,@fromaddrsize);
\r
389 result := sockets.accept(fdhandlein,fromaddr,fromaddrsize);
\r
391 //now we have accepted one request start monitoring for more again
\r
392 eventcore.rmasterset(fdhandlein,true);
\r
394 if result = -1 then begin
\r
395 raise esocketexception.create('error '+inttostr({$ifdef win32}getlasterror{$else}socketerror{$endif})+' while accepting');
\r
397 if result > absoloutemaxs then begin
\r
401 raise esocketexception.create('file discriptor out of range: '+inttostr(a));
\r
405 function tlsocket.sendto(dest:TInetSockAddrV;destlen:integer;data:pointer;len:integer):integer;
\r
407 destx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute dest;
\r
409 result := {$ifdef win32}winsock{$else}sockets{$endif}.sendto(self.fdhandleout,data^,len,0,destx,destlen);
\r
412 function tlsocket.receivefrom(data:pointer;len:integer;var src:TInetSockAddrV;var srclen:integer):integer;
\r
414 srcx : {$ifdef win32}winsock.TSockAddr{$else}TInetSockAddrV{$endif} absolute src;
\r
416 result := {$ifdef win32}winsock{$else}sockets{$endif}.recvfrom(self.fdhandlein,data^,len,0,srcx,srclen);
\r
419 procedure tlsocket.connectionfailedhandler(error:word);
\r
421 if trymoreips then begin
\r
422 // writeln('failed with error ',error);
\r
423 connecttimeout.enabled := false;
\r
424 destroying := true;
\r
425 state := wsconnected;
\r
426 self.internalclose(0);
\r
427 destroying := false;
\r
430 state := wsconnected;
\r
431 if assigned(onsessionconnected) then onsessionconnected(self,error);
\r
432 self.internalclose(0);
\r
433 recvq.del(maxlongint);
\r
437 procedure tlsocket.connectsuccesshandler;
\r
439 trymoreips := false;
\r
440 connecttimeout.enabled := false;
\r
441 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
445 procedure tlsocket.handlefdtrigger(readtrigger,writetrigger:boolean);
\r
447 tempbuf:array[0..receivebufsize-1] of byte;
\r
449 // writeln('got a fd trigger, readtrigger=',readtrigger,' writetrigger=',writetrigger,' state=',integer(state));
\r
450 if (state =wslistening) and readtrigger then begin
\r
451 { debugout('listening socket triggered on read');}
\r
452 eventcore.rmasterclr(fdhandlein);
\r
453 if assigned(onsessionAvailable) then onsessionAvailable(self,0);
\r
455 if udp and readtrigger then begin
\r
456 if assigned(ondataAvailable) then ondataAvailable(self,0);
\r
460 if (state =wsconnecting) and writetrigger then begin
\r
461 // code for dealing with the reults of a non-blocking connect is
\r
463 // if just write is triggered it means connect suceeded
\r
464 // if both read and write are triggered it can mean 2 things
\r
465 // 1: connect ok and data availible
\r
467 // to find out which you must read from the socket and look for errors
\r
468 // there if we read successfully we drop through into the code for fireing
\r
470 if not readtrigger then begin
\r
471 state := wsconnected;
\r
472 connectsuccesshandler;
\r
474 numread := myfdread(fdhandlein,tempbuf,sizeof(tempbuf));
\r
475 if numread <> -1 then begin
\r
476 state := wsconnected;
\r
477 connectsuccesshandler;
\r
478 //connectread := true;
\r
479 recvq.add(@tempbuf,numread);
\r
481 connectionfailedhandler({$ifdef win32}wsagetlasterror{$else}linuxerror{$endif});
\r
484 // if things went well here we are now in the state wsconnected with data sitting in our receive buffer
\r
485 // so we drop down into the processing for data availible
\r
487 if fdhandlein >= 0 then begin
\r
488 if state = wsconnected then begin
\r
489 eventcore.rmasterset(fdhandlein,false);
\r
491 eventcore.rmasterclr(fdhandlein);
\r
494 if fdhandleout >= 0 then begin
\r
495 if sendq.size = 0 then begin
\r
496 //don't clear the bit in fdswmaster if data is in the sendq
\r
497 eventcore.wmasterclr(fdhandleout);
\r
502 inherited handlefdtrigger(readtrigger,writetrigger);
\r
505 constructor tlsocket.Create(AOwner: TComponent);
\r
507 inherited create(aowner);
\r
508 closehandles := true;
\r
509 trymoreips := true;
\r
513 function tlsocket.getpeername(var addr:tsockaddrin;addrlen:integer):integer;
\r
515 addrx : {$ifdef win32}winsock.tsockaddr{$else}tsockaddrin{$endif} absolute addr;
\r
517 result := {$ifdef win32}winsock{$else}sockets{$endif}.getpeername(self.fdhandlein,addrx,addrlen);
\r
520 procedure tlsocket.getxaddrbin(var binip:tbinip);
\r
522 addr:tinetsockaddrv;
\r
526 fillchar(addr,sizeof(addr),0);
\r
529 winsock.getsockname(self.fdhandlein,psockaddr(@addr)^,i);
\r
531 sockets.getsocketname(self.fdhandlein,addr,i);
\r
533 binip.family := addr.inaddr.family;
\r
535 if addr.inaddr6.sin6_family = AF_INET6 then begin
\r
536 binip.ip6 := addr.inaddr6.sin6_addr;
\r
540 binip.ip := addr.inaddr.addr;
\r
542 converttov4(binip);
\r
545 procedure tlsocket.getpeeraddrbin(var binip:tbinip);
\r
547 addr:tinetsockaddrv;
\r
551 fillchar(addr,sizeof(addr),0);
\r
553 winsock.getpeername(self.fdhandlein,psockaddr(@addr)^,i);
\r
555 sockets.getpeername(self.fdhandlein,addr,i);
\r
558 binip.family := addr.inaddr.family;
\r
560 if addr.inaddr6.sin6_family = AF_INET6 then begin
\r
561 binip.ip6 := addr.inaddr6.sin6_addr;
\r
565 binip.ip := addr.inaddr.addr;
\r
567 converttov4(binip);
\r
570 function tlsocket.getXaddr:string;
\r
574 getxaddrbin(biniptemp);
\r
575 result := ipbintostr(biniptemp);
\r
576 if result = '' then result := 'error';
\r
579 function tlsocket.getpeeraddr:string;
\r
583 getpeeraddrbin(biniptemp);
\r
584 result := ipbintostr(biniptemp);
\r
585 if result = '' then result := 'error';
\r
588 function tlsocket.getXport:string;
\r
590 addr:tinetsockaddrv;
\r
595 winsock.getsockname(self.fdhandlein,psockaddrin(@addr)^,i);
\r
598 sockets.getsocketname(self.fdhandlein,addr,i);
\r
601 result := inttostr(htons(addr.InAddr.port));
\r
604 function tlsocket.getpeerport:string;
\r
606 addr:tinetsockaddrv;
\r
611 winsock.getpeername(self.fdhandlein,psockaddrin(@addr)^,i);
\r
614 sockets.getpeername(self.fdhandlein,addr,i);
\r
617 result := inttostr(htons(addr.InAddr.port));
\r
621 procedure tlsocket.myfdclose(fd : integer);
\r
625 function tlsocket.myfdwrite(fd: LongInt;const buf;size: LongInt):LongInt;
\r
627 result := winsock.send(fd,(@buf)^,size,0);
\r
629 function tlsocket.myfdread(fd: LongInt;var buf;size: LongInt):LongInt;
\r
631 result := winsock.recv(fd,buf,size,0);
\r