xaizek / vifm (License: GPLv2+) (since 2018-12-07)
Vifm is a file manager with curses interface, which provides Vi[m]-like environment for managing objects within file systems, extended with some useful ideas from mutt.
<root> / src / utils / path.c (bf73357c3ac003761a8fbdb52e0a1b0919e62e65) (15KiB) (mode 100644) [raw]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
/* vifm
 * Copyright (C) 2001 Ken Steen.
 * Copyright (C) 2011 xaizek.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include "path.h"

#ifndef _WIN32
#include <pwd.h> /* getpwnam() */
#endif
#include <unistd.h>

#include <assert.h> /* assert() */
#ifdef _WIN32
#include <ctype.h>
#endif
#include <errno.h> /* errno */
#include <stddef.h> /* NULL size_t */
#include <stdio.h>  /* snprintf() */
#include <stdlib.h> /* free() */
#include <string.h> /* memset() strcat() strcmp() strdup() strncmp() strchr()
                       strcpy() strlen() strpbrk() strrchr() */

#include "../cfg/config.h"
#include "../compat/fs_limits.h"
#include "../compat/os.h"
#include "../int/path_env.h"
#include "env.h"
#include "fs.h"
#include "str.h"
#include "utils.h"

static int skip_dotdir_if_any(const char *path[], int has_parent);
static const char * find_home_tail(const char path[]);
static char * try_replace_tilde(const char path[]);
static char * find_ext_dot(const char path[]);

void
chosp(char path[])
{
	size_t len;

	if(path[0] == '\0')
	{
		return;
	}

	len = strlen(path);
#ifndef _WIN32
	if(path[len - 1] == '/')
#else
	if(path[len - 1] == '/' || path[len - 1] == '\\')
#endif
	{
		path[len - 1] = '\0';
	}
}

int
ends_with_slash(const char *str)
{
	return str[0] != '\0' && str[strlen(str) - 1] == '/';
}

int
path_starts_with(const char path[], const char prefix[])
{
	size_t len = strlen(prefix);

	/* Special case for "/", because it doesn't fit general pattern (slash
	 * shouldn't be stripped or we get empty prefix). */
	if(prefix[0] == '/' && prefix[1] == '\0')
	{
		return (path[0] == '/');
	}

	if(len > 0U && prefix[len - 1] == '/')
	{
		--len;
	}

	return strnoscmp(path, prefix, len) == 0
	    && (path[len] == '\0' || path[len] == '/');
}

int
paths_are_equal(const char s[], const char t[])
{
	/* Some additional space is allocated for adding slashes. */
	char s_can[strlen(s) + 8];
	char t_can[strlen(t) + 8];

	canonicalize_path(s, s_can, sizeof(s_can));
	canonicalize_path(t, t_can, sizeof(t_can));

	return stroscmp(s_can, t_can) == 0;
}

void
canonicalize_path(const char directory[], char buf[], size_t buf_size)
{
	/* Source string pointer. */
	const char *p = directory;
	/* Destination string pointer. */
	char *q = buf - 1;

	memset(buf, '\0', buf_size);

#ifdef _WIN32
	/* Handle first component of a UNC path. */
	if(p[0] == '/' && p[1] == '/' && p[2] != '/')
	{
		strcpy(buf, "//");
		q = buf + 1;
		p += 2;
		while(*p != '\0' && *p != '/')
		{
			*++q = *p++;
		}
		buf = q + 1;
	}
#endif

	while(*p != '\0' && (size_t)((q + 1) - buf) < buf_size - 1U)
	{
		const int prev_dir_present = (q != buf - 1 && *q == '/');
		if(skip_dotdir_if_any(&p, prev_dir_present))
		{
			/* skip_dotdir_if_any() function did all the job for us. */
		}
		else if(prev_dir_present &&
				(strncmp(p, "../", 3) == 0 || strcmp(p, "..") == 0) &&
				!(ends_with(buf, "/../") || strcmp(buf, "../") == 0))
		{
			/* Remove the last path component added. */
#ifdef _WIN32
			/* Special handling of Windows disk name. */
			if(*(q - 1) != ':')
#endif
			{
				++p;
				--q;
				while(q >= buf && *q != '/')
				{
					--q;
				}
			}
		}
		else if(*p == '/')
		{
			/* Don't add more than one slash between path components.  And don't add
			 * leading slash if initial path is relative. */
			if(!prev_dir_present && !(q == buf - 1 && *directory != '/'))
			{
				*++q = '/';
			}
		}
		else
		{
			/* Copy current path component till the end (slash or end of
			 * line/buffer). */
			*++q = *p;
			while(p[1] != '\0' && p[1] != '/' &&
					(size_t)((q + 1) - buf) < buf_size - 1U)
			{
				*++q = *++p;
			}
		}

		++p;
	}

	/* If initial path is relative and we ended up with an empty path, produce
	 * "./". */
	if(*directory != '/' && q < buf && (size_t)((q + 1) - buf) < buf_size - 2U)
	{
		*++q = '.';
	}

	if((*directory != '\0' && q < buf) || (q >= buf && *q != '/'))
	{
		*++q = '/';
	}

	*++q = '\0';
}

/* Checks whether *path begins with current directory component ('./') and moves
 * *path to the last character of such component (to slash if present) or to the
 * previous of the last character depending on has_parent and following
 * contents of the path.  When has_parent is zero the function normalizes
 * '\.\.\.+/?' prefix on Windows to '\./?'.  Returns non-zero if a path
 * component was fully skipped. */
static int
skip_dotdir_if_any(const char *path[], int has_parent)
{
	const char *tail;

	size_t dot_count = 0U;
	while((*path)[dot_count] == '.')
	{
		++dot_count;
	}

#ifndef _WIN32
	if(dot_count != 1U)
#else
	if(dot_count == 0U || dot_count == 2U)
#endif
	{
		return 0;
	}

	tail = &(*path)[dot_count];
	if(tail[0] == '/' || tail[0] == '\0')
	{
		const int cut_off = (has_parent || (tail[0] == '/' && tail[1] == '.'));
		if(!cut_off)
		{
			--dot_count;
		}

		/* Possibly step back one character to do not fall out of the string. */
		*path += dot_count - ((*path)[dot_count] == '\0' ? 1 : 0);
		return cut_off;
	}
	return 0;
}

const char *
make_rel_path(const char path[], const char base[])
{
	static char buf[PATH_MAX + 1];

#ifdef _WIN32
	if(path[1] == ':' && base[1] == ':' && path[0] != base[0])
	{
		canonicalize_path(path, buf, sizeof(buf));
		return buf;
	}
#endif

	/* Attempt to resolve all symbolic links in paths, this should give both the
	 * shortest and valid relative path. */
	char path_real[PATH_MAX + 1], base_real[PATH_MAX + 1];
	if(os_realpath(path, path_real) == path_real)
	{
		path = path_real;
	}
	if(os_realpath(base, base_real) == base_real)
	{
		base = base_real;
	}

	const char *p = path, *b = base;
	int i;
	int nslashes;

	while(p[0] != '\0' && p[1] != '\0' && b[0] != '\0' && b[1] != '\0')
	{
		const char *op = p, *ob = b;
		if((p = strchr(p + 1, '/')) == NULL)
			p = path + strlen(path);
		if((b = strchr(b + 1, '/')) == NULL)
			b = base + strlen(base);
		if(p - path != b - base || strnoscmp(path, base, p - path) != 0)
		{
			p = op;
			b = ob;
			break;
		}
	}

	canonicalize_path(b, buf, sizeof(buf));
	chosp(buf);

	nslashes = 0;
	for(i = 0; buf[i] != '\0'; i++)
		if(buf[i] == '/')
			nslashes++;

	buf[0] = '\0';
	while(nslashes-- > 0)
		strcat(buf, "../");
	if(*p == '/')
		p++;
	if(*p != '\0')
	{
		canonicalize_path(p, buf + strlen(buf), sizeof(buf) - strlen(buf));
	}
	chosp(buf);

	if(buf[0] == '\0')
		strcpy(buf, ".");

	return buf;
}

int
is_path_absolute(const char *path)
{
#ifdef _WIN32
	if(isalpha(path[0]) && path[1] == ':')
		return 1;
	if(path[0] == '/' && path[1] == '/')
		return 1;
#endif
	return (path[0] == '/');
}

int
is_root_dir(const char *path)
{
#ifdef _WIN32
	if(isalpha(path[0]) && stroscmp(path + 1, ":/") == 0)
		return 1;

	if(path[0] == '/' && path[1] == '/' && path[2] != '\0')
	{
		char *p = strchr(path + 2, '/');
		if(p == NULL || p[1] == '\0')
			return 1;
	}
#endif
	return (path[0] == '/' && path[1] == '\0');
}

int
is_unc_root(const char *path)
{
#ifdef _WIN32
	if(is_unc_path(path) && path[2] != '\0')
	{
		char *p = strchr(path + 2, '/');
		if(p == NULL || p[1] == '\0')
			return 1;
	}
	return 0;
#else
	return 0;
#endif
}

char *
replace_home_part(const char path[])
{
	char *result = replace_home_part_strict(path);
	if(!is_root_dir(result))
	{
		chosp(result);
	}
	return result;
}

char *
replace_home_part_strict(const char path[])
{
	static char buf[PATH_MAX + 1];

	const char *home_tail = find_home_tail(path);
	if(home_tail == NULL)
	{
		copy_str(buf, sizeof(buf), path);
	}
	else
	{
		buf[0] = '~';
		buf[1] = '/';
		copy_str(buf + 2, sizeof(buf) - 2, home_tail);
	}

	return buf;
}

char *
make_tilde_path(const char path[])
{
	const char *home_tail = find_home_tail(path);
	if(home_tail == NULL)
	{
		return strdup(path);
	}

	return format_str("~/%s", home_tail);
}

/* Finds part of the path which follows home directory and any number of slashes
 * after it.  Returns pointer to the part or NULL if it's not present. */
static const char *
find_home_tail(const char path[])
{
	const size_t len = strlen(cfg.home_dir) - 1;

	/* Not using path_starts_with() because cfg.home_dir always ends with a slash
	 * and this way we can avoid repeating strlen(). */
	if(strnoscmp(path, cfg.home_dir, len) == 0 &&
			(path[len] == '\0' || path[len] == '/'))
	{
		return skip_char(path + len, '/');
	}

	return NULL;
}

char *
expand_tilde(const char path[])
{
	char *const expanded_path = try_replace_tilde(path);
	if(expanded_path == path)
	{
		return strdup(path);
	}
	return expanded_path;
}

char *
replace_tilde(char path[])
{
	char *const expanded_path = try_replace_tilde(path);
	if(expanded_path != path)
	{
		free(path);
	}
	return expanded_path;
}

/* Tries to expands tilde in the front of the path.  Returns the path or newly
 * allocated string without tilde. */
static char *
try_replace_tilde(const char path[])
{
	if(path[0] != '~')
	{
		return (char *)path;
	}

	if(path[1] == '\0' || path[1] == '/')
	{
		char *const result = format_str("%s%s", cfg.home_dir,
				(path[1] == '/') ? (path + 2) : "");
		return result;
	}

#ifndef _WIN32
	char user_name[NAME_MAX + 1];

	const char *p = until_first(path + 1, '/');
	int user_name_len = p - (path + 1);
	if(user_name_len + 1 > (int)sizeof(user_name))
	{
		return (char *)path;
	}

	copy_str(user_name, user_name_len + 1, path + 1);

	struct passwd *pw = getpwnam(user_name);
	if(pw == NULL)
	{
		return (char *)path;
	}

	return join_paths(pw->pw_dir, p);
#else
	return (char *)path;
#endif
}

char *
get_last_path_component(const char path[])
{
	char *slash = strrchr(path, '/');
	if(slash == NULL)
	{
		slash = (char *)path;
	}
	else if(slash[1] == '\0')
	{
		/* Skip slashes. */
		while(slash > path && slash[0] == '/')
		{
			--slash;
		}
		/* Skip until slash. */
		while(slash > path && slash[-1] != '/')
		{
			--slash;
		}
	}
	else
	{
		++slash;
	}
	return slash;
}

void
remove_last_path_component(char path[])
{
	char *slash;

	/* Get rid of trailing slashes, if any (in rather inefficient way). */
	while(ends_with_slash(path))
	{
		chosp(path);
	}

	slash = strrchr(path, '/');
	if(slash == NULL)
	{
		/* At most one item of path is left. */
		path[0] = '\0';
		return;
	}

	/* Take care to do not turn path in root into no path (should become just
	 * root). */
	slash[1] = '\0';
	if(!is_root_dir(path))
	{
		slash[0] = '\0';
	}
}

int
is_path_well_formed(const char *path)
{
#ifndef _WIN32
	return strchr(path, '/') != NULL;
#else
	return is_unc_path(path) || (strlen(path) >= 2 && path[1] == ':' &&
			drive_exists(path[0]));
#endif
}

void
ensure_path_well_formed(char *path)
{
	if(is_path_well_formed(path))
	{
		return;
	}

#ifndef _WIN32
	strcpy(path, "/");
#else
	strcpy(path, env_get("SYSTEMDRIVE"));
	strcat(path, "/");
#endif
}

void
to_canonic_path(const char path[], const char base[], char buf[],
		size_t buf_len)
{
	char normalized[PATH_MAX + 1];
	copy_str(normalized, sizeof(normalized), path);
	system_to_internal_slashes(normalized);

	if(!is_path_absolute(normalized))
	{
		char full_path[PATH_MAX*2 + 1];
		/* Assert is not level above to keep "." in curr_dir in tests, but this
		 * should be possible to change. */
		assert(is_path_absolute(base) && "Base path has to be absolute.");
		snprintf(full_path, sizeof(full_path), "%s/%s", base, normalized);
		canonicalize_path(full_path, buf, buf_len);
	}
	else
	{
		canonicalize_path(normalized, buf, buf_len);
	}

	if(!is_root_dir(buf))
	{
		chosp(buf);
	}
}

int
contains_slash(const char path[])
{
#ifndef _WIN32
	return (strchr(path, '/') != NULL);
#else
	return (strpbrk(path, "/\\") != NULL);
#endif
}

char *
find_slashr(const char *path)
{
	char *result = strrchr(path, '/');
#ifdef _WIN32
	if(result == NULL)
		result = strrchr(path, '\\');
#endif
	return result;
}

char *
cut_extension(char path[])
{
	char *e;
	char *ext;

	if((ext = strrchr(path, '.')) == NULL)
		return path + strlen(path);

	*ext = '\0';
	if((e = strrchr(path, '.')) != NULL && stroscmp(e + 1, "tar") == 0)
	{
		*ext = '.';
		ext = e;
	}
	*ext = '\0';

	return ext + 1;
}

void
split_ext(char path[], int *root_len, const char **ext_pos)
{
	char *const dot = find_ext_dot(path);

	if(dot == NULL)
	{
		const size_t len = strlen(path);

		*ext_pos = path + len;
		*root_len = len;

		return;
	}

	*dot = '\0';
	*ext_pos = dot + 1;
	*root_len = dot - path;
}

char *
get_ext(const char path[])
{
	char *const dot = find_ext_dot(path);

	if(dot == NULL)
	{
		return (char *)path + strlen(path);
	}

	return dot + 1;
}

/* Gets extension for file path.  Returns pointer to the dot or NULL if file
 * name has no extension. */
static char *
find_ext_dot(const char path[])
{
	const char *const basename = after_last(path, '/');
	char *const dot = strrchr(basename, '.');

	const int no_ext = dot == NULL
	                || dot == basename;
	return no_ext ? NULL : dot;
}

void
exclude_file_name(char path[])
{
	if(path_exists(path, DEREF) && !is_valid_dir(path))
	{
		remove_last_path_component(path);
	}
}

int
is_parent_dir(const char path[])
{
	return path[0] == '.' && path[1] == '.' &&
		((path[2] == '/' && path[3] == '\0') || path[2] == '\0');
}

int
is_builtin_dir(const char name[])
{
	return name[0] == '.'
	    && (name[1] == '\0' || (name[1] == '.' && name[2] == '\0'));
}

int
find_cmd_in_path(const char cmd[], size_t path_len, char path[])
{
	size_t i;
	size_t paths_count;
	char **paths;

	paths = get_paths(&paths_count);
	for(i = 0; i < paths_count; i++)
	{
		char tmp_path[PATH_MAX + 1];
		snprintf(tmp_path, sizeof(tmp_path), "%s/%s", paths[i], cmd);

		/* Need to check for executable, not just a file, as this additionally
		 * checks for path with different executable extensions on Windows. */
		if(executable_exists(tmp_path))
		{
			if(path != NULL)
			{
				copy_str(path, path_len, tmp_path);
			}
			return 0;
		}
	}
	return 1;
}

const char *
get_tmpdir(void)
{
	return env_get_one_of_def("/tmp/", "TMPDIR", "TEMP", "TEMPDIR", "TMP",
			(const char *)NULL);
}

void
build_path(char buf[], size_t buf_len, const char p1[], const char p2[])
{
	p2 = skip_char(p2, '/');
	if(p2[0] == '\0')
	{
		copy_str(buf, buf_len, p1);
	}
	else
	{
		snprintf(buf, buf_len, "%s%s%s", p1, ends_with_slash(p1) ? "" : "/", p2);
	}
}

char *
join_paths(const char p1[], const char p2[])
{
	const char *slash = (ends_with_slash(p1) ? "" : "/");
	p2 = skip_char(p2, '/');
	return format_str("%s%s%s", p1, slash, p2);
}

#ifdef _WIN32

int
is_unc_path(const char path[])
{
	return (path[0] == '/' && path[1] == '/' && path[2] != '/');
}

void
system_to_internal_slashes(char path[])
{
	replace_char(path, '\\', '/');
}

void
internal_to_system_slashes(char path[])
{
	replace_char(path, '/', '\\');
}

#endif

/* vim: set tabstop=2 softtabstop=2 shiftwidth=2 noexpandtab cinoptions-=(0 : */
/* vim: set cinoptions+=t0 filetype=c : */
Hints

Before first commit, do not forget to setup your git environment:
git config --global user.name "your_name_here"
git config --global user.email "your@email_here"

Clone this repository using HTTP(S):
git clone https://code.reversed.top/user/xaizek/vifm

Clone this repository using ssh (do not forget to upload a key first):
git clone ssh://rocketgit@code.reversed.top/user/xaizek/vifm

You are allowed to anonymously push to this repository.
This means that your pushed commits will automatically be transformed into a pull request:
... clone the repository ...
... make some changes and some commits ...
git push origin master