/* John Pfeiffer, 04jan08 safely copy up to 512 parameters of up to 512 bytes passed from commandline to an array (preventing buffer overflow)
*/
#include <stdio.h>
#include <string.h>
#define LINE_BUFFER_MAX 512
#define CMDLINE_PARAMETERS 2
void safe_parameters( int argc, char* argv[], int parameter_size_max, char safe_argv[512][512] )
{
int i=0, k=0;
for(i=0; i<argc; i++)
{
while( (k < 512) && (argv[0][i] != '\0') )
{
safe_argv[i][k] = argv[i][k];
k++;
}
safe_argv[i][k] = '\0'; /* we must always terminate a string! */
k=0;
printf("\nsafe_argv[%d]=%s\n",i,safe_argv[i]);
}
/* PROOF THAT EACH STRING IS NULL TERMINATED
printf("%c=%d",argv[0][21],argv[0][21]);
if( argv[0][21] == '\0' )
{ printf("\nsuccess end of string\n\n"); }
*/
}
/* the function below could suffer from buffer overflow (e.g. renamed exe, it should use safe_argv instead
void test_commandline_parameters( int argc, char* argv[] )
{ int i = 0;
if( (argc < CMDLINE_PARAMETERS) || (argc > CMDLINE_PARAMETERS) )
{ printf("\nCorrect usage is:\n");
printf("%s inputfile",argv[0]);
exit(1);
}
else
{ while( i < argc )
{ printf("%s ", argv[i]);
i++;
}
printf("in progress...\n\n");
}
}
*/
void test_commandline_parameters( int argc, char safe_argv[512][512] )
{ int i = 0;
printf("\n\n TESTING COMMANDLINE PARAMETERS... \n");
if( (argc < CMDLINE_PARAMETERS) || (argc > CMDLINE_PARAMETERS) )
{ printf("\nCorrect usage is:\n");
printf("%s inputfile",safe_argv[0]);
exit(1);
}
else
{ while( i < argc )
{ printf("%s ", safe_argv[i]);
i++;
}
printf("in progress...\n\n");
}
}
/* MAIN ------------------------------------------------------- */
int main(int argc, char* argv[])
{
/* char buffer[LINE_BUFFER_MAX]; */
char safe_argv[512][512];
safe_parameters(argc, argv, 512, safe_argv); /* each parameter up to 512 chars */
test_commandline_parameters( argc, safe_argv );
return 0;
}/* end main */