Skip to content

Commit c008006

Browse files
committed
fix: rework conversion algorithm to handle edge cases
1 parent a4b3f0e commit c008006

File tree

2 files changed

+37
-12
lines changed

2 files changed

+37
-12
lines changed

agent/php_nrini.c

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -241,24 +241,35 @@ char* nr_ini_to_env(const char* ini_name) {
241241
}
242242

243243
// algorithm:
244-
// 1. uppercase string
245-
// 2. copy the entire string after 'newrelic.'
246-
// 3. iterate through new string and swap each '.' with '_'
247-
// 4. snprintf append the string to 'NEW_RELIC_'
248-
// 5. return result
244+
// 1. uppercase ini string
245+
// 2. iterate through uppercase ini string and copy each character to the new
246+
// buffer, swapping each '.' with '_'.
247+
// 3. snprintf append the string to 'NEW_RELIC'
248+
// 4. return result
249249

250250
ini_upper = nr_string_to_uppercase(ini_name);
251251

252-
buf = (char*)nr_malloc(ini_len - NR_INI_PREFIX_LEN + 1);
253-
nr_strcpy(buf, ini_upper + NR_INI_PREFIX_LEN);
254-
255-
for (int i = 0; i < nr_strlen(buf); i++) {
256-
if (buf[i] == '.') {
257-
buf[i] = '_';
252+
buf = (char*)nr_zalloc(ini_len - NR_INI_PREFIX_LEN + 1);
253+
254+
for (int i = NR_INI_PREFIX_LEN, j = 0; i < nr_strlen(ini_upper); i++) {
255+
if (NR_INI_PREFIX_LEN == i
256+
&& ('.' == ini_upper[i] || '_' == ini_upper[i])) {
257+
// skip if the first character is '.' or '_' to avoid double underscores
258+
continue;
259+
} else if ('_' == ini_upper[i] && '_' == ini_upper[i - 1]) {
260+
// skip double '_' characters
261+
continue;
262+
} else if ('.' == ini_upper[i] && '_' != ini_upper[i - 1]) {
263+
// replace a '.' with '_', provided the previous character is not also '_'
264+
buf[j] = '_';
265+
} else {
266+
// copy the character
267+
buf[j] = ini_upper[i];
258268
}
269+
j++;
259270
}
260271

261-
env_name = (char*)nr_malloc(ini_len + 2);
272+
env_name = (char*)nr_zalloc(ini_len + 2);
262273

263274
snprintf(env_name, ini_len + 2, "%s_%s", "NEW_RELIC", buf);
264275

agent/tests/test_php_nrini.c

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,20 @@ static void test_nr_ini_to_env(void) {
5151
tlib_pass_if_null("reject null values", res);
5252

5353
nr_free(res);
54+
55+
res = nr_ini_to_env("newrelic.ini__value");
56+
57+
tlib_pass_if_str_equal("double underscores handled correctly",
58+
"NEW_RELIC_INI_VALUE", res);
59+
60+
nr_free(res);
61+
62+
res = nr_ini_to_env("newrelic._option_");
63+
64+
tlib_pass_if_str_equal("dot and underscores handled correctly",
65+
"NEW_RELIC_OPTION_", res);
66+
67+
nr_free(res);
5468
}
5569

5670
tlib_parallel_info_t parallel_info

0 commit comments

Comments
 (0)