Using sysctl(3) to write safe, portable code: good idea?

307 views Asked by At

When writing safe code in straight C, I'm sick and tired of coming up with arbitrary numbers to represent limitations -- specifically, the maximum amount of memory to allocate for a single line of text. I know I can always say stuff like

#define MAX_LINE_LENGTH 1024

and then pass that macro to functions such as snprintf().

I work and code in NetBSD, which has a sysctl(3) variable called "user.line_max" designed for this very purpose. So I don't need to come up with an arbitrary number like MAX_LINE_LENGTH, above. I just read the "user.line_max" sysctl variable, which by the way is settable by the user.

My question is whether this is the Right Thing in terms of safety and portability. Perhaps different operating systems have a different name for this sysctl, but I'm more interested in whether I should be using this technique at all.

And for the record, "portability" excludes Microsoft Windows in this case.

4

There are 4 answers

1
Duck On

Well the linux SYSCTL (2) man page has this to say in the Notes section:

Glibc does not provide a wrapper for this system call; call it using syscall(2). Or rather... don't call it: use of this system call has long been discouraged, and it is so unloved that it is likely to disappear in a future kernel version. Remove it from your programs now; use the /proc/sys interface instead.

So that is one consideration.

1
R.. GitHub STOP HELPING ICE On

Not a good idea. Even if it weren't for what Duck told you, relying on a system-wide setting that's runtime-variable is bad design and error-prone. If you're going to go to the trouble of having buffer size limits be variable (which typically requires dynamic allocation and checking for failure) then you should go the last step and make it configurable on a more local scope.

With your example of buffer size limits, opinions differ as to what's the best practice. Some people think you should always use dynamically-growing buffers with no hard limit. Others prefer fixed limits sufficiently large that reasonable data would not exceed them. Or, as you've noted, configurable limits are an option. In choosing what's right for your application, I would consider the user experience implications. Sure users don't like arbitrary limits, but they also don't like it when accidentally (or by somebody else's malice) reading data with no newlines in it causes your application to consume unbounded amounts of memory, start swapping, and/or eventually crash or bog down the whole system.

0
Jörg Sonnenberger On

The nearest portable construct for this is "getconf LINE_MAX" or the equivalent C.

1
hubertf On

1) Check out the Single Unix Specification, keyword: "limits"

2) s/safety/security/