Debian Codegraph @

lib/envmodules.c

raw
1 /*************************************************************************
2 *
3 * ENVMODULES.C, Modules Tcl extension library
4 * Copyright (C) 2018-2024 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
358 #if defined (__APPLE__)
359 uid_t uid;
360 struct passwd *pwd;
361 char uidstr[16];
362
363 /* Fetch user passwd entry */
364 uid = getuid();
365 if ((pwd = getpwuid(uid)) == NULL) {
366 Tcl_SetErrno(errno);
367 sprintf (uidstr, "%d", uid);
368 Tcl_SetObjResult(interp,
369 Tcl_ObjPrintf("couldn't find name for user id \"%s\": %s", uidstr,
370 Tcl_PosixError(interp)));
371 return TCL_ERROR;
372 }
373
374 groups = NULL;
375 ngroups = getgrouplist_2(pwd->pw_name, pwd->pw_gid, &groups);
376 #else
377 #if defined (HAVE_GETGROUPS)
378 ngroups = getgroups(0, (GETGROUPS_T *) NULL);
379 #endif
380
381 /* Fetch supplementary group list unless getgroups not supported */
382 groups = (GETGROUPS_T *) ckalloc((ngroups + 1) * sizeof(GETGROUPS_T));
383
384 #if defined (HAVE_GETGROUPS)
385 if ((ngroups = getgroups(ngroups, groups)) == -1) {
386 Tcl_SetErrno(errno);
387 Tcl_SetObjResult(interp,
388 Tcl_ObjPrintf("couldn't get supplementary groups: %s",
389 Tcl_PosixError(interp)));
390 ckfree((char *) groups);
391 return TCL_ERROR;
392 }
393 #endif
394 #endif
395
396 /* Sort then remove duplicates from getgroups result */
397 if (ngroups > 1) {
398 qsort(groups, ngroups, sizeof(GETGROUPS_T), __Envmodules_IntCmp);
399 j = 0;
400 for (i = 1; i < ngroups; i++) {
401 if (groups[i] != groups[j]) {
402 j++;
403 groups[j] = groups[i];
404 }
405 }
406 ngroups = j + 1;
407 }
408
409 /* Add primary group if not part of getgroups result (or if getgroups
410 * function is not available) */
411 egid = getegid();
412 for (i = 0; i < ngroups; i++) {
413 if (egid == groups[i]) {
414 egid_in_groups = 1;
415 break;
416 }
417 }
418 if (egid_in_groups == 0) {
419 groups[ngroups] = egid;
420 ngroups++;
421 }
422
423 /* Add group name of primary gid and each supplementatry gid to result
424 * list */
425 lres = Tcl_NewObj();
426 Tcl_IncrRefCount(lres);
427 for (i = 0; i < ngroups; i++) {
428 if ((grp = getgrgid(groups[i])) == NULL) {
429 Tcl_SetErrno(errno);
430 sprintf(gidstr, "%d", groups[i]);
431 Tcl_SetObjResult(interp,
432 Tcl_ObjPrintf("couldn't find name for group id \"%s\": %s",
433 gidstr, Tcl_PosixError(interp)));
434 /* groups has been allocated within getgrouplist_2 on Darwin so
435 * memory cannot be released with Tcl-specific free function */
436 #if defined (__APPLE__)
437 free((char *) groups);
438 #else
439 ckfree((char *) groups);
440 #endif
441 return TCL_ERROR;
442 }
443 Tcl_ListObjAppendElement(interp, lres, Tcl_NewStringObj(grp->gr_name,
444 -1));
445 }
446
447 Tcl_SetObjResult(interp, lres);
448 Tcl_DecrRefCount(lres);
449 #if defined (__APPLE__)
450 free((char *) groups);
451 #else
452 ckfree((char *) groups);
453 #endif
454 return TCL_OK;
455 }
456
457 /*----------------------------------------------------------------------
458 *
459 * Envmodules_InitStateClockSecondsObjCmd --
460 *
461 * This function is invoked to return current Epoch time.
462 *
463 * Results:
464 * A standard Tcl result.
465 *
466 * Side effects:
467 * None.
468 *
469 *---------------------------------------------------------------------*/
470
471 int
472 Envmodules_InitStateClockSecondsObjCmd(
473 ClientData dummy, /* Not used. */
474 Tcl_Interp *interp, /* Current interpreter. */
475 int objc, /* Number of arguments. */
476 Tcl_Obj *const objv[]) /* Argument objects. */
477 {
478 time_t now;
479
480 /* Fetch current Epoch time */
481 if ((now = time(NULL)) == -1) {
482 Tcl_SetErrno(errno);
483 Tcl_SetObjResult(interp, Tcl_ObjPrintf("couldn't get Epoch time: %s",
484 Tcl_PosixError(interp)));
485 return TCL_ERROR;
486 }
487
488 /* Set fetched time as result */
489 Tcl_SetObjResult(interp, Tcl_NewWideIntObj((Tcl_WideInt) now));
490 return TCL_OK;
491 }
492
493 /*----------------------------------------------------------------------
494 *
495 * Envmodules_ParseDateTimeArgObjCmd --
496 *
497 * This function is invoked to parse date time argument value and
498 * translate it into Epoch time.
499 *
500 * Results:
501 * A standard Tcl result.
502 *
503 * Side effects:
504 * None.
505 *
506 *---------------------------------------------------------------------*/
507
508 int
509 Envmodules_ParseDateTimeArgObjCmd(
510 ClientData dummy, /* Not used. */
511 Tcl_Interp *interp, /* Current interpreter. */
512 int objc, /* Number of arguments. */
513 Tcl_Obj *const objv[]) /* Argument objects. */
514 {
515 const char *opt;
516 const char *datetime;
517 Tcl_Size optlen;
518 Tcl_Size datetimelen;
519 char dt[17];
520 int valid_dt = 0;
521 struct tm tm;
522 time_t epoch;
523
524 /* Parse arguments. */
525 if (objc != 3) {
526 Tcl_WrongNumArgs(interp, 1, objv, "opt datetime");
527 return TCL_ERROR;
528 }
529 opt = Tcl_GetStringFromObj(objv[1], &optlen);
530 datetime = Tcl_GetStringFromObj(objv[2], &datetimelen);
531
532 /* Normalize transmitted datetime */
533 switch (datetimelen) {
534 case 16:
535 strncpy(dt, datetime, 16);
536 dt[16] = '\0';
537 valid_dt = 1;
538 break;
539 case 10:
540 strncpy(dt, datetime, 10);
541 dt[10] = '\0';
542 strcat(dt, "T00:00");
543 valid_dt = 1;
544 break;
545 }
546
547 /* Break down datetime into a time struct */
548 memset(&tm, 0, sizeof(struct tm));
549 tm.tm_isdst = -1;
550 if (valid_dt && (strptime(dt, "%Y-%m-%dT%H:%M", &tm) == NULL)) {
551 valid_dt = 0;
552 }
553
554 /* Raise error if datetime format is invalid */
555 if (valid_dt == 0) {
556 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
557 "Incorrect %s value '%s' (valid date time format is 'YYYY-MM-DD[THH:MM]')",
558 opt, datetime));
559 Tcl_SetErrorCode(interp, "MODULES_ERR_KNOWN", NULL);
560 return TCL_ERROR;
561 }
562
563 /* Convert string date in Epoch time */
564 if ((epoch = mktime(&tm)) == -1) {
565 Tcl_SetErrno(errno);
566 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
567 "couldn't convert to Epoch time: %s", Tcl_PosixError(interp)));
568 return TCL_ERROR;
569 }
570
571 /* Set converted Epoch time as result */
572 Tcl_SetObjResult(interp, Tcl_NewWideIntObj((Tcl_WideInt) epoch));
573 return TCL_OK;
574 }
575
576 /*----------------------------------------------------------------------
577 *
578 * Envmodules_Init --
579 *
580 * Initialize the Modules commands.
581 *
582 * Results:
583 * TCL_OK if the package was properly initialized.
584 *
585 * Side effects:
586 * Adds package commands to the current interp.
587 *
588 *---------------------------------------------------------------------*/
589
590 DLLEXPORT int
591 Envmodules_Init(
592 Tcl_Interp* interp /* Tcl interpreter */
593 ) {
594 /* Require at least Tcl 8.5 */
595 if (Tcl_InitStubs(interp, "8.5-", 0) == NULL) {
596 return TCL_ERROR;
597 }
598
599 /* Create the provided commands */
600 Tcl_CreateObjCommand(interp, "readFile", Envmodules_ReadFileObjCmd,
601 (ClientData) NULL, (Tcl_CmdDeleteProc*) NULL);
602 Tcl_CreateObjCommand(interp, "getFilesInDirectory",
603 Envmodules_GetFilesInDirectoryObjCmd, (ClientData) NULL,
604 (Tcl_CmdDeleteProc*) NULL);
605 Tcl_CreateObjCommand(interp, "initStateUsername",
606 Envmodules_InitStateUsernameObjCmd, (ClientData) NULL,
607 (Tcl_CmdDeleteProc*) NULL);
608 Tcl_CreateObjCommand(interp, "initStateUsergroups",
609 Envmodules_InitStateUsergroupsObjCmd, (ClientData) NULL,
610 (Tcl_CmdDeleteProc*) NULL);
611 Tcl_CreateObjCommand(interp, "initStateClockSeconds",
612 Envmodules_InitStateClockSecondsObjCmd, (ClientData) NULL,
613 (Tcl_CmdDeleteProc*) NULL);
614 Tcl_CreateObjCommand(interp, "parseDateTimeArg",
615 Envmodules_ParseDateTimeArgObjCmd, (ClientData) NULL,
616 (Tcl_CmdDeleteProc*) NULL);
617
618 /* Provide the Envmodules package */
619 return Tcl_PkgProvide(interp, PACKAGE_NAME, PACKAGE_VERSION);
620 }
621
622 /* vim:set tabstop=3 shiftwidth=3 expandtab autoindent: */