File: XSocket.cc

package info (click to toggle)
postman 2.0-9
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 8,036 kB
  • ctags: 3,078
  • sloc: cpp: 31,131; ansic: 1,948; sh: 787; makefile: 285
file content (541 lines) | stat: -rwxr-xr-x 15,116 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
/*
XSocket.cc
*/

#include "XSocket.h"

struct sigaction actx, oldactx;

XSocket::XSocket ()
  {
  wsock = INVALID_SOCKET;
  }
 
XSocket::XSocket (int awsock)
  {
  wsock = awsock;
  }
 
XSocket::~XSocket ()
  {
  }

int XSocket::getSock (void)
  {
  return wsock;
  }

void XSocket::SetSock (int sock)
  {
  wsock = sock;
  fsock = fdopen (wsock, "r+");
  }

void XSocket::Close ()
  {
  if (wsock != INVALID_SOCKET)
    {
    shutdown (wsock, 2);
    close    (wsock);
    wsock = INVALID_SOCKET;
    }
  }

/*
IF IS POSSIBLE, DO NOT USE. ADD 4 kb OF MEM FOR THE fgets
bool XSocket::Gets (char buf[], int  nbytes)
  {
  if (fgets (buf, nbytes, fsock) == NULL) return false; 
  else 
    {
    QuitaRetornoCarroDeLinea (buf);
    buf[strlen(buf)] = '\0';
    return true;
    }
  }
*/

bool XSocket::Gets (char buf[], int  nbytes)
  {
  int ret, i = 0;
  buf[0] = '\0';
  for(;;) 
    {
    if ((ret = read(wsock, &buf[i], 1) <= 0)) 
      {
      if ((ret == ERROR_SOCKET) && (errno == EINTR)) continue;
      return false;
      }
    if (buf[i] == '\r') continue;
    if (buf[i] == '\n') 
      {
      buf[i] = '\0';
      QuitaRetornoCarroDeLinea (buf);
      return true;
      }
    if (++i == nbytes) 
      {
      buf[nbytes] = '\0';
      QuitaRetornoCarroDeLinea (buf);
      return true;
      }
    }     
  }

void xsprocsignals (int signal_type)
  {
  switch (signal_type)
    {
    /* TIMEOUT. Alarm signal. */     
    case SIGALRM:              
      sigaction (SIGALRM, &oldactx, NULL);
      break;
    }
  }

/* Open a TCP connection. Return socket descriptor if OK, else ERROR_SOCKET on error*/
int XSocket::do_client_inet (char *host, char *service, int port, int timeout)
   /*
   char *host;    name or dotted-decimal addr of other system 
   char *service; name of service being requested, can be NULL, if port > 0 
   int  port;     if == 0, nothing special - use port# of service 
                  if < 0, bind a local reserved port 
                  if > 0, it's the port# of server (host-byte-order)
   */
  {
  struct sockaddr_in      srv_addr;
  xulong           inaddr;
  struct servent         *sp;
  struct hostent         *hp;
  int                     fd, res;

  /*Initialize the server's Internet address structure.
     We'll store the actual 4-byte Internet address and the
     2-byte port# below */

  memset((char *) &srv_addr, 0, sizeof(srv_addr));
  srv_addr.sin_family = AF_INET;

  if (service != NULL) 
    {
    if ((sp = getservbyname(service, "tcp")) == NULL) return(ERROR_SOCKET);
    if (port > 0) srv_addr.sin_port = htons(port);
    else srv_addr.sin_port = sp->s_port;
    } 
  else 
    {
    if (port <= 0) return(ERROR_SOCKET);
    srv_addr.sin_port = htons(port);
    }

  /*Try to convert the host name as a dotted-decimal number. If fails do we call gethostbyname().*/

  if ((inaddr = inet_addr(host)) != INADDR_BROADCAST) 
    {
    /* it's dotted-decimal */
    bcopy((char *) &inaddr, (char *) &srv_addr.sin_addr, sizeof(inaddr));
    } 
  else 
    {
    if ((hp = gethostbyname(host)) == NULL) return(ERROR_SOCKET);
    bcopy(hp->h_addr, (char *) &srv_addr.sin_addr, hp->h_length);
    }
  if (port >= 0) 
    {
    if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) return(ERROR_SOCKET);
    } 
  else if (port < 0) return(ERROR_SOCKET);

  sigemptyset(&actx.sa_mask); actx.sa_flags = 0; actx.sa_handler = xsprocsignals;
  sigaction (SIGALRM, &actx, &oldactx);      
  alarm (timeout);  
  res = connect(fd, (struct sockaddr *) &srv_addr, sizeof(srv_addr));
  sigaction (SIGALRM, &oldactx, NULL);
  
  if (res < 0) 
    {
    close(fd);
    return(ERROR_SOCKET);
    }
  return(fd); /* all OK */
  }
  
int XSocket::do_client_unix (char *filesocket)
  {
  struct sockaddr_un srv_addr;
  int sock;
  sock = socket(AF_UNIX, SOCK_STREAM, 0);
  if (sock < 0) {perror("socket"); return(ERROR_SOCKET);}
  srv_addr.sun_family = AF_UNIX;
  strncpy(srv_addr.sun_path, filesocket, sizeof(srv_addr.sun_path)-1);
  srv_addr.sun_path[sizeof(srv_addr.sun_path)-1] = '\0';
    
  if (connect (sock, (sockaddr *)&srv_addr, sizeof(srv_addr)) < 0) 
    {
    perror ("connect"); 
    perror (filesocket);
    return (ERROR_SOCKET);
    }
  return (sock);
  }  

int XSocket::Puts (const char *buf)
  {
  return (Write(buf, strlen(buf)));
  }

/* Return:
 *              val > 0         -> data available
 *              val == 0        -> no data available
 *              val == -1       -> error
 */
int XSocket::Read (char *buf, int nbytes)
  {
  int n;

  if ((n = read(wsock, buf, nbytes)) > 0)
    {
    return(n);
    }
  if ((n == ERROR_SOCKET) && (errno == EWOULDBLOCK))
    {
    return(0);
    }
  return(ERROR_SOCKET);
  }

int XSocket::Write (const char *buf, int nbytes)
  {
  int nleft, nwritten;
  nleft = nbytes;
  while(nleft > 0) 
    {
    if ((nwritten = write(wsock, buf, nleft)) == -1) 
      {
      if (errno == EWOULDBLOCK) continue;
      //Another error can be SIGPIPE (EPIPE, 32)
      else if (errno == EPIPE) return (ERROR_SOCKET_PIPE); 
      return(ERROR_SOCKET);
      }
    nleft -= nwritten;
    buf += nwritten;
    }
  return(nbytes);
  }

char *XSocket::Client_name (void)
  {
  socklen_t len;
  struct sockaddr_in sin;
  struct hostent *host, hostent;

  len = sizeof (sin);
  if (getpeername (wsock, (struct sockaddr *) &sin, &len) < 0)
    {
    return "";
    }
  else 
    {
    if ((host = gethostbyaddr ((char *) &sin.sin_addr, sizeof (struct in_addr), AF_INET)) == 0) 
      {
      host = &hostent;
      host->h_name = inet_ntoa (sin.sin_addr);
      return host->h_name;
      }
    else 
      {
      return host->h_name;
      }
    }
  }

/* Take a service name, and a service type, and return a port number.  If the
   service name is not found, it tries it as a decimal number.  The number
   returned is byte ordered for the network. */
int XSocket::atoport (char *service, char *proto)
  {
  int port;
  long int lport;
  struct servent *serv;
  char *errpos;

  serv = getservbyname(service, proto);
  if (serv != NULL) port = serv->s_port;
  else 
    {
    lport = strtol(service,&errpos,0);
    if ((errpos[0] != 0) || (lport < 1) || (lport > 65535)) {return ERROR_SOCKET;}
    port = htons((int)lport);
    }
  return port;
  }

/* This ignores the SIGPIPE signal.  This is usually a good idea, since
   the default behaviour is to terminate the application.  SIGPIPE is
   sent when you try to write to an unconnected socket.  You should
   check your return codes to make sure you catch this error! */
void XSocket::ignore_pipe(void)
  {
  struct sigaction sig;
  sig.sa_handler = SIG_IGN;
  sig.sa_flags = 0;
  sigemptyset(&sig.sa_mask);
  sigaction(SIGPIPE,&sig,NULL);
  }

/* This function listens on a port, and returns connections.  It forks
   returns off internally, so your main function doesn't have to worry
   about that.  This can be confusing if you don't know what is going on.
   The function will create a new process for every incoming connection,
   so in the listening process, it will never return.  Only when a connection
   comes in, and we create a new process for it will the function return.
   This means that your code that calls it should _not_ loop.

   The parameters are as follows:
     socket_type: SOCK_STREAM or SOCK_DGRAM (TCP or UDP sockets)
     port: The port to listen on.  Remember that ports < 1024 are
       reserved for the root user.  Must be passed in network byte
       order (see "man htons").
     listener: This is a pointer to a variable for holding the file
       descriptor of the socket which is being used to listen.  It
       is provided so that you can write a signal handler to close
       it in the event of program termination.  If you aren't interested,
       just pass NULL.  Note that all modern unixes will close file
       descriptors for you on exit, so this is not required. */
int XSocket::do_server_inet (int socket_type, u_short port, int *listener)
  {
  struct sockaddr_in address_inet;
  int listening_socket;
  int connected_socket = ERROR_SOCKET;
  int new_process;
  int reuse_addr = 1, res;

  /* Setup internet address information.This is used with the bind() call */
  memset((char *) &address_inet, 0, sizeof(address_inet));
  address_inet.sin_family = AF_INET;
  address_inet.sin_port = port;
  address_inet.sin_addr.s_addr = htonl(INADDR_ANY);    

  listening_socket = socket(AF_INET, socket_type, 0);
  if (listening_socket < 0) 
    {
    perror("socket");
    exit(EXIT_FAILURE);
    }

  if (listener != NULL) *listener = listening_socket;
  setsockopt(listening_socket, SOL_SOCKET, SO_REUSEADDR, &reuse_addr, sizeof(reuse_addr));
  
  res = bind(listening_socket, (struct sockaddr *) &address_inet, sizeof(address_inet));
    
  if (res < 0) 
    {
    perror("bind");
    close(listening_socket);
    exit(EXIT_FAILURE);
    }

  if (socket_type == SOCK_STREAM) 
    {
    listen(listening_socket, 5); /*Queue up to five connections before having them automatically rejected. */
    while(connected_socket < 0) 
      {
      connected_socket = accept(listening_socket, NULL, NULL);
      if (connected_socket < 0) 
        {
        /* Either a real error occured, or blocking was interrupted for
           some reason.  Only abort execution if a real error occured. */
        if (errno != EINTR) 
          {
          perror("accept");
          close(listening_socket);
          exit(EXIT_FAILURE);
          } 
        else 
          {
          continue;    /* don't fork - do the accept again */
          }
        }
      new_process = fork();
      if (new_process < 0) 
        {
        perror("fork");
        close(connected_socket);
        connected_socket = ERROR_SOCKET;
        }
      else 
        { /* We have a new process... */
        if (new_process == 0) 
          {
          /* This is the new process. */
          close(listening_socket); /* Close our copy of this socket */
          if (listener != NULL) *listener = -1; /* Closed in this process.  We are not responsible for it. */
          }
        else 
          {
          /* This is the main loop.Close copy of connected socket, and continue loop. */
          close(connected_socket);
          connected_socket = ERROR_SOCKET;
          }
        }
      }
    return connected_socket;
    }
  else
    {
    return listening_socket;
    }
  }

int XSocket::do_server_unix (int socket_type, int *listener)    
  {
  struct sockaddr_un address_unix;
  int listening_socket;
  int connected_socket = ERROR_SOCKET;
  int new_process;
  int reuse_addr = 1, res, socketsize;
  char fn[300];
  TBuffer tmpbuf;

  listening_socket = socket(AF_UNIX, socket_type, 0);
  if (listening_socket < 0) 
    {
    perror("socket");
    exit(EXIT_FAILURE);
    }
    
  if (listener != NULL) *listener = listening_socket;
  setsockopt(listening_socket, SOL_SOCKET, SO_REUSEADDR, &reuse_addr, sizeof(reuse_addr));    

  socketsize = SOCKETSIZE;
  setsockopt(listening_socket, SOL_SOCKET, SO_RCVBUF, &socketsize, sizeof(socketsize));
  setsockopt(listening_socket, SOL_SOCKET, SO_SNDBUF, &socketsize, sizeof(socketsize));

  strncpy (fn, make_root_socket(tmpbuf), 300 - 1);
  fn[300 - 1] = '\0';
  //if (FileExists (fn) == true) DeleteFile (fn);
  DeleteFile (fn);

  address_unix.sun_family = AF_UNIX;
  strncpy(address_unix.sun_path, fn, sizeof(address_unix.sun_path)-1);
  address_unix.sun_path[sizeof(address_unix.sun_path)-1] = '\0';
        
  res = bind(listening_socket, (sockaddr *)&address_unix, sizeof(address_unix));
  if (res < 0) {perror("bind"); close(listening_socket); exit(EXIT_FAILURE);}

  chmod (fn, S_IWOTH | S_IWGRP | S_IWUSR);
  if (socket_type == SOCK_STREAM) 
    {
    listen(listening_socket, 5); /*Queue up to five connections before having them automatically rejected. */
    while(connected_socket < 0) 
      {
      connected_socket = accept(listening_socket, NULL, NULL);
      if (connected_socket < 0) 
        {
        /* Either a real error occured, or blocking was interrupted for some reason.  Only abort execution if a real error occured. */
        if (errno != EINTR) 
          {
          perror("accept");
          close(listening_socket);
          return (ERROR_SOCKET);
          } 
        else 
          {
          continue;    /* don't fork - do the accept again */
          }
        }
      new_process = fork();
      if (new_process < 0) 
        {
        perror("fork");
        close(connected_socket);
        connected_socket = ERROR_SOCKET;
        }
      else 
        { /* We have a new process... */
        if (new_process == 0) 
          {
          /* This is the new process. */
          close(listening_socket); /* Close our copy of this socket */
          if (listener != NULL) *listener = -1; /* Closed in this process.  We are not responsible for it. */
          }
        else 
          {
          /* This is the main loop.Close copy of connected socket, and continue loop. */
          close(connected_socket);
          connected_socket = ERROR_SOCKET;
          }
        }
      }
    return connected_socket;
    }
  else
    {
    return listening_socket;
    }
  }

void XSocket::do_server_unix_only_bind (int socket_type, int *listener, char *fn)
  {
  struct sockaddr_un address_unix;
  int listening_socket;
  int reuse_addr = 1, res, socketsize;

  listening_socket = socket(AF_UNIX, socket_type, 0);
  if (listening_socket < 0) {perror("socket"); exit(EXIT_FAILURE);}
    
  if (listener != NULL) *listener = listening_socket;
  setsockopt(listening_socket, SOL_SOCKET, SO_REUSEADDR, &reuse_addr, sizeof(reuse_addr));    

  socketsize = SOCKETSIZE;
  setsockopt(listening_socket, SOL_SOCKET, SO_RCVBUF, &socketsize, sizeof(socketsize));
  setsockopt(listening_socket, SOL_SOCKET, SO_SNDBUF, &socketsize, sizeof(socketsize));

  if (FileExists (fn) == true) DeleteFile (fn);
  
  address_unix.sun_family = AF_UNIX;
  strncpy(address_unix.sun_path, fn, sizeof(address_unix.sun_path)-1);
  address_unix.sun_path[sizeof(address_unix.sun_path)-1] = '\0';
        
  res = bind(listening_socket, (sockaddr *)&address_unix, sizeof(address_unix));
  if (res < 0) {perror("bind"); close(listening_socket); exit(EXIT_FAILURE);}

  chmod (fn, S_IWOTH | S_IWGRP | S_IWUSR);

  if (socket_type == SOCK_STREAM) {listen(listening_socket, 5);}
  }
  

int XSocket::Send_TO (const char* buf, int TimeoutSeconds)
  {
  int BytesSent; 
  fd_set fd; 
  struct timeval tv; 

  FD_ZERO (&fd); 
  FD_SET (wsock, &fd); // adds sock to the file descriptor set 

  tv.tv_sec = TimeoutSeconds; 
  tv.tv_usec = 0; 
  
  if (0 == wsock) {return (0);} // Allready closed 

  // The return value is smaller than 'Size' when the Client breakes the operation down. 
  if (select (wsock + 1, NULL, &fd, NULL, &tv) == 0) 
    { 
    //UpdateSocket (Socket); 
    //Socket->m_LastFunction = "Send Timeout"; 
    return (0); 
    } 

  BytesSent = send (wsock, (char *) buf, strlen(buf), 0); 
  if (BytesSent == -1) 
    { 
    BytesSent = 0; 
    //UpdateSocket (Socket); 
    } 
  //Socket->m_LastFunction = "Send"; 
  return (BytesSent);   
  }