3 {socket code by plugwash}
\r
5 {use this code for whatever you like in programs under whater licence you like
\r
6 * This program is distributed in the hope that it will be useful,
\r
7 * but WITHOUT ANY WARRANTY; without even the implied warranty of
\r
8 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
\r
12 changes by plugwash (20030728)
\r
13 * created handlefdtrigger virtual method in tlasio (overridden in tlsocket) and moved a lot of code from messageloop into it
\r
14 * changed tlasio to tlasio
\r
15 * split fdhandle into fdhandlein and fdhandleout
\r
16 * i now use fdsrmaster and fdswmaster instead of rebuilding the lists every loop
\r
17 * split lsocket.pas into lsocket.pas and lcore.pas
\r
20 changes by beware (20030903)
\r
21 * added getxaddr, getxport (local addr, port, as string)
\r
22 * added getpeername, remote addr+port as binary
\r
23 * added htons and htonl functions (endian swap, same interface as windows API)
\r
26 * if connect failed (conn refused) set state to connected and call internalclose, to get closed handler (instead of fdclose)
\r
27 * (lcore) if closing the fd's in internalcose, set fd's to -1 because closing an fd makes it invalid
\r
30 * fixed: on connect failed, tried to close fdhandle's which were already set to -1, added check
\r
33 * added getpeeraddr, getpeerport, remote addr+port as string
\r
47 sockets,classes,pgdebugout,pgtypes,lcore,fd_utils,binipstuff,dnssync;
\r
49 sunB = packed record
\r
50 s_b1, s_b2, s_b3, s_b4: byte;
\r
53 SunW = packed record
\r
57 TInAddr = packed record
\r
61 2: (S_addr: cardinal);
\r
70 TInetSockAddr6 = packed Record
\r
71 sin6_family : sa_family_t;
\r
72 sin6_port : cuint16;
\r
73 sin6_flowinfo : cuint32;
\r
74 sin6_addr : Tin6_addr;
\r
75 sin6_scope_id : cuint32;
\r
79 TinetSockAddrv = packed record
\r
81 0: (InAddr:TInetSockAddr);
\r
83 1: (InAddr6:TInetSockAddr6);
\r
88 tsockaddrin=TInetSockAddr;
\r
91 TLsocket = class(tlasio)
\r
95 inAddr : TInetSockAddrV;
\r
96 { inAddrSize:integer;}
\r
98 //host : THostentry ;
\r
100 //mainthread : boolean ; //for debuggin only
\r
107 listenqueue:integer;
\r
108 function getaddrsize:integer;
\r
109 procedure connect; virtual;
\r
110 procedure bindsocket;
\r
112 function accept : longint;
\r
113 function sendto(dest:TInetSockAddr;destlen:integer;data:pointer;len:integer):integer; virtual;
\r
114 function receivefrom(data:pointer;len:integer;var src:TInetSockAddr;var srclen:integer):integer; virtual;
\r
115 //procedure internalclose(error:word);override;
\r
116 procedure handlefdtrigger(readtrigger,writetrigger:boolean); override;
\r
117 function send(data:pointer;len:integer):integer;override;
\r
118 procedure sendstr(const str : string);override;
\r
119 function Receive(Buf:Pointer;BufSize:integer):integer; override;
\r
120 function getpeername(var addr:tsockaddrin;addrlen:integer):integer; virtual;
\r
121 procedure getXaddrbin(var binip:tbinip); virtual;
\r
122 procedure getpeeraddrbin(var binip:tbinip); virtual;
\r
123 function getXaddr:string; virtual;
\r
124 function getpeeraddr:string; virtual;
\r
125 function getXport:string; virtual;
\r
126 function getpeerport:string; virtual;
\r
127 constructor Create(AOwner: TComponent); override;
\r
129 tsocket=longint; // for compatibility with twsocket
\r
131 twsocket=tlsocket; {easy}
\r
133 function htons(w:word):word;
\r
134 function htonl(i:integer):integer;
\r
135 {!!!function longipdns(s:string):longint;}
\r
139 v4listendefault:boolean=false;
\r
148 {$include unixstuff.inc}
\r
150 function longip(s:string):longint;inline;
\r
155 function convertbyte(const s:string):integer;inline;
\r
157 result := strtointdef(s,-1);
\r
158 if result < 0 then exit;
\r
159 if result > 255 then exit;
\r
162 if (result <> 0) and (s[1] = '0') then begin
\r
168 if not (s[1] in ['0'..'9']) then begin
\r
177 if a = 0 then exit;
\r
178 b := convertbyte(copy(s,1,a-1));if (b < 0) then exit;
\r
180 s := copy(s,a+1,256);
\r
182 if a = 0 then exit;
\r
183 b := convertbyte(copy(s,1,a-1));if (b < 0) then exit;
\r
184 l := l or b shl 16;
\r
185 s := copy(s,a+1,256);
\r
187 if a = 0 then exit;
\r
188 b := convertbyte(copy(s,1,a-1));if (b < 0) then exit;
\r
190 s := copy(s,a+1,256);
\r
191 b := convertbyte(copy(s,1,256));if (b < 0) then exit;
\r
197 function longipdns(s:string):longint;
\r
201 if s = '0.0.0.0' then begin
\r
204 result := longip(s);
\r
205 if result = 0 then begin
\r
206 if gethostbyname(s,host) then begin;
\r
207 result := htonl(Longint(Host.Addr));
\r
209 //writeln(inttohex(longint(host.addr),8))
\r
211 if result = 0 then begin
\r
212 if resolvehostbyname(s,host) then begin;
\r
213 result := htonl(Longint(Host.Addr));
\r
215 //writeln(inttohex(longint(host.addr),8))
\r
222 function htons(w:word):word;
\r
224 {$ifdef ENDIAN_LITTLE}
\r
225 result := ((w and $ff00) shr 8) or ((w and $ff) shl 8);
\r
231 function htonl(i:integer):integer;
\r
233 {$ifdef ENDIAN_LITTLE}
\r
234 result := (i shr 24) or (i shr 8 and $ff00) or (i shl 8 and $ff0000) or (i shl 24 and $ff000000);
\r
240 function tlsocket.getaddrsize:integer;
\r
243 if inaddr.inaddr.family = AF_INET6 then result := sizeof(tinetsockaddr6) else
\r
245 result := sizeof(tinetsockaddr);
\r
248 function makeinaddrv(addr,port:string;var inaddr:tinetsockaddrv):integer;
\r
253 biniptemp := forwardlookup(addr,10);
\r
254 fillchar(inaddr,sizeof(inaddr),0);
\r
255 if biniptemp.family = AF_INET then begin
\r
256 inAddr.InAddr.family:=AF_INET;
\r
257 inAddr.InAddr.port:=htons(strtointdef(port,0));
\r
258 inAddr.InAddr.addr:=biniptemp.ip;
\r
259 result := sizeof(tinetsockaddr);
\r
262 if biniptemp.family = AF_INET6 then begin
\r
263 inAddr.InAddr6.sin6_family:=AF_INET6;
\r
264 inAddr.InAddr6.sin6_port:=htons(strtointdef(port,0));
\r
265 inAddr.InAddr6.sin6_addr:=biniptemp.ip6;
\r
266 result := sizeof(tinetsockaddr6);
\r
269 raise esocketexception.create('unable to resolve address: '+addr);
\r
272 procedure tlsocket.connect;
\r
276 if state <> wsclosed then close;
\r
278 makeinaddrv(addr,port,inaddr);
\r
280 udp := uppercase(proto) = 'UDP';
\r
281 if udp then a := SOCK_DGRAM else a := SOCK_STREAM;
\r
282 a := Socket(inaddr.inaddr.family,a,0);
\r
284 if a = -1 then begin
\r
285 lasterror := socketerror;
\r
286 raise esocketexception.create('unable to create socket');
\r
292 state := wsconnected;
\r
293 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
295 state :=wsconnecting;
\r
296 sockets.Connect(fdhandlein,inADDR,getaddrsize);
\r
298 rmasterset(fdhandlein);
\r
300 wmasterclr(fdhandleout);
\r
302 wmasterset(fdhandleout);
\r
306 on e: exception do begin
\r
308 raise; //reraise the exception
\r
313 procedure tlsocket.sendstr(const str : string);
\r
316 send(@str[1],length(str))
\r
318 inherited sendstr(str);
\r
322 function tlsocket.send(data:pointer;len:integer):integer;
\r
325 result := sendto(inaddr.inaddr,getaddrsize,data,len)
\r
327 result := inherited send(data,len);
\r
332 function tlsocket.receive(Buf:Pointer;BufSize:integer):integer;
\r
335 result := fdread(self.fdhandlein,buf^,bufsize);
\r
337 result := inherited receive(buf,bufsize);
\r
341 procedure tlsocket.bindsocket;
\r
344 inAddrtemp:TInetSockAddrV;
\r
345 inaddrtempsize:integer;
\r
348 if (localaddr <> '') or (localport <> '') then begin
\r
349 if localaddr = '' then begin
\r
351 if inaddr.inaddr.family = AF_INET6 then localaddr := '::' else
\r
353 localaddr := '0.0.0.0';
\r
355 //gethostbyname(localaddr,host);
\r
357 inaddrtempsize := makeinaddrv(localaddr,localport,inaddrtemp);
\r
359 If Not Bind(fdhandlein,inaddrtemp,inaddrtempsize) Then begin
\r
361 lasterror := socketerror;
\r
362 raise ESocketException.create('unable to bind, error '+inttostr(lasterror));
\r
367 on e: exception do begin
\r
369 raise; //reraise the exception
\r
374 procedure tlsocket.listen;
\r
381 if state <> wsclosed then close;
\r
382 udp := uppercase(proto) = 'UDP';
\r
383 if udp then socktype := SOCK_DGRAM else socktype := SOCK_STREAM;
\r
386 if addr = '' then begin
\r
388 if not v4listendefault then begin
\r
394 biniptemp := forwardlookup(addr,10);
\r
395 addr := ipbintostr(biniptemp);
\r
396 fdhandlein := socket(biniptemp.family,socktype,0);
\r
398 if (addr = '::') and (origaddr = '') and (fdhandlein < 0) then begin
\r
400 fdhandlein := socket(AF_INET,socktype,0);
\r
403 if fdhandlein = -1 then raise ESocketException.create('unable to create socket');
\r
404 dup(fdhandlein); // sets up maxs and copies handle to fdhandleout among other things
\r
405 fdreverse[fdhandlein] := self;
\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
411 if SetSocketOptions(fdhandlein, SOL_SOCKET, SO_REUSEADDR,yes,sizeof(yes))=-1 then begin
\r
412 raise ESocketException.create('unable to set socket options');
\r
419 if not udp then begin
\r
420 {!!! allow custom queue length? default 5}
\r
421 if listenqueue = 0 then listenqueue := 5;
\r
422 If Not sockets.Listen(fdhandlein,listenqueue) Then raise esocketexception.create('unable to listen');
\r
423 state := wsListening;
\r
425 state := wsconnected;
\r
428 if state = wsclosed then begin
\r
429 if fdhandlein >= 0 then begin
\r
430 {one *can* get here without fd -beware}
\r
431 rmasterclr(fdhandlein);
\r
432 fdclose(fdhandlein); // we musnt leak file discriptors
\r
433 fdreverse[fdhandlein] := nil;
\r
437 rmasterset(fdhandlein);
\r
439 if fdhandleout >= 0 then wmasterclr(fdhandleout);
\r
443 function tlsocket.accept : longint;
\r
445 FromAddrSize : LongInt; // i don't realy know what to do with these at this
\r
446 FromAddr : TInetSockAddr; // at this point time will tell :)
\r
448 rmasterset(fdhandlein);
\r
449 FromAddrSize := Sizeof(FromAddr);
\r
450 result := sockets.accept(fdhandlein,fromaddr,fromaddrsize);
\r
451 if result = -1 then raise esocketexception.create('error '+inttostr(socketerror)+' while accepting');
\r
452 if result > absoloutemaxs then begin
\r
455 raise esocketexception.create('file discriptor out of range');
\r
459 function tlsocket.sendto;
\r
461 result := sockets.sendto(self.fdhandleout,data^,len,0,dest,destlen);
\r
464 function tlsocket.receivefrom;
\r
466 result := sockets.recvfrom(self.fdhandlein,data^,len,0,src,srclen);
\r
469 procedure tlsocket.handlefdtrigger(readtrigger,writetrigger:boolean);
\r
471 tempbuf:array[0..receivebufsize-1] of byte;
\r
473 if (state =wslistening) and readtrigger then begin
\r
474 { debugout('listening socket triggered on read');}
\r
475 rmasterclr(fdhandlein);
\r
476 if assigned(onsessionAvailable) then onsessionAvailable(self,0);
\r
478 if udp and readtrigger then begin
\r
479 if assigned(ondataAvailable) then ondataAvailable(self,0);
\r
483 if (state =wsconnecting) and writetrigger then begin
\r
484 // code for dealing with the reults of a non-blocking connect is
\r
486 // if just write is triggered it means connect suceeded
\r
487 // if both read and write are suceededed it can mean 2 things
\r
488 // 1: connect ok and data availible
\r
490 // to find out which you must read from the socket and look for errors
\r
491 // there if we read successfully we drop through into the code for fireing
\r
493 if not readtrigger then begin
\r
494 state := wsconnected;
\r
495 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
497 numread := fdread(fdhandlein,tempbuf,sizeof(tempbuf));
\r
498 if numread <> -1 then begin
\r
499 state := wsconnected;
\r
500 if assigned(onsessionconnected) then onsessionconnected(self,0);
\r
501 //connectread := true;
\r
502 recvq.add(@tempbuf,numread);
\r
504 state := wsconnected;
\r
505 if assigned(onsessionconnected) then onsessionconnected(self,linuxerror);
\r
506 { debugout('connect fail');}
\r
507 self.internalclose(0);
\r
508 recvq.del(maxlongint);
\r
510 // if things went well here we are now in the state wsconnected with data sitting in our receive buffer
\r
511 // so we drop down into the processing for data availible
\r
513 if fdhandlein >= 0 then begin
\r
514 if state = wsconnected then begin
\r
515 rmasterset(fdhandlein);
\r
517 rmasterclr(fdhandlein);
\r
520 if fdhandleout >= 0 then begin
\r
521 if sendq.size = 0 then begin
\r
522 //don't clear the bit in fdswmaster if data is in the sendq
\r
523 wmasterclr(fdhandleout);
\r
528 inherited handlefdtrigger(readtrigger,writetrigger);
\r
531 constructor tlsocket.Create(AOwner: TComponent);
\r
533 inherited create(aowner);
\r
534 closehandles := true;
\r
538 function tlsocket.getpeername(var addr:tsockaddrin;addrlen:integer):integer;
\r
540 result := sockets.getpeername(self.fdhandlein,addr,addrlen);
\r
543 procedure tlsocket.getxaddrbin(var binip:tbinip);
\r
545 addr:tinetsockaddrv;
\r
549 fillchar(addr,sizeof(addr),0);
\r
550 sockets.getsocketname(self.fdhandlein,addr,i);
\r
552 binip.family := addr.inaddr.family;
\r
554 if addr.inaddr6.sin6_family = AF_INET6 then begin
\r
555 binip.ip6 := addr.inaddr6.sin6_addr;
\r
559 binip.ip := addr.inaddr.addr;
\r
561 converttov4(binip);
\r
564 procedure tlsocket.getpeeraddrbin(var binip:tbinip);
\r
566 addr:tinetsockaddrv;
\r
570 fillchar(addr,sizeof(addr),0);
\r
571 sockets.getpeername(self.fdhandlein,addr,i);
\r
573 binip.family := addr.inaddr.family;
\r
575 if addr.inaddr6.sin6_family = AF_INET6 then begin
\r
576 binip.ip6 := addr.inaddr6.sin6_addr;
\r
580 binip.ip := addr.inaddr.addr;
\r
582 converttov4(binip);
\r
585 function tlsocket.getXaddr:string;
\r
589 getxaddrbin(biniptemp);
\r
590 result := ipbintostr(biniptemp);
\r
591 if result = '' then result := 'error';
\r
594 function tlsocket.getpeeraddr:string;
\r
598 getpeeraddrbin(biniptemp);
\r
599 result := ipbintostr(biniptemp);
\r
600 if result = '' then result := 'error';
\r
603 function tlsocket.getXport:string;
\r
605 addr:tinetsockaddr;
\r
609 sockets.getsocketname(self.fdhandlein,addr,i);
\r
610 i := htons(addr.port);
\r
611 result := inttostr(i);
\r
614 function tlsocket.getpeerport:string;
\r
616 addr:tinetsockaddr;
\r
620 sockets.getpeername(self.fdhandlein,addr,i);
\r
621 i := htons(addr.port);
\r
622 result := inttostr(i);
\r