Monday, August 13, 2012

Non Blocking Connect with Timeout

Connect is blocking
 If there is no response  retries will be done on interval which keeps increasing for minutes .
If we need to return quicker connect should be done as nonblocking and time can be set for how long wait for SYN ACK from Server.


fd_set fdset;
struct timeval tv;
int flags ;
  //NON blocking
    if ((flags = fcntl(sock, F_GETFL))<0 br="br">    {
       printf("fcntl get FL failed\n");
       return -1;
    }
    if( fcntl(sock, F_SETFL, O_NONBLOCK)<0 br="br">    {   printf("fcntl get FL failed\n");
       return -1;
    }
 if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
        {

          if (errno != EINPROGRESS)
           {
             perror("connect() failed");
             exit(0);
           }
        }
        printf("non blockinng connect() passed \n");

  FD_ZERO(&fdset);
  FD_SET(sock, &fdset);
  tv.tv_sec = 3;
  tv.tv_usec = 0;

   if (select(sock + 1, NULL, &fdset, NULL, &tv) == 1)
   {
      int so_error;
      socklen_t len = sizeof so_error;
      getsockopt(sock, SOL_SOCKET, SO_ERROR, &so_error, &len);
      if (so_error == 0)
      {
         printf("  CONNECTION ESTABLISHED\n");
         fflush(NULL);
      }
      else
      {
          printf("  CONNECTION FAILED\n");
           return-1;
      }
   }
   else
   {
      printf(" CONNECTION  TIMEOUT\n");
      fflush(NULL);
      return-1;
   }

Thursday, March 8, 2012

Traceroute

Q) How TraceRoute  works
 It works on the principle of TTL.Router decrements TTL while processing and if TTL is zero it drops the Packet and sends ICMP Error Time Exceeded Mesage back to source HOST. In the ICMP Reply Message source IP is of Router which drops the packet.
Now host which runs Trace route leverage out of this property. It sends packet with destination addr of remote host and TTL =1. In reply it know IP of first HOP(router) it saves the IP and details and send next Packet with TTL 2 and  keep incrementing TTL until it reaches Remote host .
every router in path must have respinded to source host and We got list of all HOPS on ROUTE.

Q)What kind of message are send in  traceroute?How can we determine when we've reached the destination?
In windows :
 It sends  ICMP echo Request with incrementing TTLs .ICMP Error TIme Exceeded signifies intermediate
 and ICMP echo reply signifies Host is reached
 In Unix like OS
Traceroute sends UDP datagrams to the destination host, but it chooses the destination UDP port number to be an unlikely value (larger than 30,000),
 making it improbable that an application at the destination is using that port.
 This causes the destination host's UDP module to generate an ICMP "port unreachable" error
 when the datagram arrives.  Traceroute  differentiate between the received ICMP messages—time exceeded versus port unreachable—to know when it's done.

Q Why cant we use IP record route option (RR). instead of Trace Route?
Ans:
  1. Not all routers have supported the record route option.
  2. The room allocated for options in the IP header isn't large enough today to handle most routes. There is room for only nine IP addresses in the IP header options field. In Today's world its not enough

Monday, March 5, 2012

IPC -What to use When??

IPC:
  1. Sockets BSD
  2. PIPE
  3. Named PIPE (FIFO)
  4. Signals
SYSTEM V IPC
  1.  Message  Queue
  2. Shared Memory
  3.  Semaphore
--------------------------------------------------------------------------------------------------------
PIPE v/s NAMED PIPE

PIPE
  • Used in related process which must have common ancestry .
  • These are not permanent. If creator process terminates pipe also goes off.
  • Half duplex Data flows in only one direction. 
  • Reading from a pipe whose write end is closed returns 0 indicating EOF
  • Writing on a PIPE whose read end  is closed generates signal SIGPIPE

Named pipe(FIFO) : FIFO is a special file whose semantics differ significantly from those of a regular file
  • Can be used between unrelated Process. Either of them or any other (command mknod) can create FIFO.
  • These are Permanent Need to be Removed Explicitly
  • Treated  just as file have size owner access permissions Can be opended closed or deleted like any other file.
  • Bytes written to a FIFO are always written as though they were written in append mode.
  • Bytes read from a FIFO are always read from the beginning of the file and then removed.  
  • When all processes which have the FIFO open close the FIFO, any bytes remaining in the FIFO are removed.
  • Writing to a FIFO which no process has open for reading results in an error condition.
  • SIGPIPE is generated when writer writes to a FIFO on which either reader is died or have closed reading file descriptor. if reader is not at all created  then by default  open()  fifo=open("fifo_writer",O_WRONLY); call will block. When reader comes writer open() unblocks and writes successfully. Now after reading if reader goes away or just closes reading fd SIGPIPE will be generated.
  • If open is NON_Blocking  fifo=open("fifo_writer",O_WRONLY| O_NONBLOCK);  then even though pipe exists and Reader is not there open will return error -1 No such device or address
On Prompt it can be created by command mknod
mknod ( FIFO_NAME, S_IFIFO | 0666, 0);    0 is the device no.  ignored .
mkfifio(name , permission ) is better

----------------------------------------------------------------------------------------------------------
 System V IPCs :   Message Queue  ,Semaphore, Shared Memory :
 Creation(msgget,semget,shmget) requires  key of type Key_t (long integer defined in sys/types.h). Key is converted in identifier by kernel

 How  to share key between unrelated Processes:
  1.   Key can be created by one process using IPC_PRIVATE and written in file (disk operation is required )
  2.    Key can be put in Header file
  3.    ftok() to generate key based on two arguments passed path name and project UNIQUE ID(any no between 0 -255)
  Each ipc will have associated struct ipc_perm wich can be changed by semctl,msgctl,shmctl functions.
  SYSTEM V IPC are system wide  do not have any refrence count
  They remain in SYSTEM untill they are deleted explixitly (Pipe are deleted as soon as the Last process refrencing Pipe terminates )
  IPC structures are not known as name in file system cant use ls,shmod.rm command on that.
  ipcs ipcrm are created to tdo these operation.
  Dont use File descriptor I/O multiplexing is not possible cant use poll() select().


Shared Memory :
  • Shared Memory is fastest form of IPC. As there is no copy of data form sender to receiver. after shmat  at different process. individudal Virtual pages maps to same physical page from RAM. And it can be accessed as any other buffer.
  • Can be used between any Processes and random access is allowed.
  • In shared memory data has to be deleted explicitly
  • Reader has to be notified for the data.

Why is shared memory the fastest form of IPC?
 Once the memory is mapped into the address space of the processes that are sharing
 the memory region, processes do not execute any system calls into
 the kernel in passing data between processes, which would otherwise be required.
 Shared memory lets two or more processes share a region of memory.
 The processes must, of course, coordinate and synchronize (using Semaphore )their use of the shared memory between themselves to prevent data loss.

Accesses to the shared memory region have to be mutually exclusive; this is achieved via the use of the semaphore

 Generally Shared Memory can be used in three ways to
 mmap ,PoSIX(shm_open, mmap) and System V IPC(shm_get,shmat())

Message Queues: 
  1. The primary difference between a System V message queue and a socket or named pipe is that message queues may have multiple processes reading and writing from and to them, or no readers at all. 
  2. Allows prioritizing of messages.
  3.  Message queues have a size limit and a surprisingly small one.  16K for Linux and 4k for Solaris. 
  4. Individual messages have size limits.  8K for Linux and 2K for Solaris.
  5. Usually faster than pipes
  6. Difference from Shared Memory:   In Message queue Message passed is deleted as soon as its read by Reader . In shared memory data has to be deleted explicitly 


Some Questions :

Q Can many apps listen to same Msg Queue ? Can many app post to came queue ?
Answer:    Many Application can listen on same Msg Queue for their corresponding Message TYPE. Message is removed once listening app reads message to its type.
Yes multiple APP can write also.
Q What to use for two way Communication for two APPS?
Socket has to be used in this case . not possible on Message queue

Digital Signature

What is digital Signature?
A digital signature scheme typically consists of three algorithms:
  • A key generation algorithm that selects a private key uniformly at random from a set of possible private keys. The algorithm outputs the private key and a corresponding public key.
  • A signing algorithm that, given a message and a private key, produces a signature.
  • A signature verifying algorithm that, given a message, public key and a signature, either accepts or rejects the message's claim to authenticity.

When is public / private key pair are used?
Answer  : used in two ways
1 Public key encryption :
message encrypted with a recipient's public key cannot be decrypted by anyone except a possessor of the matching private key. Used for Confidentiality
Asymmetric key algorithms : uses different(but Mathematically Related ) keys for Encryption and Decryption
Public encryption Key  and Private Decryption key
2  Digital Signature: message signed with a sender's private key can be verified by anyone who has access to the sender's public key. Used to check for Authenticity  of Message

What is EAP protocol Packet content?
What is PKI?

TCP IP

1Tell the scenarios in tcp connection establishmnet in which server doesnt reply.What all kind of errors can heppen

2 When is RESET used in TCP.
Ans:
1) When connection request (SYN )arrives and no process is listening on the destination port.
This is Hard Error ECONNRFUSED is returned to client as soon as RST is  reccieved
(In UDP  ICMP port unreachable  error will be sent to host)
2) In  TCP half-open connection (in a established connection if server reboots)If clients sedns data based on Preboot connection Server responds with RST
3) Receipt of any TCP segment from any device with which the device receiving the segment does not currently have a connection (other than a SYN requesting a new connection.)
4)  Receipt of a message with an invalid or incorrect Sequence Number or Acknowledgment Number field, indicating the message may belong to a prior connection or is spurious in some other way.

example: The client's host has crashed and rebooted. Here the server will receive a response
 to its keepalive probe, but the response will be a reset, causing the server to terminate the connection
sockets API provides this capability by using the "linger on close" socket option
This causes the abort to be sent when the connection is closed, instead of the normal FIN.
--RST segment elicits no response from the other end— it is not acknowledged at all.

Q) What is Linger on option in Socket?
Answer :The effect of an setsockopt(..., SO_LINGER,...) depends on what the values in the linger structure (the third parameter passed to setsockopt()) are:
Case 1:  linger->l_onoff is zero (linger->l_linger has no meaning):
            This is the default.
On close(), the underlying stack attempts to gracefully shutdown the connection after ensuring all unsent data is sent. In the case of connection-oriented protocols such as TCP, the stack also ensures that sent data is acknowledged by the peer.  The stack will perform the above-mentioned graceful shutdown in the background (after the call to close() returns), regardless of whether the socket is blocking or non-blocking.
Case 2: linger->l_onoff is non-zero and linger->l_linger is zero:
A close() returns immediately. The underlying stack discards any unsent data, and, in the case of connection-oriented protocols such as TCP, sends a RST (reset) to the peer (this is termed a hard or abortive close). All subsequent attempts by the peer's application to read()/recv() data will result in an ECONNRESET.
Case 3: linger->l_onoff is non-zero and linger->l_linger is non-zero:
A close() will either block (if a blocking socket) or fail with EWOULDBLOCK (if non-blocking) until a graceful shutdown completes or the time specified in linger->l_linger elapses (time-out). Upon time-out the stack behaves as in case 2 above.

Friday, February 17, 2012

Mutex

If a thread takes Mutex and dies.What happens to that mutex can take other take it ?

Threads

How to create Thread safe Function?
What is thread specific Data?
how to kill all threads spawned in Process.