T.P.
T.P.

Reputation: 2995

Proper way to pass C FILE pointer to curl_easy_setopt function

I am creating an SMTP client program in C on RHEL 4 Linux based on the sample program at:

http://curl.haxx.se/libcurl/c/simplesmtp.html

Whenever I pass the message body text to the program through stdin, the program works correctly. However, I experience a segfault when I try to pass a FILE pointer to the curl_easy_setopt() function. The comments (from the sample program simplesmtp.c) state that it is possible to pass a file pointer instead of stdin to the curl_easy_setopt function.

Relevant comment section from simplesmtp.c

/* You provide the payload (headers and the body of the message) as the
 * "data" element. There are two choices, either:
 * - provide a callback function and specify the function name using the
 * CURLOPT_READFUNCTION option; or
 * - just provide a FILE pointer that can be used to read the data from.
 * The easiest case is just to read from standard input, (which is available
 * as a FILE pointer) as shown here.
 */ 
curl_easy_setopt(curl, CURLOPT_READDATA, stdin);

These are the error lines from the console with the CURLOPT_VERBOSE option set.

< 250 2.1.5 <[email protected]>... Recipient ok
> DATA
< 354 Enter mail, end with "." on a line by itself
./r: line 5: 21282 Segmentation fault      ./mysmtpcli -r rcp.txt -m msg.txt

BTW: ./r is my shell script which is calling ./mysmtpcli -r rcp.txt -m msg.txt

My Snippet of Code

FILE *f_msg;
f_msg = fopen(msg_file, "r");
if(!f_msg){
  fprintf(stderr, "Could not load message file: %s\n", msg_file);
  return 1;
}

curl_easy_setopt(curl, CURLOPT_READDATA, f_msg);

fclose(f_msg);

Note: The msg_file variable is populated from the command line parameters and is a valid text file containing:

Subject: Test Message

This is a test message!

When this same file is passed to the program via stdin using "cat msg.txt | ./mysmtpcli -r rcp.txt", the program executes properly. Though, this requires replacing f_msg with stdin.

curl_easy_setopt(curl, CURLOPT_READDATA, f_msg);

Am I passing the FILE pointer correctly?

Upvotes: 1

Views: 1960

Answers (1)

user405725
user405725

Reputation:

Yes, you do pass a file pointer correctly. Though it seems like you close it right away. If you do that, curl will later try to read from that file and crash. You have to close it only when it is not needed anymore.

Upvotes: 1

Related Questions