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