星期五, 1月 16, 2009

RFC

讀書會發起


Reference:

星期三, 1月 14, 2009

CGI download file

HTML:
<form action="http://192.168.1.1/cgi-bin/test.cgi"
enctype="multipart/form-data" method="post">
<p>
Type some text (if you like):<br>
<input type="text" name="textline" size="30">
</p>
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<div>
<input type="submit" value="Send">
</div>
</form>



C: 再送檔前會有 0x0D 0x0A 這些要處理掉,尾巴也會有,而且還帶bondary "-------" n個不等,這些用 fget 會有問題,檔內有 0x0 也會造成問題,取檔前可用fget抓,取檔時改用read 開始取檔。

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



#define DATAFILE "/data/data.txt"
#define DEFSIZE 256

int main(void){
char *lenstr;
long len;
int ret;
char buf[ DEFSIZE ];

printf("%s%c%c\n","Content-Type:text/html;charset=iso-8859-1",13,10);
printf("<TITLE>Response</TITLE>\n");
lenstr = getenv("CONTENT_LENGTH");

if(lenstr == NULL || sscanf(lenstr,"%ld",&len)!=1 )
printf("<P>Error in invocation - wrong FORM probably.%d", len);
else{

FILE *wfd;
char *retstr, *bufptr, delim[5]={ 0x0d, 0x0a, 0x2d, 0x2d, 0x0 };
int lastsize;


wfd = fopen( DATAFILE, "w+");
do{
if( (retstr = fgets( buf, DEFSIZE, stdin) ) == NULL ) return -1;
if( strstr( buf, "Content-Type" ) != NULL ) break;
}while( 1 );
fgets( buf, 2, stdin); // 0x0d
fgets( buf, 2, stdin); // 0x0a
do{
ret = fread( buf, 1, DEFSIZE, stdin);
if( ret > 0 ){
if( ret != DEFSIZE ){
retstr = strstr( buf, delim);
bufptr = buf;
lastsize = retstr - bufptr;
printf("write last size=%d %s\n", lastsize, retstr);
fwrite( buf, 1, lastsize, wfd );
}
else{
printf("writee=%d\n", ret );
fwrite( buf, 1, ret, wfd );
}
}
else printf("stdin error ret=%d len=%d\n", ret, len );

}while( ret == DEFSIZE);

fclose( wfd );
printf("<P>Thank you! Your contribution has been stored. total len=%d", len);
}
return 0;
}




Reference: