fortune: avoid buffer overflow for lines >= 2K, make sure index has at least one entry, use nrand()/ntruerand() for uniform distribution

This commit is contained in:
cinap_lenrek 2017-03-19 22:04:26 +01:00
parent da9b38c75c
commit c220100005

View file

@ -35,7 +35,7 @@ main(int argc, char *argv[])
print("Misfortune?\n"); print("Misfortune?\n");
exits("misfortune"); exits("misfortune");
} }
if(ixbuf->length == 0){ if(ixbuf->length < sizeof(offs)){
/* someone else is rewriting the index */ /* someone else is rewriting the index */
goto NoIndex; goto NoIndex;
} }
@ -56,13 +56,13 @@ main(int argc, char *argv[])
} }
} }
if(oldindex){ if(oldindex){
seek(ix, truerand()%(ixbuf->length/sizeof(offs))*sizeof(offs), 0); seek(ix, ntruerand(ixbuf->length/sizeof(offs))*sizeof(offs), 0);
read(ix, off, sizeof(off)); read(ix, off, sizeof(off));
Bseek(f, off[0]|(off[1]<<8)|(off[2]<<16)|(off[3]<<24), 0); Bseek(f, off[0]|(off[1]<<8)|(off[2]<<16)|(off[3]<<24), 0);
p = Brdline(f, '\n'); p = Brdline(f, '\n');
if(p){ if(p){
p[Blinelen(f)-1] = 0; p[Blinelen(f)-1] = 0;
strcpy(choice, p); strncpy(choice, p, sizeof(choice)-1);
}else }else
strcpy(choice, "Misfortune!"); strcpy(choice, "Misfortune!");
}else{ }else{
@ -83,8 +83,8 @@ NoIndex:
off[3] = offs>>24; off[3] = offs>>24;
Bwrite(&g, off, sizeof(off)); Bwrite(&g, off, sizeof(off));
} }
if(lrand()%i==0) if(nrand(i)==0)
strcpy(choice, p); strncpy(choice, p, sizeof(choice)-1);
} }
} }
print("%s\n", choice); print("%s\n", choice);