Solved

atoi(getenv())

Posted on 1998-10-14
16
1,511 Views
Last Modified: 2013-12-25
In my cgi program (written in C) for the guestbook of my homepage, several lines of codes are listed below:

   :
  printf("Content-type: text/html%c%c",10,10);  
  len=atoi(getenv("CONTENT_LENGTH"));  
   for(i=0; len && (!feof(stdin)); i++) {
                m=i;
                inputs[i].val=ReadStdin(stdin,'&',&len);
                AddToSpace(inputs[i].val);
                Convert(inputs[i].val);
                inputs[i].name=ReadData(inputs[i].val,'=');
        }                                                           :
When I try to run it, segmentation fault exists. I notice that it is the problem of the line:
  len=atoi(getenv("CONTENT_LENGTH"));  
but I don't know how to correct it. Can anyone help?
0
Comment
Question by:onki
  • 6
  • 5
  • 2
  • +2
16 Comments
 
LVL 10

Expert Comment

by:rbr
Comment Utility
Try
char *emv;

env=getenv("CONTENT_LENGTH");
if (env) {
    len=atoi(env);
} else {
    len=0;
    fprintf(stderr;"CONTENT_LENGTH not found");
}

Are you sure that CONTENT_LENGTH is set correctly?
0
 

Author Comment

by:onki
Comment Utility
How to set the CONTENT_LENGTH?

p.s. your code doesn't work.
0
 
LVL 11

Expert Comment

by:mouatts
Comment Utility
You problem is that CONTENT_LENGTH isn't present and thus getenv returns NULL which is invalid as an arguement to atoi.

The reason that CONTENT_LENGTH is missing is because I would imagine the CGI was called via a GET which when used places the name value pairs in QUERY_STRING rather than via stdin and does not set the CONTENT_LENGTH.

To determine whether POST or GET was used you should check the environment variable REQUEST_METHOD.

rbrs code is correct except for the typo in the definition of env although I would use a different variable name as some compilers supply a function called env().

Steve
0
 

Author Comment

by:onki
Comment Utility
For my cgi program, I used
<FORM METHOD="POST" ACTION="/cgi-bin/guestmsg.cgi">  
but not "GET" as you said.
0
 
LVL 11

Expert Comment

by:mouatts
Comment Utility
According to the HTTP spec there are circumstances where browsers are known to wrongly change POSTS to GETS. Whilst you haven't said anything that implies that this is the case here it may be just as well to trap GET as well.

That aside can you post the rest of the code as it would seem that the problem is elsewhere. In particular I would be interested to see the variable definition.

In addition what Web Server is involved and what platform?
0
 
LVL 8

Expert Comment

by:MaDdUCK
Comment Utility
interesting...
0
 

Author Comment

by:onki
Comment Utility
/* below are the codes of my cgi program */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

typedef struct {
        char *name;
        char *val;
}input;

char *ReadStdin(FILE *f, char stop, int *len);
void AddToSpace(char *str);
void Convert(char *url);
char *ReadData(char *line, char stop);

main(int argc, char *argv[])
{
        char *env;
        input inputs[10000];
        register int i, m=0;
        int len;
        time_t Ourtime;
        FILE *fp, *fopen();
        fp=fopen("/Guest/guestbook.htm","a");

        printf("Content-type: text/html%c%c",10,10);
      *env=getenv("CONTENT_LENGTH");
      if(*env) len=atoi(env);
      else {
              len=0;
              fprintf(stderr,"CONTENT_LENGTH not found\n");
      }
        for(i=0; len && (!feof(stdin)); i++) {
                m=i;
                inputs[i].val=ReadStdin(stdin,'&',&len);
                AddToSpace(inputs[i].val);
                Convert(inputs[i].val);
                inputs[i].name=ReadData(inputs[i].val,'=');
        }
        printf("<H1>Thank you for you opinion, %s! </H1>", inputs[0].val);
      printf("<H3>your e-mail is %s! </H3>", inputs[1].val);
        printf("<H3>your opinion is %s! </H3>", inputs[2].val);
        fputs("\n<p>name: ", fp);
        fputs(inputs[0].val,fp);
        fputs(",email: ", fp);
        fputs(inputs[1].val, fp);
        fputs(", opinion:", fp);
        fputs(inputs[2].val, fp);

        fclose(fp);
}
0
 
LVL 1

Expert Comment

by:wisdom042597
Comment Utility
Take a look at this URL:
  http://www.icorp.net/wdg/

This lists a complete C-based guestbook (with source) that I wrote for the book, "HTML & CGI Unleashed" which uses the NCSA library code which is also on the site.  The actual link to test-run the script is outdated but the code definitely works.
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 11

Expert Comment

by:mouatts
Comment Utility
Youe problem is here

*env=getenv("CONTENT_LENGTH");
if(*env) len=atoi(env);

this should read

env=getenv("CONTENT_LENGTH");
if(env) len=atoi(env);

Steve
0
 
LVL 8

Expert Comment

by:MaDdUCK
Comment Utility
that's right...how could that slip by me...damn pointers :-)
0
 

Author Comment

by:onki
Comment Utility
Segmentation fault is not caused by those two lines of code. Segmentation fault exists after the if-then condition.
0
 
LVL 10

Expert Comment

by:rbr
Comment Utility
Can you post the code of ReadStdin pls.
0
 
LVL 11

Expert Comment

by:mouatts
Comment Utility
Yes because you have stored the returned value from getenv at the address contained in env which at this point in time is unitialised. The chances are that it has stored the value at some abstract taken from the stack or 0.

When you the subsequently access env to obtain its length the function will search through the 'string' until it finds a null character. But as the string is not being addressed it will plough on until it happens upon a null or it generates a segment fault.

If you are really unlucky the actual problem may not even manifest itself within an access to env as the action of storing a value at an arbitary address can damage other structures within a program (I don't mean C structures here) such as the stack which can cause returns to the wrong place.

Try my solution and see if the problem disappears or at least changes. Whilst I can't be certain that there aren't some other problems with you program I would be willing to gamble more than you could afford that the two lines I mentioned are wrong.

Steve
0
 

Author Comment

by:onki
Comment Utility
I have tried your answer. However, segmentation fault still exists after printing the warning
        "CONTENT_LENGHT does not find"
I know that the CONTENT_LENGTH is NULL and so the warning is printed out. But my question is how to set the CONTENT_LENGTH correctly so that it is not NULL any more. (Since I input something  to the form, the CONTENT_LEHGTH should not be NULL.)
0
 
LVL 11

Accepted Solution

by:
mouatts earned 50 total points
Comment Utility
Well that wasn't your original question but the answer is you can't set the CONTENT_LENGTH. This is set by the Web Server based on the data it recieves when the form is posted. So this means that your server isn't working correctly. (I tend to think that this is not the case).

Given that you were complaining that the seg fault was occuring on  the if(env) line and now the error message is being displayed which is on a later line then things have changed as I predicted in my previous answer and you are now dealing with a different problem.

Three things that you can try. First trun on all the warnings that you compiler will allow. Currently you either have no warnings turned on, are ignoring them or your compiler is very old.

Change the line

    FILE *fp, *fopen();

To
   FILE *fp;

As you have already included stdio.h which provides the deffinition of fopen (and your compiler should have warned you)

Change the definition of
    input inputs[10000];
to
   input inputs[1000];

As the amount of room being created on the stack may be too much depending on platform and compiler

Steve


0
 

Author Comment

by:onki
Comment Utility
Actually, the segmentation fault still exists on the line
   for((i=0; len && (!feof(stdin)); i++)
  after I have tried your answer, since the value of len is NULL.
Anyway, I don't want to argue with you anymore on  whether my original question is the question I asked. I give the marks to you now.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

The following is a collection of cases for strange behaviour when using advanced techniques in DOS batch files. You should have some basic experience in batch "programming", as I'm assuming some knowledge and not further explain the basics. For some…
Making a simple AJAX shopping cart Couple years ago I made my first shopping cart, I used iframe and JavaScript, it was very good at that time, there were no sessions or AJAX, I used cookies on clients machine. Today we have more advanced techno…
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now