How to "pull the network cable" programmatically in a large Linux application?

I have a large C ++ application on Linux with many third-party and third-party libraries built and linked to.

There are certain parts of the application that must be run without access to the file system or network (especially for downloading network files). From time to time, we find that this operation does indeed upload files, usually due to a programmer error.

How can I apply this in code? For example, something like:

try { lockFileSystem(); Application->DoImportantOperation(); unlockFileSystem(); } catch ( InvalidFileSystemAccess ) { // bad programmer, no pizza } 

Or, conversely, is there some kind of lower level callback that the application can connect when opening a file?

Note. I know about the awesomeness of strace, but it got to the point where it needs to be done as part of application execution, and not as a manual test manually.

+4
source share
2 answers

It depends on what the code is legitimately trying to do, but you could do it with setrlimit() RLIMIT_NOFILE .

Something like this should work:

 #include <sys/resource.h> struct scoped_fd_blocker { rlim_t prev; scoped_fd_blocker() { rlimit lim; getrlimit(RLIMIT_NOFILE, &lim); // get the current limit prev = lim.rlim_cur; // save old limit lim.rlim_cur = 0; // set the soft limit to 0 setrlimit(RLIMIT_NOFILE, &lim); // do the set } ~scoped_fd_blocker() { rlimit lim; getrlimit(RLIMIT_NOFILE, &lim); // get the current limit lim.rlim_cur = prev; // reset the soft limit to the previous value setrlimit(RLIMIT_NOFILE, &lim); // do the set } }; // Example Usage: void do_stuff() { scoped_fd_blocker blocker; Application->DoImportantOperation(); } 

Basically, this means that the OS does not allow your process to open any file descriptor, even if the existing one is closed, by resetting the descriptor limit of the open open process file. Please note that these are more than just files and may have some unforeseen consequences. This will include files, sockets, event objects, directories, shared resources, channels, and will also prevent C file libraries from opening. (Some C libraries use file locks and more to control concurrency.) Think of all the things that open files (like dlopen ).

Any attempt to open the file descriptor will fail (return -1), and errno will be set to EMFILE , which translates as "Error 24: Too many open files."

I put all this in a structure so that it is safe.

+5
source

Not very elegant, but you can connect, for example, open () and route it through your own call like proxy_open (), which has state. If the status is "not allowed by the file system!" then you simply return the corresponding error and / or process it as you like.

+2
source

Source: https://habr.com/ru/post/1396531/


All Articles