tools_eget 30.2 KB
Newer Older
Vitaly Lipatov's avatar
Vitaly Lipatov committed
1
#!/bin/sh
2
# eget - simply shell on wget for loading directories over http (wget does not support wildcard for http)
3
# Use:
4
# eget http://ftp.altlinux.ru/pub/security/ssl/*
Vitaly Lipatov's avatar
Vitaly Lipatov committed
5
#
6
# Copyright (C) 2014-2014, 2016, 2020, 2022  Etersoft
7
# Copyright (C) 2014 Daniil Mikhailov <danil@etersoft.ru>
8
# Copyright (C) 2016-2017, 2020, 2022 Vitaly Lipatov <lav@etersoft.ru>
Vitaly Lipatov's avatar
Vitaly Lipatov committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

24 25 26 27 28 29 30 31 32 33
PROGDIR=$(dirname "$0")
PROGNAME=$(basename "$0")
CMDSHELL="/bin/sh"
[ "$PROGDIR" = "." ] && PROGDIR="$(pwd)"
if [ "$0" = "/dev/stdin" ] || [ "$0" = "sh" ] ; then
    PROGDIR=""
    PROGNAME=""
fi


34 35 36 37 38 39
fatal()
{
    echo "FATAL: $*" >&2
    exit 1
}

40 41
info()
{
Vitaly Lipatov's avatar
Vitaly Lipatov committed
42
    [ -n "$quiet" ] && return
43 44 45 46 47
    echo "$*" >&2
}

eget()
{
48 49 50 51 52
	if [ -n "$EPMMODE" ] ; then
		# if embedded in epm
		(unset EGET_IPFS_GATEWAY; unset EGET_IPFS_API ; unset EGET_IPFS_DB ; internal_eget "$@" )
		return
	fi
53

54
	[ -n "$PROGNAME" ] || fatal "pipe mode is not supported"
55

56 57 58 59
	local bashopt=''
	#[ -n "$verbose" ] && bashopt='-x'

	(unset EGET_IPFS_GATEWAY; unset EGET_IPFS_API ; unset EGET_IPFS_DB ; $CMDSHELL $bashopt $PROGDIR/$PROGNAME "$@" )
60
}
61

62 63
# TODO:
arch="$(uname -m)"
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85

# copied from eepm project

# copied from /etc/init.d/outformat (ALT Linux)
isatty()
{
	# Set a sane TERM required for tput
	[ -n "$TERM" ] || TERM=dumb
	export TERM
	test -t 1
}

isatty2()
{
	# check stderr
	test -t 2
}


check_tty()
{
	isatty || return
86
	is_command tput >/dev/null 2>/dev/null || return
87
	# FreeBSD does not support tput -S
88 89
	echo | a= tput -S >/dev/null 2>/dev/null || return
	export USETTY="tput -S"
90 91 92 93 94 95
}

: ${BLACK:=0} ${RED:=1} ${GREEN:=2} ${YELLOW:=3} ${BLUE:=4} ${MAGENTA:=5} ${CYAN:=6} ${WHITE:=7}

set_boldcolor()
{
96
	[ -n "$USETTY" ] || return
97 98 99
	{
		echo bold
		echo setaf $1
100 101 102 103 104 105 106 107 108
	} | $USETTY
}

set_color()
{
	[ -n "$USETTY" ] || return
	{
		echo setaf $1
	} | $USETTY
109 110 111 112
}

restore_color()
{
113
	[ -n "$USETTY" ] || return
114 115 116
	{
		echo op; # set Original color Pair.
		echo sgr0; # turn off all special graphics mode (bold in our case).
117
	} | $USETTY
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
echover()
{
    [ -n "$verbose" ] || return
    echo "$*" >&2
}

# Print command line and run command line
showcmd()
{
	if [ -z "$quiet" ] ; then
		set_boldcolor $GREEN
		local PROMTSIG="\$"
		[ "$UID" = 0 ] && PROMTSIG="#"
		echo " $PROMTSIG $@"
		restore_color
	fi >&2
}

# Print command line and run command line
docmd()
{
	showcmd "$@"
	"$@"
}

146 147 148 149 150 151
verdocmd()
{
	[ -n "$verbose" ] && showcmd "$@"
	"$@"
}

152

153 154
# copied from epm
# print a path to the command if exists in $PATH
155
if a= which which 2>/dev/null >/dev/null ; then
156 157 158
    # the best case if we have which command (other ways needs checking)
    # TODO: don't use which at all, it is binary, not builtin shell command
print_command_path()
159
{
160
    a= which -- "$1" 2>/dev/null
161
}
162
elif a= type -a type 2>/dev/null >/dev/null ; then
163 164
print_command_path()
{
165
    a= type -fpP -- "$1" 2>/dev/null
166 167 168 169
}
else
print_command_path()
{
170
    a= type "$1" 2>/dev/null | sed -e 's|.* /|/|'
171
}
Vitaly Lipatov's avatar
Vitaly Lipatov committed
172 173
fi

174 175 176 177 178 179
# check if <arg> is a real command
is_command()
{
    print_command_path "$1" >/dev/null
}

Vitaly Lipatov's avatar
Vitaly Lipatov committed
180 181 182 183 184 185 186 187 188
# add realpath if missed
if ! is_command realpath ; then
realpath()
{
    [ -n "$*" ] || return
    readlink -f "$@"
}
fi

189

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
# check man glob
filter_glob()
{
	[ -z "$1" ] && cat && return
	# translate glob to regexp
	grep "$(echo "$1" | sed -e "s|\*|.*|g" -e "s|?|.|g")$"
}

filter_order()
{
    if [ -n "$SECONDLATEST" ] ; then
        sort -V | tail -n2 | head -n1
        return
    fi
    [ -z "$LATEST" ] && cat && return
    sort -V | tail -n1
}

208 209 210 211

is_fileurl()
{
    echo "$1" | grep -q "^/" && return
212
    echo "$1" | grep -q "^file:/"
213 214
}

215
path_from_url()
216 217 218 219 220 221
{
    echo "$1" | sed -e 's|^file://*|/|'
}

is_url()
{
222
    echo "$1" | grep -q "^[filehtps]*:/"
223 224
}

225 226 227 228 229 230 231
is_strange_url()
{
    local URL="$1"
    is_url "$URL" || return
    echo "$URL" | grep -q "[?&]"
}

232 233
is_ipfs_hash()
{
234 235 236 237
    # If a CID is 46 characters starting with "Qm", it's a CIDv0
    echo "$1" | grep -q -E "^Qm[[:alnum:]]{44}$" && return
    # TODO: CIDv1 support, see https://github.com/multiformats/cid
    return 1
238 239 240 241 242 243 244 245
}

is_ipfsurl()
{
    is_ipfs_hash "$1" && return
    echo "$1" | grep -q "^ipfs://"
}

246 247 248 249 250 251 252
is_httpurl()
{
    # TODO: improve
    echo "$1" | grep -q "^https://" & return
    echo "$1" | grep -q "^http://" & return
}

253 254
cid_from_url()
{
255
    echo "$1" | sed -e 's|^ipfs://*||' -e 's|\?.*||'
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
# args: cmd <URL> <options>
# will run cmd <options> <URL>
download_with_mirroring()
{
    local CMD="$1"
    shift
    local URL="$1"
    shift

    local res
    $CMD "$@" "$URL" && return
    res=$?
    [ -n "$CHECKMIRRORS" ] || return $res

    MIRROR="https://mirror.eterfund.ru"
    SECONDURL="$(echo "$URL" | sed -e "s|^.*://|$MIRROR/|")"
    $CMD "$@" "$SECONDURL" && URL="$SECONDURL" && return

    MIRROR="https://mirror.eterfund.org"
    SECONDURL="$(echo "$URL" | sed -e "s|^.*://|$MIRROR/|")"
    $CMD "$@" "$SECONDURL" && URL="$SECONDURL" && return
}

282

283 284 285

check_tty

Vitaly Lipatov's avatar
Vitaly Lipatov committed
286
quiet=''
287
verbose=''
288 289 290 291 292 293
WGETNOSSLCHECK=''
CURLNOSSLCHECK=''
WGETUSERAGENT=''
CURLUSERAGENT=''
WGETQ='' #-q
CURLQ='' #-s
294 295 296
# TODO: aria2c
# TODO: wget --trust-server-names
# TODO: 
297
WGETNAMEOPTIONS='--content-disposition'
298
CURLNAMEOPTIONS='--remote-name --remote-time --remote-header-name'
299

300 301
LISTONLY=''
CHECKURL=''
302
GETRESPONSE=''
303
GETFILENAME=''
304
GETREALURL=''
305
GETIPFSCID=''
306 307 308 309
LATEST=''
SECONDLATEST=''
CHECKMIRRORS=''
TARGETFILE=''
310
FORCEIPV=''
311

312

313 314 315 316
set_quiet()
{
    WGETQ='-q'
    CURLQ='-s'
Vitaly Lipatov's avatar
Vitaly Lipatov committed
317
    quiet=1
318 319 320
}


321 322
eget_help()
{
323 324 325 326 327 328
cat <<EOF

eget - wget like downloader wrapper with wildcard support in filename part of URL
Usage: eget [options] http://somesite.ru/dir/na*.log

Options:
329
    -q|--quiet                - quiet mode
330
    --verbose                 - verbose mode
331 332
    -k|--no-check-certificate - skip SSL certificate chain support
    -U|-A|--user-agent        - send browser like UserAgent
333 334
    -4|--ipv4|--inet4-only    - use only IPV4
    -6|--ipv6|--inet6-only    - use only IPV6
335 336 337 338 339 340 341 342
    -O-|-O -                  - output downloaded file to stdout
    -O file                   - download to this file
    --latest                  - print only latest version of a file
    --second-latest           - print only second to latest version of a file
    --allow-mirrors           - check mirrors if url is not accessible

    --list|--list-only        - print only URLs
    --check URL               - check if the URL is accessible (returns HTTP 200 OK)
343
    --get-response URL        - get response with all headers (ever if HEAD is not acceptable)
344
    --get-filename URL        - print filename for the URL (via Content-Disposition if applicable)
345
    --get-real-url URL        - print URL after all redirects
346

347 348 349
Supported URLs:
  ftp:// http:// https:// file:/ ipfs://

350 351
Supported backends (set like EGET_BACKEND=curl)
  wget curl (todo: aria2c)
352

353 354 355 356
Examples:
  $ eget http://ftp.somesite.ru/package-*.x64.tar
  $ eget http://ftp.somesite.ru/package *.tar
  $ eget https://github.com/owner/project package*.ext
357
  $ eget -O myname ipfs://QmVRUjnsnxHWkjq91KreCpUk4D9oZEbMwNQ3rzdjwND5dR
358 359 360 361 362 363
  $ eget --list http://ftp.somesite.ru/package-*.tar
  $ eget --check http://ftp.somesite.ru/test
  $ eget --list http://download.somesite.ru 'package-*.tar.xz'
  $ eget --list --latest https://github.com/telegramdesktop/tdesktop/releases 'tsetup.*.tar.xz'

EOF
364
}
365 366


367 368 369 370
if [ -z "$1" ] ; then
    echo "eget - wget like downloader wrapper with wildcard support, uses wget or curl as backend" >&2
    echo "Run $0 --help to get help" >&2
    exit 1
371 372 373
fi


374 375 376 377 378 379 380
while [ -n "$1" ] ; do

    case "$1" in
        -h|--help)
            eget_help
            exit
            ;;
381
        -q|--quiet)
382 383
            set_quiet
            ;;
384 385 386
        --verbose)
            verbose="$1"
            ;;
387 388 389 390 391 392 393 394 395
        -k|--no-check-certificate)
            WGETNOSSLCHECK='--no-check-certificate'
            CURLNOSSLCHECK='-k'
            ;;
        -U|-A|--user-agent)
            user_agent="Mozilla/5.0 (X11; Linux $arch) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"
            WGETUSERAGENT="-U '$user_agent'"
            CURLUSERAGENT="-A '$user_agent'"
            ;;
396 397 398 399 400 401
        -4|--ipv4|--inet4-only)
            FORCEIPV="-4"
            ;;
        -6|--ipv6|--inet6-only)
            FORCEIPV="-6"
            ;;
402
        --list|--list-only)
403 404 405 406 407
            LISTONLY="$1"
            set_quiet
            ;;
        --check)
            CHECKURL="$1"
408
            #set_quiet
409
            ;;
410 411 412
        --get-filename)
            GETFILENAME="$1"
            ;;
413 414 415
        --get-response)
            GETRESPONSE="$1"
            ;;
416 417 418
        --get-real-url)
            GETREALURL="$1"
            ;;
419 420 421
        --get-ipfs-cid)
            GETIPFSCID="$1"
            ;;
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
        --latest)
            LATEST="$1"
            ;;
        --second-latest)
            SECONDLATEST="$1"
            ;;
        --check-mirrors)
            CHECKMIRRORS="$1"
            ;;
        -O)
            shift
            TARGETFILE="$1"
            ;;
        -O-)
            TARGETFILE="-"
            ;;
        *)
            break
            ;;
    esac
442
    shift
443
done
444 445


446 447
#############################3
# defaults
448 449

# https://github.com/ipfs/kubo/issues/5541
450
ipfs_diag_timeout='--timeout 10s'
451

452 453 454 455 456 457 458 459 460 461 462 463 464 465
ipfs_api_local="/ip4/127.0.0.1/tcp/5001"
[ -n "$EGET_IPFS_API" ] && ipfs_api_local="$EGET_IPFS_API"

ipfs_api_brave="/ip4/127.0.0.1/tcp/45005"

ipfs_gateway="https://cloudflare-ipfs.com/ipfs"
[ -n "$EGET_IPFS_GATEWAY" ] && ipfs_gateway="$EGET_IPFS_GATEWAY"
IPFS_GATEWAY="$ipfs_gateway"

# Test data: https://etersoft.ru/templates/etersoft/images/logo.png
ipfs_checkQm="QmYwf2GAMvHxfFiUFL2Mr6KUG6QrDiupqGc8ms785ktaYw"

get_ipfs_brave()
{
466
    local ipfs_brave="$(ls ~/.config/BraveSoftware/Brave-Browser/*/*/go-ipfs_* 2>/dev/null)"
467 468 469 470 471 472
    [ -n "$ipfs_brave" ] && [ -x "$ipfs_brave" ] || return
    echo "$ipfs_brave"
}

ipfs_access()
{
473
    [ -n "$IPFS_CMD" ] || fatal "IPFS is disabled"
474
    verdocmd $IPFS_CMD --api $IPFS_API $ipfs_diag_timeout diag sys >/dev/null
475 476 477 478
}

ipfs_check()
{
479
    [ -n "$IPFS_CMD" ] || fatal "IPFS is disabled"
480
    verdocmd $IPFS_CMD --api $IPFS_API $ipfs_diag_timeout cat "$1" >/dev/null
481 482 483 484
}



485 486 487
select_ipfs_mode()
{
    IPFS_CMD="$(get_ipfs_brave)"
488 489
    # if no EGET_IPFS_API, check brave
    if [ -z "$EGET_IPFS_API" ] && [ -n "$IPFS_CMD" ] ; then
490 491 492 493 494
        IPFS_API="$ipfs_api_brave"
        if ipfs_access ; then
            if ipfs_check "$ipfs_checkQm" ; then
                ipfs_mode="brave" && return
            else
495
                info "Skipped Brave: it is accessible via $IPFS_CMD --api $IPFS_API, but can't return shared $ipfs_checkQm"
496 497 498 499 500 501 502 503 504 505 506
            fi
        fi
    fi

    IPFS_CMD="$(print_command_path ipfs)"
    if [ -n "$IPFS_CMD" ] ; then
        IPFS_API="$ipfs_api_local"
        if ipfs_access ; then
            if ipfs_check "$ipfs_checkQm" ; then
                ipfs_mode="local" && return
            else
507
                info "Skipped local: it is accessible via $IPFS_CMD --api $IPFS_API, but can't return shared $ipfs_checkQm"
508 509 510 511 512 513 514 515
            fi
        fi
    fi

    # TODO: check checksum
    if docmd eget --check "$ipfs_gateway/$ipfs_checkQm" ; then
        ipfs_mode="gateway"
        return
516 517 518 519 520
    fi

    IPFS_GATEWAY=''
    if docmd eget --check "$(dirname $ipfs_gateway)" ; then
       info "IPFS gateway $ipfs_gateway is accessible, but can't return shared $ipfs_checkQm"
521
    else
522
       info "IPFS gateway $(dirname $ipfs_gateway) is not accessible"
523 524 525 526
    fi

    ipfs_mode="disabled"
}
527 528


529
# Functions for work with eget ipfs db
530 531 532 533
get_cid_by_url()
{
    local URL="$1"
    [ -r "$EGET_IPFS_DB" ] || return
534
    is_fileurl "$URL" && return 1
535 536 537 538 539 540 541 542 543
    grep -F "$URL Qm" "$EGET_IPFS_DB" | head -n1 | cut -f2 -d" "
}

put_cid_and_url()
{
    local URL="$1"
    local CID="$2"
    local FN="$3"
    [ -w "$EGET_IPFS_DB" ] || return
544 545 546

    is_fileurl "$URL" && return

547
    echo "$URL $CID $FN" >> "$EGET_IPFS_DB"
548
    echo "Placed in $EGET_IPFS_DB: $URL $CID $FN"
549 550 551 552 553
}

get_filename_by_cid()
{
    local CID="$1"
554
    [ -z "$EGET_IPFS_DB" ] && basename "$CID" && return
555 556 557
    grep -F " $CID " "$EGET_IPFS_DB" | head -n1 | cut -f3 -d" "
}

558 559 560 561 562 563 564
get_url_by_cid()
{
    local CID="$1"
    [ -z "$EGET_IPFS_DB" ] && echo "$CID" && return
    grep -F " $CID " "$EGET_IPFS_DB" | head -n1 | cut -f1 -d" "
}

565 566
###################

567

568 569 570 571 572
ipfs_mode="$EGET_IPFS"

# enable auto mode when set $EGET_IPFS_DB
[ -z "$ipfs_mode" ] && [ -n "$EGET_IPFS_DB" ] && ipfs_mode="auto"

573 574 575 576 577
if [ -n "$LISTONLY$CHECKURL" ] ; then
    ipfs_mode="disabled"
    EGET_IPFS_DB=''
fi

578 579 580 581 582 583

if [ "$ipfs_mode" != "disabled" ] && [ -n "$EGET_IPFS_DB" ] ; then
    ddb="$(dirname "$EGET_IPFS_DB")"
    if [ -d "$ddb" ] ; then
        info "Using eget IPFS db $EGET_IPFS_DB"
        [ -r "$EGET_IPFS_DB" ] || touch "$EGET_IPFS_DB"
584 585 586 587 588 589
    else
        EGET_IPFS_DB=''
    fi
fi


590
# detect if we run with ipfs:// or with auto
591
if is_ipfsurl "$1" && [ -z "$ipfs_mode" ] || [ "$ipfs_mode" = "auto" ] ; then
Vitaly Lipatov's avatar
Vitaly Lipatov committed
592
    info "Autodetecting for available IPFS relay..."
593 594 595
    select_ipfs_mode
    info "Auto selected IPFS mode: $ipfs_mode"
else
596
    [ -n "$ipfs_mode" ] && [ "$ipfs_mode" != "disabled" ] && info "IPFS mode: $ipfs_mode"
597 598
fi

599 600 601 602 603 604
IPFS_CMD=''

if [ "$ipfs_mode" = "disabled" ] ; then

ipfs_get()
{
605
    fatal "IPFS is disabled"
606 607 608 609
}

ipfs_put()
{
610
    fatal "IPFS is disabled"
611 612 613 614
}

ipfs_cat()
{
615
    fatal "IPFS is disabled"
616 617 618 619 620
}


elif [ "$ipfs_mode" = "brave" ] ; then
    IPFS_CMD="$(get_ipfs_brave)" || fatal "Can't find ipfs command in Brave"
621
    IPFS_PRETTY_CMD="~Brave-Browser/$(basename $IPFS_CMD)"
622 623
    IPFS_API="$ipfs_api_brave"
    ipfs_access || fatal "Can't access to Brave IPFS API (Brave browser is not running and IPFS is not activated?)"
624
    info "Will use $IPFS_PRETTY_CMD --api $IPFS_API"
625 626 627

elif [ "$ipfs_mode" = "local" ] ; then
    IPFS_CMD="$(print_command_path ipfs)" || fatal "Can't find ipfs command"
628
    IPFS_PRETTY_CMD="$IPFS_CMD"
629 630
    IPFS_API="$ipfs_api_local"
    ipfs_access || fatal "Can't access to IPFS API (ipfs daemon is not running?)"
631
    info "Will use $IPFS_PRETTY_CMD --api $IPFS_API"
632 633

elif [ "$ipfs_mode" = "gateway" ] ; then
634
    info "Will use eget $IPFS_GATEWAY/HASH"
635 636

ipfs_get_real_url()
637 638
{
    [ -n "$IPFS_GATEWAY" ] || fatal "ipfs http gateway is not set"
639 640 641 642 643
    echo "$IPFS_GATEWAY/$1"
}

ipfs_get()
{
644
    if [ -n "$2" ] ; then
645
        docmd eget -O "$2" "$(ipfs_get_real_url "$1")"
646
    else
647
        docmd eget "$(ipfs_get_real_url "$1")"
648 649 650 651 652 653 654 655 656 657 658
    fi
}

ipfs_cat()
{
    # FIXME:
    ipfs_get "$1" "-"
}

ipfs_put()
{
659
    fatal "IPFS add disabled if a gateway is used"
660 661 662 663 664 665 666 667 668
}
elif [ -z "$ipfs_mode" ] ; then
    :
else
    fatal "Unsupported eget ipfs mode $ipfs_mode"
fi

if [ -n "$IPFS_CMD" ] ; then

669 670 671 672 673
ipfs_get_real_url()
{
    return 1
}

674 675 676 677
ipfs_get()
{
    [ -n "$IPFS_CMD" ] || fatal "ipfs api is not usable"
    if [ -n "$2" ] ; then
678 679
        showcmd $IPFS_PRETTY_CMD --api $IPFS_API get -o "$2" "$1"
        $IPFS_CMD --api $IPFS_API get -o "$2" "$1"
680
    else
681 682
        showcmd $IPFS_PRETTY_CMD --api $IPFS_API get "$1"
        $IPFS_CMD --api $IPFS_API get "$1"
683 684 685 686 687 688
    fi
}

ipfs_put()
{
    [ -n "$IPFS_CMD" ] || fatal "ipfs api is not usable"
689 690 691 692 693

    # detect if -q is used (will output Qm instead of addded Qm)
    local qu="$1"
    [ "$qu" = "-q" ] || qu=''

694
    showcmd $IPFS_PRETTY_CMD --api $IPFS_API add "$@"
695 696 697 698 699 700 701 702 703 704 705

    local res
    res="$($IPFS_CMD --api $IPFS_API add "$@")" || return

    if [ -z "$qu" ] ; then
        res="$(echo "$res" | grep "^added Qm")" || return
        res="$(echo "$res" | cut -f2 -d" ")"
    fi

    is_ipfs_hash "$res" && echo "$res" && return
    fatal "Can't recognize $res IPFS hash"
706 707 708 709 710
}

ipfs_cat()
{
    [ -n "$IPFS_CMD" ] || fatal "ipfs api is not usable"
711 712
    showcmd $IPFS_PRETTY_CMD --api $IPFS_API cat "$1"
    $IPFS_CMD --api $IPFS_API cat "$1"
713 714 715 716 717
}

fi
###############################

718 719


720
WGET="$(print_command_path wget)"
721
CURL="$(print_command_path curl)"
722

723

724
if is_fileurl "$1" ; then
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
    EGET_BACKEND="file"
elif is_ipfsurl "$1" ; then
    EGET_BACKEND="ipfs"
fi


case "$EGET_BACKEND" in
    file|ipfs)
        ;;
    wget)
        [ -n "$WGET" ] || fatal "There are no wget in the system but you forced using it via EGET_BACKEND. Install it with $ epm install wget"
        ;;
    curl)
        [ -n "$CURL" ] || fatal "There are no curl in the system but you forced using it via EGET_BACKEND. Install it with $ epm install curl"
        ;;
    '')
        [ -n "$WGET" ] && EGET_BACKEND="wget"
        [ -z "$EGET_BACKEND" ] && [ -n "$CURL" ] && EGET_BACKEND="curl"
        [ -n "$EGET_BACKEND" ] || fatal "There are no wget nor curl in the system. Install something with $ epm install wget"
        ;;
    *)
        fatal "Uknown EGET_BACKEND $EGET_BACKEND"
        ;;
esac



if [ "$EGET_BACKEND" = "file" ] ; then
753 754

# put remote content to stdout
755
url_scat()
756 757
{
    local URL="$1"
758
    cat "$(path_from_url "$URL")"
759 760
}
# download to default name of to $2
761
url_sget()
762 763 764 765 766 767
{
    local URL="$1"
    if [ "$2" = "/dev/stdout" ] || [ "$2" = "-" ] ; then
       scat "$URL"
       return
    elif [ -n "$2" ] ; then
768
       cp -av "$(path_from_url "$URL")" "$2"
769 770
       return
    fi
771
    cp -av "$(path_from_url "$URL")" .
772 773
}

774
url_check()
775 776
{
    local URL="$1"
777
    test -f "$(path_from_url "$URL")"
778 779
}

780 781 782 783 784
url_get_filename()
{
    basename "$1"
}

785 786 787 788 789
url_get_real_url()
{
    echo "$1"
}

790
elif [ "$EGET_BACKEND" = "ipfs" ] ; then
791 792

# put remote content to stdout
793
url_scat()
794 795
{
    local URL="$1"
796
    ipfs_cat "$(cid_from_url "$URL")"
797 798
}
# download to default name of to $2
799
url_sget()
800 801 802 803 804 805
{
    local URL="$1"
    if [ "$2" = "/dev/stdout" ] || [ "$2" = "-" ] ; then
       scat "$URL"
       return
    elif [ -n "$2" ] ; then
806
       ipfs_get "$(cid_from_url "$URL")" "$2"
807 808
       return
    fi
809 810 811 812 813 814 815

    local fn="$(url_print_filename_from_url "$URL")"
    if [ -n "$fn" ] ; then
       ipfs_get "$(cid_from_url "$URL")" "$fn"
       return
    fi

816
    ipfs_get "$(cid_from_url "$URL")"
817 818
}

819
url_check()
820 821 822 823 824 825
{
    local URL="$1"
    # TODO: improve me
    scat "$URL" >/dev/null
}

826 827 828 829 830 831 832
url_print_filename_from_url()
{
    local URL="$1"
    local fn="$(echo "$URL" | sed -e 's|ipfs://.*\?filename=||')"
    [ "$URL" != "$fn" ] && echo "$fn" && return
}

833 834
url_get_filename()
{
835
    local URL="$1"
836
    url_print_filename_from_url "$URL" && return
837 838 839 840
    local CID="$(cid_from_url "$URL")"
    get_filename_by_cid "$CID"
}

841 842 843 844
url_get_real_url()
{
    local URL="$1"
    local CID="$(cid_from_url "$URL")"
845 846
    # if we use gateway, return URL with gateway
    ipfs_get_real_url "$URL" && return
847 848 849
    get_url_by_cid "$CID"
}

850

851
elif [ "$EGET_BACKEND" = "wget" ] ; then
852 853 854
__wget()
{
    if [ -n "$WGETUSERAGENT" ] ; then
855
        docmd $WGET $FORCEIPV $WGETQ $WGETNOSSLCHECK "$WGETUSERAGENT" "$@"
856
    else
857
        docmd $WGET $FORCEIPV $WGETQ $WGETNOSSLCHECK "$@"
858 859
    fi
}
860

861
# put remote content to stdout
862
url_scat()
863
{
864
    local URL="$1"
865
    download_with_mirroring __wget "$URL" -O-
866 867
}
# download to default name of to $2
868
url_sget()
869
{
870
    local URL="$1"
871
    if [ "$2" = "/dev/stdout" ] || [ "$2" = "-" ] ; then
872 873
       scat "$URL"
       return
874
    elif [ -n "$2" ] ; then
875
       download_with_mirroring __wget "$URL" -O "$2"
876 877
       return
    fi
878 879 880 881
# TODO: поддержка rsync для известных хостов?
# Не качать, если одинаковый размер и дата
# -nc
# TODO: overwrite always
882
    download_with_mirroring __wget "$URL" $WGETNAMEOPTIONS
883 884
}

885
url_get_response()
886 887
{
    local URL="$1"
888
    local answer
889
    answer="$(quiet=1 __wget --spider -S "$URL" 2>&1)"
890 891
    # HTTP/1.1 405 Method Not Allowed
    if echo "$answer" | grep -q "^ *HTTP/[12.]* 405" ; then
892
        (quiet=1 __wget --start-pos=5000G -S "$URL" 2>&1)
893 894 895
        return
    fi
    echo "$answer"
896 897
}

898

899
elif [ "$EGET_BACKEND" = "curl" ] ; then
900

901 902 903
__curl()
{
    if [ -n "$CURLUSERAGENT" ] ; then
904
        docmd $CURL $FORCEIPV --fail -L $CURLQ "$CURLUSERAGENT" $CURLNOSSLCHECK "$@"
905
    else
906
        docmd $CURL $FORCEIPV --fail -L $CURLQ $CURLNOSSLCHECK "$@"
907 908
    fi
}
909
# put remote content to stdout
910
url_scat()
911
{
912
    local URL="$1"
913
    download_with_mirroring __curl "$URL" --output -
914 915
}
# download to default name of to $2
916
url_sget()
917
{
918 919
    local URL="$1"
    local res
920 921
    if [ "$2" = "/dev/stdout" ] || [ "$2" = "-" ] ; then
       scat "$1"
922
       return
923
    elif [ -n "$2" ] ; then
924
       download_with_mirroring __curl "$URL" --output "$2"
925
       return
926
    fi
927

928
    download_with_mirroring __curl "$URL" $CURLNAMEOPTIONS
929
}
930

931
url_get_response()
932 933
{
    local URL="$1"
934
    local answer
935
    answer="$(quiet=1 __curl -LI "$URL" 2>&1)"
936 937
    # HTTP/1.1 405 Method Not Allowed
    if echo "$answer" | grep -q "^ *HTTP/[12.]* 405" ; then
938
        (quiet=1 __curl -L -i -r0-0 "$URL" 2>&1)
939 940 941
        return
    fi
    echo "$answer"
942 943
}

944

945 946 947 948 949 950
fi


# Common code for both wget and curl (http related)
if [ "$EGET_BACKEND" = "wget" ] || [ "$EGET_BACKEND" = "curl" ] ; then

951 952 953 954 955 956 957 958 959
url_get_headers()
{
    local URL="$1"
    url_get_response "$URL" | grep -i "^ *[[:alpha:]].*: " | sed -e 's|^ *||' -e 's|\r$||'
}

url_check()
{
    local URL="$1"
Vitaly Lipatov's avatar
Vitaly Lipatov committed
960
    url_get_response "$URL" | grep "HTTP/" | tail -n1 | grep -q -w "200\|404"
961 962
}

963 964 965 966
url_get_header()
{
    local URL="$1"
    local HEADER="$2"
967
    url_get_headers "$URL" | grep -i "^ *$HEADER: " | sed -e "s|^ *$HEADER: ||i"
968 969
}

970 971 972 973 974 975 976 977 978
url_get_real_url()
{
    local URL="$1"

    ! is_httpurl "$URL" && echo "$URL" && return

    # don't check location if we have made form of the URL
    [ -n "$MADEURL" ] && [ "$MADEURL" = "$URL" ] && echo "$URL" && return

979
    local loc
980
    for loc in $(url_get_header "$URL" "Location" | tac | sed -e 's| .*||') ; do
981 982 983 984 985
        if ! is_strange_url "$loc" ; then
            echo "$loc"
            return
        fi
    done
986 987 988 989

    echo "$URL"
}

990 991
url_get_filename()
{
992
    local URL="$1"
993 994 995

    ! is_httpurl "$URL" && basename "$URL" && return

996
    # FIXME with wget
997
    local cd="$(url_get_header "$URL" "Content-Disposition")"
998 999
    if echo "$cd" | grep -q "filename=" ; then
        #Content-Disposition: attachment; filename=postman-linux-x64.tar.gz
1000
        #content-disposition: attachment; filename="code-1.77.1-1680651749.el7.x86_64.rpm"
1001
        echo "$cd" | sed -e 's|.*filename=||' -e 's|^"||' -e 's|";$||' -e 's|"$||'
1002 1003 1004
        return
    fi

1005
    basename "$(url_get_real_url "$URL")"
1006 1007
}

1008 1009
fi

1010

1011
if [ "$ipfs_mode" != "disabled" ] && [ -n "$EGET_IPFS_DB" ] &&  ! is_ipfsurl "$1"  ; then
1012

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
download_to_ipfs()
{
    local URL="$1"
    local res
    #res="$(url_scat "$URL" | ipfs_put )" || return
    #res="$(echo "$res" | grep "^added Qm")" || return 1
    #CID="$(echo "$res" | cut -f2 -d" ")"
    # with -q to disable progress (mixed with download progress)
    res="$(url_scat "$URL" | ipfs_put -q)" || return
    is_ipfs_hash "$res" || return 1
    echo "$res"
}

1026 1027 1028 1029
# put remote content to stdout
scat()
{
    local URL="$1"
1030 1031 1032
    url_scat "$URL"

    # It is list only function. Don't save to IPFS
1033 1034 1035
    return

    ###################
1036

1037 1038 1039 1040 1041 1042 1043
    local CID="$(get_cid_by_url "$URL")"
    if [ -n "$CID" ] ; then
        info "$URL -> $CID"
        ipfs_cat "$CID"
        return
    fi

1044
    CID="$(download_to_ipfs "$URL")" || return
1045 1046 1047 1048 1049 1050 1051

    ipfs_cat "$CID" || return

    local FN="$(url_get_filename "$URL")" || return

    put_cid_and_url "$URL" "$CID" "$FN"
}
1052

1053 1054 1055 1056
# download to default name of to $2
sget()
{
    local URL="$1"
1057
    local TARGET="$2"
1058 1059 1060 1061

    if [ -n "$GETFILENAME" ] ; then
        get_filename "$URL"
        exit
1062 1063
    fi

Vitaly Lipatov's avatar
Vitaly Lipatov committed
1064
    local REALURL="$(get_real_url "$URL")" || return
1065

Vitaly Lipatov's avatar
Vitaly Lipatov committed
1066 1067 1068 1069 1070
    if [ -n "$GETREALURL" ] ; then
        echo "$REALURL"
        exit
    fi

1071 1072 1073 1074 1075 1076 1077
    # skip ipfs for cat
    if [ "$TARGET" = "/dev/stdout" ] || [ "$TARGET" = "-" ] ; then
       url_scat "$URL"
       return
    fi


1078 1079 1080 1081 1082
    #if is_strange_url "$REALURL" ; then
    #    info "Just download strange URL $REALURL, skipping IPFS"
    #    url_sget "$REALURL" "$TARGET"
    #    return
    #fi
Vitaly Lipatov's avatar
Vitaly Lipatov committed
1083 1084

    local CID="$(get_cid_by_url "$REALURL")"
1085
    if [ -n "$CID" ] ; then
1086

1087 1088 1089 1090 1091
        if [ -n "$GETIPFSCID" ] ; then
            echo "$CID"
            exit
        fi

1092 1093 1094 1095 1096
        if [ -n "$GETFILENAME" ] ; then
            get_filename_by_cid "$CID"
            exit
        fi

1097 1098 1099 1100 1101
        if [ -n "$GETREALURL" ] ; then
            get_url_by_cid "$CID"
            exit
        fi

1102
        if [ -z "$TARGET" ] ; then
1103
            # TODO: in some cases we can get name from URL...
1104 1105 1106 1107 1108
            TARGET="$(get_filename_by_cid "$CID")"
            if [ -z "$TARGET" ] ; then
                TARGET="$CID"
            fi
        fi
Vitaly Lipatov's avatar
Vitaly Lipatov committed
1109
        [ "$URL" = "$REALURL" ] && info "$URL -> $CID -> $TARGET" || info "$URL -> $REALURL -> $CID -> $TARGET"
1110 1111 1112 1113
        ipfs_get "$CID" "$TARGET" && return

        # fail get from IPFS, fallback
        url_sget "$REALURL" "$TARGET"
1114 1115 1116
        return
    fi

1117 1118

    # download and put to IPFS
Vitaly Lipatov's avatar
Vitaly Lipatov committed
1119
    local FN="$(url_get_filename "$REALURL")" || return
1120 1121 1122 1123
    if [ -z "$TARGET" ] ; then
        TARGET="$FN"
    fi

1124
    if [ -n "$GETIPFSCID" ] ; then
1125
         # add to IPFS and print out CID
1126
         CID="$(ipfs_put --progress "$REALURL")" || return
1127 1128
         echo "$CID"
         exit
1129 1130
    fi

1131 1132
    # download file and add to IPFS
    url_sget "$REALURL" "$TARGET" || return
1133
    CID="$(ipfs_put --progress "$TARGET")" || return
1134

Vitaly Lipatov's avatar
Vitaly Lipatov committed
1135
    put_cid_and_url "$REALURL" "$CID" "$FN"
1136 1137 1138 1139 1140
}

check_url_is_accessible()
{
    local URL="$1"
Vitaly Lipatov's avatar
Vitaly Lipatov committed
1141 1142
    local REALURL="$(get_real_url "$URL")" || return
    local CID="$(get_cid_by_url "$REALURL")"
1143
    if [ -n "$CID" ] ; then
Vitaly Lipatov's avatar
Vitaly Lipatov committed
1144
        [ "$URL" = "$REALURL" ] && info "$URL -> $CID" || info "$URL -> $REALURL -> $CID"
1145 1146 1147 1148
        ipfs_check "$CID"
        return
    fi

1149
    CID="$(download_to_ipfs "$REALURL")" || return
1150

Vitaly Lipatov's avatar
Vitaly Lipatov committed
1151
    local FN="$(url_get_filename "$REALURL")" || return
1152
    ipfs_cat "$CID" >/dev/null || return
Vitaly Lipatov's avatar
Vitaly Lipatov committed
1153
    put_cid_and_url "$REALURL" "$CID" "$FN"
1154 1155 1156 1157 1158 1159 1160
}

get_filename()
{
    url_get_filename "$1"
}

1161 1162 1163 1164 1165
get_real_url()
{
    url_get_real_url "$1"
}

1166
else
1167 1168 1169 1170 1171 1172 1173
scat()
{
    url_scat "$@"
}

sget()
{
1174 1175 1176 1177 1178
    if [ -n "$GETFILENAME" ] ; then
        get_filename "$1"
        exit
    fi

1179 1180 1181 1182 1183
    if [ -n "$GETREALURL" ] ; then
        get_real_url "$1"
        exit
    fi

1184 1185 1186 1187 1188 1189 1190
    url_sget "$@"
}

check_url_is_accessible()
{
    url_check "$@"
}
1191 1192 1193 1194 1195 1196

get_filename()
{
    url_get_filename "$1"
}

Vitaly Lipatov's avatar
Vitaly Lipatov committed
1197 1198 1199 1200 1201
get_real_url()
{
    url_get_real_url "$1"
}

1202 1203 1204
fi


1205 1206 1207 1208 1209 1210 1211
get_github_urls()
{
    # https://github.com/OWNER/PROJECT
    local owner="$(echo "$1" | sed -e "s|^https://github.com/||" -e "s|/.*||")" #"
    local project="$(echo "$1" | sed -e "s|^https://github.com/$owner/||" -e "s|/.*||")" #"
    [ -n "$owner" ] || fatal "Can't get owner from $1"
    [ -n "$project" ] || fatal "Can't get project from $1"
1212
    local URL="https://api.github.com/repos/$owner/$project/releases"
1213
    scat $URL | \
1214 1215 1216
        grep -i -o -E '"browser_download_url": "https://.*"' | cut -d'"' -f4
}

1217 1218 1219 1220 1221 1222
# drop file path from URL
get_host_only()
{
    echo "$1/" | grep -Eo '(.*://[^/]+)'
}

1223 1224 1225 1226 1227 1228 1229 1230
concatenate_url_and_filename()
{
    local url="$1"
    local fn="$2"
    # workaround for a slash in the end of URL
    echo "$(echo "$url" | sed -e 's|/*$||' )/$fn"
}

1231 1232 1233
# MADEURL filled with latest made URL as flag it is end form of URL
MADEURL=''

1234 1235 1236 1237 1238
# Args: URL filename
make_fileurl()
{
    local url="$1"
    local fn="$2"
1239

1240
    fn="$(echo "$fn" | sed -e 's|^./||' -e 's|^/+||')"
1241

1242
    if is_fileurl "$url" ; then
1243 1244 1245 1246 1247 1248 1249 1250
        # if it is url
        :
    elif echo "$fn" | grep -q "^/" ; then
        # if there is file path from the root of the site
        url="$(get_host_only "$url")"
    elif echo "$url" | grep -q -v "/$" ; then
        # if there is no slash in the end of URL
        url="$(dirname "$url")"
1251
    fi
1252

1253 1254
    MADEURL="$(concatenate_url_and_filename "$url" "$fn")"
    echo "$MADEURL"
1255 1256
}

1257
get_urls()
Vitaly Lipatov's avatar
Vitaly Lipatov committed
1258
{
1259
    if is_fileurl "$URL" ; then
1260
        ls -1 "$(path_from_url "$URL")"
1261 1262 1263
        return
    fi

1264
    # cat html, divide to lines by tags and cut off hrefs only
1265
    scat $URL | sed -e 's|<|<\n|g' -e 's|data-file=|href=|g' -e "s|'|\"|g" | \
1266
         grep -i -o -E 'href="(.+)"' | cut -d'"' -f2
Vitaly Lipatov's avatar
Vitaly Lipatov committed
1267 1268
}

1269 1270

if [ -n "$CHECKURL" ] ; then
1271
    #set_quiet
1272 1273 1274 1275 1276 1277 1278
    URL="$1"
    check_url_is_accessible "$URL"
    res=$?
    if [ -n "$verbose" ] ; then
        [ "$res" = "0" ] && echo "$URL is accessible via network" || echo "$URL is NOT accessible via network"
    fi
    exit $res
1279 1280
fi

1281 1282 1283 1284 1285
if [ -n "$GETRESPONSE" ] ; then
    url_get_response "$1"
    exit
fi

1286 1287

# separate part for github downloads
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
if echo "$1" | grep -q "^https://github.com/" && \
   echo "$1" | grep -q -v "/download/" && [ -n "$2" ] ; then
    MASK="$2"

    if [ -n "$LISTONLY" ] ; then
        get_github_urls "$1" | filter_glob "$MASK" | filter_order
        exit
    fi

    ERROR=0
    for fn in $(get_github_urls "$1" | filter_glob "$MASK" | filter_order) ; do
1299
        MADEURL="$fn" # mark it is the end form of the URL
1300 1301 1302 1303 1304 1305
        sget "$fn" "$TARGETFILE" || ERROR=1
        [ -n "$TARGETFILE" ] && [ "$ERROR" = "0" ] && break
    done
    exit
fi

1306 1307 1308 1309 1310
if is_ipfsurl "$1" ; then
    [ -n "$2" ] && fatal "too many args when ipfs://Qm... used: extra '$2' arg"
    sget "$1" "$TARGETFILE"
    exit
fi
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323

# if mask is the second arg
if [ -n "$2" ] ; then
    URL="$1"
    MASK="$2"
else
    # do not support / at the end without separately specified mask
    if echo "$1" | grep -q "/$" ; then
        fatal "Use http://example.com/e/* to download all files in dir"
    fi

    # drop mask part
    URL="$(dirname "$1")/"
1324 1325
    # wildcards allowed only in the last part of path
    MASK=$(basename "$1")
1326 1327
fi

1328 1329 1330
# https://www.freeoffice.com/download.php?filename=freeoffice-2021-1062.x86_64.rpm
if echo "$URL" | grep -q "[*]" ; then
    fatal "Error: there are globbing symbol (*) in $URL. It is allowed only for mask part"
1331 1332
fi

1333 1334
is_url "$MASK" && fatal "eget supports only one URL as argument"
[ -n "$3" ] && fatal "too many args: extra '$3'. May be you need use quotes for arg with wildcards."
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344

# TODO: curl?
# If ftp protocol, just download
if echo "$URL" | grep -q "^ftp://" ; then
    [ -n "$LISTONLY" ] && fatal "TODO: list files for ftp:// is not supported yet"
    sget "$1" "$TARGETFILE"
    exit
fi


1345 1346 1347 1348 1349 1350 1351 1352
if [ -n "$LISTONLY" ] ; then
    for fn in $(get_urls | filter_glob "$MASK" | filter_order) ; do
        is_url "$fn" && echo "$fn" && continue
        make_fileurl "$URL" "$fn"
    done
    exit
fi

1353 1354 1355 1356 1357 1358
# If there is no wildcard symbol like asterisk, just download
if echo "$MASK" | grep -qv "[*?]" || echo "$MASK" | grep -q "[?].*="; then
    sget "$1" "$TARGETFILE"
    exit
fi

1359
ERROR=0
1360
for fn in $(get_urls | filter_glob "$MASK" | filter_order) ; do
1361
    is_url "$fn" || fn="$(make_fileurl "$URL" "$fn" )" #"
1362 1363
    sget "$fn" "$TARGETFILE" || ERROR=1
    [ -n "$TARGETFILE" ] && [ "$ERROR" = "0" ] && break
1364 1365
done
exit $ERROR
Vitaly Lipatov's avatar
Vitaly Lipatov committed
1366