Debian Codegraph @

lib/envmodules.c

raw
1 /*************************************************************************
2 *
3 * ENVMODULES.C, Modules Tcl extension library
4 * Copyright (C) 2018-2026 Xavier Delaruelle
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 *
19 ************************************************************************/
20
21 #define _ISOC99_SOURCE
22 #define _XOPEN_SOURCE
23
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <errno.h>
27 #include <limits.h>
28 #include <sys/types.h>
29 #include <dirent.h>
30 #include <pwd.h>
31 #include <grp.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <time.h>
36 #include "config.h"
37 #include "envmodules.h"
38
39 /* A specific function named getgrouplist_2 should be used on Darwin systems
40 * to be able to fetch all user groups, especially if user is member of more
41 * then 16 groups */
42 #if defined (__APPLE__)
43 int32_t getgrouplist_2(const char *, gid_t, gid_t **);
44 #endif
45
46 /* Utility function to compare 2 integers for qsort function. */
47 int
48 __Envmodules_IntCmp(
49 const void* i,
50 const void* j)
51 {
52 return (i > j) - (i < j);
53 }
54
55 /*----------------------------------------------------------------------
56 *
57 * Envmodules_GetFilesInDirectoryObjCmd --
58 *
59 * This function is invoked to read the content of a directory in a more
60 * IO-optimized way than native Tcl commands perform by avoiding specific
61 * additional queries to get hidden files like .modulerc and .version.
62 *
63 * Results:
64 * A standard Tcl result.
65 *
66 * Side effects:
67 * None.
68 *
69 *---------------------------------------------------------------------*/
70
71 int
72 Envmodules_GetFilesInDirectoryObjCmd(
73 ClientData dummy, /* Not used. */
74 Tcl_Interp *interp, /* Current interpreter. */
75 int objc, /* Number of arguments. */
76 Tcl_Obj *const objv[]) /* Argument objects. */
77 {
78 int fetch_dotversion;
79 const char *dir;
80 Tcl_Size dirlen;
81 DIR *did;
82 Tcl_Obj *ltmp, *lres;
83 struct dirent *direntry;
84 int have_modulerc = 0;
85 int have_version = 0;
86 int is_hidden;
87 char path[PATH_MAX];
88
89 /* Parse arguments. */
90 if (objc == 3) {
91 /* fetch_dotversion */
92 if (Tcl_GetBooleanFromObj(interp, objv[2], &fetch_dotversion)!=TCL_OK) {
93 Tcl_SetErrorCode(interp, "TCL", "VALUE", "BOOLEAN", NULL);
94 return TCL_ERROR;
95 }
96 } else {
97 Tcl_WrongNumArgs(interp, 1, objv, "dir fetch_dotversion");
98 return TCL_ERROR;
99 }
100
101 dir = Tcl_GetStringFromObj(objv[1], &dirlen);
102
103 /* Open directory. */
104 if ((did = opendir(dir)) == NULL) {
105 Tcl_SetErrno(errno);
106 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
107 "couldn't open directory \"%s\": %s", dir, Tcl_PosixError(interp)));
108 return TCL_ERROR;
109 }
110
111 /* Read directory. */
112 ltmp = Tcl_NewListObj(0, NULL);
113 Tcl_IncrRefCount(ltmp);
114 errno = 0;
115 while ((direntry = readdir(did)) != NULL) {
116 snprintf(path, sizeof(path), "%s/%s", dir, direntry->d_name);
117 /* ignore . and .. */
118 if (!strcmp(direntry->d_name, ".") || !strcmp(direntry->d_name, "..")) {
119 continue;
120 } else if (!strcmp(direntry->d_name, ".modulerc")) {
121 if (!access(path, R_OK)) {
122 have_modulerc = 1;
123 }
124 } else if (!strcmp(direntry->d_name, ".version")) {
125 if (fetch_dotversion && !access(path, R_OK)) {
126 have_version = 1;
127 }
128 } else {
129 Tcl_ListObjAppendElement(interp, ltmp, Tcl_NewStringObj(path, -1));
130 is_hidden = (direntry->d_name[0] == '.') ? 1 : 0;
131 Tcl_ListObjAppendElement(interp, ltmp, Tcl_NewIntObj(is_hidden));
132 }
133 }
134 /* Do not treat error happening during read to send list of valid files. */
135
136 /* Close directory. */
137 if (closedir(did) == -1) {
138 Tcl_SetErrno(errno);
139 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
140 "couldn't close directory \"%s\": %s", dir, Tcl_PosixError(interp)));
141 Tcl_DecrRefCount(ltmp);
142 return TCL_ERROR;
143 }
144
145 /* Build result list. */
146 lres = Tcl_NewObj();
147 Tcl_IncrRefCount(lres);
148 /* Ensure .modulerc and .version are first entries in result list */
149 if (have_modulerc) {
150 snprintf(path, sizeof(path), "%s/%s", dir, ".modulerc");
151 Tcl_ListObjAppendElement(interp, lres, Tcl_NewStringObj(path, -1));
152 Tcl_ListObjAppendElement(interp, lres, Tcl_NewIntObj(0));
153 }
154 if (have_version) {
155 snprintf(path, sizeof(path), "%s/%s", dir, ".version");
156 Tcl_ListObjAppendElement(interp, lres, Tcl_NewStringObj(path, -1));
157 Tcl_ListObjAppendElement(interp, lres, Tcl_NewIntObj(0));
158 }
159 /* Then append regular elements. */
160 Tcl_ListObjAppendList(interp, lres, ltmp);
161 Tcl_DecrRefCount(ltmp);
162
163
164 Tcl_SetObjResult(interp, lres);
165 Tcl_DecrRefCount(lres);
166 return TCL_OK;
167 }
168
169 /*----------------------------------------------------------------------
170 *
171 * Envmodules_ReadFileObjCmd --
172 *
173 * This function is invoked to open/read/close a regular file in a
174 * more IO-optimized way than native Tcl commands perform by avoiding
175 * useless lstat, fcntl and ioctl syscalls.
176 *
177 * Results:
178 * A standard Tcl result.
179 *
180 * Side effects:
181 * None.
182 *
183 *---------------------------------------------------------------------*/
184
185 int
186 Envmodules_ReadFileObjCmd(
187 ClientData dummy, /* Not used. */
188 Tcl_Interp *interp, /* Current interpreter. */
189 int objc, /* Number of arguments. */
190 Tcl_Obj *const objv[]) /* Argument objects. */
191 {
192 int firstline;
193 int must_have_cookie;
194 const char *filename;
195 Tcl_Size filenamelen;
196 int fid;
197 int firstread;
198 ssize_t len;
199 char buf[READ_BUFFER_SIZE];
200 Tcl_Obj *res;
201
202 /* Parse arguments. */
203 if (objc < 2 || objc > 4) {
204 Tcl_WrongNumArgs(interp, 1, objv,
205 "filename ?firstline? ?must_have_cookie?");
206 return TCL_ERROR;
207 }
208 if (objc > 2) {
209 if (Tcl_GetBooleanFromObj(interp, objv[2], &firstline) != TCL_OK) {
210 Tcl_SetErrorCode(interp, "TCL", "VALUE", "BOOLEAN", NULL);
211 return TCL_ERROR;
212 }
213 } else {
214 firstline = 0;
215 }
216 if (objc > 3) {
217 if (Tcl_GetBooleanFromObj(interp, objv[3], &must_have_cookie) !=
218 TCL_OK) {
219 Tcl_SetErrorCode(interp, "TCL", "VALUE", "BOOLEAN", NULL);
220 return TCL_ERROR;
221 }
222 } else {
223 must_have_cookie = 0;
224 }
225
226 filename = Tcl_GetStringFromObj(objv[1], &filenamelen);
227
228 /* Open file. */
229 if ((fid = open(filename, O_RDONLY)) == -1) {
230 Tcl_SetErrno(errno);
231 Tcl_SetObjResult(interp, Tcl_ObjPrintf("couldn't open \"%s\": %s",
232 filename, Tcl_PosixError(interp)));
233 return TCL_ERROR;
234 }
235
236 /* Read file. */
237 res = Tcl_NewObj();
238 Tcl_IncrRefCount(res);
239 /* Only read first characters to get magic cookie. */
240 if (firstline == 1) {
241 if ((len = read(fid, buf, FIRSTLINE_LENGTH)) > 0) {
242 Tcl_AppendToObj(res, buf, len);
243 }
244 } else {
245 firstread = 1;
246 while ((len = read(fid, buf, READ_BUFFER_SIZE)) > 0) {
247 Tcl_AppendToObj(res, buf, len);
248 /* Stop reading if magic cookie is mandatory but not found at the
249 * beginning of file. */
250 if (firstread == 1) {
251 firstread = 0;
252 if (must_have_cookie == 1 && strncmp(buf, MODULES_MAGIC_COOKIE, 8)
253 != 0) {
254 break;
255 }
256 }
257 }
258 }
259 /* Error during read. */
260 if (len == -1) {
261 Tcl_SetErrno(errno);
262 Tcl_SetObjResult(interp, Tcl_ObjPrintf("error reading \"%s\": %s",
263 filename, Tcl_PosixError(interp)));
264 Tcl_DecrRefCount(res);
265 close(fid);
266 return TCL_ERROR;
267 }
268
269 /* Close file. */
270 close(fid);
271
272 Tcl_SetObjResult(interp, res);
273 Tcl_DecrRefCount(res);
274 return TCL_OK;
275 }
276
277 /*----------------------------------------------------------------------
278 *
279 * Envmodules_InitStateUsernameObjCmd --
280 *
281 * This function is invoked to return the username of user running
282 * current process.
283 *
284 * Results:
285 * A standard Tcl result.
286 *
287 * Side effects:
288 * None.
289 *
290 *---------------------------------------------------------------------*/
291
292 int
293 Envmodules_InitStateUsernameObjCmd(
294 ClientData dummy, /* Not used. */
295 Tcl_Interp *interp, /* Current interpreter. */
296 int objc, /* Number of arguments. */
297 Tcl_Obj *const objv[]) /* Argument objects. */
298 {
299 uid_t uid;
300 struct passwd *pwd;
301 char uidstr[16];
302 Tcl_Obj *res;
303
304 /* Get current user id */
305 uid = getuid();
306
307 /* Fetch corresponding passwd entry */
308 if ((pwd = getpwuid(uid)) == NULL) {
309 Tcl_SetErrno(errno);
310 sprintf (uidstr, "%d", uid);
311 Tcl_SetObjResult(interp,
312 Tcl_ObjPrintf("couldn't find name for user id \"%s\": %s", uidstr,
313 Tcl_PosixError(interp)));
314 return TCL_ERROR;
315 }
316
317 /* Set username as result */
318 res = Tcl_NewObj();
319 Tcl_IncrRefCount(res);
320 Tcl_AppendToObj(res, pwd->pw_name, strlen(pwd->pw_name));
321
322 Tcl_SetObjResult(interp, res);
323 Tcl_DecrRefCount(res);
324 return TCL_OK;
325 }
326
327 /*----------------------------------------------------------------------
328 *
329 * Envmodules_InitStateUsergroupsObjCmd --
330 *
331 * This function is invoked to return all the groups the user running
332 * current process is member of.
333 *
334 * Results:
335 * A standard Tcl result.
336 *
337 * Side effects:
338 * None.
339 *
340 *---------------------------------------------------------------------*/
341
342 int
343 Envmodules_InitStateUsergroupsObjCmd(
344 ClientData dummy, /* Not used. */
345 Tcl_Interp *interp, /* Current interpreter. */
346 int objc, /* Number of arguments. */
347 Tcl_Obj *const objv[]) /* Argument objects. */
348 {
349 GETGROUPS_T *groups;
350 int ngroups = 0;
351 int egid_in_groups = 0;
352 GETGROUPS_T egid;
353 int i, j;
354 struct group *grp;
355 char gidstr[16];
356 Tcl_Obj *lres;
357 Tcl_Obj *sgrp;
358
359 #if defined (__APPLE__)
360 uid_t uid;
361 struct passwd *pwd;
362 char uidstr[16];
363
364 /* Fetch user passwd entry */
365 uid = getuid();
366 if ((pwd = getpwuid(uid)) == NULL) {
367 Tcl_SetErrno(errno);
368 sprintf (uidstr, "%d", uid);
369 Tcl_SetObjResult(interp,
370 Tcl_ObjPrintf("couldn't find name for user id \"%s\": %s", uidstr,
371 Tcl_PosixError(interp)));
372 return TCL_ERROR;
373 }
374
375 groups = NULL;
376 ngroups = getgrouplist_2(pwd->pw_name, pwd->pw_gid, &groups);
377 #else
378 #if defined (HAVE_GETGROUPS)
379 ngroups = getgroups(0, (GETGROUPS_T *) NULL);
380 #endif
381
382 /* Fetch supplementary group list unless getgroups not supported */
383 groups = (GETGROUPS_T *) ckalloc((ngroups + 1) * sizeof(GETGROUPS_T));
384
385 #if defined (HAVE_GETGROUPS)
386 if ((ngroups = getgroups(ngroups, groups)) == -1) {
387 Tcl_SetErrno(errno);
388 Tcl_SetObjResult(interp,
389 Tcl_ObjPrintf("couldn't get supplementary groups: %s",
390 Tcl_PosixError(interp)));
391 ckfree((char *) groups);
392 return TCL_ERROR;
393 }
394 #endif
395 #endif
396
397 /* Sort then remove duplicates from getgroups result */
398 if (ngroups > 1) {
399 qsort(groups, ngroups, sizeof(GETGROUPS_T), __Envmodules_IntCmp);
400 j = 0;
401 for (i = 1; i < ngroups; i++) {
402 if (groups[i] != groups[j]) {
403 j++;
404 groups[j] = groups[i];
405 }
406 }
407 ngroups = j + 1;
408 }
409
410 /* Add primary group if not part of getgroups result (or if getgroups
411 * function is not available) */
412 egid = getegid();
413 for (i = 0; i < ngroups; i++) {
414 if (egid == groups[i]) {
415 egid_in_groups = 1;
416 break;
417 }
418 }
419 if (egid_in_groups == 0) {
420 groups[ngroups] = egid;
421 ngroups++;
422 }
423
424 /* Add group name of primary gid and each supplementatry gid to result
425 * list */
426 lres = Tcl_NewObj();
427 Tcl_IncrRefCount(lres);
428 for (i = 0; i < ngroups; i++) {
429 /* If group name cannot be resolved, add use gid number as group name */
430 if ((grp = getgrgid(groups[i])) == NULL) {
431 sprintf(gidstr, "%d", groups[i]);
432 sgrp = Tcl_NewStringObj(gidstr, -1);
433 } else {
434 sgrp = Tcl_NewStringObj(grp->gr_name, -1);
435 }
436 Tcl_ListObjAppendElement(interp, lres, sgrp);
437 }
438
439 Tcl_SetObjResult(interp, lres);
440 Tcl_DecrRefCount(lres);
441 #if defined (__APPLE__)
442 free((char *) groups);
443 #else
444 ckfree((char *) groups);
445 #endif
446 return TCL_OK;
447 }
448
449 /*----------------------------------------------------------------------
450 *
451 * Envmodules_InitStateClockSecondsObjCmd --
452 *
453 * This function is invoked to return current Epoch time.
454 *
455 * Results:
456 * A standard Tcl result.
457 *
458 * Side effects:
459 * None.
460 *
461 *---------------------------------------------------------------------*/
462
463 int
464 Envmodules_InitStateClockSecondsObjCmd(
465 ClientData dummy, /* Not used. */
466 Tcl_Interp *interp, /* Current interpreter. */
467 int objc, /* Number of arguments. */
468 Tcl_Obj *const objv[]) /* Argument objects. */
469 {
470 time_t now;
471
472 /* Fetch current Epoch time */
473 if ((now = time(NULL)) == -1) {
474 Tcl_SetErrno(errno);
475 Tcl_SetObjResult(interp, Tcl_ObjPrintf("couldn't get Epoch time: %s",
476 Tcl_PosixError(interp)));
477 return TCL_ERROR;
478 }
479
480 /* Set fetched time as result */
481 Tcl_SetObjResult(interp, Tcl_NewWideIntObj((Tcl_WideInt) now));
482 return TCL_OK;
483 }
484
485 /*----------------------------------------------------------------------
486 *
487 * Envmodules_ParseDateTimeArgObjCmd --
488 *
489 * This function is invoked to parse date time argument value and
490 * translate it into Epoch time.
491 *
492 * Results:
493 * A standard Tcl result.
494 *
495 * Side effects:
496 * None.
497 *
498 *---------------------------------------------------------------------*/
499
500 int
501 Envmodules_ParseDateTimeArgObjCmd(
502 ClientData dummy, /* Not used. */
503 Tcl_Interp *interp, /* Current interpreter. */
504 int objc, /* Number of arguments. */
505 Tcl_Obj *const objv[]) /* Argument objects. */
506 {
507 const char *opt;
508 const char *datetime;
509 Tcl_Size optlen;
510 Tcl_Size datetimelen;
511 char dt[17];
512 int valid_dt = 0;
513 struct tm tm;
514 time_t epoch;
515
516 /* Parse arguments. */
517 if (objc != 3) {
518 Tcl_WrongNumArgs(interp, 1, objv, "opt datetime");
519 return TCL_ERROR;
520 }
521 opt = Tcl_GetStringFromObj(objv[1], &optlen);
522 datetime = Tcl_GetStringFromObj(objv[2], &datetimelen);
523
524 /* Normalize transmitted datetime */
525 switch (datetimelen) {
526 case 16:
527 strncpy(dt, datetime, 16);
528 dt[16] = '\0';
529 valid_dt = 1;
530 break;
531 case 10:
532 strncpy(dt, datetime, 10);
533 dt[10] = '\0';
534 strcat(dt, "T00:00");
535 valid_dt = 1;
536 break;
537 }
538
539 /* Break down datetime into a time struct */
540 memset(&tm, 0, sizeof(struct tm));
541 tm.tm_isdst = -1;
542 if (valid_dt && (strptime(dt, "%Y-%m-%dT%H:%M", &tm) == NULL)) {
543 valid_dt = 0;
544 }
545
546 /* Raise error if datetime format is invalid */
547 if (valid_dt == 0) {
548 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
549 "Incorrect %s value '%s' (valid date time format is 'YYYY-MM-DD[THH:MM]')",
550 opt, datetime));
551 Tcl_SetErrorCode(interp, "MODULES_ERR_KNOWN", NULL);
552 return TCL_ERROR;
553 }
554
555 /* Convert string date in Epoch time */
556 if ((epoch = mktime(&tm)) == -1) {
557 Tcl_SetErrno(errno);
558 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
559 "couldn't convert to Epoch time: %s", Tcl_PosixError(interp)));
560 return TCL_ERROR;
561 }
562
563 /* Set converted Epoch time as result */
564 Tcl_SetObjResult(interp, Tcl_NewWideIntObj((Tcl_WideInt) epoch));
565 return TCL_OK;
566 }
567
568 /*----------------------------------------------------------------------
569 *
570 * Envmodules_Init --
571 *
572 * Initialize the Modules commands.
573 *
574 * Results:
575 * TCL_OK if the package was properly initialized.
576 *
577 * Side effects:
578 * Adds package commands to the current interp.
579 *
580 *---------------------------------------------------------------------*/
581
582 DLLEXPORT int
583 Envmodules_Init(
584 Tcl_Interp* interp /* Tcl interpreter */
585 ) {
586 /* Require at least Tcl 8.5 */
587 if (Tcl_InitStubs(interp, "8.5-", 0) == NULL) {
588 return TCL_ERROR;
589 }
590
591 /* Create the provided commands */
592 Tcl_CreateObjCommand(interp, "readFile", Envmodules_ReadFileObjCmd,
593 (ClientData) NULL, (Tcl_CmdDeleteProc*) NULL);
594 Tcl_CreateObjCommand(interp, "getFilesInDirectory",
595 Envmodules_GetFilesInDirectoryObjCmd, (ClientData) NULL,
596 (Tcl_CmdDeleteProc*) NULL);
597 Tcl_CreateObjCommand(interp, "initStateUsername",
598 Envmodules_InitStateUsernameObjCmd, (ClientData) NULL,
599 (Tcl_CmdDeleteProc*) NULL);
600 Tcl_CreateObjCommand(interp, "initStateUsergroups",
601 Envmodules_InitStateUsergroupsObjCmd, (ClientData) NULL,
602 (Tcl_CmdDeleteProc*) NULL);
603 Tcl_CreateObjCommand(interp, "initStateClockSeconds",
604 Envmodules_InitStateClockSecondsObjCmd, (ClientData) NULL,
605 (Tcl_CmdDeleteProc*) NULL);
606 Tcl_CreateObjCommand(interp, "parseDateTimeArg",
607 Envmodules_ParseDateTimeArgObjCmd, (ClientData) NULL,
608 (Tcl_CmdDeleteProc*) NULL);
609
610 /* Provide the Envmodules package */
611 return Tcl_PkgProvide(interp, PACKAGE_NAME, PACKAGE_VERSION);
612 }
613
614 /* vim:set tabstop=3 shiftwidth=3 expandtab autoindent: */