]> git.ipfire.org Git - thirdparty/util-linux.git/blame - misc-utils/lslocks.c
Use --help suggestion on invalid option
[thirdparty/util-linux.git] / misc-utils / lslocks.c
CommitLineData
3dc02ef4
DB
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>
9e930041 7 * Since it stopped being maintained over a decade ago, this
3dc02ef4
DB
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
07c916cf 35#include <libmount.h>
ba1bf716 36#include <libsmartcols.h>
07c916cf 37
3dc02ef4
DB
38#include "pathnames.h"
39#include "canonicalize.h"
40#include "nls.h"
3dc02ef4 41#include "xalloc.h"
3dc02ef4
DB
42#include "strutils.h"
43#include "c.h"
ba1bf716 44#include "list.h"
c05a80ca 45#include "closestream.h"
b3a2e889 46#include "optutils.h"
0e756dae 47#include "procutils.h"
3dc02ef4
DB
48
49/* column IDs */
50enum {
51 COL_SRC = 0,
52 COL_PID,
74fa8244 53 COL_TYPE,
3dc02ef4 54 COL_SIZE,
74fa8244 55 COL_MODE,
3dc02ef4
DB
56 COL_M,
57 COL_START,
58 COL_END,
59 COL_PATH,
7badb909 60 COL_BLOCKER
3dc02ef4
DB
61};
62
63/* column names */
64struct colinfo {
65 const char *name; /* header */
66 double whint; /* width hint (N < 1 is in percent of termwidth) */
ba1bf716 67 int flags; /* SCOLS_FL_* */
3dc02ef4
DB
68 const char *help;
69};
70
71/* columns descriptions */
c4137d39 72static struct colinfo infos[] = {
74fa8244 73 [COL_SRC] = { "COMMAND",15, 0, N_("command of the process holding the lock") },
ba1bf716
OO
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") },
74fa8244
DB
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)")},
ba1bf716
OO
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") }
3dc02ef4 83};
21abf83d
KZ
84
85static int columns[ARRAY_SIZE(infos) * 2];
40b17508 86static size_t ncolumns;
21abf83d 87
3dc02ef4 88static pid_t pid = 0;
3dc02ef4 89
07c916cf
KZ
90static struct libmnt_table *tab; /* /proc/self/mountinfo */
91
ba1bf716
OO
92/* basic output flags */
93static int no_headings;
f29bc6e1 94static int no_inaccessible;
ba1bf716 95static int raw;
b3a2e889 96static int json;
ba1bf716 97
3dc02ef4
DB
98struct lock {
99 struct list_head locks;
100
101 char *cmdname;
102 pid_t pid;
103 char *path;
104 char *type;
74fa8244 105 char *mode;
3dc02ef4
DB
106 off_t start;
107 off_t end;
55c0d16b
KZ
108 unsigned int mandatory :1,
109 blocked :1;
3dc02ef4 110 char *size;
7badb909 111 int id;
3dc02ef4
DB
112};
113
f29bc6e1
KZ
114static 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
c4137d39
KZ
128static void disable_columns_truncate(void)
129{
130 size_t i;
131
21abf83d 132 for (i = 0; i < ARRAY_SIZE(infos); i++)
ba1bf716 133 infos[i].flags &= ~SCOLS_FL_TRUNC;
c4137d39
KZ
134}
135
3dc02ef4
DB
136/*
137 * Associate the device's mountpoint for a filename
138 */
139static char *get_fallback_filename(dev_t dev)
140{
07c916cf 141 struct libmnt_fs *fs;
f29bc6e1 142 char *res = NULL;
3dc02ef4 143
07c916cf
KZ
144 if (!tab) {
145 tab = mnt_new_table_from_file(_PATH_PROC_MOUNTINFO);
146 if (!tab)
147 return NULL;
148 }
3dc02ef4 149
07c916cf
KZ
150 fs = mnt_table_find_devno(tab, dev, MNT_ITER_BACKWARD);
151 if (!fs)
152 return NULL;
3dc02ef4 153
f29bc6e1
KZ
154 xasprintf(&res, "%s...", mnt_fs_get_target(fs));
155 return res;
3dc02ef4
DB
156}
157
158/*
159 * Return the absolute path of a file from
160 * a given inode number (and its size)
161 */
7ee26cbf 162static char *get_filename_sz(ino_t inode, pid_t lock_pid, size_t *size)
3dc02ef4
DB
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 */
7ee26cbf 180 sprintf(path, "/proc/%d/fd/", lock_pid);
3dc02ef4
DB
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
2208b3cc 199 if (!fstatat(fd, dp->d_name, &sb, 0)
3dc02ef4
DB
200 && inode != sb.st_ino)
201 continue;
202
2208b3cc 203 if ((len = readlinkat(fd, dp->d_name, sym, sizeof(sym) - 1)) < 1)
3dc02ef4
DB
204 goto out;
205
206 *size = sb.st_size;
207 sym[len] = '\0';
208
209 ret = xstrdup(sym);
210 break;
fbf9034e 211 }
3dc02ef4
DB
212out:
213 closedir(dirp);
214 return ret;
215}
216
217/*
218 * Return the inode number from a string
219 */
220static ino_t get_dev_inode(char *str, dev_t *dev)
221{
64a265bf 222 unsigned int maj = 0, min = 0;
3dc02ef4
DB
223 ino_t inum = 0;
224
46d4ce56 225 sscanf(str, "%02x:%02x:%ju", &maj, &min, &inum);
3dc02ef4
DB
226
227 *dev = (dev_t) makedev(maj, min);
228 return inum;
229}
230
231static int get_local_locks(struct list_head *locks)
232{
233 int i;
234 ino_t inode = 0;
235 FILE *fp;
f29bc6e1 236 char buf[PATH_MAX], *tok = NULL;
3dc02ef4
DB
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 /*
74fa8244 253 * /proc/locks has *exactly* 8 "blocks" of text
3dc02ef4
DB
254 * separated by ' ' - check <kernel>/fs/locks.c
255 */
256 switch (i) {
7badb909
KZ
257 case 0: /* ID: */
258 tok[strlen(tok) - 1] = '\0';
259 l->id = strtos32_or_err(tok, _("failed to parse ID"));
74fa8244
DB
260 break;
261 case 1: /* posix, flock, etc */
55c0d16b
KZ
262 if (strcmp(tok, "->") == 0) { /* optional field */
263 l->blocked = 1;
264 i--;
265 } else
266 l->type = xstrdup(tok);
3dc02ef4
DB
267 break;
268
269 case 2: /* is this a mandatory lock? other values are advisory or noinode */
55c0d16b 270 l->mandatory = *tok == 'M' ? 1 : 0;
3dc02ef4 271 break;
74fa8244
DB
272 case 3: /* lock mode */
273 l->mode = xstrdup(tok);
3dc02ef4
DB
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 */
db41a429 281 l->pid = strtos32_or_err(tok, _("failed to parse pid"));
0e756dae 282 l->cmdname = proc_get_command_name(l->pid);
3dc02ef4
DB
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 :
db41a429 293 strtou64_or_err(tok, _("failed to parse start"));
3dc02ef4
DB
294 break;
295
296 case 7: /* end */
297 /* replace '\n' character */
298 tok[strlen(tok)-1] = '\0';
299 l->end = !strcmp(tok, "EOF") ? 0 :
db41a429 300 strtou64_or_err(tok, _("failed to parse end"));
3dc02ef4
DB
301 break;
302 default:
303 break;
304 }
f29bc6e1 305 }
3dc02ef4 306
f29bc6e1 307 l->path = get_filename_sz(inode, l->pid, &sz);
3dc02ef4 308
f29bc6e1
KZ
309 /* no permissions -- ignore */
310 if (!l->path && no_inaccessible) {
311 rem_lock(l);
312 continue;
3dc02ef4
DB
313 }
314
f29bc6e1
KZ
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
3dc02ef4
DB
323 list_add(&l->locks, locks);
324 }
325
326 fclose(fp);
327 return 0;
328}
329
330static int column_name_to_id(const char *name, size_t namesz)
331{
332 size_t i;
333
334 assert(name);
335
21abf83d 336 for (i = 0; i < ARRAY_SIZE(infos); i++) {
3dc02ef4
DB
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
346static inline int get_column_id(int num)
347{
40b17508
KZ
348 assert(num >= 0);
349 assert((size_t) num < ncolumns);
21abf83d 350 assert(columns[num] < (int) ARRAY_SIZE(infos));
3dc02ef4
DB
351
352 return columns[num];
353}
354
355
356static inline struct colinfo *get_column_info(unsigned num)
357{
358 return &infos[ get_column_id(num) ];
359}
360
7badb909
KZ
361static 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
ba1bf716 375static void add_scols_line(struct libscols_table *table, struct lock *l, struct list_head *locks)
3dc02ef4 376{
40b17508 377 size_t i;
ba1bf716 378 struct libscols_line *line;
3dc02ef4
DB
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);
ba1bf716 387 assert(table);
3dc02ef4 388
ba1bf716 389 line = scols_table_new_line(table, NULL);
3dc02ef4
DB
390 if (!line) {
391 warn(_("failed to add line to output"));
392 return;
393 }
394
395 for (i = 0; i < ncolumns; i++) {
396 char *str = NULL;
3dc02ef4
DB
397
398 switch (get_column_id(i)) {
399 case COL_SRC:
0d7ebfc4 400 xasprintf(&str, "%s", l->cmdname ? l->cmdname : notfnd);
3dc02ef4
DB
401 break;
402 case COL_PID:
0d7ebfc4 403 xasprintf(&str, "%d", l->pid);
3dc02ef4 404 break;
74fa8244 405 case COL_TYPE:
0d7ebfc4 406 xasprintf(&str, "%s", l->type);
74fa8244 407 break;
3dc02ef4 408 case COL_SIZE:
0d7ebfc4 409 xasprintf(&str, "%s", l->size);
3dc02ef4 410 break;
74fa8244 411 case COL_MODE:
55c0d16b 412 xasprintf(&str, "%s%s", l->mode, l->blocked ? "*" : "");
3dc02ef4
DB
413 break;
414 case COL_M:
55c0d16b 415 xasprintf(&str, "%d", l->mandatory ? 1 : 0);
3dc02ef4
DB
416 break;
417 case COL_START:
46d4ce56 418 xasprintf(&str, "%jd", l->start);
3dc02ef4
DB
419 break;
420 case COL_END:
46d4ce56 421 xasprintf(&str, "%jd", l->end);
3dc02ef4
DB
422 break;
423 case COL_PATH:
0d7ebfc4 424 xasprintf(&str, "%s", l->path ? l->path : notfnd);
3dc02ef4 425 break;
7badb909
KZ
426 case COL_BLOCKER:
427 {
428 pid_t bl = l->blocked && l->id ?
429 get_blocker(l->id, locks) : 0;
430 if (bl)
431 xasprintf(&str, "%d", (int) bl);
432 }
3dc02ef4
DB
433 default:
434 break;
435 }
436
0d7ebfc4 437 if (str)
ba1bf716 438 scols_line_set_data(line, i, str);
3dc02ef4
DB
439 }
440}
441
ba1bf716 442static int show_locks(struct list_head *locks)
3dc02ef4 443{
40b17508
KZ
444 int rc = 0;
445 size_t i;
3dc02ef4 446 struct list_head *p, *pnext;
ba1bf716 447 struct libscols_table *table;
3dc02ef4 448
0925a9dd 449 table = scols_new_table();
ba1bf716 450 if (!table) {
3dc02ef4
DB
451 warn(_("failed to initialize output table"));
452 return -1;
453 }
0925a9dd 454 scols_table_enable_raw(table, raw);
b3a2e889 455 scols_table_enable_json(table, json);
0925a9dd 456 scols_table_enable_noheadings(table, no_headings);
3dc02ef4 457
b3a2e889
KZ
458 if (json)
459 scols_table_set_name(table, "locks");
460
3dc02ef4
DB
461 for (i = 0; i < ncolumns; i++) {
462 struct colinfo *col = get_column_info(i);
463
ba1bf716 464 if (!scols_table_new_column(table, col->name, col->whint, col->flags)) {
3dc02ef4
DB
465 warnx(_("failed to initialize output column"));
466 rc = -1;
467 goto done;
468 }
469 }
470
7badb909
KZ
471 /* prepare data for output */
472 list_for_each(p, locks) {
473 struct lock *l = list_entry(p, struct lock, locks);
474
475 if (pid && pid != l->pid)
476 continue;
477
ba1bf716 478 add_scols_line(table, l, locks);
7badb909
KZ
479 }
480
481 /* destroy the list */
3dc02ef4 482 list_for_each_safe(p, pnext, locks) {
7badb909
KZ
483 struct lock *l = list_entry(p, struct lock, locks);
484 rem_lock(l);
3dc02ef4
DB
485 }
486
ba1bf716 487 scols_print_table(table);
3dc02ef4 488done:
ba1bf716 489 scols_unref_table(table);
3dc02ef4
DB
490 return rc;
491}
492
493
494static void __attribute__ ((__noreturn__)) usage(FILE * out)
495{
496 size_t i;
497
498 fputs(USAGE_HEADER, out);
499
500 fprintf(out,
501 _(" %s [options]\n"), program_invocation_short_name);
502
451dbcfa
BS
503 fputs(USAGE_SEPARATOR, out);
504 fputs(_("List local system locks.\n"), out);
505
e9b46759 506 fputs(USAGE_OPTIONS, out);
315be52f 507 fputs(_(" -J, --json use JSON output format\n"), out);
f29bc6e1 508 fputs(_(" -i, --noinaccessible ignore locks without read permissions\n"), out);
315be52f
BS
509 fputs(_(" -n, --noheadings don't print headings\n"), out);
510 fputs(_(" -o, --output <list> define which output columns to use\n"), out);
511 fputs(_(" -p, --pid <pid> display only locks held by this process\n"), out);
512 fputs(_(" -r, --raw use the raw output format\n"), out);
513 fputs(_(" -u, --notruncate don't truncate text in columns\n"), out);
514
515 fputs(USAGE_SEPARATOR, out);
516 fputs(USAGE_HELP, out);
517 fputs(USAGE_VERSION, out);
3dc02ef4
DB
518
519 fputs(_("\nAvailable columns (for --output):\n"), out);
520
21abf83d 521 for (i = 0; i < ARRAY_SIZE(infos); i++)
3dc02ef4
DB
522 fprintf(out, " %11s %s\n", infos[i].name, _(infos[i].help));
523
524 fprintf(out, USAGE_MAN_TAIL("lslocks(8)"));
525
526 exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
527}
528
529int main(int argc, char *argv[])
530{
ba1bf716 531 int c, rc = 0;
3dc02ef4 532 struct list_head locks;
e68948e1 533 char *outarg = NULL;
3dc02ef4 534 static const struct option long_opts[] = {
b3a2e889 535 { "json", no_argument, NULL, 'J' },
3dc02ef4
DB
536 { "pid", required_argument, NULL, 'p' },
537 { "help", no_argument, NULL, 'h' },
538 { "output", required_argument, NULL, 'o' },
c4137d39 539 { "notruncate", no_argument, NULL, 'u' },
3dc02ef4
DB
540 { "version", no_argument, NULL, 'V' },
541 { "noheadings", no_argument, NULL, 'n' },
542 { "raw", no_argument, NULL, 'r' },
f29bc6e1 543 { "noinaccessible", no_argument, NULL, 'i' },
3dc02ef4
DB
544 { NULL, 0, NULL, 0 }
545 };
546
b3a2e889
KZ
547 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
548 { 'J','r' },
549 { 0 }
550 };
551 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
3dc02ef4
DB
552 setlocale(LC_ALL, "");
553 bindtextdomain(PACKAGE, LOCALEDIR);
554 textdomain(PACKAGE);
c05a80ca 555 atexit(close_stdout);
3dc02ef4
DB
556
557 while ((c = getopt_long(argc, argv,
f29bc6e1 558 "iJp:o:nruhV", long_opts, NULL)) != -1) {
b3a2e889
KZ
559
560 err_exclusive_options(c, long_opts, excl, excl_st);
3dc02ef4
DB
561
562 switch(c) {
f29bc6e1
KZ
563 case 'i':
564 no_inaccessible = 1;
565 break;
b3a2e889
KZ
566 case 'J':
567 json = 1;
568 break;
3dc02ef4 569 case 'p':
db41a429 570 pid = strtos32_or_err(optarg, _("invalid PID argument"));
3dc02ef4
DB
571 break;
572 case 'o':
e68948e1 573 outarg = optarg;
3dc02ef4
DB
574 break;
575 case 'V':
576 printf(UTIL_LINUX_VERSION);
577 return EXIT_SUCCESS;
578 case 'h':
579 usage(stdout);
580 case 'n':
ba1bf716 581 no_headings = 1;
3dc02ef4
DB
582 break;
583 case 'r':
ba1bf716 584 raw = 1;
3dc02ef4 585 break;
c4137d39
KZ
586 case 'u':
587 disable_columns_truncate();
588 break;
3dc02ef4 589 default:
677ec86c 590 errtryhelp(EXIT_FAILURE);
3dc02ef4
DB
591 }
592 }
593
594 INIT_LIST_HEAD(&locks);
595
596 if (!ncolumns) {
597 /* default columns */
598 columns[ncolumns++] = COL_SRC;
599 columns[ncolumns++] = COL_PID;
74fa8244 600 columns[ncolumns++] = COL_TYPE;
3dc02ef4 601 columns[ncolumns++] = COL_SIZE;
74fa8244 602 columns[ncolumns++] = COL_MODE;
3dc02ef4
DB
603 columns[ncolumns++] = COL_M;
604 columns[ncolumns++] = COL_START;
605 columns[ncolumns++] = COL_END;
606 columns[ncolumns++] = COL_PATH;
607 }
608
e68948e1
KZ
609 if (outarg && string_add_to_idarray(outarg, columns, ARRAY_SIZE(columns),
610 &ncolumns, column_name_to_id) < 0)
611 return EXIT_FAILURE;
612
710ed55d
KZ
613 scols_init_debug(0);
614
3dc02ef4
DB
615 rc = get_local_locks(&locks);
616
617 if (!rc && !list_empty(&locks))
ba1bf716 618 rc = show_locks(&locks);
3dc02ef4 619
50fccba1 620 mnt_unref_table(tab);
3dc02ef4
DB
621 return rc;
622}