
/* WPsServer.c */

/*  A server for remote versions of the w and ps 
    commands.

    User can check load on machine without logging 
    in (or even without being able to log in).   
*/


/* these are needed for socket calls */
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>


/* this is needed for the disk read */
#include <fcntl.h>


#define WPSPORT 2088  /* server port number */
#define BUFSIZE 1000


int ClntDescriptor,  /* socket descriptor to client */
    SrvrDescriptor;  /* socket descriptor for server */


char InBuf[BUFSIZE],  /* messages from client */
     OutBuf[BUFSIZE];  /* messages to client */


Write()

{  int FD,NB;

   FD = open("tmp.client",O_RDONLY);
   NB = read(FD,OutBuf,BUFSIZE);
   write(ClntDescriptor,OutBuf,NB);
   unlink("tmp.client");
}


Respond()

{  memset(OutBuf,0,sizeof(OutBuf));  /* clear buffer */
   if (!strcmp(InBuf,"w"))  
      system("w > tmp.client");
   else if (!strcmp(InBuf,"ps")) 
      system("ps -ax > tmp.client");
   else 
      system("echo 'invalid command' > tmp.client");
   Write();
}


main(int argc, char **argv)

{  struct sockaddr_in BindInfo;

   /* create an Internet TCP socket */
   SrvrDescriptor = socket(AF_INET,SOCK_STREAM,0);

   /* bind it to port 2000 (> 1023, to avoid the 
      "well-known ports"), allowing connections from 
      any NIC */
   BindInfo.sin_family = AF_INET;
   BindInfo.sin_port = WPSPORT;
   BindInfo.sin_addr.s_addr = INADDR_ANY;
   bind(SrvrDescriptor,(sockaddr *) &BindInfo,sizeof(BindInfo));

   /* OK, listen in loop for client calls */
   listen(SrvrDescriptor,5); 
   
   while (1)  {
      /* wait for a call */
      ClntDescriptor = accept(SrvrDescriptor,0,0);
      /* read client command */
      memset(InBuf,0,sizeof(InBuf));  
      read(ClntDescriptor,InBuf,sizeof(InBuf)); 
      /* process the command */
      Respond();
   }
}

      

