]> git.ipfire.org Git - thirdparty/util-linux.git/blob - misc-utils/lslocks.c
87ddfdcdc7469c0cf6145c59f298b51cde418ae2
[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 "procfs.h"
48
49 /* column IDs */
50 enum {
51 COL_SRC = 0,
52 COL_PID,
53 COL_TYPE,
54 COL_SIZE,
55 COL_INODE,
56 COL_MAJMIN,
57 COL_MODE,
58 COL_M,
59 COL_START,
60 COL_END,
61 COL_PATH,
62 COL_BLOCKER
63 };
64
65 /* column names */
66 struct colinfo {
67 const char * const name; /* header */
68 double whint; /* width hint (N < 1 is in percent of termwidth) */
69 int flags; /* SCOLS_FL_* */
70 const char *help;
71 };
72
73 /* columns descriptions */
74 static struct colinfo infos[] = {
75 [COL_SRC] = { "COMMAND",15, 0, N_("command of the process holding the lock") },
76 [COL_PID] = { "PID", 5, SCOLS_FL_RIGHT, N_("PID of the process holding the lock") },
77 [COL_TYPE] = { "TYPE", 5, SCOLS_FL_RIGHT, N_("kind of lock") },
78 [COL_SIZE] = { "SIZE", 4, SCOLS_FL_RIGHT, N_("size of the lock") },
79 [COL_INODE] = { "INODE", 5, SCOLS_FL_RIGHT, N_("inode number") },
80 [COL_MAJMIN] = { "MAJ:MIN", 6, 0, N_("major:minor device number") },
81 [COL_MODE] = { "MODE", 5, 0, N_("lock access mode") },
82 [COL_M] = { "M", 1, 0, N_("mandatory state of the lock: 0 (none), 1 (set)")},
83 [COL_START] = { "START", 10, SCOLS_FL_RIGHT, N_("relative byte offset of the lock")},
84 [COL_END] = { "END", 10, SCOLS_FL_RIGHT, N_("ending offset of the lock")},
85 [COL_PATH] = { "PATH", 0, SCOLS_FL_TRUNC, N_("path of the locked file")},
86 [COL_BLOCKER] = { "BLOCKER", 0, SCOLS_FL_RIGHT, N_("PID of the process blocking the lock") }
87 };
88
89 static int columns[ARRAY_SIZE(infos) * 2];
90 static size_t ncolumns;
91
92 static pid_t pid = 0;
93
94 static struct libmnt_table *tab; /* /proc/self/mountinfo */
95
96 /* basic output flags */
97 static int no_headings;
98 static int no_inaccessible;
99 static int raw;
100 static int json;
101 static int bytes;
102
103 struct lock {
104 struct list_head locks;
105
106 char *cmdname;
107 pid_t pid;
108 char *path;
109 char *type;
110 char *mode;
111 off_t start;
112 off_t end;
113 ino_t inode;
114 dev_t dev;
115 unsigned int mandatory :1,
116 blocked :1;
117 uint64_t size;
118 int id;
119 };
120
121 static void rem_lock(struct lock *lock)
122 {
123 if (!lock)
124 return;
125
126 free(lock->path);
127 free(lock->mode);
128 free(lock->cmdname);
129 free(lock->type);
130 list_del(&lock->locks);
131 free(lock);
132 }
133
134 static void disable_columns_truncate(void)
135 {
136 size_t i;
137
138 for (i = 0; i < ARRAY_SIZE(infos); i++)
139 infos[i].flags &= ~SCOLS_FL_TRUNC;
140 }
141
142 /*
143 * Associate the device's mountpoint for a filename
144 */
145 static char *get_fallback_filename(dev_t dev)
146 {
147 struct libmnt_fs *fs;
148 char *res = NULL;
149
150 if (!tab) {
151 tab = mnt_new_table_from_file(_PATH_PROC_MOUNTINFO);
152 if (!tab)
153 return NULL;
154 }
155
156 fs = mnt_table_find_devno(tab, dev, MNT_ITER_BACKWARD);
157 if (!fs)
158 return NULL;
159
160 xasprintf(&res, "%s...", mnt_fs_get_target(fs));
161 return res;
162 }
163
164 /*
165 * Return the absolute path of a file from
166 * a given inode number (and its size)
167 */
168 static char *get_filename_sz(ino_t inode, pid_t lock_pid, size_t *size)
169 {
170 struct stat sb;
171 struct dirent *dp;
172 DIR *dirp;
173 size_t len;
174 int fd;
175 char path[PATH_MAX], sym[PATH_MAX], *ret = NULL;
176
177 *size = 0;
178 memset(path, 0, sizeof(path));
179 memset(sym, 0, sizeof(sym));
180
181 if (lock_pid < 0)
182 /* pid could be -1 for OFD locks */
183 return NULL;
184
185 /*
186 * We know the pid so we don't have to
187 * iterate the *entire* filesystem searching
188 * for the damn file.
189 */
190 snprintf(path, sizeof(path), "/proc/%d/fd/", lock_pid);
191 if (!(dirp = opendir(path)))
192 return NULL;
193
194 if ((len = strlen(path)) >= (sizeof(path) - 2))
195 goto out;
196
197 if ((fd = dirfd(dirp)) < 0 )
198 goto out;
199
200 while ((dp = readdir(dirp))) {
201 if (!strcmp(dp->d_name, ".") ||
202 !strcmp(dp->d_name, ".."))
203 continue;
204
205 errno = 0;
206
207 /* care only for numerical descriptors */
208 if (!strtol(dp->d_name, (char **) NULL, 10) || errno)
209 continue;
210
211 if (!fstatat(fd, dp->d_name, &sb, 0)
212 && inode != sb.st_ino)
213 continue;
214
215 if ((len = readlinkat(fd, dp->d_name, sym, sizeof(sym) - 1)) < 1)
216 goto out;
217
218 *size = sb.st_size;
219 sym[len] = '\0';
220
221 ret = xstrdup(sym);
222 break;
223 }
224 out:
225 closedir(dirp);
226 return ret;
227 }
228
229 /*
230 * Return the inode number from a string
231 */
232 static ino_t get_dev_inode(char *str, dev_t *dev)
233 {
234 unsigned int maj = 0, min = 0;
235 ino_t inum = 0;
236
237 if (sscanf(str, "%x:%x:%ju", &maj, &min, &inum) != 3)
238 errx(EXIT_FAILURE, _("failed to parse '%s'"), str);
239
240 *dev = (dev_t) makedev(maj, min);
241 return inum;
242 }
243
244 static int get_local_locks(struct list_head *locks)
245 {
246 int i;
247 FILE *fp;
248 char buf[PATH_MAX], *tok = NULL;
249 size_t sz;
250 struct lock *l;
251
252 if (!(fp = fopen(_PATH_PROC_LOCKS, "r")))
253 return -1;
254
255 while (fgets(buf, sizeof(buf), fp)) {
256
257 l = xcalloc(1, sizeof(*l));
258 INIT_LIST_HEAD(&l->locks);
259
260 for (tok = strtok(buf, " "), i = 0; tok;
261 tok = strtok(NULL, " "), i++) {
262
263 /*
264 * /proc/locks has *exactly* 8 "blocks" of text
265 * separated by ' ' - check <kernel>/fs/locks.c
266 */
267 switch (i) {
268 case 0: /* ID: */
269 tok[strlen(tok) - 1] = '\0';
270 l->id = strtos32_or_err(tok, _("failed to parse ID"));
271 break;
272 case 1: /* posix, flock, etc */
273 if (strcmp(tok, "->") == 0) { /* optional field */
274 l->blocked = 1;
275 i--;
276 } else
277 l->type = xstrdup(tok);
278 break;
279
280 case 2: /* is this a mandatory lock? other values are advisory or noinode */
281 l->mandatory = *tok == 'M' ? 1 : 0;
282 break;
283 case 3: /* lock mode */
284 l->mode = xstrdup(tok);
285 break;
286
287 case 4: /* PID */
288 /*
289 * If user passed a pid we filter it later when adding
290 * to the list, no need to worry now. OFD locks use -1 PID.
291 */
292 l->pid = strtos32_or_err(tok, _("failed to parse pid"));
293 if (l->pid > 0) {
294 l->cmdname = pid_get_cmdname(l->pid);
295 if (!l->cmdname)
296 l->cmdname = xstrdup(_("(unknown)"));
297 } else
298 l->cmdname = xstrdup(_("(undefined)"));
299 break;
300
301 case 5: /* device major:minor and inode number */
302 l->inode = get_dev_inode(tok, &l->dev);
303 break;
304
305 case 6: /* start */
306 l->start = !strcmp(tok, "EOF") ? 0 :
307 strtou64_or_err(tok, _("failed to parse start"));
308 break;
309
310 case 7: /* end */
311 /* replace '\n' character */
312 tok[strlen(tok)-1] = '\0';
313 l->end = !strcmp(tok, "EOF") ? 0 :
314 strtou64_or_err(tok, _("failed to parse end"));
315 break;
316 default:
317 break;
318 }
319 }
320
321 l->path = get_filename_sz(l->inode, l->pid, &sz);
322
323 /* no permissions -- ignore */
324 if (!l->path && no_inaccessible) {
325 rem_lock(l);
326 continue;
327 }
328
329 if (!l->path) {
330 /* probably no permission to peek into l->pid's path */
331 l->path = get_fallback_filename(l->dev);
332 l->size = 0;
333 } else
334 l->size = sz;
335
336 list_add(&l->locks, locks);
337 }
338
339 fclose(fp);
340 return 0;
341 }
342
343 static int column_name_to_id(const char *name, size_t namesz)
344 {
345 size_t i;
346
347 assert(name);
348
349 for (i = 0; i < ARRAY_SIZE(infos); i++) {
350 const char *cn = infos[i].name;
351
352 if (!strncasecmp(name, cn, namesz) && !*(cn + namesz))
353 return i;
354 }
355 warnx(_("unknown column: %s"), name);
356 return -1;
357 }
358
359 static inline int get_column_id(int num)
360 {
361 assert(num >= 0);
362 assert((size_t) num < ncolumns);
363 assert(columns[num] < (int) ARRAY_SIZE(infos));
364
365 return columns[num];
366 }
367
368
369 static inline const struct colinfo *get_column_info(unsigned num)
370 {
371 return &infos[ get_column_id(num) ];
372 }
373
374 static pid_t get_blocker(int id, struct list_head *locks)
375 {
376 struct list_head *p;
377
378 list_for_each(p, locks) {
379 struct lock *l = list_entry(p, struct lock, locks);
380
381 if (l->id == id && !l->blocked)
382 return l->pid;
383 }
384
385 return 0;
386 }
387
388 static void add_scols_line(struct libscols_table *table, struct lock *l, struct list_head *locks)
389 {
390 size_t i;
391 struct libscols_line *line;
392 /*
393 * Whenever cmdname or filename is NULL it is most
394 * likely because there's no read permissions
395 * for the specified process.
396 */
397 const char *notfnd = "";
398
399 assert(l);
400 assert(table);
401
402 line = scols_table_new_line(table, NULL);
403 if (!line)
404 err(EXIT_FAILURE, _("failed to allocate output line"));
405
406 for (i = 0; i < ncolumns; i++) {
407 char *str = NULL;
408
409 switch (get_column_id(i)) {
410 case COL_SRC:
411 xasprintf(&str, "%s", l->cmdname ? l->cmdname : notfnd);
412 break;
413 case COL_PID:
414 xasprintf(&str, "%d", l->pid);
415 break;
416 case COL_TYPE:
417 xasprintf(&str, "%s", l->type);
418 break;
419 case COL_INODE:
420 xasprintf(&str, "%ju", (uintmax_t) l->inode);
421 break;
422 case COL_MAJMIN:
423 if (json || raw)
424 xasprintf(&str, "%u:%u", major(l->dev), minor(l->dev));
425 else
426 xasprintf(&str, "%3u:%-3u", major(l->dev), minor(l->dev));
427 break;
428 case COL_SIZE:
429 if (!l->size)
430 break;
431 if (bytes)
432 xasprintf(&str, "%ju", l->size);
433 else
434 str = size_to_human_string(SIZE_SUFFIX_1LETTER, l->size);
435 break;
436 case COL_MODE:
437 xasprintf(&str, "%s%s", l->mode, l->blocked ? "*" : "");
438 break;
439 case COL_M:
440 xasprintf(&str, "%d", l->mandatory ? 1 : 0);
441 break;
442 case COL_START:
443 xasprintf(&str, "%jd", l->start);
444 break;
445 case COL_END:
446 xasprintf(&str, "%jd", l->end);
447 break;
448 case COL_PATH:
449 xasprintf(&str, "%s", l->path ? l->path : notfnd);
450 break;
451 case COL_BLOCKER:
452 {
453 pid_t bl = l->blocked && l->id ?
454 get_blocker(l->id, locks) : 0;
455 if (bl)
456 xasprintf(&str, "%d", (int) bl);
457 }
458 default:
459 break;
460 }
461
462 if (str && scols_line_refer_data(line, i, str))
463 err(EXIT_FAILURE, _("failed to add output data"));
464 }
465 }
466
467 static int show_locks(struct list_head *locks)
468 {
469 int rc = 0;
470 size_t i;
471 struct list_head *p, *pnext;
472 struct libscols_table *table;
473
474 table = scols_new_table();
475 if (!table)
476 err(EXIT_FAILURE, _("failed to allocate output table"));
477
478 scols_table_enable_raw(table, raw);
479 scols_table_enable_json(table, json);
480 scols_table_enable_noheadings(table, no_headings);
481
482 if (json)
483 scols_table_set_name(table, "locks");
484
485 for (i = 0; i < ncolumns; i++) {
486 struct libscols_column *cl;
487 const struct colinfo *col = get_column_info(i);
488
489 cl = scols_table_new_column(table, col->name, col->whint, col->flags);
490 if (!cl)
491 err(EXIT_FAILURE, _("failed to allocate output column"));
492
493 if (json) {
494 int id = get_column_id(i);
495
496 switch (id) {
497 case COL_SIZE:
498 if (!bytes)
499 break;
500 /* fallthrough */
501 case COL_PID:
502 case COL_START:
503 case COL_END:
504 case COL_BLOCKER:
505 case COL_INODE:
506 scols_column_set_json_type(cl, SCOLS_JSON_NUMBER);
507 break;
508 case COL_M:
509 scols_column_set_json_type(cl, SCOLS_JSON_BOOLEAN);
510 break;
511 default:
512 scols_column_set_json_type(cl, SCOLS_JSON_STRING);
513 break;
514 }
515 }
516
517 }
518
519 /* prepare data for output */
520 list_for_each(p, locks) {
521 struct lock *l = list_entry(p, struct lock, locks);
522
523 if (pid && pid != l->pid)
524 continue;
525
526 add_scols_line(table, l, locks);
527 }
528
529 /* destroy the list */
530 list_for_each_safe(p, pnext, locks) {
531 struct lock *l = list_entry(p, struct lock, locks);
532 rem_lock(l);
533 }
534
535 scols_print_table(table);
536 scols_unref_table(table);
537 return rc;
538 }
539
540
541 static void __attribute__((__noreturn__)) usage(void)
542 {
543 FILE *out = stdout;
544 size_t i;
545
546 fputs(USAGE_HEADER, out);
547
548 fprintf(out,
549 _(" %s [options]\n"), program_invocation_short_name);
550
551 fputs(USAGE_SEPARATOR, out);
552 fputs(_("List local system locks.\n"), out);
553
554 fputs(USAGE_OPTIONS, out);
555 fputs(_(" -b, --bytes print SIZE in bytes rather than in human readable format\n"), out);
556 fputs(_(" -J, --json use JSON output format\n"), out);
557 fputs(_(" -i, --noinaccessible ignore locks without read permissions\n"), out);
558 fputs(_(" -n, --noheadings don't print headings\n"), out);
559 fputs(_(" -o, --output <list> define which output columns to use\n"), out);
560 fputs(_(" --output-all output all columns\n"), out);
561 fputs(_(" -p, --pid <pid> display only locks held by this process\n"), out);
562 fputs(_(" -r, --raw use the raw output format\n"), out);
563 fputs(_(" -u, --notruncate don't truncate text in columns\n"), out);
564
565 fputs(USAGE_SEPARATOR, out);
566 printf(USAGE_HELP_OPTIONS(24));
567
568 fputs(USAGE_COLUMNS, out);
569
570 for (i = 0; i < ARRAY_SIZE(infos); i++)
571 fprintf(out, " %11s %s\n", infos[i].name, _(infos[i].help));
572
573 printf(USAGE_MAN_TAIL("lslocks(8)"));
574
575 exit(EXIT_SUCCESS);
576 }
577
578 int main(int argc, char *argv[])
579 {
580 int c, rc = 0;
581 struct list_head locks;
582 char *outarg = NULL;
583 enum {
584 OPT_OUTPUT_ALL = CHAR_MAX + 1
585 };
586 static const struct option long_opts[] = {
587 { "bytes", no_argument, NULL, 'b' },
588 { "json", no_argument, NULL, 'J' },
589 { "pid", required_argument, NULL, 'p' },
590 { "help", no_argument, NULL, 'h' },
591 { "output", required_argument, NULL, 'o' },
592 { "output-all", no_argument, NULL, OPT_OUTPUT_ALL },
593 { "notruncate", no_argument, NULL, 'u' },
594 { "version", no_argument, NULL, 'V' },
595 { "noheadings", no_argument, NULL, 'n' },
596 { "raw", no_argument, NULL, 'r' },
597 { "noinaccessible", no_argument, NULL, 'i' },
598 { NULL, 0, NULL, 0 }
599 };
600
601 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
602 { 'J','r' },
603 { 0 }
604 };
605 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
606 setlocale(LC_ALL, "");
607 bindtextdomain(PACKAGE, LOCALEDIR);
608 textdomain(PACKAGE);
609 close_stdout_atexit();
610
611 while ((c = getopt_long(argc, argv,
612 "biJp:o:nruhV", long_opts, NULL)) != -1) {
613
614 err_exclusive_options(c, long_opts, excl, excl_st);
615
616 switch(c) {
617 case 'b':
618 bytes = 1;
619 break;
620 case 'i':
621 no_inaccessible = 1;
622 break;
623 case 'J':
624 json = 1;
625 break;
626 case 'p':
627 pid = strtos32_or_err(optarg, _("invalid PID argument"));
628 break;
629 case 'o':
630 outarg = optarg;
631 break;
632 case OPT_OUTPUT_ALL:
633 for (ncolumns = 0; ncolumns < ARRAY_SIZE(infos); ncolumns++)
634 columns[ncolumns] = ncolumns;
635 break;
636 case 'n':
637 no_headings = 1;
638 break;
639 case 'r':
640 raw = 1;
641 break;
642 case 'u':
643 disable_columns_truncate();
644 break;
645
646 case 'V':
647 print_version(EXIT_SUCCESS);
648 case 'h':
649 usage();
650 default:
651 errtryhelp(EXIT_FAILURE);
652 }
653 }
654
655 INIT_LIST_HEAD(&locks);
656
657 if (!ncolumns) {
658 /* default columns */
659 columns[ncolumns++] = COL_SRC;
660 columns[ncolumns++] = COL_PID;
661 columns[ncolumns++] = COL_TYPE;
662 columns[ncolumns++] = COL_SIZE;
663 columns[ncolumns++] = COL_MODE;
664 columns[ncolumns++] = COL_M;
665 columns[ncolumns++] = COL_START;
666 columns[ncolumns++] = COL_END;
667 columns[ncolumns++] = COL_PATH;
668 }
669
670 if (outarg && string_add_to_idarray(outarg, columns, ARRAY_SIZE(columns),
671 &ncolumns, column_name_to_id) < 0)
672 return EXIT_FAILURE;
673
674 scols_init_debug(0);
675
676 rc = get_local_locks(&locks);
677
678 if (!rc && !list_empty(&locks))
679 rc = show_locks(&locks);
680
681 mnt_unref_table(tab);
682 return rc;
683 }