Skip to content

Commit

Permalink
Generate boundary by choosing a random character
Browse files Browse the repository at this point in the history
Instead of rejecting random characters that are not in the boundary
character set, draw a random index and select the character at that
position. The probability distribution is not perfectly uniform with
this method, but reduces the number of calls to rand() by 4 times on
average.
  • Loading branch information
rodarima committed Sep 9, 2024
1 parent 7ba398c commit 4c11d0e
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions src/form.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
* File: form.cc
*
* Copyright 2008 Jorge Arellano Cid <[email protected]>
* Copyright 2024 Rodrigo Arias Mallo <[email protected]>
*
* 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
Expand Down Expand Up @@ -1246,20 +1247,23 @@ Dstr *DilloHtmlForm::buildQueryData(DilloHtmlInput *active_submit)
return DataStr;
}

/**
* Generate a random boundary.
*
* Using 70 random characters makes the probability that it collides
* with a 1 TiB random file less than 1e-117, so there is no need for
* checking for collisions. */
static void generate_boundary(Dstr *boundary)
{
for (int i = 0; i < 70; i++) {
/* Extracted from RFC 2046, section 5.1.1. */
static const char set[] = "abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789";
char s[sizeof " "] = {0};
/* Extracted from RFC 2046, section 5.1.1. */
static const char set[] = "abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789";
static const size_t n = strlen(set);

do {
*s = rand();
} while (!strspn(s, set));

dStr_append(boundary, s);
for (int i = 0; i < 70; i++) {
int c = (unsigned char) set[rand() % n];
dStr_append_c(boundary, c);
}
}

Expand Down

0 comments on commit 4c11d0e

Please sign in to comment.