]> git.ipfire.org Git - thirdparty/util-linux.git/blob - misc-utils/lslocks.c
libfdisk: (docs) add missing 'since' tags
[thirdparty/util-linux.git] / misc-utils / lslocks.c
1 /*
2 * lslocks(8) - list local system locks
3 *
4 * Copyright (C) 2012 Davidlohr Bueso <dave@gnu.org>
5 *
6 * Very generally based on lslk(8) by Victor A. Abell <abe@purdue.edu>
7 * Since it stopped being maintained over a decade ago, this
8 * program should be considered its replacement.
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it would be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software Foundation,
22 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 */
24
25 #include <stdio.h>
26 #include <string.h>
27 #include <getopt.h>
28 #include <stdlib.h>
29 #include <assert.h>
30 #include <dirent.h>
31 #include <unistd.h>
32 #include <sys/stat.h>
33 #include <sys/types.h>
34
35 #include <libmount.h>
36 #include <libsmartcols.h>
37
38 #include "pathnames.h"
39 #include "canonicalize.h"
40 #include "nls.h"
41 #include "xalloc.h"
42 #include "strutils.h"
43 #include "c.h"
44 #include "list.h"
45 #include "closestream.h"
46 #include "optutils.h"
47 #include "procutils.h"
48
49 /* column IDs */
50 enum {
51 COL_SRC = 0,
52 COL_PID,
53 COL_TYPE,
54 COL_SIZE,
55 COL_MODE,
56 COL_M,
57 COL_START,
58 COL_END,
59 COL_PATH,
60 COL_BLOCKER
61 };
62
63 /* column names */
64 struct colinfo {
65 const char *name; /* header */
66 double whint; /* width hint (N < 1 is in percent of termwidth) */
67 int flags; /* SCOLS_FL_* */
68 const char *help;
69 };
70
71 /* columns descriptions */
72 static struct colinfo infos[] = {
73 [COL_SRC] = { "COMMAND",15, 0, N_("command of the process holding the lock") },
74 [COL_PID] = { "PID", 5, SCOLS_FL_RIGHT, N_("PID of the process holding the lock") },
75 [COL_TYPE] = { "TYPE", 5, SCOLS_FL_RIGHT, N_("kind of lock: FL_FLOCK or FL_POSIX.") },
76 [COL_SIZE] = { "SIZE", 4, SCOLS_FL_RIGHT, N_("size of the lock") },
77 [COL_MODE] = { "MODE", 5, 0, N_("lock access mode") },
78 [COL_M] = { "M", 1, 0, N_("mandatory state of the lock: 0 (none), 1 (set)")},
79 [COL_START] = { "START", 10, SCOLS_FL_RIGHT, N_("relative byte offset of the lock")},
80 [COL_END] = { "END", 10, SCOLS_FL_RIGHT, N_("ending offset of the lock")},
81 [COL_PATH] = { "PATH", 0, SCOLS_FL_TRUNC, N_("path of the locked file")},
82 [COL_BLOCKER] = { "BLOCKER", 0, SCOLS_FL_RIGHT, N_("PID of the process blocking the lock") }
83 };
84
85 static int columns[ARRAY_SIZE(infos) * 2];
86 static size_t ncolumns;
87
88 static pid_t pid = 0;
89
90 static struct libmnt_table *tab; /* /proc/self/mountinfo */
91
92 /* basic output flags */
93 static int no_headings;
94 static int no_inaccessible;
95 static int raw;
96 static int json;
97
98 struct lock {
99 struct list_head locks;
100
101 char *cmdname;
102 pid_t pid;
103 char *path;
104 char *type;
105 char *mode;
106 off_t start;
107 off_t end;
108 unsigned int mandatory :1,
109 blocked :1;
110 char *size;
111 int id;
112 };
113
114 static void rem_lock(struct lock *lock)
115 {
116 if (!lock)
117 return;
118
119 free(lock->path);
120 free(lock->size);
121 free(lock->mode);
122 free(lock->cmdname);
123 free(lock->type);
124 list_del(&lock->locks);
125 free(lock);
126 }
127
128 static void disable_columns_truncate(void)
129 {
130 size_t i;
131
132 for (i = 0; i < ARRAY_SIZE(infos); i++)
133 infos[i].flags &= ~SCOLS_FL_TRUNC;
134 }
135
136 /*
137 * Associate the device's mountpoint for a filename
138 */
139 static char *get_fallback_filename(dev_t dev)
140 {
141 struct libmnt_fs *fs;
142 char *res = NULL;
143
144 if (!tab) {
145 tab = mnt_new_table_from_file(_PATH_PROC_MOUNTINFO);
146 if (!tab)
147 return NULL;
148 }
149
150 fs = mnt_table_find_devno(tab, dev, MNT_ITER_BACKWARD);
151 if (!fs)
152 return NULL;
153
154 xasprintf(&res, "%s...", mnt_fs_get_target(fs));
155 return res;
156 }
157
158 /*
159 * Return the absolute path of a file from
160 * a given inode number (and its size)
161 */
162 static char *get_filename_sz(ino_t inode, pid_t lock_pid, size_t *size)
163 {
164 struct stat sb;
165 struct dirent *dp;
166 DIR *dirp;
167 size_t len;
168 int fd;
169 char path[PATH_MAX], sym[PATH_MAX], *ret = NULL;
170
171 *size = 0;
172 memset(path, 0, sizeof(path));
173 memset(sym, 0, sizeof(sym));
174
175 /*
176 * We know the pid so we don't have to
177 * iterate the *entire* filesystem searching
178 * for the damn file.
179 */
180 sprintf(path, "/proc/%d/fd/", lock_pid);
181 if (!(dirp = opendir(path)))
182 return NULL;
183
184 if ((len = strlen(path)) >= (sizeof(path) - 2))
185 goto out;
186
187 if ((fd = dirfd(dirp)) < 0 )
188 goto out;
189
190 while ((dp = readdir(dirp))) {
191 if (!strcmp(dp->d_name, ".") ||
192 !strcmp(dp->d_name, ".."))
193 continue;
194
195 /* care only for numerical descriptors */
196 if (!strtol(dp->d_name, (char **) NULL, 10))
197 continue;
198
199 if (!fstatat(fd, dp->d_name, &sb, 0)
200 && inode != sb.st_ino)
201 continue;
202
203 if ((len = readlinkat(fd, dp->d_name, sym, sizeof(sym) - 1)) < 1)
204 goto out;
205
206 *size = sb.st_size;
207 sym[len] = '\0';
208
209 ret = xstrdup(sym);
210 break;
211 }
212 out:
213 closedir(dirp);
214 return ret;
215 }
216
217 /*
218 * Return the inode number from a string
219 */
220 static ino_t get_dev_inode(char *str, dev_t *dev)
221 {
222 unsigned int maj = 0, min = 0;
223 ino_t inum = 0;
224
225 sscanf(str, "%02x:%02x:%ju", &maj, &min, &inum);
226
227 *dev = (dev_t) makedev(maj, min);
228 return inum;
229 }
230
231 static int get_local_locks(struct list_head *locks)
232 {
233 int i;
234 ino_t inode = 0;
235 FILE *fp;
236 char buf[PATH_MAX], *tok = NULL;
237 size_t sz;
238 struct lock *l;
239 dev_t dev = 0;
240
241 if (!(fp = fopen(_PATH_PROC_LOCKS, "r")))
242 return -1;
243
244 while (fgets(buf, sizeof(buf), fp)) {
245
246 l = xcalloc(1, sizeof(*l));
247 INIT_LIST_HEAD(&l->locks);
248
249 for (tok = strtok(buf, " "), i = 0; tok;
250 tok = strtok(NULL, " "), i++) {
251
252 /*
253 * /proc/locks has *exactly* 8 "blocks" of text
254 * separated by ' ' - check <kernel>/fs/locks.c
255 */
256 switch (i) {
257 case 0: /* ID: */
258 tok[strlen(tok) - 1] = '\0';
259 l->id = strtos32_or_err(tok, _("failed to parse ID"));
260 break;
261 case 1: /* posix, flock, etc */
262 if (strcmp(tok, "->") == 0) { /* optional field */
263 l->blocked = 1;
264 i--;
265 } else
266 l->type = xstrdup(tok);
267 break;
268
269 case 2: /* is this a mandatory lock? other values are advisory or noinode */
270 l->mandatory = *tok == 'M' ? 1 : 0;
271 break;
272 case 3: /* lock mode */
273 l->mode = xstrdup(tok);
274 break;
275
276 case 4: /* PID */
277 /*
278 * If user passed a pid we filter it later when adding
279 * to the list, no need to worry now.
280 */
281 l->pid = strtos32_or_err(tok, _("failed to parse pid"));
282 l->cmdname = proc_get_command_name(l->pid);
283 if (!l->cmdname)
284 l->cmdname = xstrdup(_("(unknown)"));
285 break;
286
287 case 5: /* device major:minor and inode number */
288 inode = get_dev_inode(tok, &dev);
289 break;
290
291 case 6: /* start */
292 l->start = !strcmp(tok, "EOF") ? 0 :
293 strtou64_or_err(tok, _("failed to parse start"));
294 break;
295
296 case 7: /* end */
297 /* replace '\n' character */
298 tok[strlen(tok)-1] = '\0';
299 l->end = !strcmp(tok, "EOF") ? 0 :
300 strtou64_or_err(tok, _("failed to parse end"));
301 break;
302 default:
303 break;
304 }
305 }
306
307 l->path = get_filename_sz(inode, l->pid, &sz);
308
309 /* no permissions -- ignore */
310 if (!l->path && no_inaccessible) {
311 rem_lock(l);
312 continue;
313 }
314
315 if (!l->path) {
316 /* probably no permission to peek into l->pid's path */
317 l->path = get_fallback_filename(dev);
318 l->size = xstrdup("");
319 } else
320 /* avoid leaking */
321 l->size = size_to_human_string(SIZE_SUFFIX_1LETTER, sz);
322
323 list_add(&l->locks, locks);
324 }
325
326 fclose(fp);
327 return 0;
328 }
329
330 static int column_name_to_id(const char *name, size_t namesz)
331 {
332 size_t i;
333
334 assert(name);
335
336 for (i = 0; i < ARRAY_SIZE(infos); i++) {
337 const char *cn = infos[i].name;
338
339 if (!strncasecmp(name, cn, namesz) && !*(cn + namesz))
340 return i;
341 }
342 warnx(_("unknown column: %s"), name);
343 return -1;
344 }
345
346 static inline int get_column_id(int num)
347 {
348 assert(num >= 0);
349 assert((size_t) num < ncolumns);
350 assert(columns[num] < (int) ARRAY_SIZE(infos));
351
352 return columns[num];
353 }
354
355
356 static inline struct colinfo *get_column_info(unsigned num)
357 {
358 return &infos[ get_column_id(num) ];
359 }
360
361 static pid_t get_blocker(int id, struct list_head *locks)
362 {
363 struct list_head *p;
364
365 list_for_each(p, locks) {
366 struct lock *l = list_entry(p, struct lock, locks);
367
368 if (l->id == id && !l->blocked)
369 return l->pid;
370 }
371
372 return 0;
373 }
374
375 static void add_scols_line(struct libscols_table *table, struct lock *l, struct list_head *locks)
376 {
377 size_t i;
378 struct libscols_line *line;
379 /*
380 * Whenever cmdname or filename is NULL it is most
381 * likely because there's no read permissions
382 * for the specified process.
383 */
384 const char *notfnd = "";
385
386 assert(l);
387 assert(table);
388
389 line = scols_table_new_line(table, NULL);
390 if (!line)
391 err(EXIT_FAILURE, _("failed to allocate output line"));
392
393 for (i = 0; i < ncolumns; i++) {
394 char *str = NULL;
395
396 switch (get_column_id(i)) {
397 case COL_SRC:
398 xasprintf(&str, "%s", l->cmdname ? l->cmdname : notfnd);
399 break;
400 case COL_PID:
401 xasprintf(&str, "%d", l->pid);
402 break;
403 case COL_TYPE:
404 xasprintf(&str, "%s", l->type);
405 break;
406 case COL_SIZE:
407 xasprintf(&str, "%s", l->size);
408 break;
409 case COL_MODE:
410 xasprintf(&str, "%s%s", l->mode, l->blocked ? "*" : "");
411 break;
412 case COL_M:
413 xasprintf(&str, "%d", l->mandatory ? 1 : 0);
414 break;
415 case COL_START:
416 xasprintf(&str, "%jd", l->start);
417 break;
418 case COL_END:
419 xasprintf(&str, "%jd", l->end);
420 break;
421 case COL_PATH:
422 xasprintf(&str, "%s", l->path ? l->path : notfnd);
423 break;
424 case COL_BLOCKER:
425 {
426 pid_t bl = l->blocked && l->id ?
427 get_blocker(l->id, locks) : 0;
428 if (bl)
429 xasprintf(&str, "%d", (int) bl);
430 }
431 default:
432 break;
433 }
434
435 if (str && scols_line_set_data(line, i, str))
436 err(EXIT_FAILURE, _("failed to add output data"));
437 }
438 }
439
440 static int show_locks(struct list_head *locks)
441 {
442 int rc = 0;
443 size_t i;
444 struct list_head *p, *pnext;
445 struct libscols_table *table;
446
447 table = scols_new_table();
448 if (!table)
449 err(EXIT_FAILURE, _("failed to allocate output table"));
450
451 scols_table_enable_raw(table, raw);
452 scols_table_enable_json(table, json);
453 scols_table_enable_noheadings(table, no_headings);
454
455 if (json)
456 scols_table_set_name(table, "locks");
457
458 for (i = 0; i < ncolumns; i++) {
459 struct colinfo *col = get_column_info(i);
460
461 if (!scols_table_new_column(table, col->name, col->whint, col->flags))
462 err(EXIT_FAILURE, _("failed to allocate output column"));
463 }
464
465 /* prepare data for output */
466 list_for_each(p, locks) {
467 struct lock *l = list_entry(p, struct lock, locks);
468
469 if (pid && pid != l->pid)
470 continue;
471
472 add_scols_line(table, l, locks);
473 }
474
475 /* destroy the list */
476 list_for_each_safe(p, pnext, locks) {
477 struct lock *l = list_entry(p, struct lock, locks);
478 rem_lock(l);
479 }
480
481 scols_print_table(table);
482 scols_unref_table(table);
483 return rc;
484 }
485
486
487 static void __attribute__ ((__noreturn__)) usage(FILE * out)
488 {
489 size_t i;
490
491 fputs(USAGE_HEADER, out);
492
493 fprintf(out,
494 _(" %s [options]\n"), program_invocation_short_name);
495
496 fputs(USAGE_SEPARATOR, out);
497 fputs(_("List local system locks.\n"), out);
498
499 fputs(USAGE_OPTIONS, out);
500 fputs(_(" -J, --json use JSON output format\n"), out);
501 fputs(_(" -i, --noinaccessible ignore locks without read permissions\n"), out);
502 fputs(_(" -n, --noheadings don't print headings\n"), out);
503 fputs(_(" -o, --output <list> define which output columns to use\n"), out);
504 fputs(_(" -p, --pid <pid> display only locks held by this process\n"), out);
505 fputs(_(" -r, --raw use the raw output format\n"), out);
506 fputs(_(" -u, --notruncate don't truncate text in columns\n"), out);
507
508 fputs(USAGE_SEPARATOR, out);
509 fputs(USAGE_HELP, out);
510 fputs(USAGE_VERSION, out);
511
512 fputs(_("\nAvailable columns (for --output):\n"), out);
513
514 for (i = 0; i < ARRAY_SIZE(infos); i++)
515 fprintf(out, " %11s %s\n", infos[i].name, _(infos[i].help));
516
517 fprintf(out, USAGE_MAN_TAIL("lslocks(8)"));
518
519 exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
520 }
521
522 int main(int argc, char *argv[])
523 {
524 int c, rc = 0;
525 struct list_head locks;
526 char *outarg = NULL;
527 static const struct option long_opts[] = {
528 { "json", no_argument, NULL, 'J' },
529 { "pid", required_argument, NULL, 'p' },
530 { "help", no_argument, NULL, 'h' },
531 { "output", required_argument, NULL, 'o' },
532 { "notruncate", no_argument, NULL, 'u' },
533 { "version", no_argument, NULL, 'V' },
534 { "noheadings", no_argument, NULL, 'n' },
535 { "raw", no_argument, NULL, 'r' },
536 { "noinaccessible", no_argument, NULL, 'i' },
537 { NULL, 0, NULL, 0 }
538 };
539
540 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
541 { 'J','r' },
542 { 0 }
543 };
544 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
545 setlocale(LC_ALL, "");
546 bindtextdomain(PACKAGE, LOCALEDIR);
547 textdomain(PACKAGE);
548 atexit(close_stdout);
549
550 while ((c = getopt_long(argc, argv,
551 "iJp:o:nruhV", long_opts, NULL)) != -1) {
552
553 err_exclusive_options(c, long_opts, excl, excl_st);
554
555 switch(c) {
556 case 'i':
557 no_inaccessible = 1;
558 break;
559 case 'J':
560 json = 1;
561 break;
562 case 'p':
563 pid = strtos32_or_err(optarg, _("invalid PID argument"));
564 break;
565 case 'o':
566 outarg = optarg;
567 break;
568 case 'V':
569 printf(UTIL_LINUX_VERSION);
570 return EXIT_SUCCESS;
571 case 'h':
572 usage(stdout);
573 case 'n':
574 no_headings = 1;
575 break;
576 case 'r':
577 raw = 1;
578 break;
579 case 'u':
580 disable_columns_truncate();
581 break;
582 default:
583 errtryhelp(EXIT_FAILURE);
584 }
585 }
586
587 INIT_LIST_HEAD(&locks);
588
589 if (!ncolumns) {
590 /* default columns */
591 columns[ncolumns++] = COL_SRC;
592 columns[ncolumns++] = COL_PID;
593 columns[ncolumns++] = COL_TYPE;
594 columns[ncolumns++] = COL_SIZE;
595 columns[ncolumns++] = COL_MODE;
596 columns[ncolumns++] = COL_M;
597 columns[ncolumns++] = COL_START;
598 columns[ncolumns++] = COL_END;
599 columns[ncolumns++] = COL_PATH;
600 }
601
602 if (outarg && string_add_to_idarray(outarg, columns, ARRAY_SIZE(columns),
603 &ncolumns, column_name_to_id) < 0)
604 return EXIT_FAILURE;
605
606 scols_init_debug(0);
607
608 rc = get_local_locks(&locks);
609
610 if (!rc && !list_empty(&locks))
611 rc = show_locks(&locks);
612
613 mnt_unref_table(tab);
614 return rc;
615 }