MT#59962 ModSys: refactor SCTmpNamAction using `mkstemp()`

Instead of using the `tmpnam()` which doesn't exclude
race conditions on the system (same filenames created
simultaneously), because it doesn't open/reserve the file,
just use the `mkstemp()` which actually genereates a filename
and creates the file for the process.

Upon creating the file, close the FD, as not needed atm.
This file can be then later opened using `SCPopenAction`
or anything alike.

Current new implementation does not unlink the file from
the filesystem and a user of it has to explicitly do that
later with for example the `sys.unlink()` from this same
library.

Additionally: to be able to have excplicit file path (so dir),
add a second parameter to this function to provide a directory.

Fixes:
    warning: the use of `tmpnam' is dangerous, better use `mkstemp'

Change-Id: Ib5e89461b2d2288be77d5f1a899e5293b76ebf90
master
Donat Zenichev 2 months ago
parent 8211e8ca55
commit ccdebb29c4

@ -247,14 +247,33 @@ EXEC_ACTION_START(SCUnlinkArrayAction) {
}
} EXEC_ACTION_END;
/**
* Must only be used with awareness that dst directory exists,
* e.g. with `sys.mkdir` from this lib.
* Later, removal not handled automatically, so must be unlinked
* with something like `sys.unlink` from this lib.
*/
CONST_ACTION_2P(SCTmpNamAction, ',', true);
EXEC_ACTION_START(SCTmpNamAction) {
string varname = resolveVars(arg, sess, sc_sess, event_params);
char fname[L_tmpnam];
if (!tmpnam(fname)) {
string varname = resolveVars(par1, sess, sc_sess, event_params);
string directory = resolveVars(par2, sess, sc_sess, event_params);
/* XXXXXX is required for mkstemp, this will be swapped with some random chars */
string path_template = directory + "/" + varname + "XXXXXX";
/* TODO: C-like strings here, possibly to rework later using C++ strings only? */
char tmpl[path_template.size() + 1];
strcpy(tmpl, path_template.c_str());
int fd = mkstemp(tmpl);
if (fd == -1) {
ERROR("unique name cannot be generated\n");
sc_sess->SET_ERRNO(DSM_ERRNO_FILE);
} else {
sc_sess->var[varname] = fname;
close(fd); /* not needed atm */
sc_sess->var[varname] = tmpl;
sc_sess->SET_ERRNO(DSM_ERRNO_OK);
}
} EXEC_ACTION_END;

@ -38,7 +38,7 @@ DEF_ACTION_1P(SCMkDirRecursiveAction);
DEF_ACTION_2P(SCRenameAction);
DEF_ACTION_1P(SCUnlinkAction);
DEF_ACTION_2P(SCUnlinkArrayAction);
DEF_ACTION_1P(SCTmpNamAction);
DEF_ACTION_2P(SCTmpNamAction);
DEF_ACTION_2P(SCPopenAction);
DEF_ACTION_1P(SCSysGetTimestampAction);

Loading…
Cancel
Save