├── .editorconfig ├── .github └── workflows │ └── build.yml ├── .gitignore ├── .gitmodules ├── AUTHORS ├── LICENSE ├── Makefile ├── README.md ├── com.github.dimkr.gplaces.appdata.xml ├── finger.c ├── gopher.c ├── gophers.c ├── gplaces.1 ├── gplaces.c ├── gplaces.desktop.in ├── gplaces.svg ├── gplacesrc.in ├── guppy.c ├── prompt.png ├── queue.h ├── socket.c ├── spartan.c ├── tcp.c └── titan.c /.editorconfig: -------------------------------------------------------------------------------- 1 | # top-most EditorConfig file 2 | root = true 3 | 4 | # Unix-style newlines with a newline ending every file 5 | [*] 6 | end_of_line = lf 7 | insert_final_newline = true 8 | charset = utf-8 9 | indent_style = tab 10 | indent_size = 4 11 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: 4 | push: 5 | pull_request: 6 | schedule: 7 | - cron: '0 0 * * 4' 8 | workflow_dispatch: 9 | 10 | jobs: 11 | debian: 12 | runs-on: ubuntu-latest 13 | strategy: 14 | matrix: 15 | image: ["ubuntu:jammy", "ubuntu:latest", "debian:bullseye-slim", "debian:stable-slim", "debian:sid-slim"] 16 | container: 17 | image: ${{ matrix.image }} 18 | steps: 19 | - name: Install dependencies 20 | run: | 21 | apt-get update -qq 22 | apt-get install --no-install-recommends -y git ca-certificates gcc libc6-dev make pkg-config libssl-dev libcurl4-openssl-dev libidn2-dev libidn11-dev libmagic-dev 23 | - name: Checkout code 24 | uses: actions/checkout@v2 25 | with: 26 | path: gplaces # mitigation for build failure after CVE-2022-24765 was mitigated 27 | submodules: recursive 28 | fetch-depth: 0 29 | - name: Build 30 | run: | 31 | cd gplaces 32 | CFLAGS="-O3 -Wall -Wextra -pedantic -Wno-unused-result -Wstack-usage=1024 -Werror" make install 33 | make uninstall 34 | make clean 35 | CFLAGS="-O0 -Wall -Wextra -pedantic -Wno-unused-result -Werror" make WITH_LIBIDN2=0 36 | make clean 37 | CFLAGS="-O0 -Wall -Wextra -pedantic -Wno-unused-result -Werror" make WITH_LIBIDN2=0 WITH_LIBIDN=0 38 | make clean 39 | CFLAGS="-O0 -Wall -Wextra -pedantic -Wno-unused-result -Werror" make WITH_LIBMAGIC=0 40 | make clean 41 | CFLAGS="-O0 -Wall -Wextra -pedantic -Wno-unused-result -Werror" make WITH_TITAN=0 WITH_GOPHER=0 WITH_GOPHERS=0 WITH_SPARTAN=0 WITH_FINGER=0 WITH_GUPPY=0 42 | make clean 43 | CFLAGS="-O0 -Wall -Wextra -pedantic -Wno-unused-result -Werror" make WITH_GOPHER=0 WITH_GOPHERS=1 44 | alpine: 45 | runs-on: ubuntu-latest 46 | strategy: 47 | matrix: 48 | include: 49 | - image: "alpine:3.15" 50 | libssl: openssl 51 | - image: "alpine:3.15" 52 | libssl: libressl 53 | - image: "alpine:latest" 54 | libssl: openssl 55 | - image: "alpine:edge" 56 | libssl: openssl 57 | container: 58 | image: ${{ matrix.image }} 59 | steps: 60 | - name: Install dependencies 61 | run: | 62 | apk add git gcc musl-dev make pkgconf ${{ matrix.libssl }}-dev curl-dev libidn-dev file-dev 63 | - name: Checkout code 64 | uses: actions/checkout@v2 65 | with: 66 | path: gplaces # mitigation for build failure after CVE-2022-24765 was mitigated 67 | submodules: recursive 68 | fetch-depth: 0 69 | - name: Build 70 | run: | 71 | cd gplaces 72 | CFLAGS="-O3 -Wall -Wextra -pedantic -Wno-unused-result -Wstack-usage=1024 -Werror" make install 73 | make uninstall 74 | make clean 75 | CFLAGS="-O0 -Wall -Wextra -pedantic -Wno-unused-result -Werror" make WITH_LIBIDN=0 76 | make clean 77 | CFLAGS="-O0 -Wall -Wextra -pedantic -Wno-unused-result -Werror" make WITH_LIBMAGIC=0 78 | make clean 79 | CFLAGS="-O0 -Wall -Wextra -pedantic -Wno-unused-result -Werror" make WITH_TITAN=0 WITH_GOPHER=0 WITH_GOPHERS=0 WITH_SPARTAN=0 WITH_FINGER=0 WITH_GUPPY=0 80 | make clean 81 | CFLAGS="-O0 -Wall -Wextra -pedantic -Wno-unused-result -Werror" make WITH_GOPHER=0 WITH_GOPHERS=1 82 | arch: 83 | runs-on: ubuntu-latest 84 | container: 85 | image: archlinux:base 86 | steps: 87 | - name: Install dependencies 88 | run: | 89 | pacman -Syu --noconfirm 90 | pacman -S --noconfirm git gcc make pkgconf libidn 91 | - name: Checkout code 92 | uses: actions/checkout@v2 93 | with: 94 | path: gplaces # mitigation for build failure after CVE-2022-24765 was mitigated 95 | submodules: recursive 96 | fetch-depth: 0 97 | - name: Build 98 | run: | 99 | cd gplaces 100 | CFLAGS="-O3 -Wall -Wextra -pedantic -Wno-unused-result -Wstack-usage=1024 -Werror" make install 101 | make uninstall 102 | make clean 103 | CFLAGS="-O0 -Wall -Wextra -pedantic -Wno-unused-result -Werror" make WITH_LIBIDN2=0 104 | make clean 105 | CFLAGS="-O0 -Wall -Wextra -pedantic -Wno-unused-result -Werror" make WITH_LIBIDN2=0 WITH_LIBIDN=0 106 | make clean 107 | CFLAGS="-O0 -Wall -Wextra -pedantic -Wno-unused-result -Werror" make WITH_LIBMAGIC=0 108 | make clean 109 | CFLAGS="-O0 -Wall -Wextra -pedantic -Wno-unused-result -Werror" make WITH_TITAN=0 WITH_GOPHER=0 WITH_GOPHERS=0 WITH_SPARTAN=0 WITH_FINGER=0 WITH_GUPPY=0 110 | make clean 111 | CFLAGS="-O0 -Wall -Wextra -pedantic -Wno-unused-result -Werror" make WITH_GOPHER=0 WITH_GOPHERS=1 112 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /gplaces 2 | /*.o 3 | /gplacesrc 4 | /gplaces.desktop 5 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "bestline"] 2 | path = bestline 3 | url = https://github.com/jart/bestline 4 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Sebastian Steinhauer 2 | Dima Krasner 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # see LICENSE for copyright and license details 2 | PREFIX = /usr/local 3 | CONFDIR ?= $(PREFIX)/etc 4 | CC = cc 5 | CFLAGS ?= -O2 -Wall -Wextra -Wno-unused-result 6 | VERSION ?= $(shell git describe --tags 2>/dev/null | sed s/^v//) 7 | ifeq ($(VERSION),) 8 | VERSION = ? 9 | endif 10 | CFLAGS += -D_GNU_SOURCE -DPREFIX=\"$(PREFIX)\" -DCONFDIR=\"$(CONFDIR)\" -DGPLACES_VERSION=\"$(VERSION)\" $(shell pkg-config --cflags libcurl libssl libcrypto) 11 | LDFLAGS ?= 12 | LDFLAGS += $(shell pkg-config --libs libcurl libssl libcrypto) 13 | MIMETYPES = 14 | KEYWORDS = 15 | WITH_TITAN ?= 1 16 | ifeq ($(WITH_TITAN),1) 17 | CFLAGS += -DGPLACES_WITH_TITAN 18 | MIMETYPES := $(MIMETYPES);x-scheme-handler/titan 19 | KEYWORDS := $(KEYWORDS);titan 20 | endif 21 | WITH_GOPHER ?= 1 22 | ifeq ($(WITH_GOPHER),1) 23 | CFLAGS += -DGPLACES_WITH_GOPHER 24 | MIMETYPES := $(MIMETYPES);x-scheme-handler/gopher 25 | KEYWORDS := $(KEYWORDS);gopher 26 | endif 27 | WITH_GOPHERS ?= 1 28 | ifeq ($(WITH_GOPHERS),1) 29 | CFLAGS += -DGPLACES_WITH_GOPHERS 30 | MIMETYPES := $(MIMETYPES);x-scheme-handler/gophers 31 | KEYWORDS := $(KEYWORDS);gophers 32 | endif 33 | WITH_SPARTAN ?= 1 34 | ifeq ($(WITH_SPARTAN),1) 35 | CFLAGS += -DGPLACES_WITH_SPARTAN 36 | MIMETYPES := $(MIMETYPES);x-scheme-handler/spartan 37 | KEYWORDS := $(KEYWORDS);spartan 38 | endif 39 | WITH_FINGER ?= 1 40 | ifeq ($(WITH_FINGER),1) 41 | CFLAGS += -DGPLACES_WITH_FINGER 42 | MIMETYPES := $(MIMETYPES);x-scheme-handler/finger 43 | KEYWORDS := $(KEYWORDS);finger 44 | endif 45 | WITH_GUPPY ?= 1 46 | ifeq ($(WITH_GUPPY),1) 47 | CFLAGS += -DGPLACES_WITH_GUPPY 48 | MIMETYPES := $(MIMETYPES);x-scheme-handler/guppy 49 | KEYWORDS := $(KEYWORDS);guppy 50 | endif 51 | WITH_LIBIDN2 ?= $(shell pkg-config --exists libidn2 && echo 1 || echo 0) 52 | ifeq ($(WITH_LIBIDN2),1) 53 | CFLAGS += -DGPLACES_USE_LIBIDN2 $(shell pkg-config --cflags libidn2) 54 | LDFLAGS += $(shell pkg-config --libs libidn2) 55 | else 56 | WITH_LIBIDN ?= $(shell pkg-config --exists libidn && echo 1 || echo 0) 57 | ifeq ($(WITH_LIBIDN),1) 58 | CFLAGS += -DGPLACES_USE_LIBIDN $(shell pkg-config --cflags libidn) 59 | LDFLAGS += $(shell pkg-config --libs libidn) 60 | endif 61 | endif 62 | WITH_LIBMAGIC ?= $(shell pkg-config --exists libmagic && echo 1 || echo 0) 63 | ifeq ($(WITH_LIBMAGIC),1) 64 | CFLAGS += -DGPLACES_USE_LIBMAGIC $(shell pkg-config --cflags libmagic) 65 | LDFLAGS += $(shell pkg-config --libs libmagic) 66 | endif 67 | ifeq ($(WITH_FLATPAK_SPAWN),1) 68 | CFLAGS += -DGPLACES_USE_FLATPAK_SPAWN 69 | endif 70 | OBJ = bestline/bestline.o gplaces.o 71 | BIN = gplaces 72 | 73 | all: $(BIN) gplacesrc gplaces.desktop 74 | 75 | $(BIN): $(OBJ) 76 | $(CC) $(CFLAGS) -o $(BIN) $(OBJ) $(LDFLAGS) 77 | 78 | gplaces.o: gplaces.c titan.c gopher.c gophers.c spartan.c finger.c guppy.c tcp.c socket.c 79 | 80 | gplaces.desktop: gplaces.desktop.in 81 | @sed -e "s~^MimeType=.*~&$(MIMETYPES)~" -e "s~^Keywords=.*~&$(KEYWORDS)~" $< > $@ 82 | 83 | gplacesrc: gplacesrc.in 84 | sed s~DOCDIR~$(PREFIX)/share/doc/gplaces~g $^ > $@ 85 | 86 | .PHONY: clean 87 | clean: 88 | @rm -f $(BIN) $(OBJ) gplacesrc gplaces.desktop 89 | 90 | install: all 91 | @install -D -m 755 $(BIN) $(DESTDIR)$(PREFIX)/bin/${BIN} 92 | @install -D -m 644 gplacesrc $(DESTDIR)$(CONFDIR)/gplacesrc 93 | @install -D -m 644 README.md $(DESTDIR)$(PREFIX)/share/doc/gplaces/README.gmi 94 | @install -m 644 LICENSE $(DESTDIR)$(PREFIX)/share/doc/gplaces/LICENSE 95 | @install -m 644 AUTHORS $(DESTDIR)$(PREFIX)/share/doc/gplaces/AUTHORS 96 | @install -D -m 644 gplaces.1 $(DESTDIR)$(PREFIX)/share/man/man1/gplaces.1 97 | @install -D -m 644 gplaces.svg $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/apps/gplaces.svg 98 | @install -D -m 644 gplaces.desktop $(DESTDIR)$(PREFIX)/share/applications/gplaces.desktop 99 | @install -D -m 644 com.github.dimkr.gplaces.appdata.xml $(DESTDIR)$(PREFIX)/share/metainfo/com.github.dimkr.gplaces.appdata.xml 100 | 101 | uninstall: 102 | @rm -f $(DESTDIR)$(PREFIX)/bin/$(BIN) 103 | @rm -f $(DESTDIR)$(CONFDIR)/gplacesrc 104 | @rm -rf $(DESTDIR)$(PREFIX)/share/doc/gplaces 105 | @rm -f $(DESTDIR)$(PREFIX)/share/man/man1/gplaces.1 106 | @rm -f $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/apps/gplaces.svg 107 | @rm -f $(DESTDIR)$(PREFIX)/share/applications/gplaces.desktop 108 | @rm -f $(DESTDIR)$(PREFIX)/share/metainfo/com.github.dimkr.gplaces.appdata.xml 109 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # gplaces - a simple terminal Gemini client 2 | 3 | Because Gemini deserves a light client with a high power to weight ratio! 4 | 5 | gplaces is named after Going Places, the 1965 album by Herb Alpert and The Tijuana Brass. The "o" is omitted from the executable name so it doesn't mess up tab completion for Gopher users and Go developers. 6 | 7 | => https://en.wikipedia.org/wiki/Going_Places_(Herb_Alpert_and_the_Tijuana_Brass_album) Going Places 8 | 9 | The gplaces logo is an artist's impression of a Gemini VII capsule with the red accents of a Humes and Berg Stonelined straight trumpet mute. Sort of. 10 | 11 | => https://humesandberg.com Humes and Berg 12 | 13 | gplaces is originally a Gemini port of the delve Gopher client by Sebastian Steinhauer. 14 | 15 | => https://github.com/kieselsteini/delve delve 16 | 17 | ## Features 18 | 19 | * SSH-style TOFU with $XDG_DATA_HOME/gplaces_hosts or ~/.gplaces_hosts 20 | * client certificates support via $XDG_DATA_HOME/gplaces_$host_$port_$path.{crt,key} or ~/.gplaces_$host_$port_$path.{crt,key} 21 | * subscriptions 22 | * permanent redirects with $XDG_DATA_HOME/gplaces_redirects or ~/.gplaces_redirects 23 | * support for non-interactive operation 24 | * single configuration file: $XDG_DATA_HOME/gplacesrc, ~/.gplacesrc or /etc/gplacesrc 25 | * configurable MIME type handlers, with support for streaming to stdin 26 | * "powerful" shell with tab completion, hints and aliases 27 | * VT100 compatible with ANSI escape sequences and NO_COLOR support 28 | * sh-style history with $XDG_DATA_HOME/gplaces_history or ~/.gplaces_history 29 | * UTF-8 word wrapping 30 | * configurable external pager 31 | * optional Titan support 32 | * optional Gopher support 33 | * optional gophers:// (Gopher+TLS+TOFU) support 34 | * optional Spartan support 35 | * optional Finger support 36 | * optional Guppy support 37 | * small, hackable codebase 38 | * no exotic external dependencies, no NIH: bestline, openssl or libressl, libcurl, libidn2 or libidn (optional) and libmagic (optional) 39 | * ~100K executable when built with -O3 and -Wl,-s on x86_64 40 | 41 | ## How to install? 42 | 43 | * Using Flatpak: `flatpak install com.github.dimkr.gplaces` 44 | * compile yourself 45 | 46 | => https://flathub.org/apps/details/com.github.dimkr.gplaces gplaces on Flathub 47 | 48 | ## How to compile? 49 | 50 | * clone this repo: `git clone --recursive https://github.com/dimkr/gplaces` 51 | * type `cd gplaces` 52 | * type `make PREFIX=/usr CONFDIR=/etc`, or `make WITH_TITAN=0 WITH_GOPHER=0 WITH_GOPHERS=0 WITH_SPARTAN=0 WITH_FINGER=0 WITH_GUPPY=0 WITH_LIBIDN2=0 WITH_LIBIDN=0 WITH_LIBMAGIC=0` to disable all optional dependencies and features 53 | * type `make install` to install it on the system (defaults to /usr/local) 54 | 55 | ## How to use? 56 | 57 | ``` 58 | > gemini.circumlunar.space 59 | ``` 60 | 61 | to show a Gemini page, type its URL, press `ENTER` and gplaces will stream the page contents to the terminal. 62 | 63 | to abort the download, press `CTRL+c`. 64 | 65 | when the download is finished, gplaces will display the downloaded page using less(1), the same tool man(1) uses to display man pages. 66 | 67 | ``` 68 | `less -r` has exited with exit status 0 69 | gemini.circumlunar.space/> 70 | ``` 71 | 72 | use the arrow keys to scroll, `/` to search and `q` to exit less and return to the gplaces prompt. 73 | 74 | ``` 75 | (reverse-i-search `g') gemini.circumlunar.space 76 | ``` 77 | 78 | in addition, gplaces adds the page URL to the history: use the `Up` and `Down` keys to navigate through the history, or `CTRL+r` to search through it. these are only three examples of key bindings from shells like bash(1) which work in gplaces, too: see bestline/README.md for a list of navigation and editing shortcuts. 79 | 80 | ``` 81 | cached 2023-04-29 19:41:44 82 | gemini.circumlunar.space/> 83 | ``` 84 | 85 | if you visit the same page again, gplaces will return a cached copy and show the time the page was fetched. gplaces remembers up to `histsize` pages, so you can return to previously viewed pages immediately, without downloading them again. type `get` and press `ENTER` to force gplaces to fetch a cached page again. 86 | 87 | ``` 88 | > gemini://konpeito.media/konpeito-09-a.mp3 89 | ``` 90 | 91 | gplaces displays only Gemtext, gophermaps or plain text files: it downloads other kinds of files (like images, audio and video) to temporary files and runs external "handler" programs (one for each file type) defined in the gplaces configuration file. 92 | 93 | ``` 94 | > save gemini.circumlunar.space/docs/specification.gmi 95 | enter filename: /home/user/Downloads/specification.gmi 96 | ``` 97 | 98 | to download a file instead of displaying it or saving it to a temporary file, type `save`, followed by its URL, then press `ENTER`. 99 | 100 | ``` 101 | > save gemini.circumlunar.space/docs/specification.gmi /tmp/spec.gmi 102 | ``` 103 | 104 | you can also specify the destination path and skip the prompt. 105 | 106 | ``` 107 | > save gemini://konpeito.media/konpeito-09-a.mp3 - 108 | ``` 109 | 110 | alternatively, to stream a file into standard input of the handler program without saving to a file on disk and waiting for the download to complete, use `-` as the download destination. this is useful for audio or video streaming, and works only with some programs and some file formats. 111 | 112 | ``` 113 | gemini.circumlunar.space/> 2 docs/ 114 | ``` 115 | 116 | gplaces associates a number with each link in the last viewed page. type the number of a link to show its URL, then press `ENTER` to follow it. 117 | 118 | to edit the URL of a link, type the link number, press `Tab`, edit the URL and press `ENTER`. for example, this is useful if a link leads to a post in another gemlog, but you want to see its homepage. 119 | 120 | ``` 121 | gemini.circumlunar.space/> #gemini://gemini.circumlunar.space/docs/ 122 | gemini.circumlunar.space/> 123 | ``` 124 | 125 | the history can be used as a reading list: prefix a URL with `#` and press `ENTER` to add it to the history without opening it first. for example, to add the URL of link 2 to the history, type `2`, press `Tab` to edit the URL, press `CTRL+a` or `Home` to go to the beginning of the line, type `#` and press `ENTER`. to open this URL later, press the `Up` key, press `CTRL+a` or `Home`, press `Delete` to remove the leading `#`, then press `ENTER`. 126 | 127 | ``` 128 | gemini.circumlunar.space/docs/> save 2 129 | enter filename (press ENTER for `/home/user/Downloads/specification.gmi`): 130 | ``` 131 | 132 | this number can be used to download the link, too. 133 | 134 | ``` 135 | gemini.circumlunar.space/docs/> search 136 | Search query> gplaces 137 | ``` 138 | 139 | the gplaces configuration file allows you to define short aliases for URLs you visit often. for example, the default configuration file defines the `home` alias for the Gemini project homepage and the `search` alias for a Gemini search engine. type `search` and press `ENTER` to search geminispace. 140 | 141 | ``` 142 | > geminispace.info/search gplaces 143 | > search gplaces 144 | > search "gemini client" 145 | ``` 146 | 147 | if a URL accepts input, you can specify the input in a second argument, to avoid another request to the same URL and skip the prompt. this works with aliases, too. 148 | 149 | to show a feed of new posts, type `sub`, then press `ENTER`. the list of URLs gplaces is "subscribed" to is defined in the configuration file. 150 | 151 | to exit gplaces, press `CTRL+d`. 152 | 153 | additional documentation and more details are available in `man gplaces`. type `help` and press `ENTER` to see short descriptions of available commands. 154 | 155 | ## How to configure? 156 | 157 | if installed through Flatpak, copy the read-only configuration file to your home directory so you can edit: 158 | 159 | ``` 160 | ~$ flatpak run --command=sh com.github.dimkr.gplaces 161 | ~$ cp /app/etc/gplacesrc $XDG_CONFIG_HOME/ 162 | ~$ exit 163 | ~$ xdg-open ~/.var/app/com.github.dimkr.gplaces/config 164 | ``` 165 | 166 | otherwise, you can edit /etc/gplacesrc directly or edit a copy under your home directory: 167 | 168 | ``` 169 | ~$ cp /etc/gplacesrc $XDG_CONFIG_HOME/ 170 | ~$ xdg-open $XDG_CONFIG_HOME/gplacesrc 171 | ``` 172 | 173 | ## License 174 | 175 | => LICENSE GPLv3 176 | -------------------------------------------------------------------------------- /com.github.dimkr.gplaces.appdata.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | com.github.dimkr.gplaces 4 | FSFAP 5 | GPL-3.0+ 6 | gplaces 7 | A terminal based Gemini client 8 | 9 | 10 |

11 | gplaces is a light Gemini client with a high power to weight ratio. In a tiny package, it features: 12 |

13 |
    14 |
  • A VT100-compatible shell with completion, history and hints
  • 15 |
  • .gmi subscriptions
  • 16 |
  • TOFU and permanent redirects
  • 17 |
  • Generation of client certificates
  • 18 |
  • Slightly prettified Gemtext output
  • 19 |
  • Configurable handlers for various file types
  • 20 |
  • Quick navigation to recently viewed pages
  • 21 |
  • Support for other "small internet" protocols: Titan, Spartan, Gopher, Finger and Guppy
  • 22 |
23 |

24 | gplaces should be fairly straightforward to use for anyone used to the command-line and man pages. Type "readme" for a short introduction. 25 |

26 |
27 | 28 | 29 | gemini 30 | titan 31 | spartan 32 | gopher 33 | finger 34 | guppy 35 | gemtext 36 | client 37 | browser 38 | 39 | 40 | 41 | Network 42 | WebBrowser 43 | ConsoleOnly 44 | 45 | 46 | 47 | gplaces 48 | x-scheme-handler/gemini 49 | x-scheme-handler/titan 50 | x-scheme-handler/spartan 51 | x-scheme-handler/gopher 52 | x-scheme-handler/gophers 53 | x-scheme-handler/finger 54 | x-scheme-handler/guppy 55 | 56 | 57 | com.github.dimkr.gplaces.desktop 58 | 59 | https://github.com/dimkr/gplaces 60 | 61 | 62 | 63 | https://raw.githubusercontent.com/dimkr/gplaces/gemini/prompt.png 64 | 65 | 66 | 67 | Dima Krasner 68 | 69 | 70 | 71 | 72 |
    73 |
  • The workaround for non-compliant servers that don't send close_notify is removed
  • 74 |
75 |
76 |
77 | 78 | 79 | 80 |
    81 |
  • Slightly darker logo
  • 82 |
83 |
84 |
85 | 86 | 87 | 88 |
    89 |
  • New logo
  • 90 |
91 |
92 |
93 | 94 | 95 | 96 |
    97 |
  • History is no longer populated with gplacesrc after first run
  • 98 |
99 |
100 |
101 | 102 | 103 | 104 |
    105 |
  • Improved Flatpak package metadata
  • 106 |
107 |
108 |
109 | 110 | 111 | 112 |
    113 |
  • Version and legal information are moved to a command
  • 114 |
  • Updated default aliases
  • 115 |
116 |
117 |
118 | 119 | 120 | 121 |
    122 |
  • Shell hints when typing upload input or download destination
  • 123 |
  • More documentation
  • 124 |
125 |
126 |
127 | 128 | 129 | 130 |
    131 |
  • More intuitive tab completion for paths
  • 132 |
133 |
134 |
135 | 136 | 137 | 138 |
    139 |
  • Support for an additional protocol: Titan
  • 140 |
  • Tab completion for paths
  • 141 |
  • Fix for broken guppy:// redirects
  • 142 |
143 |
144 |
145 | 146 | 147 | 148 |
    149 |
  • Disruptive change: certificate scope is determined by host and port, not host alone
  • 150 |
151 |
152 |
153 | 154 | 155 | 156 |
    157 |
  • Fix for crash on save or sub with unsupported protocol
  • 158 |
159 |
160 |
161 | 162 | 163 | 164 |
    165 |
  • Support for an additional protocol: Guppy
  • 166 |
167 |
168 |
169 | 170 | 171 | 172 |
    173 |
  • Fix for crash when handler ends with %u
  • 174 |
175 |
176 |
177 | 178 | 179 | 180 |
    181 |
  • Updated aliases in the default configuration file
  • 182 |
  • Nicer printing of the handler program exit code
  • 183 |
184 |
185 |
186 | 187 | 188 | 189 |
    190 |
  • Fix for unsafe memory access when path is /
  • 191 |
192 |
193 |
194 | 195 | 196 | 197 |
    198 |
  • Fix client certificate loading failure for URLs with trailing /
  • 199 |
200 |
201 |
202 | 203 | 204 | 205 |
    206 |
  • Add caching of pages downloaded when updating the feed
  • 207 |
  • Fix inability to refresh the feed
  • 208 |
209 |
210 |
211 | 212 | 213 | 214 |
    215 |
  • Fix broken links in feed
  • 216 |
217 |
218 |
219 | 220 | 221 | 222 |
    223 |
  • Add support for caching of Gopher search results
  • 224 |
  • New alias in the default configuration file: gsearch
  • 225 |
226 |
227 |
228 | 229 | 230 | 231 |
    232 |
  • README is converted to Gemtext
  • 233 |
234 |
235 |
236 | 237 | 238 | 239 |
    240 |
  • :70 is omitted from Gopher URLs
  • 241 |
242 |
243 |
244 | 245 | 246 | 247 |
    248 |
  • Fix for file descriptor leak when streaming
  • 249 |
  • Fix for bad handling of Gopher selectors without leading /
  • 250 |
  • Fix for bad handling of empty Gopher selectors
  • 251 |
252 |
253 |
254 | 255 | 256 | 257 |
    258 |
  • Fix crash when the current page is refreshed many times
  • 259 |
260 |
261 |
262 | 263 | 264 | 265 |
    266 |
  • Fix for crash on save
  • 267 |
  • Fix for bad handling of Gopher selectors containing ?
  • 268 |
  • Shorter Gopher search prompt
  • 269 |
270 |
271 |
272 | 273 | 274 | 275 |
    276 |
  • Support for more protocols: Gopher, gophers://, Spartan and Finger
  • 277 |
  • Support for permanent redirects
  • 278 |
  • Support for quick navigation using cached pages
  • 279 |
  • The download destination is now easier to change
  • 280 |
  • More efficient parsing
  • 281 |
  • Fix for broken handling of redirects
  • 282 |
283 |
284 |
285 | 286 | 287 | 288 |
    289 |
  • Fix inconsistent formatting of quotes with paragraphs
  • 290 |
291 |
292 |
293 | 294 | 295 | 296 |
    297 |
  • The Flatpak build is now allowed to run handler programs on the host
  • 298 |
299 |
300 |
301 | 302 | 303 | 304 |
    305 |
  • Enable non-interactive mode when stdin is a pipe
  • 306 |
  • When streaming, close connections on EOF without waiting for the handler
  • 307 |
308 |
309 |
310 | 311 | 312 | 313 |
    314 |
  • Fix inconsistent formatting of multiline headings
  • 315 |
316 |
317 |
318 | 319 | 320 | 321 |
    322 |
  • A warning on unexpected EOF
  • 323 |
324 |
325 |
326 | 327 | 328 | 329 |
    330 |
  • Efficiency improvement and reduced memory consumption
  • 331 |
332 |
333 |
334 | 335 | 336 | 337 |
    338 |
  • Fix for wrong link numbers when page is filtered
  • 339 |
  • Efficiency improvements and reduced memory consumption
  • 340 |
341 |
342 |
343 | 344 | 345 | 346 |
    347 |
  • Improved link hints
  • 348 |
349 |
350 |
351 | 352 | 353 | 354 |
    355 |
  • Support for automatic handling of certificate change
  • 356 |
  • MIME type handler input is no longer redirected to /dev/null
  • 357 |
358 |
359 |
360 | 361 | 362 | 363 |
    364 |
  • MIME type handler output is no longer redirected to /dev/null
  • 365 |
  • The default image viewer as been changed to chafa
  • 366 |
367 |
368 |
369 | 370 | 371 | 372 |
    373 |
  • Fix use of uninitialized variables
  • 374 |
375 |
376 |
377 | 378 | 379 | 380 |
    381 |
  • Support for "-" as the download destination
  • 382 |
  • Support for selecting MIME type handlers by prefix
  • 383 |
384 |
385 |
386 | 387 | 388 | 389 |
    390 |
  • Improved error reporting
  • 391 |
  • More useful default settings
  • 392 |
393 |
394 |
395 | 396 | 397 | 398 |
    399 |
  • Faster TOFU validation and improved handling of corner cases
  • 400 |
  • More consistent error reporting on timeout
  • 401 |
  • Fix for cut subscription headings since 0.16.23
  • 402 |
403 |
404 |
405 | 406 | 407 | 408 |
    409 |
  • Fix inconsistent formatting of UTF-8 text with a BOM
  • 410 |
411 |
412 |
413 | 414 | 415 | 416 |
    417 |
  • Fix inconsistent formatting of heading lines
  • 418 |
419 |
420 |
421 | 422 | 423 | 424 |
    425 |
  • Fix bad encoding of input with spaces, in interactive mode
  • 426 |
427 |
428 |
429 | 430 | 431 | 432 |
    433 |
  • Fix bad encoding of input with spaces
  • 434 |
435 |
436 |
437 | 438 | 439 | 440 |
    441 |
  • Allow input to be specified as an argument
  • 442 |
443 |
444 |
445 | 446 | 447 | 448 |
    449 |
  • Fix history saving of URLs that begin with a number
  • 450 |
  • Respect NO_COLOR
  • 451 |
452 |
453 |
454 | 455 | 456 | 457 |
    458 |
  • Fix for bad man page installation path
  • 459 |
460 |
461 |
462 | 463 | 464 | 465 |
    466 |
  • More detailed menu categories list
  • 467 |
  • More useful default settings
  • 468 |
469 |
470 |
471 | 472 | 473 | 474 |
    475 |
  • Extended support for plain text files
  • 476 |
  • URLs with user input are now saved to history
  • 477 |
  • More useful default settings
  • 478 |
479 |
480 |
481 | 482 | 483 | 484 |
    485 |
  • Fix for crash on save without arguments
  • 486 |
487 |
488 |
489 | 490 | 491 | 492 |
    493 |
  • Word wrapping
  • 494 |
495 |
496 |
497 | 498 | 499 | 500 |
    501 |
  • Shell completion using link indices
  • 502 |
503 |
504 |
505 | 506 | 507 | 508 |
    509 |
  • Fix for breakge of file:// handling
  • 510 |
  • Fix for use-after-free when parsing large blocks of preformatted text
  • 511 |
  • The pager exit code is no longer logged when it's 0
  • 512 |
513 |
514 |
515 | 516 | 517 | 518 |
    519 |
  • IDN support
  • 520 |
  • Improved documentation
  • 521 |
522 |
523 |
524 | 525 | 526 | 527 |
    528 |
  • Fix for a parsing regression in 0.16.9
  • 529 |
530 |
531 |
532 | 533 | 534 | 535 |
    536 |
  • Whole .gmi pages are no longer kept in memory during download
  • 537 |
538 |
539 |
540 | 541 | 542 | 543 |
    544 |
  • Page contents are now streamed during download
  • 545 |
  • Files without a matching handler are no longer downloaded
  • 546 |
547 |
548 |
549 | 550 | 551 | 552 |
    553 |
  • Proper handling of zero-width characters
  • 554 |
555 |
556 |
557 | 558 | 559 | 560 |
    561 |
  • Consistent line wrapping across English and non-English text
  • 562 |
  • More useful default settings
  • 563 |
564 |
565 |
566 | 567 | 568 | 569 |
    570 |
  • Variable values are now shown in hints
  • 571 |
  • Invalid link indices are now ignored
  • 572 |
573 |
574 |
575 | 576 | 577 | 578 |
    579 |
  • Relative URLs in hints, to improve usability with narrow terminal windows
  • 580 |
  • Improved error handling upon MIME type detection failure
  • 581 |
582 |
583 |
584 | 585 | 586 | 587 |
    588 |
  • Headings are now underlined
  • 589 |
  • Increased line length limit
  • 590 |
591 |
592 |
593 | 594 | 595 | 596 |
    597 |
  • Smarter choice of default download filename
  • 598 |
  • Link URLs are now shown in hints
  • 599 |
  • If download_dir is empty, the fallback is $XDG_DOWNLOAD_DIR, ~/Downloads or ~
  • 600 |
  • The range of link IDs is now shown in a hint
  • 601 |
602 |
603 |
604 | 605 | 606 | 607 |

Moved files from ~ to $XDG_{CONFIG,DATA}_HOME

608 |
609 |
610 | 611 | 612 | 613 |

First release

614 |
615 |
616 |
617 | 618 | 619 |
-------------------------------------------------------------------------------- /finger.c: -------------------------------------------------------------------------------- 1 | /* 2 | ================================================================================ 3 | 4 | gplaces - a simple terminal Gemini client 5 | Copyright (C) 2022 - 2024 Dima Krasner 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | ================================================================================ 21 | */ 22 | static void *finger_download(const Selector *sel, URL *url, char **mime, Parser *parser, unsigned int redirs, int ask) { 23 | static char buffer[1024 + 3]; /* path\r\n\0 */ 24 | char *user = NULL; 25 | int fd = -1, len = 0; 26 | 27 | (void)sel; 28 | (void)redirs; 29 | (void)ask; 30 | 31 | switch (curl_url_get(url->cu, CURLUPART_USER, &user, 0)) { 32 | case CURLUE_OK: len = snprintf(buffer, sizeof(buffer), "%s\r\n", user); break; 33 | case CURLUE_NO_USER: break; 34 | default: return NULL; 35 | } 36 | 37 | if ((fd = socket_connect(url, SOCK_STREAM)) == -1) return NULL; 38 | if ((len == 0 && sendall(fd, "\r\n", 2, MSG_NOSIGNAL) != 2) || (len > 0 && sendall(fd, buffer, len, MSG_NOSIGNAL) != len)) { 39 | if (errno == EAGAIN || errno == EWOULDBLOCK) error(0, "cannot send request to `%s`:`%s`: cancelled", url->host, url->port); 40 | else error(0, "cannot send request to `%s`:`%s`: %s", url->host, url->port, strerror(errno)); 41 | close(fd); 42 | return NULL; 43 | } 44 | 45 | *mime = "text/plain"; 46 | *parser = parse_plaintext_line; 47 | 48 | return (void *)(intptr_t)fd; 49 | } 50 | 51 | 52 | const Protocol finger = {"finger", "79", tcp_read, tcp_peek, socket_error, tcp_close, finger_download, set_fragment}; 53 | -------------------------------------------------------------------------------- /gopher.c: -------------------------------------------------------------------------------- 1 | /* 2 | ================================================================================ 3 | 4 | gplaces - a simple terminal Gemini client 5 | Copyright (C) 2022 - 2024 Dima Krasner 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | ================================================================================ 21 | */ 22 | static void parse_gophermap_line(char *line, int *pre, Selector **sel, SelectorList *list) { 23 | char *path, *host, *port; 24 | 25 | (void)pre; 26 | 27 | *sel = NULL; 28 | 29 | if ((line[0] == '.' && line[1] == '\0') || line[0] == '\0') return; 30 | 31 | *sel = new_selector(*line == 'i' ? '`' : 'l'); 32 | 33 | if (*(path = line + 1 + strcspn(line + 1, "\t")) == '\0') goto fail; 34 | *path = '\0'; 35 | ++path; 36 | if (*(host = path + strcspn(path, "\t")) == '\0') goto fail; 37 | *host = '\0'; 38 | ++host; 39 | if (*(port = host + strcspn(host, "\t")) == '\0') goto fail; 40 | *port = '\0'; 41 | ++port; 42 | *(port + strcspn(port, "\t")) = '\0'; 43 | 44 | (*sel)->repr = str_copy(line + 1); 45 | 46 | if ((*line == '1' || *line == '0' || *line == '7' || *line == '9' || *line == 'g' || *line == 'I' || *line == '8' || *line == '2' || *line == '6' || *line == '5' || *line == '4' || *line == 'T') && (strcmp(port, "70") == 0 ? asprintf(&(*sel)->rawurl, "%s://%s/%c%s", "gopher", host, *line, path) : asprintf(&(*sel)->rawurl, "%s://%s:%s/%c%s", "gopher", host, port, *line, path)) < 0) { (*sel)->rawurl = NULL; goto fail; } 47 | else if (*line == 'h' && strncmp(path, "URL:", 4) == 0 && !copy_url(*sel, path + 4)) goto fail; 48 | 49 | SIMPLEQ_INSERT_TAIL(list, *sel, next); 50 | return; 51 | 52 | fail: 53 | free_selector(*sel); 54 | *sel = NULL; 55 | } 56 | 57 | 58 | /*============================================================================*/ 59 | static char *gopher_request(const Selector *sel, URL *url, int ask, int *len, size_t skip) { 60 | static char buffer[1024 + 3]; /* path\r\n\0 */ 61 | char *input = NULL, *fragment = NULL; 62 | const char *path, *end; 63 | 64 | if (url->path[0] == '/' && url->path[1] == '7') { 65 | switch (curl_url_get(url->cu, CURLUPART_FRAGMENT, &fragment, 0)) { 66 | case CURLUE_OK: input = fragment; break; 67 | case CURLUE_NO_FRAGMENT: break; 68 | default: return NULL; 69 | } 70 | if (input == NULL) { 71 | if (!ask || (input = bestline(color ? "\33[35mQuery>\33[0m " : "Query> ")) == NULL || !set_fragment(url, input)) return NULL; 72 | if (interactive) { bestlineHistoryAdd(input); bestlineHistoryAdd(url->url); } 73 | *len = snprintf(buffer, sizeof(buffer), "%s\t%s\r\n", sel->rawurl + skip + strcspn(sel->rawurl + skip, "/") + 2, input); 74 | } else { 75 | path = sel->rawurl + skip + strcspn(sel->rawurl + skip, "/") + 2; 76 | if ((end = strrchr(path, '?')) == NULL) *len = snprintf(buffer, sizeof(buffer), "%s\t%s\r\n", path, input); 77 | else *len = snprintf(buffer, sizeof(buffer), "%.*s\t%s\r\n", (int)(end - path), path, input); 78 | } 79 | if (input != fragment) free(input); 80 | curl_free(fragment); 81 | } else if (url->path[0] == '/' && url->path[1] != '\0') *len = snprintf(buffer, sizeof(buffer), "%s\r\n", sel->rawurl + skip + strcspn(sel->rawurl + skip, "/") + 2); 82 | else *len = snprintf(buffer, sizeof(buffer), "%s\r\n", sel->rawurl + skip + strcspn(sel->rawurl + skip, "/")); 83 | 84 | return buffer; 85 | } 86 | 87 | 88 | /*============================================================================*/ 89 | static void gopher_type(void *c, const URL *url, char **mime, Parser *parser) { 90 | #ifdef GPLACES_USE_LIBMAGIC 91 | static char buffer[1024]; 92 | magic_t mag; 93 | ssize_t len, had = 0; 94 | const char *tmp = NULL; 95 | #else 96 | static char buffer[2]; 97 | 98 | (void)c; 99 | #endif 100 | 101 | if (url->path[1] == '0' || url->path[1] == '+') *parser = parse_plaintext_line; 102 | else if (url->path[1] == '1' || url->path[1] == '7' || url->path[1] == '\0' || url->path[2] != '/') *parser = parse_gophermap_line; 103 | #ifdef GPLACES_USE_LIBMAGIC 104 | else { 105 | if ((len = url->proto->peek(c, buffer, sizeof(buffer))) <= 0 || (mag = magic_open(MAGIC_MIME_TYPE | MAGIC_NO_CHECK_COMPRESS | MAGIC_ERROR)) == NULL) goto unk; 106 | if (magic_load(mag, NULL) == -1) { magic_close(mag); goto unk; } 107 | do { 108 | if ((tmp = magic_buffer(mag, buffer, (size_t)len)) == NULL) continue; 109 | if (strncmp(tmp, "text/plain", 10) == 0) *parser = parse_plaintext_line; 110 | strncpy(buffer, tmp, sizeof(buffer)); 111 | buffer[sizeof(buffer) - 1] = '\0'; 112 | *mime = buffer; 113 | had = len; 114 | } while (len < (ssize_t)sizeof(buffer) && (len = url->proto->peek(c, buffer, sizeof(buffer))) > 0 && len > had); 115 | magic_close(mag); 116 | if (tmp != NULL) return; 117 | } 118 | unk: 119 | #endif 120 | 121 | buffer[0] = (url->path[1] != '\0' && url->path[1] != '/' && url->path[2] == '/') ? url->path[1] : '1'; 122 | buffer[1] = '\0'; 123 | *mime = buffer; 124 | } 125 | 126 | 127 | static void *gopher_download(const Selector *sel, URL *url, char **mime, Parser *parser, unsigned int redirs, int ask) { 128 | char *buffer; 129 | int fd = -1, len; 130 | 131 | (void)redirs; 132 | 133 | if ((buffer = gopher_request(sel, url, ask, &len, 9)) == NULL || (fd = socket_connect(url, SOCK_STREAM)) == -1) goto fail; 134 | if (sendall(fd, buffer, len, MSG_NOSIGNAL) != len) { 135 | if (errno == EAGAIN || errno == EWOULDBLOCK) error(0, "cannot send request to `%s`:`%s`: cancelled", url->host, url->port); 136 | else error(0, "cannot send request to `%s`:`%s`: %s", url->host, url->port, strerror(errno)); 137 | close(fd); fd = -1; 138 | } 139 | 140 | if (fd != -1) gopher_type((void *)(intptr_t)fd, url, mime, parser); 141 | 142 | fail: 143 | return fd == -1 ? NULL : (void *)(intptr_t)fd; 144 | } 145 | 146 | 147 | const Protocol gopher = {"gopher", "70", tcp_read, tcp_peek, socket_error, tcp_close, gopher_download, set_fragment}; 148 | -------------------------------------------------------------------------------- /gophers.c: -------------------------------------------------------------------------------- 1 | /* 2 | ================================================================================ 3 | 4 | gplaces - a simple terminal Gemini client 5 | Copyright (C) 2022 - 2024 Dima Krasner 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | ================================================================================ 21 | */ 22 | static void *gophers_download(const Selector *sel, URL *url, char **mime, Parser *parser, unsigned int redirs, int ask) { 23 | char *buffer; 24 | SSL_CTX *ctx = NULL; 25 | SSL *ssl = NULL; 26 | int len, err; 27 | 28 | (void)redirs; 29 | 30 | if ((ctx = SSL_CTX_new(TLS_client_method())) == NULL) return NULL; 31 | SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL); 32 | 33 | if ((buffer = gopher_request(sel, url, ask, &len, 10)) == NULL || (ssl = ssl_connect(url, ctx, ask)) == NULL) goto fail; 34 | if ((err = SSL_get_error(ssl, SSL_write(ssl, buffer, len))) != SSL_ERROR_NONE) { 35 | if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) error(0, "cannot send request to `%s`:`%s`: cancelled", url->host, url->port); 36 | else error(0, "cannot send request to `%s`:`%s`: error %d", url->host, url->port, err); 37 | SSL_free(ssl); ssl = NULL; 38 | } 39 | 40 | if (ssl != NULL) gopher_type(ssl, url, mime, parser); 41 | 42 | fail: 43 | SSL_CTX_free(ctx); 44 | return ssl; 45 | } 46 | 47 | 48 | const Protocol gophers = {"gophers", "70", ssl_read, ssl_peek, ssl_error, ssl_close, gophers_download, set_fragment}; 49 | -------------------------------------------------------------------------------- /gplaces.1: -------------------------------------------------------------------------------- 1 | .TH gplaces 1 2 | .SH NAME 3 | gplaces - a Gemini client 4 | .SH SYNOPSIS 5 | .B gplaces 6 | [-r rc-file] [url] 7 | .SH DESCRIPTION 8 | A simple terminal based Gemini client. 9 | .SH COMMAND SYNTAX 10 | .TP 11 | .B HELP 12 | .RS 13 | Syntax: 14 | .RS 15 | HELP [] 16 | .RE 17 | Description: 18 | .RS 19 | Show all help topics or the help text for a specific . 20 | .RE 21 | .RE 22 | .TP 23 | .B SAVE 24 | .RS 25 | Syntax: 26 | .RS 27 | SAVE [] 28 | .RE 29 | Description: 30 | .RS 31 | Saves the given from the menu or a given to the disk. If no filename is specified, you will be asked for it. If filename is "-", the downloaded data is streamed to the handler program via standard input. 32 | .RE 33 | .RE 34 | .TP 35 | .B GET 36 | .RS 37 | Syntax: 38 | .RS 39 | GET 40 | .RE 41 | Description: 42 | .RS 43 | Updates the cached copy of the currently viewed url. 44 | .RE 45 | .RE 46 | .TP 47 | .B SET 48 | .RS 49 | Syntax: 50 | .RS 51 | SET 52 | .RE 53 | Description: 54 | .RS 55 | Sets the value of a variable. When the variable does not exist the variable will be created. 56 | .RE 57 | .RE 58 | .TP 59 | .B SHOW 60 | .RS 61 | Syntax: 62 | .RS 63 | SHOW [] 64 | .RE 65 | Description: 66 | .RS 67 | Show the current menu. If a is specified, it will show all selectors containing the in name or path. 68 | .RE 69 | .RE 70 | .TP 71 | .B SUB 72 | .RS 73 | Syntax: 74 | .RS 75 | SUB [] 76 | .RE 77 | Description: 78 | .RS 79 | Subscribes to . If no is specified, it will show the list of subscriptions and the recent entries in each. 80 | .RE 81 | .RE 82 | .SH FORMAT STRINGS 83 | A format string can have the following formating options: 84 | .RS 85 | .IP 86 | %% - simply a `%` 87 | .IP 88 | %s - scheme 89 | .IP 90 | %h - hostname 91 | .IP 92 | %p - port 93 | .IP 94 | %P - path 95 | .IP 96 | %r - human-readable string 97 | .IP 98 | %u - URL 99 | .IP 100 | %f - filename 101 | .RE 102 | .RE 103 | .SH OPTIONS 104 | .TP 105 | .B -r 106 | Specifies the initialization file to use. If unspecified, gplaces tries $XDG_CONFIG_HOME/gplacesrc, ~/.gplacesrc and /etc/gplacesrc. 107 | .SH CONFIGURATION 108 | .TP 109 | .B curve 110 | Specifies the elliptic curve to use when generating client certificates. If unspecified or empty, the default is prime256v1. 111 | .TP 112 | .B digest 113 | Specifies the message digest to use when generating client certificates. If unspecified or empty, the default is sha256. 114 | .TP 115 | .B cn 116 | Specifies the Common Name to use when generating client certificates. If unspecified or empty, the default is the value of the USER environment variable. 117 | .TP 118 | .B days 119 | Specifies the expiration of time of generated client certificates, in days. If unspecified or invalid, the default is 1825 days (5 years). 120 | .TP 121 | .B pager 122 | Specifies a pager used to display pages. If unspecified, the default is the value of the PAGER environment variable, if set, otherwise "less -r". If set to "cat", paging is disabled. 123 | .TP 124 | .B timeout 125 | Specifies the download timeout. If unspecified or invalid, the default is 15 seconds. 126 | .TP 127 | .B download_directory 128 | Specifies the download directory. If unspecified or invalid, the default is the value of the XDG_DOWNLOAD_DIR environment variable, ~/Downloads or ~. 129 | .SH AUTHOR 130 | .P 131 | Dima Krasner (dima@dimakrasner.com) 132 | .P 133 | Sebastian Steinhauer 134 | -------------------------------------------------------------------------------- /gplaces.c: -------------------------------------------------------------------------------- 1 | /* 2 | ================================================================================ 3 | 4 | gplaces - a simple terminal Gemini client 5 | Copyright (C) 2022 - 2024 Dima Krasner 6 | Copyright (C) 2019 Sebastian Steinhauer 7 | 8 | This program is free software: you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | This program is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with this program. If not, see . 20 | 21 | ================================================================================ 22 | */ 23 | /*============================================================================*/ 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include 46 | #include 47 | #include "queue.h" 48 | 49 | #include 50 | #include 51 | #include 52 | #include 53 | #include 54 | #include 55 | 56 | #include 57 | 58 | #ifdef GPLACES_USE_LIBIDN2 59 | #include 60 | #elif defined(GPLACES_USE_LIBIDN) 61 | #include 62 | #endif 63 | 64 | #ifdef GPLACES_USE_LIBMAGIC 65 | #include 66 | #endif 67 | 68 | #include "bestline/bestline.h" 69 | 70 | /*============================================================================*/ 71 | typedef struct Selector Selector; 72 | typedef SIMPLEQ_HEAD(, Selector) SelectorList; 73 | typedef struct URL URL; 74 | typedef struct Page Page; 75 | typedef TAILQ_HEAD(PageList, Page) PageList; 76 | typedef void (*Parser)(char *, int *pre, Selector **, SelectorList *); 77 | 78 | typedef struct Protocol { 79 | const char *scheme, *port; 80 | int (*read)(void *, void *, int); 81 | int (*peek)(void *, void *, int); 82 | int (*error)(const URL *, void *, int); 83 | void (*close)(void *); 84 | void *(*download)(const Selector *, URL *, char **mime, Parser *, unsigned int redirs, int ask); 85 | int (*set_input)(URL *url, const char *input); 86 | } Protocol; 87 | 88 | struct Selector { 89 | SIMPLEQ_ENTRY(Selector) next; 90 | int level; 91 | #if defined(GPLACES_WITH_SPARTAN) 92 | char prompt; 93 | #endif 94 | char type, *repr, *rawurl; 95 | CURLU *cu; 96 | }; 97 | 98 | struct URL { 99 | char *scheme, *host, *port, *path, *url; 100 | CURLU *cu; 101 | const Protocol *proto; 102 | }; 103 | 104 | struct Page { 105 | char prompt[256]; 106 | SelectorList menu; 107 | time_t fetched; 108 | char *url; 109 | TAILQ_ENTRY(Page) next; 110 | }; 111 | 112 | typedef struct Variable { 113 | LIST_ENTRY(Variable) next; 114 | char *name, *data; 115 | } Variable; 116 | 117 | typedef LIST_HEAD(, Variable) VariableList; 118 | 119 | typedef struct Command { 120 | const char *name; 121 | void (*func)(char *line); 122 | } Command; 123 | 124 | 125 | /*============================================================================*/ 126 | const Protocol gemini; 127 | #ifdef GPLACES_WITH_TITAN 128 | const Protocol titan; 129 | #endif 130 | #ifdef GPLACES_WITH_GOPHERS 131 | const Protocol gophers; 132 | #endif 133 | #ifdef GPLACES_WITH_GOPHER 134 | const Protocol gopher; 135 | #endif 136 | #ifdef GPLACES_WITH_SPARTAN 137 | const Protocol spartan; 138 | #endif 139 | #ifdef GPLACES_WITH_FINGER 140 | const Protocol finger; 141 | #endif 142 | #ifdef GPLACES_WITH_GUPPY 143 | const Protocol guppy; 144 | #endif 145 | 146 | 147 | /*============================================================================*/ 148 | static VariableList variables = LIST_HEAD_INITIALIZER(variables); 149 | static SelectorList subscriptions = SIMPLEQ_HEAD_INITIALIZER(subscriptions); 150 | static PageList history = TAILQ_HEAD_INITIALIZER(history); 151 | static const Selector feed_sel = {.rawurl = "gplaces://sub/"}; 152 | SelectorList blank = SIMPLEQ_HEAD_INITIALIZER(blank); 153 | #define currentmenu TAILQ_EMPTY(&history) ? blank : TAILQ_FIRST(&history)->menu 154 | #define currenturl TAILQ_EMPTY(&history) ? NULL : TAILQ_FIRST(&history)->url 155 | static int depth; 156 | static int interactive; 157 | static int color; 158 | static int inshell; 159 | 160 | 161 | /*============================================================================*/ 162 | __attribute__((format(printf, 2, 3))) 163 | static void error(int fatal, const char *fmt, ...) { 164 | va_list va; 165 | if (color) fwrite("\33[31m\n", 1, 6, stderr); 166 | else fputc('\n', stderr); 167 | va_start(va, fmt); 168 | vfprintf(stderr, fmt, va); 169 | va_end(va); 170 | if (color) fwrite("\33[0m\n", 1, 5, stderr); 171 | else fputc('\n', stderr); 172 | if (fatal) exit(EXIT_FAILURE); 173 | } 174 | 175 | 176 | /*============================================================================*/ 177 | static char *str_copy(const char *str) { 178 | char *new; 179 | if ((new = strdup(str)) == NULL) error(1, "cannot allocate new string"); 180 | return new; 181 | } 182 | 183 | /*============================================================================*/ 184 | static void free_variables(VariableList *vars) { 185 | Variable *var, *tmp; 186 | LIST_FOREACH_SAFE(var, vars, next, tmp) { 187 | free(var->name); 188 | free(var->data); 189 | free(var); 190 | } 191 | } 192 | 193 | 194 | static char *set_var(VariableList *list, const char *name, const char *value) { 195 | Variable *var; 196 | 197 | if (name == NULL) return NULL; 198 | LIST_FOREACH(var, list, next) { 199 | if (!strcasecmp(var->name, name)) break; 200 | } 201 | 202 | if (value) { 203 | if (var == NULL) { 204 | if ((var = malloc(sizeof(Variable))) == NULL) error(1, "cannot allocate new variable"); 205 | var->name = str_copy((char*)name); 206 | var->data = str_copy(value); 207 | LIST_INSERT_HEAD(list, var, next); 208 | } else { 209 | free(var->data); 210 | var->data = str_copy(value); 211 | } 212 | } 213 | 214 | return var ? var->data : NULL; 215 | } 216 | 217 | 218 | static int get_var_integer(const char *name, int def) { 219 | int value; 220 | char *data = set_var(&variables, name, NULL); 221 | if (data == NULL || sscanf(data, "%d", &value) != 1) return def; 222 | return value; 223 | } 224 | 225 | 226 | /*============================================================================*/ 227 | static void *map_file(const char *name, int *fd, size_t *size) { 228 | static char path[1024]; 229 | struct stat stbuf; 230 | const char *home; 231 | void *p; 232 | 233 | if ((home = getenv("XDG_DATA_HOME")) != NULL) snprintf(path, sizeof(path), "%s/gplaces_%s", home, name); 234 | else if ((home = getenv("HOME")) != NULL) snprintf(path, sizeof(path), "%s/.gplaces_%s", home, name); 235 | else return NULL; 236 | 237 | if ((*fd = open(path, O_RDWR | O_CREAT | O_APPEND, 0600)) == -1) return NULL; 238 | if (fstat(*fd, &stbuf) == -1) { close(*fd); return NULL; } 239 | if ((*size = (size_t)stbuf.st_size) == 0) return NULL; 240 | if ((p = mmap(NULL, stbuf.st_size % SIZE_MAX, PROT_READ | PROT_WRITE, MAP_SHARED, *fd, 0)) == MAP_FAILED) { close(*fd); return NULL; } 241 | return p; 242 | } 243 | 244 | 245 | __attribute__((format(printf, 2, 3))) 246 | static int append_line(int fd, const char *fmt, ...) { 247 | va_list va; 248 | FILE *fp; 249 | int ret; 250 | if ((fp = fdopen(fd, "a")) == NULL) return 0; 251 | va_start(va, fmt); 252 | ret = vfprintf(fp, fmt, va) > 0; 253 | va_end(va); 254 | fclose(fp); 255 | return ret; 256 | } 257 | 258 | 259 | /*============================================================================*/ 260 | static Selector *new_selector(const char type) { 261 | Selector *new = calloc(1, sizeof(Selector)); 262 | if (new == NULL) error(1, "cannot allocate new selector"); 263 | new->type = type; 264 | return new; 265 | } 266 | 267 | 268 | static void free_selector(Selector *sel) { 269 | free(sel->repr); 270 | free(sel->rawurl); 271 | free(sel); 272 | } 273 | 274 | 275 | static void free_url(URL *url) { 276 | curl_free(url->scheme); 277 | curl_free(url->host); 278 | if (url->proto != NULL && url->port != url->proto->port) curl_free(url->port); 279 | curl_free(url->path); 280 | curl_free(url->url); 281 | if (url->cu != NULL) curl_url_cleanup(url->cu); 282 | } 283 | 284 | 285 | static void free_selectors(SelectorList *list) { 286 | Selector *sel, *tmp; 287 | SIMPLEQ_FOREACH_SAFE(sel, list, next, tmp) free_selector(sel); 288 | } 289 | 290 | 291 | static int set_query(URL *url, const char *input) { 292 | char *query, *tmp; 293 | if ((query = curl_easy_escape(NULL, input, 0)) == NULL) return 0; 294 | if (curl_url_set(url->cu, CURLUPART_QUERY, query, CURLU_NON_SUPPORT_SCHEME) != CURLUE_OK || curl_url_get(url->cu, CURLUPART_URL, &tmp, 0) != CURLUE_OK) { curl_free(query); return 0; } 295 | curl_free(url->url); url->url = tmp; 296 | curl_free(query); 297 | return 1; 298 | } 299 | 300 | 301 | #if defined(GPLACES_WITH_TITAN) || defined(GPLACES_WITH_GOPHER) || defined(GPLACES_WITH_GOPHERS) || defined(GPLACSE_WITH_FINGER) 302 | static int set_fragment(URL *url, const char *input) { 303 | char *tmp; 304 | if (curl_url_set(url->cu, CURLUPART_FRAGMENT, input, CURLU_NON_SUPPORT_SCHEME) != CURLUE_OK || curl_url_get(url->cu, CURLUPART_URL, &tmp, 0) != CURLUE_OK) return 0; 305 | curl_free(url->url); url->url = tmp; 306 | return 1; 307 | } 308 | #endif 309 | 310 | 311 | static int parse_url(URL *url, const char *rawurl, const char *from, const char *input) { 312 | static char buffer[1024]; 313 | #if defined(GPLACES_USE_LIBIDN2) || defined(GPLACES_USE_LIBIDN) 314 | char *host; 315 | #endif 316 | int file; 317 | 318 | if ((url->cu == NULL && (url->cu = curl_url()) == NULL) || (from != NULL && curl_url_set(url->cu, CURLUPART_URL, from, CURLU_NON_SUPPORT_SCHEME) != CURLUE_OK)) return 0; 319 | 320 | /* TODO: why does curl_url_set() return CURLE_OUT_OF_MEMORY if the scheme is missing, but only inside the Flatpak sandbox? */ 321 | if (curl_url_set(url->cu, CURLUPART_URL, rawurl, CURLU_NON_SUPPORT_SCHEME) != CURLUE_OK) { 322 | #if defined(GPLACES_WITH_GOPHER) && defined(CURLU_ALLOW_SPACE) 323 | if (strncmp(rawurl, "gopher://", 9) == 0) { 324 | if (curl_url_set(url->cu, CURLUPART_URL, rawurl, CURLU_NON_SUPPORT_SCHEME | CURLU_ALLOW_SPACE) == CURLUE_OK) goto valid; 325 | return 0; 326 | } 327 | #endif 328 | #if defined(GPLACES_WITH_GOPHERS) && defined(CURLU_ALLOW_SPACE) 329 | if (strncmp(rawurl, "gophers://", 10) == 0) { 330 | if (curl_url_set(url->cu, CURLUPART_URL, rawurl, CURLU_NON_SUPPORT_SCHEME | CURLU_ALLOW_SPACE) == CURLUE_OK) goto valid; 331 | return 0; 332 | } 333 | #endif 334 | snprintf(buffer, sizeof(buffer), "gemini://%s", rawurl); 335 | if (curl_url_set(url->cu, CURLUPART_URL, buffer, CURLU_NON_SUPPORT_SCHEME) != CURLUE_OK) return 0; 336 | } 337 | #if (defined(GPLACES_WITH_GOPHER) || defined(GPLACES_WITH_GOPHERS)) && defined(CURLU_ALLOW_SPACE) 338 | valid: 339 | #endif 340 | 341 | if (curl_url_get(url->cu, CURLUPART_SCHEME, &url->scheme, 0) != CURLUE_OK) return 0; 342 | 343 | if (strcmp(url->scheme, "gemini") == 0) { 344 | url->proto = &gemini; 345 | #ifdef GPLACES_WITH_TITAN 346 | } else if (strcmp(url->scheme, "titan") == 0) { 347 | url->proto = &titan; 348 | #endif 349 | #ifdef GPLACES_WITH_GOPHER 350 | } else if (strcmp(url->scheme, "gopher") == 0) { 351 | url->proto = &gopher; 352 | #endif 353 | #ifdef GPLACES_WITH_GOPHERS 354 | } else if (strcmp(url->scheme, "gophers") == 0) { 355 | url->proto = &gophers; 356 | #endif 357 | #ifdef GPLACES_WITH_SPARTAN 358 | } else if (strcmp(url->scheme, "spartan") == 0) { 359 | url->proto = &spartan; 360 | #endif 361 | #ifdef GPLACES_WITH_FINGER 362 | } else if (strcmp(url->scheme, "finger") == 0) { 363 | url->proto = &finger; 364 | #endif 365 | #ifdef GPLACES_WITH_GUPPY 366 | } else if (strcmp(url->scheme, "guppy") == 0) { 367 | url->proto = &guppy; 368 | #endif 369 | } 370 | 371 | if (input != NULL && input[0] != '\0' && !url->proto->set_input(url, input)) return 0; 372 | else if ((input == NULL || input[0] == '\0') && curl_url_get(url->cu, CURLUPART_URL, &url->url, 0) != CURLUE_OK) return 0; 373 | 374 | if (!(file = (strcmp(url->scheme, "file")) == 0) && curl_url_get(url->cu, CURLUPART_HOST, &url->host, 0) != CURLUE_OK) return 0; 375 | 376 | #if defined(GPLACES_USE_LIBIDN2) || defined(GPLACES_USE_LIBIDN) 377 | #ifdef GPLACES_USE_LIBIDN2 378 | if (!file && (idn2_to_ascii_8z(url->host, &host, IDN2_NONTRANSITIONAL) == IDN2_OK || idn2_to_ascii_8z(url->host, &host, IDN2_TRANSITIONAL) == IDN2_OK)) { 379 | #elif defined(GPLACES_USE_LIBIDN) 380 | if (!file && idna_to_ascii_8z(url->host, &host, 0) == IDNA_SUCCESS) { 381 | #endif 382 | if (curl_url_set(url->cu, CURLUPART_HOST, host, 0) != CURLUE_OK) { free(host); return 0; } 383 | free(host); 384 | curl_free(url->host); url->host = NULL; 385 | if (curl_url_get(url->cu, CURLUPART_HOST, &url->host, 0) != CURLUE_OK) return 0; 386 | } 387 | #endif 388 | 389 | if (curl_url_get(url->cu, CURLUPART_PATH, &url->path, 0) != CURLUE_OK) return 0; 390 | 391 | if (file) return 1; 392 | 393 | switch (curl_url_get(url->cu, CURLUPART_PORT, &url->port, 0)) { 394 | case CURLUE_OK: break; 395 | case CURLUE_NO_PORT: 396 | if (url->proto != NULL) url->port = str_copy(url->proto->port); 397 | break; 398 | /* fall through */ 399 | default: return 0; 400 | } 401 | 402 | return 1; 403 | } 404 | 405 | 406 | static int redirect(URL *url, const char *to, size_t len, int ask) { 407 | URL tmp = {0}; 408 | char *rawurl; 409 | if ((rawurl = len > 0 ? strndup(to, len) : strdup(to)) == NULL) error(1, "cannot allocate new string"); 410 | if (!parse_url(&tmp, rawurl, url->url, NULL)) { free(rawurl); return 40; } 411 | free(rawurl); 412 | free_url(url); 413 | memcpy(url, &tmp, sizeof(URL)); 414 | fprintf(stderr, "redirected to `%s`\n", url->url); 415 | if (ask) bestlineHistoryAdd(url->url); 416 | return 31; 417 | } 418 | 419 | 420 | static int perm_redirect(URL *url, const char *to, int ask) { 421 | size_t size = 1, len; 422 | const char *p, *start, *end; 423 | int fd, ret = 20, found = 0; 424 | 425 | len = strlen(url->url); 426 | 427 | if ((p = map_file("redirs", &fd, &size)) == NULL && size > 0) return 40; 428 | else if (p != NULL) { 429 | for (end = p; !found && (start = memmem(end, size - (end - p), url->url, len)) != NULL; end = start + len + 1) { 430 | if (!(found = ((start == p || *(start - 1) == '\n') && size - (start - p) >= len + 2 && start[len] == ' ' && start[len + 1] != '\n'))) continue; 431 | ret = redirect(url, &start[len + 1], strcspn(&start[len + 1], " \n"), ask); 432 | } 433 | munmap((void *)p, size); 434 | } 435 | if (to != NULL && !found) ret = append_line(fd, "%s %s\n", url->url, to) ? redirect(url, to, -1, ask) : 40; 436 | close(fd); 437 | return ret; 438 | } 439 | 440 | 441 | static const Selector *find_selector(const SelectorList list, int index) { 442 | const Selector *sel; 443 | long i = 0; 444 | SIMPLEQ_FOREACH(sel, &list, next) if (sel->type == 'l' && ++i == index) return sel; 445 | return NULL; 446 | } 447 | 448 | 449 | static int copy_url(Selector *sel, const char *url) { 450 | if (url == NULL || *url == '\0') return 0; 451 | 452 | sel->rawurl = str_copy(url); 453 | 454 | return 1; 455 | } 456 | 457 | 458 | /*============================================================================*/ 459 | static void free_page(Page *page) { 460 | free_selectors(&page->menu); 461 | free(page->url); 462 | free(page); 463 | } 464 | 465 | 466 | static void free_history(PageList *pages) { 467 | Page *page, *tmp; 468 | TAILQ_FOREACH_SAFE(page, pages, next, tmp) free_page(page); 469 | } 470 | 471 | 472 | static void history_pop(void) { 473 | Page *page = TAILQ_LAST(&history, PageList); 474 | TAILQ_REMOVE(&history, page, next); 475 | free_selectors(&page->menu); 476 | free(page->url); 477 | free(page); 478 | } 479 | 480 | 481 | static void history_push(const char *url, SelectorList menu, const char *fmt, ...) { 482 | va_list va; 483 | Page *page; 484 | int max; 485 | 486 | if ((max = get_var_integer("HISTSIZE", 10)) < 1) max = 1; 487 | 488 | if ((page = malloc(sizeof(Page))) == NULL) error(1, "cannot allocate new page"); 489 | 490 | page->url = url == NULL ? NULL : str_copy(url); 491 | 492 | va_start(va, fmt); 493 | vsnprintf(page->prompt, sizeof(page->prompt), fmt, va); 494 | va_end(va); 495 | 496 | page->menu = menu; 497 | 498 | if (time(&page->fetched) == -1) page->fetched = 0; 499 | 500 | for (; depth > 0 && depth >= max; --depth) history_pop(); 501 | TAILQ_INSERT_HEAD(&history, page, next); 502 | ++depth; 503 | } 504 | 505 | 506 | static Page *history_lookup(const char *url) { 507 | Page *page, *tmp; 508 | TAILQ_FOREACH_SAFE(page, &history, next, tmp) { 509 | if (page->url == NULL || strcmp(page->url, url) != 0) continue; 510 | TAILQ_REMOVE(&history, page, next); 511 | TAILQ_INSERT_HEAD(&history, page, next); 512 | return page; 513 | } 514 | return NULL; 515 | } 516 | 517 | 518 | /*============================================================================*/ 519 | static int socket_connect(const URL *url, int socktype) { 520 | struct addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = socktype}, *result, *it; 521 | struct timeval tv = {0}; 522 | int timeout, err, fd = -1; 523 | 524 | if ((timeout = get_var_integer("TIMEOUT", 15)) < 1) timeout = 15; 525 | tv.tv_sec = timeout; 526 | 527 | if ((err = getaddrinfo(url->host, url->port, &hints, &result)) != 0) { 528 | error(0, "cannot resolve hostname `%s`: %s", url->host, gai_strerror(err)); 529 | return -1; 530 | } 531 | 532 | for (it = result; it && err != EINTR; it = it->ai_next) { 533 | if ((fd = socket(it->ai_family, it->ai_socktype, it->ai_protocol)) == -1) { err = errno; continue; } 534 | if (fcntl(fd, F_SETFD, FD_CLOEXEC) == 0 && setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) == 0 && setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) == 0 && connect(fd, it->ai_addr, it->ai_addrlen) == 0) break; 535 | err = errno; 536 | close(fd); fd = -1; 537 | } 538 | 539 | freeaddrinfo(result); 540 | 541 | if (fd == -1 && err == EINPROGRESS) error(0, "cannot connect to `%s`:`%s`: cancelled", url->host, url->port); 542 | else if (fd == -1 && err != 0) error(0, "cannot connect to `%s`:`%s`: %s", url->host, url->port, strerror(err)); 543 | return fd; 544 | } 545 | 546 | 547 | static int tcp_connect(const URL *url) { 548 | return socket_connect(url, SOCK_STREAM); 549 | } 550 | 551 | 552 | /*============================================================================*/ 553 | static void parse_plaintext_line(char *line, int *pre, Selector **sel, SelectorList *list) { 554 | (void)pre; 555 | (void)index; 556 | 557 | *sel = new_selector('`'); 558 | (*sel)->repr = str_copy(line); 559 | SIMPLEQ_INSERT_TAIL(list, *sel, next); 560 | } 561 | 562 | 563 | static void parse_gemtext_line(char *line, int *pre, Selector **sel, SelectorList *list) { 564 | char *url; 565 | int level; 566 | 567 | *sel = NULL; 568 | 569 | if (strncmp(line, "```", 3) == 0) { 570 | *pre = !*pre; 571 | return; 572 | } 573 | 574 | if (*pre) { 575 | *sel = new_selector('`'); 576 | (*sel)->repr = str_copy(line); 577 | } else if (line[0] == '=' && line[1] == '>') { 578 | *sel = new_selector('l'); 579 | url = line + 2 + strspn(line + 2, " \t"); 580 | line = url + strcspn(url, " \t"); 581 | if (*line != '\0') { 582 | *line = '\0'; 583 | line += 1 + strspn(line + 1, " \t"); 584 | } 585 | if (!copy_url(*sel, url)) { free_selector(*sel); *sel = NULL; return; } 586 | if (*line) (*sel)->repr = str_copy(line); 587 | else (*sel)->repr = str_copy(url); 588 | } else if (line[0] == '#' && (level = 1 + strspn(&line[1], "#")) <= 3) { 589 | *sel = new_selector('#'); 590 | (*sel)->repr = str_copy(line + level + strspn(line + level, " \t")); 591 | (*sel)->level = level; 592 | } else if (*line == '>' || (line[0] == '*' && line[1] == ' ')) { 593 | *sel = new_selector(*line); 594 | (*sel)->repr = str_copy(line + 1 + strspn(line + 1, " \t")); 595 | } else { 596 | *sel = new_selector('i'); 597 | (*sel)->repr = str_copy(line); 598 | } 599 | 600 | SIMPLEQ_INSERT_TAIL(list, *sel, next); 601 | } 602 | 603 | 604 | static SelectorList parse_file(FILE *fp, const Parser parser) { 605 | static char buffer[LINE_MAX]; 606 | char *line; 607 | SelectorList list = SIMPLEQ_HEAD_INITIALIZER(list); 608 | size_t len; 609 | Selector *sel; 610 | int pre = 0, start = 1; 611 | 612 | for (sel = NULL; (line = fgets(buffer, sizeof(buffer), fp)) != NULL; sel = NULL, start = 0) { 613 | if ((len = strlen(line)) > 1 && buffer[len - 2] == '\r') buffer[len - 2] = '\0'; 614 | else if (line[len - 1] == '\n') line[len - 1] = '\0'; 615 | parser((start && strncmp(line, "\xef\xbb\xbf", 3) == 0) ? line + 3: line, &pre, &sel, &list); 616 | } 617 | 618 | return list; 619 | } 620 | 621 | 622 | /*============================================================================*/ 623 | static char *next_token(char **str) { 624 | char *begin; 625 | if (*str == NULL) return NULL; 626 | *str += strspn(*str, " \v\t"); 627 | switch (**str) { 628 | case '\0': case '#': return NULL; 629 | case '"': ++*str; return strtok_r(*str, "\"", str); 630 | default: 631 | begin = *str; 632 | *str += strcspn(*str, " \v\t"); 633 | if (**str != '\0') { **str = '\0'; ++*str; } 634 | return begin; 635 | } 636 | } 637 | 638 | 639 | static int get_terminal_width() { 640 | struct winsize wz; 641 | ioctl(STDOUT_FILENO, TIOCGWINSZ, &wz); 642 | return wz.ws_col > 20 ? wz.ws_col : 20; 643 | } 644 | 645 | 646 | /*============================================================================*/ 647 | static const char *find_mime_handler(const char *mime) { 648 | Variable *var; 649 | const char *handler = NULL; 650 | size_t length, longest = 0; 651 | 652 | LIST_FOREACH(var, &variables, next) { 653 | if ((length = strlen(var->name)) > longest && !strncasecmp(mime, var->name, length)) { 654 | longest = length; 655 | handler = var->data; 656 | } 657 | } 658 | 659 | if (!handler) fprintf(stderr, "no handler for `%s`\n", mime); 660 | return handler; 661 | } 662 | 663 | 664 | static void reap(const char *command, pid_t pid, int silent) { 665 | pid_t ret; 666 | int status; 667 | 668 | while ((ret = waitpid(pid, &status, 0)) < 0 && errno == EINTR); 669 | if (!silent && ret == pid && WIFEXITED(status)) fprintf(stderr, "`%s` has exited with exit status %d\n", command, WEXITSTATUS(status)); 670 | else if (ret == pid && !WIFEXITED(status)) fprintf(stderr, "`%s` has exited abnormally\n", command); 671 | } 672 | 673 | 674 | static pid_t start_handler(const char *handler, const char *filename, char *command, size_t length, const Selector *sel, const URL *url, int stdin) { 675 | static char buffer[sizeof("/proc/self/fd/2147483647")]; 676 | size_t i; 677 | pid_t pid; 678 | 679 | if (stdin != -1) { 680 | sprintf(buffer, "/proc/self/fd/%d", stdin); 681 | filename = buffer; 682 | } 683 | 684 | for (i = 0; *handler && i < length - 1; ) { 685 | if (handler[0] == '%' && handler[1] != '\0') { 686 | const char *append = ""; 687 | switch (handler[1]) { 688 | case '%': append = "%"; break; 689 | case 's': append = url->scheme; break; 690 | case 'h': append = url->host; break; 691 | case 'p': append = url->port; break; 692 | case 'P': append = url->path; break; 693 | case 'r': append = sel->repr; break; 694 | case 'u': append = url->url; break; 695 | case 'f': append = filename; break; 696 | } 697 | handler += 2; 698 | while (*append && i < length - 1) command[i++] = *append++; 699 | } else command[i++] = *handler++; 700 | } 701 | command[i] = '\0'; 702 | 703 | if ((pid = fork()) == 0) { 704 | #ifdef GPLACES_USE_FLATPAK_SPAWN 705 | if (stdin == -1) execl("/usr/bin/flatpak-spawn", "flatpak-spawn", "--host", "--", "sh", "-c", command, (char *)NULL); 706 | else { 707 | sprintf(buffer, "--forward-fd=%d", stdin); 708 | execl("/usr/bin/flatpak-spawn", "flatpak-spawn", "--host", buffer, "--", "sh", "-c", command, (char *)NULL); 709 | } 710 | #else 711 | execl("/bin/sh", "sh", "-c", command, (char *)NULL); 712 | #endif 713 | exit(EXIT_FAILURE); 714 | } else if (pid < 0) error(0, "could not execute `%s`", command); 715 | return pid; 716 | } 717 | 718 | 719 | static void execute_handler(const char *handler, const char *filename, const Selector *sel, const URL *url) { 720 | static char command[1024]; 721 | pid_t pid; 722 | if ((pid = start_handler(handler, filename, command, sizeof(command), sel, url, -1)) > 0) reap(command, pid, 0); 723 | } 724 | 725 | 726 | /*============================================================================*/ 727 | static int ndigits(int n) { 728 | int digits = 0; 729 | for ( ; n > 0; n /= 10, ++digits); 730 | return digits; 731 | } 732 | 733 | 734 | static void print_line(FILE *fp, const Selector *sel, const regex_t *filter, int width, int *links) { 735 | mbstate_t ps; 736 | size_t size, mbs; 737 | wchar_t wchar; 738 | const char *p; 739 | int w, wchars, out, extra, i = 0; 740 | 741 | if (sel->type == 'l') ++*links; 742 | 743 | if (filter && regexec(filter, sel->repr, 0, NULL, 0) != 0 && (sel->rawurl == NULL || regexec(filter, sel->rawurl, 0, NULL, 0) != 0)) return; 744 | if (!interactive) { fprintf(fp, "%s\n", sel->repr); return; } 745 | 746 | size = strlen(sel->repr); 747 | 748 | do { 749 | out = (int)size; 750 | 751 | extra = 0; 752 | switch (sel->type) { 753 | case 'l': if (i == 0) extra = 3 + ndigits(*links); break; 754 | case '`': goto print; 755 | case '>': 756 | case '*': extra = 2; break; 757 | case '#': if (i == 0) extra = sel->level + 1; 758 | } 759 | 760 | memset(&ps, 0, sizeof(ps)); 761 | for (wchars = 0, out = 0, p = &sel->repr[i]; out < (int)size - i && wchars < width - extra; out += mbs, p = &sel->repr[i + out], wchars += w) { 762 | if ((mbs = mbrtowc(&wchar, p, size - i - out, &ps)) == (size_t)-1 || mbs == (size_t)-2 || mbs == 0 || (w = wcwidth(wchar)) < 0) { 763 | /* best-effort, we assume 1 character == 1 byte */ 764 | mbs = 1; 765 | w = 1; 766 | } else if (wchars + w > width - extra) break; 767 | } 768 | 769 | /* if it's a full line followed by a non-whitespace character, drop the cut word from the end */ 770 | if (wchars + extra == width && i + out < (int)size && sel->repr[i + out] != ' ' && sel->repr[i + out] != '\t') { 771 | for (p = &sel->repr[i + out - 1]; p >= &sel->repr[i] && *p != ' ' && *p != '\t'; --p); 772 | if (p > &sel->repr[i]) out = p - &sel->repr[i]; 773 | } 774 | 775 | print: 776 | switch (sel->type) { 777 | case 'l': 778 | if (i == 0) { 779 | if (color) fprintf(fp, "\33[4;36m[%d]\33[0;39m %.*s\n", *links, out, &sel->repr[i]); 780 | else fprintf(fp, "[%d] %.*s\n", *links, out, &sel->repr[i]); 781 | break; 782 | } 783 | /* fall through */ 784 | case 'i': fprintf(fp, "%.*s\n", out, &sel->repr[i]); break; 785 | case '#': 786 | if (i == 0 && color) fprintf(fp, "\33[4m%.*s %.*s\33[0m\n", sel->level, "###", out, &sel->repr[i]); 787 | else if (i == 0 && !color) fprintf(fp, "%.*s %.*s\n", sel->level, "###", out, &sel->repr[i]); 788 | else if (color) fprintf(fp, "\33[4m%.*s\33[0m\n", out, &sel->repr[i]); 789 | else fprintf(fp, "%.*s\n", out, &sel->repr[i]); 790 | break; 791 | case '`': 792 | fprintf(fp, "%s\n", &sel->repr[i]); 793 | break; 794 | case '>': 795 | fprintf(fp, "%c %.*s\n", sel->type, out, &sel->repr[i]); 796 | break; 797 | default: 798 | if (i == 0) fprintf(fp, "%c %.*s\n", sel->type, out, &sel->repr[i]); 799 | else fprintf(fp, " %.*s\n", out, &sel->repr[i]); 800 | } 801 | 802 | i += out + strspn(&sel->repr[i + out], " "); 803 | } while (i < (int)size); 804 | } 805 | 806 | 807 | static void print_text(FILE *fp, const SelectorList list, const char *filter) { 808 | regex_t re; 809 | const Selector *sel; 810 | int width, links = 0; 811 | 812 | if (filter && regcomp(&re, filter, REG_NOSUB) != 0) filter = NULL; 813 | width = get_terminal_width(); 814 | SIMPLEQ_FOREACH(sel, &list, next) print_line(fp, sel, filter ? &re : NULL, width, &links); 815 | if (filter) regfree(&re); 816 | } 817 | 818 | 819 | /*============================================================================*/ 820 | static int tofu(X509 *cert, const URL *url, int ask) { 821 | static char buffer[1024], hex[EVP_MAX_MD_SIZE * 2 + 1]; 822 | static unsigned char md[EVP_MAX_MD_SIZE]; 823 | size_t size = 1, hlen, plen; 824 | const char *p, *end; 825 | char *line, *start; 826 | unsigned int mdlen, i; 827 | int fd = -1, found = 0, trust = 0; 828 | 829 | if (X509_digest(cert, EVP_sha512(), md, &mdlen) == 0) return 0; 830 | 831 | for (i = 0; i < mdlen; ++i) { 832 | hex[i * 2] = "0123456789ABCDEF"[md[i] >> 4]; 833 | hex[i * 2 + 1] = "0123456789ABCDEF"[md[i] & 0xf]; 834 | } 835 | hex[mdlen * 2] = '\0'; 836 | 837 | hlen = strlen(url->host); 838 | plen = strlen(url->port); 839 | 840 | if ((p = map_file("hosts", &fd, &size)) == NULL && size > 0) return 0; 841 | else if (p != NULL) { 842 | for (end = p; !found && (start = memmem(end, size - (end - p), url->host, hlen)) != NULL; end = start + hlen + 1) { 843 | if (!(found = ((start == p || *(start - 1) == '\n') && size - (start - p) >= hlen + 1 + plen + 1 + mdlen * 2 + 1 && start[hlen] == ':' && memcmp(&start[hlen + 1], url->port, plen) == 0 && start[hlen + 1 + plen] == ' ' && start[hlen + 1 + plen + 1 + mdlen * 2] == '\n'))) continue; 844 | if ((trust = memcmp(&start[hlen + 1 + plen + 1], hex, mdlen * 2) == 0) || !ask) break; 845 | if (color) snprintf(buffer, sizeof(buffer), "\33[35mTrust new certificate for `%s:%s`? (y/n)>\33[0m ", url->host, url->port); 846 | else snprintf(buffer, sizeof(buffer), "Trust new certificate for `%s:%s`? (y/n)> ", url->host, url->port); 847 | if ((line = bestline(buffer)) != NULL) { 848 | if (*line == 'y' || *line == 'Y') { 849 | memcpy(&start[hlen + 1 + plen + 1], hex, mdlen * 2); 850 | trust = 1; 851 | } 852 | free(line); 853 | } 854 | munmap((void *)p, size); 855 | } 856 | } 857 | if (!found) trust = append_line(fd, "%s:%s %s\n", url->host, url->port, hex); 858 | close(fd); 859 | return trust; 860 | } 861 | 862 | 863 | static SSL *ssl_connect(const URL *url, SSL_CTX *ctx, int ask) { 864 | BIO *bio = NULL; 865 | SSL *ssl = NULL; 866 | X509 *cert = NULL; 867 | int fd = -1, ok = 0, err; 868 | 869 | if ((fd = tcp_connect(url)) == -1) goto out; 870 | 871 | if ((ssl = SSL_new(ctx)) == NULL || (bio = BIO_new_socket(fd, BIO_CLOSE)) == NULL || SSL_set_tlsext_host_name(ssl, url->host) == 0) { 872 | error(0, "cannot establish secure connection to `%s`:`%s`", url->host, url->port); 873 | goto out; 874 | } 875 | SSL_set_bio(ssl, bio, bio); 876 | SSL_set_connect_state(ssl); 877 | 878 | if ((err = SSL_get_error(ssl, SSL_do_handshake(ssl))) != SSL_ERROR_NONE) { 879 | if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) error(0, "cannot establish secure connection to `%s`:`%s`: cancelled", url->host, url->port); 880 | else error(0, "cannot establish secure connection to `%s`:`%s`: error %d", url->host, url->port, err); 881 | goto out; 882 | } 883 | 884 | if ((cert = SSL_get_peer_certificate(ssl)) == NULL) { 885 | error(0, "cannot establish secure connection to `%s`:`%s`: no peer certificate", url->host, url->port); 886 | goto out; 887 | } 888 | 889 | if (!(ok = tofu(cert, url, ask))) error(0, "cannot establish secure connection to `%s`:`%s`: bad certificate", url->host, url->port); 890 | 891 | out: 892 | if (cert) X509_free(cert); 893 | if (!ok && ssl) SSL_free(ssl); 894 | else if (!ok && bio) BIO_free(bio); 895 | else if (!ok && fd != -1) close(fd); 896 | return ok ? ssl : NULL; 897 | } 898 | 899 | 900 | static void mkcert(const char *crtpath, const char *keypath) { 901 | EVP_PKEY *key = NULL; 902 | #if OPENSSL_VERSION_NUMBER < 0x30000000L 903 | EC_KEY *eckey = NULL; 904 | #endif 905 | X509 *cert = NULL; 906 | X509_NAME *name; 907 | const char *curve, *digest, *cn; 908 | const EVP_MD *md; 909 | FILE *crtf = NULL, *keyf = NULL; 910 | long days; 911 | int ok = 0; 912 | #if OPENSSL_VERSION_NUMBER < 0x30000000L 913 | int assigned = 0, nid; 914 | #endif 915 | 916 | if ((days = get_var_integer("DAYS", 1825)) <= 0) days = 1825; 917 | if ((curve = set_var(&variables, "CURVE", NULL)) == NULL || *curve == '\0') curve = SN_X9_62_prime256v1; 918 | if ((digest = set_var(&variables, "DIGEST", NULL)) == NULL || *digest == '\0') digest = LN_sha256; 919 | 920 | #if OPENSSL_VERSION_NUMBER < 0x30000000L 921 | ok = ((((cn = set_var(&variables, "CN", NULL)) != NULL && *cn != '\0') || ((cn = getenv("USER")) != NULL && *cn != '\0')) && (md = EVP_get_digestbyname(digest)) != NULL && (cert = X509_new()) != NULL && X509_set_version(cert, 2) == 1 && X509_gmtime_adj(X509_get_notBefore(cert), 0) != NULL && X509_gmtime_adj(X509_get_notAfter(cert), 60 * 60 * 24 * days) != NULL && (name = X509_get_subject_name(cert)) != NULL && X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (const unsigned char *)cn, -1, -1, 0) == 1 && (key = EVP_PKEY_new()) != NULL && (nid = OBJ_sn2nid(curve)) != NID_undef && (eckey = EC_KEY_new_by_curve_name(nid)) != NULL && EC_KEY_generate_key(eckey) == 1 && (assigned = EVP_PKEY_assign_EC_KEY(key, eckey)) == 1 && X509_set_pubkey(cert, key) == 1 && X509_sign(cert, key, md) != 0 && (crtf = fopen(crtpath, "w")) != NULL && (keyf = fopen(keypath, "w")) != NULL && PEM_write_X509(crtf, cert) != 0 && PEM_write_PrivateKey(keyf, key, NULL, NULL, 0, NULL, NULL) != 0); 922 | #else 923 | ok = ((((cn = set_var(&variables, "CN", NULL)) != NULL && *cn != '\0') || ((cn = getenv("USER")) != NULL && *cn != '\0')) && (md = EVP_get_digestbyname(digest)) != NULL && (cert = X509_new()) != NULL && X509_set_version(cert, X509_VERSION_3) == 1 && X509_gmtime_adj(X509_get_notBefore(cert), 0) != NULL && X509_gmtime_adj(X509_get_notAfter(cert), 60 * 60 * 24 * days) != NULL && (name = X509_get_subject_name(cert)) != NULL && X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (const unsigned char *)cn, -1, -1, 0) == 1 && (key = EVP_EC_gen(curve)) != NULL && X509_set_pubkey(cert, key) == 1 && X509_sign(cert, key, md) != 0 && (crtf = fopen(crtpath, "w")) != NULL && (keyf = fopen(keypath, "w")) != NULL && PEM_write_X509(crtf, cert) != 0 && PEM_write_PrivateKey(keyf, key, NULL, NULL, 0, NULL, NULL) != 0); 924 | #endif 925 | 926 | if (keyf) { 927 | fclose(keyf); 928 | if (ok == 0) unlink(keypath); 929 | } 930 | if (crtf) { 931 | fclose(crtf); 932 | if (ok == 0) unlink(crtpath); 933 | } 934 | #if OPENSSL_VERSION_NUMBER < 0x30000000L 935 | if (!assigned && eckey) EC_KEY_free(eckey); 936 | #endif 937 | if (key) EVP_PKEY_free(key); 938 | if (cert) X509_free(cert); 939 | } 940 | 941 | 942 | static int ssl_error(const URL *url, void *c, int err) { 943 | if ((err = SSL_get_error((SSL *)c, err)) == SSL_ERROR_ZERO_RETURN) return 0; 944 | if (err == SSL_ERROR_SSL) error(0, "protocol error while downloading `%s`", url->url); 945 | else if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) error(0, "failed to download `%s`: cancelled", url->url); 946 | else error(0, "failed to download `%s`: error %d", url->url, err); 947 | return 1; 948 | } 949 | 950 | 951 | static int ssl_read(void *c, void *buffer, int length) { 952 | return SSL_read((SSL *)c, buffer, length); 953 | } 954 | 955 | 956 | static int ssl_peek(void *c, void *buffer, int length) { 957 | return SSL_peek((SSL *)c, buffer, length); 958 | } 959 | 960 | 961 | static void ssl_close(void *c) { 962 | SSL_free((SSL *)c); 963 | } 964 | 965 | 966 | static int save_body(const URL *url, void *c, FILE *fp) { 967 | static char buffer[2048]; 968 | size_t total; 969 | int received, prog = 0; 970 | for (total = 0; total < SIZE_MAX - sizeof(buffer) && (received = url->proto->read(c, buffer, sizeof(buffer))) > 0 && fwrite(buffer, 1, received, fp) == (size_t)received; total += received) { 971 | if ((total > 2048 && total - prog > total / 20)) { fputc('.', stderr); prog = total; } 972 | } 973 | if (prog > 0) fputc('\n', stderr); 974 | if (ferror(fp)) { error(0, "failed to download `%s`: failed to write", url->url); return 0; } 975 | return !url->proto->error(url, c, received); 976 | } 977 | 978 | 979 | static int ssl_download(URL *url, SSL **body, char **mime, int request(const URL *, SSL *, void *), void *p, int ask) { 980 | static char crtpath[1024], keypath[1024], suffix[1024], buffer[1024], data[2 + 1 + 1024 + 2 + 1]; /* 99 meta\r\n\0 */ 981 | struct stat stbuf; 982 | const char *home; 983 | SSL_CTX *ctx = NULL; 984 | char *crlf, *meta = &data[3], *line; 985 | int redir, off, len, i, total, received, ret = 40, err = 0; 986 | SSL *ssl = NULL; 987 | 988 | if ((redir = perm_redirect(url, NULL, ask)) == 31) return 31; 989 | else if (redir == 40) goto fail; 990 | 991 | if ((home = getenv("XDG_DATA_HOME")) != NULL) { 992 | if ((off = snprintf(crtpath, sizeof(crtpath), "%s/gplaces_%s_%s", home, url->host, url->port)) >= (int)sizeof(crtpath)) goto fail;; 993 | } else if ((home = getenv("HOME")) == NULL || (off = snprintf(crtpath, sizeof(crtpath), "%s/.gplaces_%s_%s", home, url->host, url->port)) >= (int)sizeof(crtpath)) goto fail; 994 | 995 | if ((ctx = SSL_CTX_new(TLS_client_method())) == NULL) goto fail; 996 | SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1); 997 | SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL); 998 | 999 | /* 1000 | * If the user requests gemini://example.com/foo/bar/baz.gmi, try to load: 1001 | * 1002 | * 1) The certificate for gemini://example.com/foo/bar/baz.gmi 1003 | * 2) The certificate for gemini://example.com/foo/bar 1004 | * 3) The certificate for gemini://example.com/foo 1005 | * 4) The certificate for gemini://example.com 1006 | * 1007 | * If we found a certificate for one of these, stop even if loading fails. 1008 | */ 1009 | for (len = 0; len < (int)sizeof(suffix) - 1 && url->path[len] != '\0'; ++len) suffix[len] = url->path[len] == '/' ? '_' : url->path[len]; 1010 | if (suffix[len - 1] == '_') --len; /* ignore trailing / */ 1011 | suffix[len] = '\0'; 1012 | memcpy(keypath, crtpath, off); 1013 | for (i = (len > 0 && url->path[len - 1] == '/') ? len - 1 : len; i >= 0; --i) { 1014 | if (i < len && url->path[i] != '/') continue; 1015 | snprintf(&crtpath[off], sizeof(crtpath) - off, "%.*s.crt", i, suffix); 1016 | snprintf(&keypath[off], sizeof(keypath) - off, "%.*s.key", i, suffix); 1017 | if (stat(crtpath, &stbuf) == 0 && stat(keypath, &stbuf) == 0) { 1018 | SSL_CTX_use_certificate_file(ctx, crtpath, SSL_FILETYPE_PEM); 1019 | SSL_CTX_use_PrivateKey_file(ctx, keypath, SSL_FILETYPE_PEM); 1020 | goto loaded; 1021 | } 1022 | } 1023 | 1024 | /* 1025 | * if we failed to find a matching certificate and a certificate is 1026 | * generated, we want to associate it with the full path 1027 | */ 1028 | snprintf(&crtpath[off], sizeof(crtpath) - off, "%s.crt", suffix); 1029 | snprintf(&keypath[off], sizeof(keypath) - off, "%s.key", suffix); 1030 | loaded: 1031 | 1032 | if ((ssl = ssl_connect(url, ctx, ask)) == NULL) goto fail; 1033 | 1034 | if ((err = request(url, ssl, p)) != SSL_ERROR_NONE) { 1035 | if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) error(0, "cannot send request to `%s`:`%s`: cancelled", url->host, url->port); 1036 | else error(0, "cannot send request to `%s`:`%s`: error %d", url->host, url->port, err); 1037 | goto fail; 1038 | } 1039 | 1040 | for (total = 0; total < (int)sizeof(data) - 1 && (total < 4 || (data[total - 2] != '\r' && data[total - 1] != '\n')) && (received = SSL_read(ssl, &data[total], 1)) > 0; ++total); 1041 | if (received <= 0 && ssl_error(url, ssl, received)) goto fail; 1042 | else if (total < 4 || data[0] < '1' || data[0] > '6' || data[1] < '0' || data[1] > '9' || (total > 4 && data[2] != ' ') || data[total - 2] != '\r' || data[total - 1] != '\n') { error(0, "failed to download `%s`: invalid status line", url->url); goto fail; } 1043 | data[total] = '\0'; 1044 | 1045 | crlf = &data[total - 2]; 1046 | *crlf = '\0'; 1047 | if (meta >= crlf) meta = ""; 1048 | 1049 | switch (data[0]) { 1050 | case '2': 1051 | if (!*meta) goto fail; 1052 | *body = ssl; 1053 | ssl = NULL; 1054 | *mime = meta; 1055 | break; 1056 | 1057 | case '1': 1058 | if (!ask || !*meta) goto fail; 1059 | if (color) snprintf(buffer, sizeof(buffer), "\33[35m%.*s>\33[0m ", get_terminal_width() - 2, meta); 1060 | else snprintf(buffer, sizeof(buffer), "%.*s> ", get_terminal_width() - 2, meta); 1061 | if (data[1] == '1') bestlineMaskModeEnable(); 1062 | if ((line = bestline(buffer)) == NULL) goto fail; 1063 | if (data[1] != '1' && interactive) bestlineHistoryAdd(line); 1064 | if (data[1] == '1') bestlineMaskModeDisable(); 1065 | if (!set_query(url, line)) { free(line); goto fail; } 1066 | free(line); 1067 | if (data[1] != '1' && interactive) bestlineHistoryAdd(url->url); 1068 | break; 1069 | 1070 | case '3': 1071 | if (!*meta) goto fail; 1072 | if (data[1] == '1' && perm_redirect(url, meta, ask) == 40) goto fail; 1073 | else if (data[1] != '1' && redirect(url, meta, total - 2, ask) == 40) goto fail; 1074 | break; 1075 | 1076 | case '6': 1077 | if (*meta) error(0, "`%s`: %s", url->host, meta); 1078 | else error(0, "client certificate is required for `%s`", url->host); 1079 | if (ask && stat(crtpath, &stbuf) != 0 && errno == ENOENT && stat(keypath, &stbuf) != 0 && errno == ENOENT) { 1080 | if (color) snprintf(buffer, sizeof(buffer), "\33[35mGenerate client certificate for `%s`? (y/n)>\33[0m ", url->host); 1081 | else snprintf(buffer, sizeof(buffer), "Generate client certificate for `%s`? (y/n)> ", url->host); 1082 | if ((line = bestline(buffer)) != NULL) { 1083 | if (*line == 'y' || *line == 'Y') mkcert(crtpath, keypath); 1084 | free(line); 1085 | } 1086 | } 1087 | if (SSL_CTX_use_certificate_file(ctx, crtpath, SSL_FILETYPE_PEM) == 1 && SSL_CTX_use_PrivateKey_file(ctx, keypath, SSL_FILETYPE_PEM) == 1) break; 1088 | error(0, "failed to load client certificate for `%s`: %s", url->host, ERR_reason_error_string(ERR_get_error())); 1089 | ret = 50; 1090 | goto fail; 1091 | 1092 | default: 1093 | error(0, "cannot download `%s`: %s", url->url, *meta ? meta : data); 1094 | } 1095 | 1096 | ret = (data[0] - '0') * 10 + (data[1] - '0'); 1097 | 1098 | fail: 1099 | if (ssl) SSL_free(ssl); 1100 | if (ctx) SSL_CTX_free(ctx); 1101 | return ret; 1102 | } 1103 | 1104 | 1105 | /*============================================================================*/ 1106 | static int gemini_request(const URL *url, SSL *ssl, void *p) { 1107 | static char buffer[1024]; 1108 | int len; 1109 | 1110 | (void)p; 1111 | 1112 | len = snprintf(buffer, sizeof(buffer), "%s\r\n", url->url); 1113 | return SSL_get_error(ssl, SSL_write(ssl, buffer, len >= (int)sizeof(buffer) ? (int)sizeof(buffer) - 1 : len)); 1114 | } 1115 | 1116 | 1117 | static void *gemini_download(const Selector *sel, URL *url, char **mime, Parser *parser, unsigned int redirs, int ask) { 1118 | SSL *ssl = NULL; 1119 | int status = -1; 1120 | 1121 | (void)sel; 1122 | 1123 | do { 1124 | status = ssl_download(url, &ssl, mime, gemini_request, NULL, ask); 1125 | if (status >= 20 && status <= 29) break; 1126 | } while ((status >= 10 && status <= 19) || (status >= 60 && status <= 69) || (status >= 30 && status <= 39 && ++redirs < 5 && url->proto->download == gemini_download)); 1127 | 1128 | if (redirs < 5 && url->proto->download != gemini_download) return url->proto->download(sel, url, mime, parser, redirs, ask); 1129 | 1130 | if (ssl != NULL && strncmp(*mime, "text/gemini", 11) == 0) *parser = parse_gemtext_line; 1131 | else if (ssl != NULL && (!interactive || strncmp(*mime, "text/plain", 10) == 0)) *parser = parse_plaintext_line; 1132 | 1133 | if (redirs == 5) error(0, "too many redirects from `%s`", url->url); 1134 | return ssl; 1135 | } 1136 | 1137 | 1138 | const Protocol gemini = {"gemini", "1965", ssl_read, ssl_peek, ssl_error, ssl_close, gemini_download, set_query}; 1139 | 1140 | 1141 | /*============================================================================*/ 1142 | #ifdef GPLACES_WITH_TITAN 1143 | #include "titan.c" 1144 | #endif 1145 | #if defined(GPLACES_WITH_GOPHER) || defined(GPLACES_WITH_SPARTAN) || defined(GPLACES_WITH_FINGER) || defined(GPLACES_WITH_GUPPY) 1146 | #include "socket.c" 1147 | #endif 1148 | #if defined(GPLACES_WITH_GOPHER) || defined(GPLACES_WITH_SPARTAN) || defined(GPLACES_WITH_FINGER) 1149 | #include "tcp.c" 1150 | #endif 1151 | #if defined(GPLACES_WITH_GOPHER) || defined(GPLACES_WITH_GOPHERS) 1152 | #include "gopher.c" 1153 | #endif 1154 | #ifdef GPLACES_WITH_GOPHERS 1155 | #include "gophers.c" 1156 | #endif 1157 | #ifdef GPLACES_WITH_SPARTAN 1158 | #include "spartan.c" 1159 | #endif 1160 | #ifdef GPLACES_WITH_FINGER 1161 | #include "finger.c" 1162 | #endif 1163 | #ifdef GPLACES_WITH_GUPPY 1164 | #include "guppy.c" 1165 | #endif 1166 | 1167 | 1168 | /*============================================================================*/ 1169 | static const char *get_filename(const URL *url, size_t *len) { 1170 | /* 1171 | * skip the leading / 1172 | * trim all trailing / 1173 | * if the path is /, use the hostname 1174 | * find the last / and skip it 1175 | * if there's no /, return the path 1176 | */ 1177 | const char *p; 1178 | *len = strlen(&url->path[1]); 1179 | while (*len > 0 && url->path[1 + *len - 1] == '/') --*len; 1180 | if (*len == 0) { 1181 | *len = strlen(url->host); 1182 | return url->host; 1183 | } 1184 | p = memrchr(&url->path[1], '/', *len); 1185 | if (p == NULL) return &url->path[1]; 1186 | *len -= p + 1 - &url->path[1]; 1187 | return p + 1; 1188 | } 1189 | 1190 | 1191 | static void stream_to_handler(const Selector *sel, URL *url, const char *filename) { 1192 | static char command[1024]; 1193 | int fds[2]; 1194 | char *mime = NULL; 1195 | void *c; 1196 | Parser parser; 1197 | const char *handler; 1198 | FILE *fp; 1199 | pid_t pid; 1200 | 1201 | if (pipe(fds) == -1) return; 1202 | if (fcntl(fds[1], F_SETFD, FD_CLOEXEC) == 0 && (fp = fdopen(fds[1], "w")) != NULL) { 1203 | setbuf(fp, NULL); 1204 | if ((c = url->proto->download(sel, url, &mime, &parser, 0, 1)) != NULL) { 1205 | if ((handler = find_mime_handler(mime)) != NULL && (pid = start_handler(handler, filename, command, sizeof(command), sel, url, fds[0])) > 0) { 1206 | close(fds[0]); fds[0] = -1; 1207 | save_body(url, c, fp); 1208 | fclose(fp); fp = NULL; 1209 | url->proto->close(c); /* close the connection while the handler is running */ 1210 | reap(command, pid, 0); 1211 | } else url->proto->close(c); 1212 | } 1213 | if (fds[0] != -1) close(fds[0]); 1214 | if (fp != NULL) fclose(fp); 1215 | } else { 1216 | close(fds[0]); 1217 | close(fds[1]); 1218 | } 1219 | } 1220 | 1221 | 1222 | static void download_to_file(const Selector *sel, URL *url, const char *def) { 1223 | static char suggestion[256]; 1224 | FILE *fp; 1225 | char *mime = NULL, *input = NULL, *download_dir; 1226 | const char *filename = def; 1227 | void *c; 1228 | Parser parser; 1229 | size_t len; 1230 | int ret = 0; 1231 | 1232 | if (url->proto == NULL) return; 1233 | if (def != NULL && strcmp(def, "-") == 0) { stream_to_handler(sel, url, def); return; } 1234 | 1235 | if (def == NULL) { 1236 | def = get_filename(url, &len); 1237 | if (((download_dir = set_var(&variables, "DOWNLOAD_DIRECTORY", NULL)) != NULL && *download_dir != '\0') || (download_dir = getenv("XDG_DOWNLOAD_DIR")) != NULL) snprintf(suggestion, sizeof(suggestion), "%s/%.*s", download_dir, (int)len, def); 1238 | else if ((download_dir = getenv("HOME")) != NULL) { 1239 | snprintf(suggestion, sizeof(suggestion), "%s/Downloads", download_dir); 1240 | if (access(suggestion, F_OK) == 0) snprintf(suggestion, sizeof(suggestion), "%s/Downloads/%.*s", download_dir, (int)len, def); 1241 | else snprintf(suggestion, sizeof(suggestion), "%s/%.*s", download_dir, (int)len, def); 1242 | } else snprintf(suggestion, sizeof(suggestion), "./%.*s", (int)len, def); 1243 | if ((input = bestlineInit("enter filename: ", suggestion)) == NULL) return; 1244 | if (*input != '\0') filename = input; 1245 | else filename = suggestion; 1246 | } 1247 | if ((fp = fopen(filename, "wb")) == NULL) error(0, "cannot create file `%s`: %s", filename, strerror(errno)); 1248 | else { 1249 | if ((c = url->proto->download(sel, url, &mime, &parser, 0, 1)) != NULL) { 1250 | ret = save_body(url, c, fp); 1251 | url->proto->close(c); 1252 | } 1253 | 1254 | fclose(fp); 1255 | if (!ret) unlink(filename); 1256 | } 1257 | free(input); 1258 | } 1259 | 1260 | 1261 | static void save_and_handle(const Selector *sel, URL *url, void *c, const char *mime) { 1262 | static char filename[1024]; 1263 | FILE *fp = NULL; 1264 | const char *tmpdir, *handler = NULL; 1265 | int fd = -1; 1266 | 1267 | if ((handler = find_mime_handler(mime)) == NULL) return; 1268 | #ifdef GPLACES_USE_FLATPAK_SPAWN 1269 | if ((tmpdir = getenv("XDG_DATA_HOME")) == NULL) tmpdir = "/tmp"; 1270 | #else 1271 | if ((tmpdir = getenv("TMPDIR")) == NULL) tmpdir = "/tmp"; 1272 | #endif 1273 | snprintf(filename, sizeof(filename), "%s/gplaces.XXXXXXXX", tmpdir); 1274 | if ((fd = mkstemp(filename)) == -1 || (fp = fdopen(fd, "w")) == NULL) error(0, "cannot create temporary file: %s", strerror(errno)); 1275 | else if (save_body(url, c, fp) && fflush(fp) == 0) execute_handler(handler, filename, sel, url); 1276 | 1277 | if (fp != NULL) fclose(fp); 1278 | if (fd != -1) { 1279 | if (fp == NULL) close(fd); 1280 | unlink(filename); 1281 | } 1282 | } 1283 | 1284 | 1285 | /*============================================================================*/ 1286 | static SelectorList download_text(const Selector *sel, URL *url, int ask, int handle, int print) { 1287 | static char buffer[LINE_MAX]; 1288 | SelectorList list = SIMPLEQ_HEAD_INITIALIZER(list); 1289 | Parser parser = NULL; 1290 | Selector *it; 1291 | char *mime, *start, *end; 1292 | void *c = NULL; 1293 | size_t parsed, length = 0, total = 0, prog = 0; 1294 | int received, pre = 0, width, ok = 0, links = 0; 1295 | 1296 | if (url->proto == NULL || (c = url->proto->download(sel, url, &mime, &parser, 0, ask)) == NULL) goto out; 1297 | if (parser == NULL) { 1298 | if (handle) save_and_handle(sel, url, c, mime); 1299 | goto out; 1300 | } 1301 | width = get_terminal_width(); 1302 | while ((received = url->proto->read(c, &buffer[length], sizeof(buffer) - length)) > 0) { 1303 | for (length += received, parsed = 0, start = buffer; start < buffer + length; parsed += end - start + 1, start = end + 1) { 1304 | if ((end = memchr(start, '\n', length - parsed)) == NULL) { 1305 | if (parsed > 0 || length < sizeof(buffer)) break; /* if we still don't have the end of the line, receive more */ 1306 | end = &buffer[sizeof(buffer) - 1]; /* if the buffer is full and we haven't found a \n, terminate the line */ 1307 | } 1308 | if (end > start && end[-1] == '\r') end[-1] = '\0'; 1309 | else *end = '\0'; 1310 | parser((parsed == 0 && strncmp(start, "\xef\xbb\xbf", 3) == 0) ? start + 3: start, &pre, &it, &list); 1311 | if (print && it) print_line(stdout, it, NULL, width, &links); 1312 | } 1313 | length -= parsed; 1314 | memmove(buffer, &buffer[parsed], length); 1315 | buffer[length] = '\0'; 1316 | total += received; 1317 | if (!print && total > 2048 && total - prog > total / 20) { fputc('.', stderr); prog = total; } 1318 | if (total > SIZE_MAX - sizeof(buffer)) break; 1319 | } 1320 | if (prog > 0) fputc('\n', stderr); 1321 | if (!(ok = (received <= 0 && !url->proto->error(url, c, received)))) goto out; 1322 | if (length > 0) { 1323 | parser((parsed == 0 && strncmp(buffer, "\xef\xbb\xbf", 3) == 0) ? buffer + 3: buffer, &pre, &it, &list); 1324 | if (print && it) print_line(stdout, it, NULL, width, &links); 1325 | } 1326 | 1327 | out: 1328 | if (c != NULL) url->proto->close(c); 1329 | if (!ok) { free_selectors(&list); SIMPLEQ_INIT(&list); } 1330 | return list; 1331 | } 1332 | 1333 | 1334 | static SelectorList download_feed(void) { 1335 | URL url, lurl; 1336 | char ts[11]; 1337 | SelectorList list, feed = SIMPLEQ_HEAD_INITIALIZER(feed); 1338 | const Selector *sel; 1339 | Selector *it, *copy; 1340 | struct tm *tm; 1341 | time_t t; 1342 | 1343 | t = time(NULL); 1344 | tm = gmtime(&t); 1345 | strftime(ts, sizeof(ts), "%Y-%m-%d", tm); 1346 | 1347 | SIMPLEQ_FOREACH(sel, &subscriptions, next) { 1348 | memset(&url, 0, sizeof(url)); 1349 | if (!parse_url(&url, sel->rawurl, NULL, NULL)) continue; 1350 | 1351 | list = download_text(sel, &url, 0, 0, 0); 1352 | if (SIMPLEQ_EMPTY(&list)) { free_url(&url); continue; } 1353 | 1354 | if (color) history_push(url.url, list, "\33[35m%s>\33[0m ", url.url + strlen(url.scheme) + 3); 1355 | else history_push(url.url, list, "%s> ", url.url + strlen(url.scheme) + 3); 1356 | 1357 | copy = new_selector('l'); 1358 | if (!copy_url(copy, url.url)) { free_selector(copy); free_url(&url); continue; } 1359 | 1360 | SIMPLEQ_FOREACH(it, &list, next) { 1361 | if (it->type == '#' && it->level == 1) { 1362 | copy->repr = str_copy(it->repr); 1363 | break; 1364 | } 1365 | } 1366 | 1367 | if (copy->repr == NULL) copy->repr = str_copy(sel->rawurl); 1368 | 1369 | SIMPLEQ_INSERT_TAIL(&feed, copy, next); 1370 | 1371 | SIMPLEQ_FOREACH(it, &list, next) { 1372 | if (it->type == 'l' && !strncmp(it->repr, ts, 10)) { 1373 | memset(&lurl, 0, sizeof(lurl)); 1374 | if (!parse_url(&lurl, it->rawurl, url.url, NULL)) { free_url(&lurl); continue; } 1375 | copy = new_selector('l'); 1376 | if (!copy_url(copy, lurl.url)) { free_selector(copy); free_url(&lurl); continue; } 1377 | free_url(&lurl); 1378 | copy->repr = str_copy(it->repr); 1379 | SIMPLEQ_INSERT_TAIL(&feed, copy, next); 1380 | } 1381 | } 1382 | 1383 | free_url(&url); 1384 | } 1385 | 1386 | return feed; 1387 | } 1388 | 1389 | 1390 | static void page_gemtext(const SelectorList list) { 1391 | int fds[2]; 1392 | FILE *fp; 1393 | pid_t pid; 1394 | const char *pager; 1395 | 1396 | if ((pager = set_var(&variables, "PAGER", NULL)) == NULL && (pager = getenv("PAGER")) == NULL) pager = "less -r"; 1397 | if (!strcmp(pager, "cat")) return; 1398 | 1399 | if (pipe(fds) < 0) return; 1400 | if ((pid = fork()) == 0) { 1401 | close(fds[1]); 1402 | dup2(fds[0], STDIN_FILENO); 1403 | close(fds[0]); 1404 | execl("/bin/sh", "sh", "-c", pager, (char *)NULL); 1405 | exit(EXIT_FAILURE); 1406 | } else if (pid < 0) return; 1407 | 1408 | close(fds[0]); 1409 | 1410 | if ((fp = fdopen(fds[1], "w")) == NULL) close(fds[1]); 1411 | else { 1412 | print_text(fp, list, NULL); 1413 | fclose(fp); 1414 | } 1415 | 1416 | reap(pager, pid, 1); 1417 | } 1418 | 1419 | 1420 | static SelectorList navigate(const Selector *sel, URL *url) { 1421 | char buf[20]; 1422 | const char *handler = NULL, *ext; 1423 | Page *page; 1424 | SelectorList new = SIMPLEQ_HEAD_INITIALIZER(new); 1425 | FILE *fp; 1426 | #ifdef GPLACES_USE_LIBMAGIC 1427 | magic_t mag; 1428 | #endif 1429 | const char *mime = NULL; 1430 | int plain = 0, gemtext = 0, off = 0; 1431 | 1432 | if ((page = history_lookup(url->url)) != NULL) { 1433 | print_text(stdout, page->menu, NULL); 1434 | if (strftime(buf, sizeof(buf), "%F %T", localtime(&page->fetched)) == 0) memcpy(buf, "?", 2); 1435 | fprintf(stderr, "cached %s\n", buf); 1436 | if (interactive) page_gemtext(page->menu); 1437 | return page->menu; 1438 | } 1439 | 1440 | if (!strcmp(sel->rawurl, feed_sel.rawurl)) { 1441 | new = download_feed(); 1442 | off = 7; 1443 | } else if (!strcmp(url->scheme, "file")) { 1444 | if ((ext = strrchr(url->path, '.')) == NULL || (!(plain = (strcmp(ext, ".txt") == 0)) && !(gemtext = (strcmp(ext, ".gmi") == 0)))) { 1445 | #ifdef GPLACES_USE_LIBMAGIC 1446 | if ((mag = magic_open(MAGIC_MIME_TYPE | MAGIC_NO_CHECK_COMPRESS | MAGIC_ERROR)) == NULL) return new; 1447 | if (magic_load(mag, NULL) == 0 && (mime = magic_file(mag, url->path)) != NULL && !(plain = (strncmp(mime, "text/plain", 10) == 0)) && !(gemtext = (strncmp(mime, "text/gemini", 11) == 0))) handler = find_mime_handler(mime); 1448 | magic_close(mag); 1449 | #endif 1450 | if (mime == NULL) error(0, "unable to detect the MIME type of %s", url->path); 1451 | } 1452 | if (!plain && !gemtext) goto handle; 1453 | if ((fp = fopen(url->path, "r")) == NULL) return new; 1454 | new = parse_file(fp, plain ? parse_plaintext_line : parse_gemtext_line); 1455 | fclose(fp); 1456 | off = 4; 1457 | } else if (url->proto == NULL) { 1458 | handler = find_mime_handler(url->scheme); 1459 | goto handle; 1460 | } else { 1461 | new = download_text(sel, url, interactive, 1, 1); 1462 | off = strlen(url->scheme); 1463 | } 1464 | 1465 | if (SIMPLEQ_EMPTY(&new)) return new; 1466 | if (color) history_push(url->url, new, "\33[35m%s>\33[0m ", url->url + off + 3); 1467 | else history_push(url->url, new, "%s> ", url->url + off + 3); 1468 | if (interactive) page_gemtext(new); 1469 | return new; 1470 | 1471 | handle: 1472 | if (handler) execute_handler(handler, url->url, sel, url); 1473 | return new; 1474 | } 1475 | 1476 | 1477 | /*============================================================================*/ 1478 | static const char *help[] = { 1479 | "save []", 1480 | "set ", 1481 | "show []", 1482 | "sub []", 1483 | "get", 1484 | "help", 1485 | "version" 1486 | }; 1487 | 1488 | 1489 | /*============================================================================*/ 1490 | static void cmd_show(char *line) { 1491 | const char *filter; 1492 | if ((filter = next_token(&line)) == NULL) page_gemtext(currentmenu); 1493 | print_text(stdout, currentmenu, filter); 1494 | } 1495 | 1496 | 1497 | static void cmd_save(char *line) { 1498 | URL url = {0}; 1499 | char *path, *end; 1500 | Selector tmp = {.type = 'l'}; 1501 | const Selector *sel; 1502 | long index; 1503 | if ((tmp.rawurl = next_token(&line)) == NULL) return; 1504 | path = next_token(&line); 1505 | if ((index = strtol(tmp.rawurl, &end, 10)) > 0 && index < INT_MAX && *end == '\0' && (sel = find_selector(currentmenu, (int)index)) != NULL && parse_url(&url, sel->rawurl, currenturl, NULL)) download_to_file(sel, &url, path); 1506 | else if ((index == LONG_MIN || index == LONG_MAX || *end != '\0') && parse_url(&url, tmp.rawurl, NULL, NULL)) download_to_file(&tmp, &url, path); 1507 | free_url(&url); 1508 | } 1509 | 1510 | 1511 | static void cmd_get(char *line) { 1512 | URL url = {0}; 1513 | Page *page; 1514 | Selector sel = {.type = 'l'}; 1515 | SelectorList new = SIMPLEQ_HEAD_INITIALIZER(new); 1516 | 1517 | (void)line; 1518 | 1519 | if (TAILQ_EMPTY(&history)) return; 1520 | 1521 | page = TAILQ_FIRST(&history); 1522 | TAILQ_REMOVE(&history, page, next); 1523 | --depth; 1524 | 1525 | sel.rawurl = page->url; 1526 | if (parse_url(&url, page->url, NULL, NULL)) new = navigate(&sel, &url); 1527 | free_url(&url); 1528 | 1529 | if (SIMPLEQ_EMPTY(&new)) { 1530 | TAILQ_INSERT_HEAD(&history, page, next); 1531 | ++depth; 1532 | } else free_page(page); 1533 | } 1534 | 1535 | 1536 | static void cmd_help(char *line) { 1537 | size_t i; 1538 | 1539 | (void)line; 1540 | 1541 | puts("available commands:"); 1542 | for (i = 0; i < sizeof(help) / sizeof(help[0]); ++i) puts(help[i]); 1543 | } 1544 | 1545 | 1546 | static void cmd_sub(char *line) { 1547 | static URL url = {.url = feed_sel.rawurl}; 1548 | char *newurl = next_token(&line); 1549 | if (newurl) { 1550 | Selector *sel = new_selector('l'); 1551 | if (copy_url(sel, newurl)) SIMPLEQ_INSERT_TAIL(&subscriptions, sel, next); 1552 | else free_selector(sel); 1553 | } else navigate(&feed_sel, &url); 1554 | } 1555 | 1556 | 1557 | static void cmd_set(char *line) { 1558 | char *name = next_token(&line); 1559 | char *data = next_token(&line); 1560 | 1561 | if (name != NULL && data != NULL) set_var(&variables, name, data); 1562 | } 1563 | 1564 | 1565 | static void cmd_version(char *line) { 1566 | (void) line; 1567 | 1568 | puts( 1569 | "gplaces - "GPLACES_VERSION" Copyright (C) 2022 - 2024 Dima Krasner\n" \ 1570 | "Based on delve 0.15.4 Copyright (C) 2019 Sebastian Steinhauer\n" \ 1571 | "This program is free software and comes with ABSOLUTELY NO WARRANTY;\n" \ 1572 | "see "PREFIX"/share/doc/gplaces/LICENSE for details." 1573 | ); 1574 | } 1575 | 1576 | 1577 | static const Command commands[] = { 1578 | { "show", cmd_show }, 1579 | { "save", cmd_save }, 1580 | { "get", cmd_get }, 1581 | { "help", cmd_help }, 1582 | { "sub", cmd_sub }, 1583 | { "set", cmd_set }, 1584 | { "version", cmd_version }, 1585 | { NULL, NULL } 1586 | }; 1587 | 1588 | 1589 | /*============================================================================*/ 1590 | static void eval(const char *input, const char *filename, int line_no) { 1591 | URL url = {0}; 1592 | const Command *cmd; 1593 | Selector tmp = {.type = 'l'}; 1594 | const Selector *sel; 1595 | char *copy, *line, *token, *var, *rawurl, *end; 1596 | long index; 1597 | 1598 | if ((index = strtol(input, &end, 10)) > 0 && index < INT_MAX && *end == '\0' && (sel = find_selector(currentmenu, (int)index)) != NULL) { 1599 | if (parse_url(&url, sel->rawurl, currenturl, NULL) && interactive) { bestlineHistoryAdd(url.url); navigate(sel, &url); } 1600 | else if (interactive) bestlineHistoryAdd(input); 1601 | free_url(&url); 1602 | return; 1603 | } else if (index > 0 && index != LONG_MAX && *end == '\0') return; 1604 | 1605 | if (interactive) bestlineHistoryAdd(input); 1606 | 1607 | copy = line = str_copy(input); /* copy input as it will be modified */ 1608 | 1609 | if ((token = rawurl = next_token(&line)) != NULL && *token != '\0') { 1610 | for (cmd = commands; cmd->name; ++cmd) { 1611 | if (!strcasecmp(cmd->name, token)) { 1612 | cmd->func(line); 1613 | free(copy); 1614 | return; 1615 | } 1616 | } 1617 | if ((var = set_var(&variables, token, NULL)) != NULL) rawurl = var; 1618 | tmp.rawurl = rawurl; 1619 | if (parse_url(&url, rawurl, NULL, next_token(&line))) navigate(&tmp, &url); 1620 | else if (filename == NULL) error(0, "unknown command `%s`", token); 1621 | else error(0, "unknown command `%s` in file `%s` at line %d", token, filename, line_no); 1622 | free_url(&url); 1623 | } 1624 | 1625 | free(copy); 1626 | } 1627 | 1628 | 1629 | static void shell_name_completion(const char *text, bestlineCompletions *lc) { 1630 | static char buffer[1024]; 1631 | URL url = {0}; 1632 | const Command *cmd; 1633 | const Variable *var; 1634 | const Selector *sel; 1635 | long index; 1636 | char *end; 1637 | int fd; 1638 | size_t len, namelen; 1639 | char *sep; 1640 | DIR *dir; 1641 | struct dirent *ent; 1642 | 1643 | if ((index = strtol(text, &end, 10)) > 0 && index < INT_MAX && *end == '\0' && (sel = find_selector(currentmenu, (int)index)) != NULL) { 1644 | if (parse_url(&url, sel->rawurl, currenturl, NULL)) bestlineAddCompletion(lc, url.url); 1645 | free_url(&url); 1646 | } 1647 | 1648 | len = strlen(text); 1649 | 1650 | for (cmd = commands; cmd->name; ++cmd) 1651 | if (!strncasecmp(cmd->name, text, len)) bestlineAddCompletion(lc, cmd->name); 1652 | 1653 | LIST_FOREACH(var, &variables, next) 1654 | if (!strncasecmp(var->name, text, len)) bestlineAddCompletion(lc, var->name); 1655 | 1656 | if ((sep = strrchr(text, '/')) == NULL || (size_t)(sep - text) >= sizeof(buffer)) return; 1657 | if (sep == text) { 1658 | buffer[0] = '/'; 1659 | buffer[1] = '\0'; 1660 | } else { 1661 | memcpy(buffer, text, sep - text); 1662 | buffer[sep - text] = '\0'; 1663 | } 1664 | 1665 | if ((dir = opendir(buffer)) == NULL) return; 1666 | if ((fd = dirfd(dir)) == -1) { closedir(dir); return; } 1667 | if (sep > text) buffer[sep - text] = '/'; 1668 | while ((ent = readdir(dir)) != NULL) { 1669 | if (ent->d_name[0] == '.') continue; 1670 | if (strncmp(ent->d_name, sep + 1, len - (sep - text) - 1) != 0) continue; 1671 | namelen = strlen(ent->d_name); 1672 | if (sizeof(buffer) <= (size_t)(sep - text + 1 + namelen)) continue; 1673 | memcpy(&buffer[sep - text + 1], ent->d_name, namelen); 1674 | buffer[sep - text + 1 + namelen] = '\0'; 1675 | bestlineAddCompletion(lc, buffer); 1676 | } 1677 | closedir(dir); 1678 | } 1679 | 1680 | 1681 | static char *shell_hints(const char *buf, const char **ansi1, const char **ansi2) { 1682 | static char hint[1024]; 1683 | struct stat stbuf; 1684 | const SelectorList list = currentmenu; 1685 | const Selector *sel; 1686 | const char *val, *pos; 1687 | char *end; 1688 | long index; 1689 | int links = 0; 1690 | if (!color) *ansi1 = *ansi2 = ""; 1691 | if (inshell && strcspn(buf, " ") == 0) { 1692 | SIMPLEQ_FOREACH(sel, &list, next) if (sel->type == 'l') ++links; 1693 | if (links > 1) { 1694 | snprintf(hint, sizeof(hint), "1-%d, URL, variable or command", links); 1695 | return hint; 1696 | } else if (links == 1) return "1, URL, variable or command"; 1697 | else return "URL, variable or command; type `help` for help"; 1698 | } 1699 | if ((pos = strrchr(buf, ' ')) != NULL) buf = &pos[1]; 1700 | if ((index = strtol(buf, &end, 10)) > 0 && index < INT_MAX && *end == '\0') { 1701 | if ((sel = find_selector(currentmenu, (int)index)) == NULL) return NULL; 1702 | if (strncmp(sel->rawurl, "gemini://", 9) == 0) snprintf(hint, sizeof(hint), " %s", &sel->rawurl[9]); 1703 | else snprintf(hint, sizeof(hint), " %s", sel->rawurl); 1704 | } else if ((val = set_var(&variables, buf, NULL)) != NULL) { 1705 | if (strncmp(val, "gemini://", 9) == 0) snprintf(hint, sizeof(hint), " %s", &val[9]); 1706 | else if (strncmp(val, "file://", 7) == 0) snprintf(hint, sizeof(hint), " %s", &val[7]); 1707 | else snprintf(hint, sizeof(hint), " %s", val); 1708 | } else if (buf[0] == '/' && stat(buf, &stbuf) == 0 && S_ISDIR(stbuf.st_mode)) return "/"; 1709 | else return NULL; 1710 | return hint; 1711 | } 1712 | 1713 | 1714 | static void shell(int argc, char **argv) { 1715 | static char path[1024]; 1716 | const char *home = NULL, *prompt; 1717 | char *line; 1718 | 1719 | if (interactive) { 1720 | bestlineSetCompletionCallback(shell_name_completion); 1721 | if ((home = getenv("XDG_DATA_HOME")) != NULL) { 1722 | snprintf(path, sizeof(path), "%s/gplaces_history", home); 1723 | bestlineHistoryLoad(path); 1724 | } else if ((home = getenv("HOME")) != NULL) { 1725 | snprintf(path, sizeof(path), "%s/.gplaces_history", home); 1726 | bestlineHistoryLoad(path); 1727 | } 1728 | bestlineSetHintsCallback(shell_hints); 1729 | } 1730 | 1731 | if (optind < argc) eval(argv[optind], NULL, 0); 1732 | 1733 | for (prompt = color ? "\33[35m>\33[0m " : "> "; ; prompt = TAILQ_EMPTY(&history) ? prompt : TAILQ_FIRST(&history)->prompt) { 1734 | inshell = 1; 1735 | if ((line = bestline(prompt)) == NULL) break; 1736 | inshell = 0; 1737 | eval(line, NULL, 0); 1738 | free(line); 1739 | } 1740 | 1741 | if (interactive && home != NULL) bestlineHistorySave(path); 1742 | } 1743 | 1744 | 1745 | /*============================================================================*/ 1746 | static int load_rc_file(const char *filename) { 1747 | static char buffer[1024]; 1748 | char *line; 1749 | FILE *fp; 1750 | int line_no = 0, ret; 1751 | 1752 | if ((fp = fopen(filename, "rb")) == NULL) return 0; 1753 | while ((line = fgets(buffer, sizeof(buffer), fp)) != NULL) { 1754 | line[strcspn(line, "\r\n")] = '\0'; 1755 | eval(buffer, filename, ++line_no); 1756 | } 1757 | 1758 | ret = feof(fp); 1759 | 1760 | fclose(fp); 1761 | return ret; 1762 | } 1763 | 1764 | 1765 | static void load_rc_files(const char *rcfile) { 1766 | static char buffer[1024]; 1767 | const char *home; 1768 | 1769 | if (rcfile) { load_rc_file(rcfile); return; } 1770 | if ((home = getenv("XDG_CONFIG_HOME")) != NULL) { 1771 | snprintf(buffer, sizeof(buffer), "%s/gplacesrc", home); 1772 | if (load_rc_file(buffer)) return; 1773 | } 1774 | if ((home = getenv("HOME")) != NULL) { 1775 | snprintf(buffer, sizeof(buffer), "%s/.gplacesrc", home); 1776 | if (load_rc_file(buffer)) return; 1777 | } 1778 | load_rc_file(CONFDIR"/gplacesrc"); 1779 | } 1780 | 1781 | 1782 | static const char *parse_arguments(int argc, char **argv) { 1783 | const char *rcfile = NULL; 1784 | int ch; 1785 | while ((ch = getopt(argc, argv, "r:")) != -1) { 1786 | switch (ch) { 1787 | case 'r': 1788 | rcfile = optarg; 1789 | break; 1790 | 1791 | default: 1792 | fprintf(stderr, "usage: gplaces [-r rc-file] [url]\n"); 1793 | exit(EXIT_SUCCESS); 1794 | } 1795 | } 1796 | return rcfile; 1797 | } 1798 | 1799 | 1800 | static void quit_client() { 1801 | free_variables(&variables); 1802 | free_selectors(&subscriptions); 1803 | free_history(&history); 1804 | if (interactive) puts("\33[0m"); 1805 | } 1806 | 1807 | 1808 | static void sigint(int sig) { 1809 | (void)sig; 1810 | } 1811 | 1812 | 1813 | int main(int argc, char **argv) { 1814 | struct sigaction sa = {.sa_handler = sigint}; 1815 | 1816 | setlocale(LC_ALL, ""); 1817 | atexit(quit_client); 1818 | setlinebuf(stdout); /* if stdout is a file, flush after every line */ 1819 | sigemptyset(&sa.sa_mask); 1820 | sigaction(SIGINT, &sa, NULL); 1821 | signal(SIGPIPE, SIG_IGN); 1822 | 1823 | SSL_library_init(); 1824 | SSL_load_error_strings(); 1825 | 1826 | color = (getenv("NO_COLOR") == NULL); 1827 | 1828 | load_rc_files(parse_arguments(argc, argv)); 1829 | 1830 | interactive = isatty(STDIN_FILENO) && isatty(STDOUT_FILENO); 1831 | color = color && interactive; 1832 | 1833 | shell(argc, argv); 1834 | 1835 | return 0; 1836 | } 1837 | /* vim: set ts=4 sw=4 noexpandtab: */ 1838 | -------------------------------------------------------------------------------- /gplaces.desktop.in: -------------------------------------------------------------------------------- 1 | [Desktop Entry] 2 | Name=gplaces 3 | Comment=A simple terminal based Gemini client 4 | Exec=gplaces %u 5 | Icon=gplaces 6 | Terminal=true 7 | Type=Application 8 | MimeType=x-scheme-handler/gemini 9 | Categories=Network;WebBrowser;ConsoleOnly; 10 | Keywords=gemini;client;browser 11 | -------------------------------------------------------------------------------- /gplaces.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /gplacesrc.in: -------------------------------------------------------------------------------- 1 | # gplaces Gemini client initialization example 2 | # place this file in $XDG_CONFIG_HOME/gplacesrc, ~/.gplacesrc or /etc/gplacesrc 3 | 4 | # define default handlers 5 | set https "xdg-open %u" 6 | set image/ "chafa %f" 7 | set audio/ "mpv %f" 8 | set video/ "mpv %f" 9 | set application/pdf "xdg-open %f" 10 | 11 | # define some aliases 12 | set readme file://DOCDIR/README.gmi 13 | set license file://DOCDIR/LICENSE 14 | set authors file://DOCDIR/AUTHORS 15 | set search tlgs.one/search 16 | set gsearch gopher://gopher.floodgap.com/7/v2/vs 17 | set home geminiprotocol.net 18 | set capcom gemini.circumlunar.space/capcom 19 | set spacewalk rawtext.club/~sloum/spacewalk.gmi 20 | set gmisub calcuode.com/gmisub-aggregate.gmi 21 | set bbs bbs.geminispace.org 22 | set station station.martinrue.com 23 | set antenna warmedal.se/~antenna/ 24 | set explore tilde.team/~sumpygump/explore/ 25 | set gemipedia gemi.dev/cgi-bin/wp.cgi 26 | set whatis gemi.dev/cgi-bin/wp.cgi/view 27 | 28 | # subscribe to some pages 29 | sub rawtext.club/~sloum/spacewalk.gmi 30 | sub midnight.pub 31 | sub warmedal.se/~antenna/ 32 | 33 | # define the client certificate curve or "" to fall back to prime256v1 34 | set curve "prime256v1" 35 | 36 | # define the client certificate digest or "" to fall back to sha256 37 | set digest "sha256" 38 | 39 | # define the client certificate CN or "" to fall back to $USER 40 | set cn "" 41 | 42 | # define the client certificate expiration time (days) 43 | set days 1825 44 | 45 | # pager for long text; change to cat to disable paging 46 | set pager "less -r" 47 | 48 | # download timeout 49 | set timeout 15 50 | 51 | # history size; this is the maximum number of cached pages 52 | set histsize 10 53 | -------------------------------------------------------------------------------- /guppy.c: -------------------------------------------------------------------------------- 1 | /* 2 | ================================================================================ 3 | 4 | gplaces - a simple terminal Gemini client 5 | Copyright (C) 2022 - 2024 Dima Krasner 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | ================================================================================ 21 | */ 22 | #include 23 | 24 | 25 | /*============================================================================*/ 26 | typedef struct GuppyChunk { 27 | long seq; 28 | ssize_t length, skip; 29 | char buffer[USHRT_MAX + 1]; 30 | LIST_ENTRY(GuppyChunk) next; 31 | } GuppyChunk; 32 | typedef LIST_HEAD(GuppyChunks, GuppyChunk) GuppyChunks; 33 | 34 | typedef struct GuppySocket { 35 | int fd; /* must be first so socket_*() work */ 36 | GuppyChunks chunks; 37 | long first, last; 38 | } GuppySocket; 39 | 40 | 41 | /*============================================================================*/ 42 | static void guppy_close(void *c) { 43 | GuppySocket *s = (GuppySocket *)c; 44 | GuppyChunk *chunk, *tmp; 45 | close(s->fd); 46 | LIST_FOREACH_SAFE(chunk, &s->chunks, next, tmp) free(chunk); 47 | free(c); 48 | } 49 | 50 | 51 | static int guppy_ack(int fd, long seq) { 52 | char ack[23]; 53 | int length; 54 | ssize_t sent; 55 | 56 | length = sprintf(ack, "%ld\r\n", seq); 57 | 58 | if ((sent = send(fd, ack, length, 0)) < 0) return 0; 59 | if (sent != (ssize_t)length) { errno = EPROTO; return 0; } 60 | 61 | return 1; 62 | } 63 | 64 | 65 | static int do_guppy_download(URL *url, GuppySocket *s, char **mime, int ask) { 66 | static char buffer[1024], prompt[1024]; 67 | struct pollfd pfd = {.fd = s->fd, .events = POLLIN}; 68 | GuppyChunk *chunk = NULL, *last, *tmp; 69 | char *crlf, *end, *input; 70 | long eof = 0; 71 | int len, timeout, i, n, rc, dup; 72 | 73 | if ((len = strlen(url->url)) > (int)sizeof(buffer) - 2) return 4; 74 | 75 | memcpy(buffer, url->url, len); 76 | buffer[len] = '\r'; 77 | buffer[len + 1] = '\n'; 78 | 79 | if ((timeout = get_var_integer("TIMEOUT", 15)) < 1) timeout = 15; 80 | 81 | for (i = 0; i < timeout; ++i) { 82 | request: 83 | /* send or re-transmit the request */ 84 | if (send(pfd.fd, buffer, len + 2, 0) <= 0) { 85 | free(chunk); 86 | if (errno == EAGAIN || errno == EWOULDBLOCK) error(0, "cannot send request to `%s`:`%s`: cancelled", url->host, url->port); 87 | else error(0, "cannot send request to `%s`:`%s`: %s", url->host, url->port, strerror(errno)); 88 | return 4; 89 | } 90 | 91 | pfd.revents = 0; 92 | if ((n = poll(&pfd, 1, 1000)) == 0) continue; 93 | if (n < 0) { free(chunk); return 4; } 94 | 95 | while (1) { 96 | if (chunk == NULL && (chunk = malloc(sizeof(GuppyChunk))) == NULL) { free(chunk); return 4; } 97 | 98 | if ((chunk->length = recv(pfd.fd, chunk->buffer, sizeof(chunk->buffer) - 1, MSG_DONTWAIT)) < 0) { 99 | /* if we received all incoming packets, resend the request */ 100 | if (errno == EAGAIN || errno == EWOULDBLOCK) goto request; 101 | error(0, "cannot send request to `%s`:`%s`: %s", url->host, url->port, strerror(errno)); 102 | free(chunk); 103 | return 4; 104 | } 105 | 106 | if (chunk->length < 5 || (crlf = memchr(chunk->buffer, '\r', chunk->length - 1)) == NULL || *(crlf + 1) != '\n') continue; 107 | *crlf = '\0'; 108 | 109 | if (chunk->buffer[1] == ' ') { 110 | rc = chunk->buffer[0] - '0'; 111 | if (chunk->buffer[0] == '1') { 112 | if (!ask) { free(chunk); return 4; } 113 | if (color) snprintf(prompt, sizeof(prompt), "\33[35m%.*s>\33[0m ", get_terminal_width() - 2, &chunk->buffer[2]); 114 | else snprintf(prompt, sizeof(prompt), "%.*s> ", get_terminal_width() - 2, &chunk->buffer[2]); 115 | free(chunk); 116 | if ((input = bestline(prompt)) == NULL) return 4; 117 | if (interactive) bestlineHistoryAdd(input); 118 | if (!set_query(url, input)) { free(input); return 4; } 119 | free(input); 120 | if (interactive) bestlineHistoryAdd(url->url); 121 | } else if (chunk->buffer[0] == '3') { 122 | if (!redirect(url, &chunk->buffer[2], chunk->length - 4, ask)) { free(chunk); return 4; } 123 | free(chunk); 124 | } else if (chunk->buffer[0] == '4') { 125 | error(0, "cannot download `%s`: %s", url->url, &chunk->buffer[2]); 126 | free(chunk); 127 | } 128 | return rc; 129 | } 130 | 131 | chunk->seq = strtol(chunk->buffer, &end, 10); 132 | if (chunk->seq < 6 || chunk->seq > INT_MAX || end == NULL || (*end != ' ' && (*end != '\r' || *(end + 1) != '\n'))) continue; 133 | chunk->skip = crlf - chunk->buffer + 2; 134 | 135 | /* ack the chunk */ 136 | if (!guppy_ack(s->fd, chunk->seq)) { free(chunk); return 4; } 137 | 138 | /* check if we already have this chunk */ 139 | dup = 0; 140 | LIST_FOREACH_SAFE(last, &s->chunks, next, tmp) { 141 | dup = dup || (last->seq == chunk->seq); 142 | } 143 | if (dup) continue; 144 | 145 | if (!eof && chunk->skip == chunk->length) eof = chunk->seq; 146 | 147 | /* add the chunk to the queue */ 148 | if (last == NULL || *end == ' ') LIST_INSERT_HEAD(&s->chunks, chunk, next); 149 | else LIST_INSERT_AFTER(last, chunk, next); 150 | 151 | /* if this is not the first chunk, receive another one */ 152 | if (*end != ' ') { chunk = NULL; continue; } 153 | 154 | /* otherwise, free chunks we won't need and stop */ 155 | s->first = chunk->seq; 156 | *mime = end + 1; 157 | rc = chunk->seq; 158 | 159 | LIST_FOREACH_SAFE(chunk, &s->chunks, next, tmp) { 160 | if (chunk->seq < s->first || (eof && chunk->seq > eof)) { LIST_REMOVE(chunk, next); free(chunk); } 161 | } 162 | 163 | return rc; 164 | } 165 | } 166 | 167 | free(chunk); 168 | error(0, "cannot send request to `%s`:`%s`: cancelled", url->host, url->port); 169 | return 4; 170 | } 171 | 172 | 173 | static void *guppy_download(const Selector *sel, URL *url, char **mime, Parser *parser, unsigned int redirs, int ask) { 174 | GuppySocket *s = NULL; 175 | int status; 176 | 177 | (void)sel; 178 | 179 | if ((s = malloc(sizeof(GuppySocket))) == NULL) return NULL; 180 | s->fd = s->last = -1; 181 | LIST_INIT(&s->chunks); 182 | 183 | do { 184 | if (s->fd != -1) close(s->fd); 185 | if ((s->fd = socket_connect(url, SOCK_DGRAM)) == -1) { guppy_close(s); return NULL; } 186 | status = do_guppy_download(url, s, mime, ask); 187 | /* stop on success, on error or when the redirect limit is exhausted */ 188 | if (status > 5) break; 189 | } while (status == 1 || ((status == 3 && ++redirs < 5 && url->proto->download == guppy_download))); 190 | 191 | if (redirs < 5 && url->proto->download != guppy_download) { guppy_close(s); return url->proto->download(sel, url, mime, parser, redirs, ask); } 192 | 193 | if (status > 6 && strncmp(*mime, "text/gemini", 11) == 0) *parser = parse_gemtext_line; 194 | else if (status > 6 && strncmp(*mime, "text/plain", 10) == 0) *parser = parse_plaintext_line; 195 | else if (redirs == 5) error(0, "too many redirects from `%s`", url->url); 196 | 197 | if (status <= 6) { guppy_close(s); return NULL; } 198 | return s; 199 | } 200 | 201 | 202 | static int guppy_read(void *c, void *buffer, int length) { 203 | GuppySocket *s = (GuppySocket*)c; 204 | GuppyChunk *chunk = NULL, *last, *tmp; 205 | struct pollfd pfd = {.fd = s->fd, .events = POLLIN}; 206 | char *end; 207 | int timeout, i, n, ret, dup; 208 | 209 | LIST_FOREACH(chunk, &s->chunks, next) { 210 | /* if we already have the next chunk, remove it from the queue */ 211 | if ((s->last == -1 && chunk->seq == s->first) || chunk->seq == s->last + 1) { 212 | LIST_REMOVE(chunk, next); 213 | goto have; 214 | } 215 | } 216 | 217 | if ((timeout = get_var_integer("TIMEOUT", 15)) < 1) timeout = 15; 218 | 219 | for (i = 0; i < timeout; ++i) { 220 | while (1) { 221 | if (chunk == NULL && (chunk = malloc(sizeof(GuppyChunk))) == NULL) return -1; 222 | 223 | /* otherwise, receive a chunk */ 224 | if ((chunk->length = recv(s->fd, chunk->buffer, sizeof(chunk->buffer) - 1, MSG_DONTWAIT)) < 0) { 225 | if (errno == EAGAIN || errno == EWOULDBLOCK) break; 226 | free(chunk); 227 | return -1; 228 | } 229 | if (chunk->length == 0) { free(chunk); errno = ECONNRESET; return 0; } 230 | 231 | /* extract the sequence number */ 232 | chunk->buffer[chunk->length] = '\0'; 233 | if ((chunk->seq = strtol(chunk->buffer, &end, 10)) < s->first || chunk->seq > INT_MAX || end == NULL || *end != '\r' || *(end + 1) != '\n') continue; 234 | chunk->skip = end - chunk->buffer + 2; 235 | 236 | /* ack the chunk */ 237 | if (!guppy_ack(s->fd, chunk->seq)) { free(chunk); return -1; } 238 | 239 | /* receive another chunk if we already have this one */ 240 | if (s->last != -1 && chunk->seq <= s->last) continue; 241 | /* stop if this is the next chunk */ 242 | if (chunk->seq == s->last + 1) goto have; 243 | 244 | /* otherwise, append the chunk to the queue if needed and receive another one */ 245 | dup = 0; 246 | LIST_FOREACH_SAFE(last, &s->chunks, next, tmp) { 247 | dup = dup || (last->seq == chunk->seq); 248 | } 249 | if (last == NULL) LIST_INSERT_HEAD(&s->chunks, chunk, next); 250 | else if (dup) continue; 251 | else LIST_INSERT_AFTER(last, chunk, next); 252 | chunk = NULL; 253 | } 254 | 255 | /* wait for the next chunk and resend ack for the previous on timeout */ 256 | if ((n = poll(&pfd, 1, 200)) < 0 || (n == 0 && s->last != -1 && !guppy_ack(s->fd, s->last))) { free(chunk); return -1; } 257 | } 258 | 259 | free(chunk); 260 | errno = ETIMEDOUT; 261 | return -1; 262 | 263 | have: 264 | /* signal EOF if this is the EOF packet */ 265 | if (chunk->skip == chunk->length) { free(chunk); return 0; } 266 | 267 | s->last = chunk->seq; 268 | ret = (length > chunk->length - chunk->skip ? chunk->length - chunk->skip : length); 269 | memmove(buffer, chunk->buffer + chunk->skip, ret); 270 | free(chunk); 271 | return ret; 272 | } 273 | 274 | 275 | const Protocol guppy = {"guppy", "6775", guppy_read, NULL, socket_error, guppy_close, guppy_download, set_query}; 276 | -------------------------------------------------------------------------------- /prompt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dimkr/gplaces/e9dc803f86ddff68f3ff5b46694d58eae5576dec/prompt.png -------------------------------------------------------------------------------- /queue.h: -------------------------------------------------------------------------------- 1 | /* $OpenBSD: queue.h,v 1.46 2020/12/30 13:33:12 millert Exp $ */ 2 | /* $NetBSD: queue.h,v 1.11 1996/05/16 05:17:14 mycroft Exp $ */ 3 | 4 | /* 5 | * Copyright (c) 1991, 1993 6 | * The Regents of the University of California. All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions 10 | * are met: 11 | * 1. Redistributions of source code must retain the above copyright 12 | * notice, this list of conditions and the following disclaimer. 13 | * 2. Redistributions in binary form must reproduce the above copyright 14 | * notice, this list of conditions and the following disclaimer in the 15 | * documentation and/or other materials provided with the distribution. 16 | * 3. Neither the name of the University nor the names of its contributors 17 | * may be used to endorse or promote products derived from this software 18 | * without specific prior written permission. 19 | * 20 | * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 21 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 23 | * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 24 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 26 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 27 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 28 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 29 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 30 | * SUCH DAMAGE. 31 | * 32 | * @(#)queue.h 8.5 (Berkeley) 8/20/94 33 | */ 34 | 35 | #ifndef _SYS_QUEUE_H_ 36 | #define _SYS_QUEUE_H_ 37 | 38 | __asm__(".ident\t\"\\n\\n\ 39 | queue.h (BSD-3)\\n\ 40 | Copyright (c) 1991, 1993 The Regents of the University of California\""); 41 | 42 | /* 43 | * This file defines five types of data structures: singly-linked lists, 44 | * lists, simple queues, tail queues and XOR simple queues. 45 | * 46 | * 47 | * A singly-linked list is headed by a single forward pointer. The elements 48 | * are singly linked for minimum space and pointer manipulation overhead at 49 | * the expense of O(n) removal for arbitrary elements. New elements can be 50 | * added to the list after an existing element or at the head of the list. 51 | * Elements being removed from the head of the list should use the explicit 52 | * macro for this purpose for optimum efficiency. A singly-linked list may 53 | * only be traversed in the forward direction. Singly-linked lists are ideal 54 | * for applications with large datasets and few or no removals or for 55 | * implementing a LIFO queue. 56 | * 57 | * A list is headed by a single forward pointer (or an array of forward 58 | * pointers for a hash table header). The elements are doubly linked 59 | * so that an arbitrary element can be removed without a need to 60 | * traverse the list. New elements can be added to the list before 61 | * or after an existing element or at the head of the list. A list 62 | * may only be traversed in the forward direction. 63 | * 64 | * A simple queue is headed by a pair of pointers, one to the head of the 65 | * list and the other to the tail of the list. The elements are singly 66 | * linked to save space, so elements can only be removed from the 67 | * head of the list. New elements can be added to the list before or after 68 | * an existing element, at the head of the list, or at the end of the 69 | * list. A simple queue may only be traversed in the forward direction. 70 | * 71 | * A tail queue is headed by a pair of pointers, one to the head of the 72 | * list and the other to the tail of the list. The elements are doubly 73 | * linked so that an arbitrary element can be removed without a need to 74 | * traverse the list. New elements can be added to the list before or 75 | * after an existing element, at the head of the list, or at the end of 76 | * the list. A tail queue may be traversed in either direction. 77 | * 78 | * An XOR simple queue is used in the same way as a regular simple queue. 79 | * The difference is that the head structure also includes a "cookie" that 80 | * is XOR'd with the queue pointer (first, last or next) to generate the 81 | * real pointer value. 82 | * 83 | * For details on the use of these macros, see the queue(3) manual page. 84 | */ 85 | 86 | #if defined(QUEUE_MACRO_DEBUG) || (defined(_KERNEL) && defined(DIAGNOSTIC)) 87 | #define _Q_INVALID ((void *)-1) 88 | #define _Q_INVALIDATE(a) (a) = _Q_INVALID 89 | #else 90 | #define _Q_INVALIDATE(a) 91 | #endif 92 | 93 | /* 94 | * Singly-linked List definitions. 95 | */ 96 | #define SLIST_HEAD(name, type) \ 97 | struct name { \ 98 | struct type *slh_first; /* first element */ \ 99 | } 100 | 101 | #define SLIST_HEAD_INITIALIZER(head) \ 102 | { NULL } 103 | 104 | #define SLIST_ENTRY(type) \ 105 | struct { \ 106 | struct type *sle_next; /* next element */ \ 107 | } 108 | 109 | /* 110 | * Singly-linked List access methods. 111 | */ 112 | #define SLIST_FIRST(head) ((head)->slh_first) 113 | #define SLIST_END(head) NULL 114 | #define SLIST_EMPTY(head) (SLIST_FIRST(head) == SLIST_END(head)) 115 | #define SLIST_NEXT(elm, field) ((elm)->field.sle_next) 116 | 117 | #define SLIST_FOREACH(var, head, field) \ 118 | for((var) = SLIST_FIRST(head); \ 119 | (var) != SLIST_END(head); \ 120 | (var) = SLIST_NEXT(var, field)) 121 | 122 | #define SLIST_FOREACH_SAFE(var, head, field, tvar) \ 123 | for ((var) = SLIST_FIRST(head); \ 124 | (var) && ((tvar) = SLIST_NEXT(var, field), 1); \ 125 | (var) = (tvar)) 126 | 127 | /* 128 | * Singly-linked List functions. 129 | */ 130 | #define SLIST_INIT(head) { \ 131 | SLIST_FIRST(head) = SLIST_END(head); \ 132 | } 133 | 134 | #define SLIST_INSERT_AFTER(slistelm, elm, field) do { \ 135 | (elm)->field.sle_next = (slistelm)->field.sle_next; \ 136 | (slistelm)->field.sle_next = (elm); \ 137 | } while (0) 138 | 139 | #define SLIST_INSERT_HEAD(head, elm, field) do { \ 140 | (elm)->field.sle_next = (head)->slh_first; \ 141 | (head)->slh_first = (elm); \ 142 | } while (0) 143 | 144 | #define SLIST_REMOVE_AFTER(elm, field) do { \ 145 | (elm)->field.sle_next = (elm)->field.sle_next->field.sle_next; \ 146 | } while (0) 147 | 148 | #define SLIST_REMOVE_HEAD(head, field) do { \ 149 | (head)->slh_first = (head)->slh_first->field.sle_next; \ 150 | } while (0) 151 | 152 | #define SLIST_REMOVE(head, elm, type, field) do { \ 153 | if ((head)->slh_first == (elm)) { \ 154 | SLIST_REMOVE_HEAD((head), field); \ 155 | } else { \ 156 | struct type *curelm = (head)->slh_first; \ 157 | \ 158 | while (curelm->field.sle_next != (elm)) \ 159 | curelm = curelm->field.sle_next; \ 160 | curelm->field.sle_next = \ 161 | curelm->field.sle_next->field.sle_next; \ 162 | } \ 163 | _Q_INVALIDATE((elm)->field.sle_next); \ 164 | } while (0) 165 | 166 | /* 167 | * List definitions. 168 | */ 169 | #define LIST_HEAD(name, type) \ 170 | struct name { \ 171 | struct type *lh_first; /* first element */ \ 172 | } 173 | 174 | #define LIST_HEAD_INITIALIZER(head) \ 175 | { NULL } 176 | 177 | #define LIST_ENTRY(type) \ 178 | struct { \ 179 | struct type *le_next; /* next element */ \ 180 | struct type **le_prev; /* address of previous next element */ \ 181 | } 182 | 183 | /* 184 | * List access methods. 185 | */ 186 | #define LIST_FIRST(head) ((head)->lh_first) 187 | #define LIST_END(head) NULL 188 | #define LIST_EMPTY(head) (LIST_FIRST(head) == LIST_END(head)) 189 | #define LIST_NEXT(elm, field) ((elm)->field.le_next) 190 | 191 | #define LIST_FOREACH(var, head, field) \ 192 | for((var) = LIST_FIRST(head); \ 193 | (var)!= LIST_END(head); \ 194 | (var) = LIST_NEXT(var, field)) 195 | 196 | #define LIST_FOREACH_SAFE(var, head, field, tvar) \ 197 | for ((var) = LIST_FIRST(head); \ 198 | (var) && ((tvar) = LIST_NEXT(var, field), 1); \ 199 | (var) = (tvar)) 200 | 201 | /* 202 | * List functions. 203 | */ 204 | #define LIST_INIT(head) do { \ 205 | LIST_FIRST(head) = LIST_END(head); \ 206 | } while (0) 207 | 208 | #define LIST_INSERT_AFTER(listelm, elm, field) do { \ 209 | if (((elm)->field.le_next = (listelm)->field.le_next) != NULL) \ 210 | (listelm)->field.le_next->field.le_prev = \ 211 | &(elm)->field.le_next; \ 212 | (listelm)->field.le_next = (elm); \ 213 | (elm)->field.le_prev = &(listelm)->field.le_next; \ 214 | } while (0) 215 | 216 | #define LIST_INSERT_BEFORE(listelm, elm, field) do { \ 217 | (elm)->field.le_prev = (listelm)->field.le_prev; \ 218 | (elm)->field.le_next = (listelm); \ 219 | *(listelm)->field.le_prev = (elm); \ 220 | (listelm)->field.le_prev = &(elm)->field.le_next; \ 221 | } while (0) 222 | 223 | #define LIST_INSERT_HEAD(head, elm, field) do { \ 224 | if (((elm)->field.le_next = (head)->lh_first) != NULL) \ 225 | (head)->lh_first->field.le_prev = &(elm)->field.le_next;\ 226 | (head)->lh_first = (elm); \ 227 | (elm)->field.le_prev = &(head)->lh_first; \ 228 | } while (0) 229 | 230 | #define LIST_REMOVE(elm, field) do { \ 231 | if ((elm)->field.le_next != NULL) \ 232 | (elm)->field.le_next->field.le_prev = \ 233 | (elm)->field.le_prev; \ 234 | *(elm)->field.le_prev = (elm)->field.le_next; \ 235 | _Q_INVALIDATE((elm)->field.le_prev); \ 236 | _Q_INVALIDATE((elm)->field.le_next); \ 237 | } while (0) 238 | 239 | #define LIST_REPLACE(elm, elm2, field) do { \ 240 | if (((elm2)->field.le_next = (elm)->field.le_next) != NULL) \ 241 | (elm2)->field.le_next->field.le_prev = \ 242 | &(elm2)->field.le_next; \ 243 | (elm2)->field.le_prev = (elm)->field.le_prev; \ 244 | *(elm2)->field.le_prev = (elm2); \ 245 | _Q_INVALIDATE((elm)->field.le_prev); \ 246 | _Q_INVALIDATE((elm)->field.le_next); \ 247 | } while (0) 248 | 249 | /* 250 | * Simple queue definitions. 251 | */ 252 | #define SIMPLEQ_HEAD(name, type) \ 253 | struct name { \ 254 | struct type *sqh_first; /* first element */ \ 255 | struct type **sqh_last; /* addr of last next element */ \ 256 | } 257 | 258 | #define SIMPLEQ_HEAD_INITIALIZER(head) \ 259 | { NULL, &(head).sqh_first } 260 | 261 | #define SIMPLEQ_ENTRY(type) \ 262 | struct { \ 263 | struct type *sqe_next; /* next element */ \ 264 | } 265 | 266 | /* 267 | * Simple queue access methods. 268 | */ 269 | #define SIMPLEQ_FIRST(head) ((head)->sqh_first) 270 | #define SIMPLEQ_END(head) NULL 271 | #define SIMPLEQ_EMPTY(head) (SIMPLEQ_FIRST(head) == SIMPLEQ_END(head)) 272 | #define SIMPLEQ_NEXT(elm, field) ((elm)->field.sqe_next) 273 | 274 | #define SIMPLEQ_FOREACH(var, head, field) \ 275 | for((var) = SIMPLEQ_FIRST(head); \ 276 | (var) != SIMPLEQ_END(head); \ 277 | (var) = SIMPLEQ_NEXT(var, field)) 278 | 279 | #define SIMPLEQ_FOREACH_SAFE(var, head, field, tvar) \ 280 | for ((var) = SIMPLEQ_FIRST(head); \ 281 | (var) && ((tvar) = SIMPLEQ_NEXT(var, field), 1); \ 282 | (var) = (tvar)) 283 | 284 | /* 285 | * Simple queue functions. 286 | */ 287 | #define SIMPLEQ_INIT(head) do { \ 288 | (head)->sqh_first = NULL; \ 289 | (head)->sqh_last = &(head)->sqh_first; \ 290 | } while (0) 291 | 292 | #define SIMPLEQ_INSERT_HEAD(head, elm, field) do { \ 293 | if (((elm)->field.sqe_next = (head)->sqh_first) == NULL) \ 294 | (head)->sqh_last = &(elm)->field.sqe_next; \ 295 | (head)->sqh_first = (elm); \ 296 | } while (0) 297 | 298 | #define SIMPLEQ_INSERT_TAIL(head, elm, field) do { \ 299 | (elm)->field.sqe_next = NULL; \ 300 | *(head)->sqh_last = (elm); \ 301 | (head)->sqh_last = &(elm)->field.sqe_next; \ 302 | } while (0) 303 | 304 | #define SIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do { \ 305 | if (((elm)->field.sqe_next = (listelm)->field.sqe_next) == NULL)\ 306 | (head)->sqh_last = &(elm)->field.sqe_next; \ 307 | (listelm)->field.sqe_next = (elm); \ 308 | } while (0) 309 | 310 | #define SIMPLEQ_REMOVE_HEAD(head, field) do { \ 311 | if (((head)->sqh_first = (head)->sqh_first->field.sqe_next) == NULL) \ 312 | (head)->sqh_last = &(head)->sqh_first; \ 313 | } while (0) 314 | 315 | #define SIMPLEQ_REMOVE_AFTER(head, elm, field) do { \ 316 | if (((elm)->field.sqe_next = (elm)->field.sqe_next->field.sqe_next) \ 317 | == NULL) \ 318 | (head)->sqh_last = &(elm)->field.sqe_next; \ 319 | } while (0) 320 | 321 | #define SIMPLEQ_CONCAT(head1, head2) do { \ 322 | if (!SIMPLEQ_EMPTY((head2))) { \ 323 | *(head1)->sqh_last = (head2)->sqh_first; \ 324 | (head1)->sqh_last = (head2)->sqh_last; \ 325 | SIMPLEQ_INIT((head2)); \ 326 | } \ 327 | } while (0) 328 | 329 | /* 330 | * XOR Simple queue definitions. 331 | */ 332 | #define XSIMPLEQ_HEAD(name, type) \ 333 | struct name { \ 334 | struct type *sqx_first; /* first element */ \ 335 | struct type **sqx_last; /* addr of last next element */ \ 336 | unsigned long sqx_cookie; \ 337 | } 338 | 339 | #define XSIMPLEQ_ENTRY(type) \ 340 | struct { \ 341 | struct type *sqx_next; /* next element */ \ 342 | } 343 | 344 | /* 345 | * XOR Simple queue access methods. 346 | */ 347 | #define XSIMPLEQ_XOR(head, ptr) ((__typeof(ptr))((head)->sqx_cookie ^ \ 348 | (unsigned long)(ptr))) 349 | #define XSIMPLEQ_FIRST(head) XSIMPLEQ_XOR(head, ((head)->sqx_first)) 350 | #define XSIMPLEQ_END(head) NULL 351 | #define XSIMPLEQ_EMPTY(head) (XSIMPLEQ_FIRST(head) == XSIMPLEQ_END(head)) 352 | #define XSIMPLEQ_NEXT(head, elm, field) XSIMPLEQ_XOR(head, ((elm)->field.sqx_next)) 353 | 354 | 355 | #define XSIMPLEQ_FOREACH(var, head, field) \ 356 | for ((var) = XSIMPLEQ_FIRST(head); \ 357 | (var) != XSIMPLEQ_END(head); \ 358 | (var) = XSIMPLEQ_NEXT(head, var, field)) 359 | 360 | #define XSIMPLEQ_FOREACH_SAFE(var, head, field, tvar) \ 361 | for ((var) = XSIMPLEQ_FIRST(head); \ 362 | (var) && ((tvar) = XSIMPLEQ_NEXT(head, var, field), 1); \ 363 | (var) = (tvar)) 364 | 365 | /* 366 | * XOR Simple queue functions. 367 | */ 368 | #define XSIMPLEQ_INIT(head) do { \ 369 | arc4random_buf(&(head)->sqx_cookie, sizeof((head)->sqx_cookie)); \ 370 | (head)->sqx_first = XSIMPLEQ_XOR(head, NULL); \ 371 | (head)->sqx_last = XSIMPLEQ_XOR(head, &(head)->sqx_first); \ 372 | } while (0) 373 | 374 | #define XSIMPLEQ_INSERT_HEAD(head, elm, field) do { \ 375 | if (((elm)->field.sqx_next = (head)->sqx_first) == \ 376 | XSIMPLEQ_XOR(head, NULL)) \ 377 | (head)->sqx_last = XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \ 378 | (head)->sqx_first = XSIMPLEQ_XOR(head, (elm)); \ 379 | } while (0) 380 | 381 | #define XSIMPLEQ_INSERT_TAIL(head, elm, field) do { \ 382 | (elm)->field.sqx_next = XSIMPLEQ_XOR(head, NULL); \ 383 | *(XSIMPLEQ_XOR(head, (head)->sqx_last)) = XSIMPLEQ_XOR(head, (elm)); \ 384 | (head)->sqx_last = XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \ 385 | } while (0) 386 | 387 | #define XSIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do { \ 388 | if (((elm)->field.sqx_next = (listelm)->field.sqx_next) == \ 389 | XSIMPLEQ_XOR(head, NULL)) \ 390 | (head)->sqx_last = XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \ 391 | (listelm)->field.sqx_next = XSIMPLEQ_XOR(head, (elm)); \ 392 | } while (0) 393 | 394 | #define XSIMPLEQ_REMOVE_HEAD(head, field) do { \ 395 | if (((head)->sqx_first = XSIMPLEQ_XOR(head, \ 396 | (head)->sqx_first)->field.sqx_next) == XSIMPLEQ_XOR(head, NULL)) \ 397 | (head)->sqx_last = XSIMPLEQ_XOR(head, &(head)->sqx_first); \ 398 | } while (0) 399 | 400 | #define XSIMPLEQ_REMOVE_AFTER(head, elm, field) do { \ 401 | if (((elm)->field.sqx_next = XSIMPLEQ_XOR(head, \ 402 | (elm)->field.sqx_next)->field.sqx_next) \ 403 | == XSIMPLEQ_XOR(head, NULL)) \ 404 | (head)->sqx_last = \ 405 | XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \ 406 | } while (0) 407 | 408 | 409 | /* 410 | * Tail queue definitions. 411 | */ 412 | #define TAILQ_HEAD(name, type) \ 413 | struct name { \ 414 | struct type *tqh_first; /* first element */ \ 415 | struct type **tqh_last; /* addr of last next element */ \ 416 | } 417 | 418 | #define TAILQ_HEAD_INITIALIZER(head) \ 419 | { NULL, &(head).tqh_first } 420 | 421 | #define TAILQ_ENTRY(type) \ 422 | struct { \ 423 | struct type *tqe_next; /* next element */ \ 424 | struct type **tqe_prev; /* address of previous next element */ \ 425 | } 426 | 427 | /* 428 | * Tail queue access methods. 429 | */ 430 | #define TAILQ_FIRST(head) ((head)->tqh_first) 431 | #define TAILQ_END(head) NULL 432 | #define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) 433 | #define TAILQ_LAST(head, headname) \ 434 | (*(((struct headname *)((head)->tqh_last))->tqh_last)) 435 | /* XXX */ 436 | #define TAILQ_PREV(elm, headname, field) \ 437 | (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) 438 | #define TAILQ_EMPTY(head) \ 439 | (TAILQ_FIRST(head) == TAILQ_END(head)) 440 | 441 | #define TAILQ_FOREACH(var, head, field) \ 442 | for((var) = TAILQ_FIRST(head); \ 443 | (var) != TAILQ_END(head); \ 444 | (var) = TAILQ_NEXT(var, field)) 445 | 446 | #define TAILQ_FOREACH_SAFE(var, head, field, tvar) \ 447 | for ((var) = TAILQ_FIRST(head); \ 448 | (var) != TAILQ_END(head) && \ 449 | ((tvar) = TAILQ_NEXT(var, field), 1); \ 450 | (var) = (tvar)) 451 | 452 | 453 | #define TAILQ_FOREACH_REVERSE(var, head, headname, field) \ 454 | for((var) = TAILQ_LAST(head, headname); \ 455 | (var) != TAILQ_END(head); \ 456 | (var) = TAILQ_PREV(var, headname, field)) 457 | 458 | #define TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar) \ 459 | for ((var) = TAILQ_LAST(head, headname); \ 460 | (var) != TAILQ_END(head) && \ 461 | ((tvar) = TAILQ_PREV(var, headname, field), 1); \ 462 | (var) = (tvar)) 463 | 464 | /* 465 | * Tail queue functions. 466 | */ 467 | #define TAILQ_INIT(head) do { \ 468 | (head)->tqh_first = NULL; \ 469 | (head)->tqh_last = &(head)->tqh_first; \ 470 | } while (0) 471 | 472 | #define TAILQ_INSERT_HEAD(head, elm, field) do { \ 473 | if (((elm)->field.tqe_next = (head)->tqh_first) != NULL) \ 474 | (head)->tqh_first->field.tqe_prev = \ 475 | &(elm)->field.tqe_next; \ 476 | else \ 477 | (head)->tqh_last = &(elm)->field.tqe_next; \ 478 | (head)->tqh_first = (elm); \ 479 | (elm)->field.tqe_prev = &(head)->tqh_first; \ 480 | } while (0) 481 | 482 | #define TAILQ_INSERT_TAIL(head, elm, field) do { \ 483 | (elm)->field.tqe_next = NULL; \ 484 | (elm)->field.tqe_prev = (head)->tqh_last; \ 485 | *(head)->tqh_last = (elm); \ 486 | (head)->tqh_last = &(elm)->field.tqe_next; \ 487 | } while (0) 488 | 489 | #define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ 490 | if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != NULL)\ 491 | (elm)->field.tqe_next->field.tqe_prev = \ 492 | &(elm)->field.tqe_next; \ 493 | else \ 494 | (head)->tqh_last = &(elm)->field.tqe_next; \ 495 | (listelm)->field.tqe_next = (elm); \ 496 | (elm)->field.tqe_prev = &(listelm)->field.tqe_next; \ 497 | } while (0) 498 | 499 | #define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \ 500 | (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \ 501 | (elm)->field.tqe_next = (listelm); \ 502 | *(listelm)->field.tqe_prev = (elm); \ 503 | (listelm)->field.tqe_prev = &(elm)->field.tqe_next; \ 504 | } while (0) 505 | 506 | #define TAILQ_REMOVE(head, elm, field) do { \ 507 | if (((elm)->field.tqe_next) != NULL) \ 508 | (elm)->field.tqe_next->field.tqe_prev = \ 509 | (elm)->field.tqe_prev; \ 510 | else \ 511 | (head)->tqh_last = (elm)->field.tqe_prev; \ 512 | *(elm)->field.tqe_prev = (elm)->field.tqe_next; \ 513 | _Q_INVALIDATE((elm)->field.tqe_prev); \ 514 | _Q_INVALIDATE((elm)->field.tqe_next); \ 515 | } while (0) 516 | 517 | #define TAILQ_REPLACE(head, elm, elm2, field) do { \ 518 | if (((elm2)->field.tqe_next = (elm)->field.tqe_next) != NULL) \ 519 | (elm2)->field.tqe_next->field.tqe_prev = \ 520 | &(elm2)->field.tqe_next; \ 521 | else \ 522 | (head)->tqh_last = &(elm2)->field.tqe_next; \ 523 | (elm2)->field.tqe_prev = (elm)->field.tqe_prev; \ 524 | *(elm2)->field.tqe_prev = (elm2); \ 525 | _Q_INVALIDATE((elm)->field.tqe_prev); \ 526 | _Q_INVALIDATE((elm)->field.tqe_next); \ 527 | } while (0) 528 | 529 | #define TAILQ_CONCAT(head1, head2, field) do { \ 530 | if (!TAILQ_EMPTY(head2)) { \ 531 | *(head1)->tqh_last = (head2)->tqh_first; \ 532 | (head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \ 533 | (head1)->tqh_last = (head2)->tqh_last; \ 534 | TAILQ_INIT((head2)); \ 535 | } \ 536 | } while (0) 537 | 538 | /* 539 | * Singly-linked Tail queue declarations. 540 | */ 541 | #define STAILQ_HEAD(name, type) \ 542 | struct name { \ 543 | struct type *stqh_first; /* first element */ \ 544 | struct type **stqh_last; /* addr of last next element */ \ 545 | } 546 | 547 | #define STAILQ_HEAD_INITIALIZER(head) \ 548 | { NULL, &(head).stqh_first } 549 | 550 | #define STAILQ_ENTRY(type) \ 551 | struct { \ 552 | struct type *stqe_next; /* next element */ \ 553 | } 554 | 555 | /* 556 | * Singly-linked Tail queue access methods. 557 | */ 558 | #define STAILQ_FIRST(head) ((head)->stqh_first) 559 | #define STAILQ_END(head) NULL 560 | #define STAILQ_EMPTY(head) (STAILQ_FIRST(head) == STAILQ_END(head)) 561 | #define STAILQ_NEXT(elm, field) ((elm)->field.stqe_next) 562 | 563 | #define STAILQ_FOREACH(var, head, field) \ 564 | for ((var) = STAILQ_FIRST(head); \ 565 | (var) != STAILQ_END(head); \ 566 | (var) = STAILQ_NEXT(var, field)) 567 | 568 | #define STAILQ_FOREACH_SAFE(var, head, field, tvar) \ 569 | for ((var) = STAILQ_FIRST(head); \ 570 | (var) && ((tvar) = STAILQ_NEXT(var, field), 1); \ 571 | (var) = (tvar)) 572 | 573 | /* 574 | * Singly-linked Tail queue functions. 575 | */ 576 | #define STAILQ_INIT(head) do { \ 577 | STAILQ_FIRST((head)) = NULL; \ 578 | (head)->stqh_last = &STAILQ_FIRST((head)); \ 579 | } while (0) 580 | 581 | #define STAILQ_INSERT_HEAD(head, elm, field) do { \ 582 | if ((STAILQ_NEXT((elm), field) = STAILQ_FIRST((head))) == NULL) \ 583 | (head)->stqh_last = &STAILQ_NEXT((elm), field); \ 584 | STAILQ_FIRST((head)) = (elm); \ 585 | } while (0) 586 | 587 | #define STAILQ_INSERT_TAIL(head, elm, field) do { \ 588 | STAILQ_NEXT((elm), field) = NULL; \ 589 | *(head)->stqh_last = (elm); \ 590 | (head)->stqh_last = &STAILQ_NEXT((elm), field); \ 591 | } while (0) 592 | 593 | #define STAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ 594 | if ((STAILQ_NEXT((elm), field) = STAILQ_NEXT((elm), field)) == NULL)\ 595 | (head)->stqh_last = &STAILQ_NEXT((elm), field); \ 596 | STAILQ_NEXT((elm), field) = (elm); \ 597 | } while (0) 598 | 599 | #define STAILQ_REMOVE_HEAD(head, field) do { \ 600 | if ((STAILQ_FIRST((head)) = \ 601 | STAILQ_NEXT(STAILQ_FIRST((head)), field)) == NULL) \ 602 | (head)->stqh_last = &STAILQ_FIRST((head)); \ 603 | } while (0) 604 | 605 | #define STAILQ_REMOVE_AFTER(head, elm, field) do { \ 606 | if ((STAILQ_NEXT(elm, field) = \ 607 | STAILQ_NEXT(STAILQ_NEXT(elm, field), field)) == NULL) \ 608 | (head)->stqh_last = &STAILQ_NEXT((elm), field); \ 609 | } while (0) 610 | 611 | #define STAILQ_REMOVE(head, elm, type, field) do { \ 612 | if (STAILQ_FIRST((head)) == (elm)) { \ 613 | STAILQ_REMOVE_HEAD((head), field); \ 614 | } else { \ 615 | struct type *curelm = (head)->stqh_first; \ 616 | while (STAILQ_NEXT(curelm, field) != (elm)) \ 617 | curelm = STAILQ_NEXT(curelm, field); \ 618 | STAILQ_REMOVE_AFTER(head, curelm, field); \ 619 | } \ 620 | } while (0) 621 | 622 | #define STAILQ_CONCAT(head1, head2) do { \ 623 | if (!STAILQ_EMPTY((head2))) { \ 624 | *(head1)->stqh_last = (head2)->stqh_first; \ 625 | (head1)->stqh_last = (head2)->stqh_last; \ 626 | STAILQ_INIT((head2)); \ 627 | } \ 628 | } while (0) 629 | 630 | #define STAILQ_LAST(head, type, field) \ 631 | (STAILQ_EMPTY((head)) ? NULL : \ 632 | ((struct type *)(void *) \ 633 | ((char *)((head)->stqh_last) - offsetof(struct type, field)))) 634 | 635 | #endif /* !_SYS_QUEUE_H_ */ 636 | -------------------------------------------------------------------------------- /socket.c: -------------------------------------------------------------------------------- 1 | /* 2 | ================================================================================ 3 | 4 | gplaces - a simple terminal Gemini client 5 | Copyright (C) 2022, 2023 Dima Krasner 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | ================================================================================ 21 | */ 22 | static int socket_error(const URL *url, void *c, int err) { 23 | (void)c; 24 | if (err == 0) return 0; 25 | if (errno == EAGAIN || errno == EWOULDBLOCK) error(0, "failed to download `%s`: cancelled", url->url); 26 | else error(0, "failed to download `%s`: %s", url->url, strerror(errno)); 27 | return 1; 28 | } 29 | -------------------------------------------------------------------------------- /spartan.c: -------------------------------------------------------------------------------- 1 | /* 2 | ================================================================================ 3 | 4 | gplaces - a simple terminal Gemini client 5 | Copyright (C) 2022 - 2024 Dima Krasner 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | ================================================================================ 21 | */ 22 | static void parse_spartan_line(char *line, int *pre, Selector **sel, SelectorList *list) { 23 | if (!*pre && line[0] == '=' && line[1] == ':') { 24 | line[1] = '>'; 25 | parse_gemtext_line(line, pre, sel, list); 26 | if (*sel != NULL) (*sel)->prompt = 1; 27 | } else parse_gemtext_line(line, pre, sel, list); 28 | } 29 | 30 | 31 | /*============================================================================*/ 32 | static int do_spartan_download(URL *url, int *body, char **mime, const char *input, size_t inputlen, int ask) { 33 | static char buffer[1024], data[1 + 1 + 1024 + 2 + 1]; /* 9 meta\r\n\0 */ 34 | char *crlf, *meta = &data[2]; 35 | int fd = -1, len, total, received, ret = 40; 36 | 37 | len = snprintf(buffer, sizeof(buffer), "%s %s %zu\r\n", url->host, url->path, inputlen); 38 | if ((fd = socket_connect(url, SOCK_STREAM)) == -1) goto fail; 39 | if (sendall(fd, buffer, len, MSG_NOSIGNAL) != len || (inputlen > 0 && sendall(fd, input, inputlen, MSG_NOSIGNAL) != (ssize_t)inputlen)) { 40 | if (errno == EAGAIN || errno == EWOULDBLOCK) error(0, "cannot send request to `%s`:`%s`: cancelled", url->host, url->port); 41 | else error(0, "cannot send request to `%s`:`%s`: %s", url->host, url->port, strerror(errno)); 42 | goto fail; 43 | } 44 | 45 | for (total = 0; total < (int)sizeof(data) - 1 && (total < 5 || (data[total - 2] != '\r' && data[total - 1] != '\n')) && (received = recv(fd, &data[total], 1, 0)) > 0; ++total); 46 | if (total < 5 || data[0] < '2' || data[0] > '5' || (total > 1 && data[1] != ' ') || data[total - 2] != '\r' || data[total - 1] != '\n' || received < 0) goto fail; 47 | data[total] = '\0'; 48 | 49 | crlf = &data[total - 2]; 50 | *crlf = '\0'; 51 | if (meta >= crlf) meta = ""; 52 | 53 | switch (data[0]) { 54 | case '2': 55 | if (!*meta) goto fail; 56 | *body = fd; 57 | fd = -1; 58 | *mime = meta; 59 | break; 60 | 61 | case '3': 62 | if (!*meta) goto fail; 63 | if (!redirect(url, meta, total - 2, ask)) goto fail; 64 | fprintf(stderr, "redirected to `%s`\n", url->url); 65 | break; 66 | 67 | default: 68 | error(0, "cannot download `%s`: %s", url->url, *meta ? meta : data); 69 | } 70 | 71 | ret = data[0] - '0'; 72 | 73 | fail: 74 | if (fd != -1) close(fd); 75 | return ret; 76 | } 77 | 78 | 79 | static void *spartan_download(const Selector *sel, URL *url, char **mime, Parser *parser, unsigned int redirs, int ask) { 80 | char *input = NULL, *query = NULL; 81 | size_t inputlen = 0; 82 | static int fd = -1; 83 | int status; 84 | 85 | switch (curl_url_get(url->cu, CURLUPART_QUERY, &query, 0)) { 86 | case CURLUE_OK: input = query; break; 87 | case CURLUE_NO_QUERY: break; 88 | default: return NULL; 89 | } 90 | if (sel->prompt && (input == NULL || *input == '\0')) { 91 | if (!ask || (input = bestline(color ? "\33[35mData>\33[0m " : "Data> ")) == NULL || !set_query(url, input)) goto fail; 92 | if (interactive) { bestlineHistoryAdd(input); bestlineHistoryAdd(url->url); } 93 | } 94 | if (input != NULL) inputlen = strlen(input); 95 | 96 | do { 97 | status = do_spartan_download(url, &fd, mime, input, inputlen, ask); 98 | if (status == 2) break; 99 | } while (status == 3 && ++redirs < 5 && url->proto->download == spartan_download); 100 | 101 | if (redirs < 5 && url->proto->download != spartan_download) return url->proto->download(sel, url, mime, parser, redirs, ask); 102 | 103 | if (fd != -1 && strncmp(*mime, "text/gemini", 11) == 0) *parser = parse_spartan_line; 104 | else if (fd != -1 && strncmp(*mime, "text/plain", 10) == 0) *parser = parse_plaintext_line; 105 | 106 | if (redirs == 5) error(0, "too many redirects from `%s`", url->url); 107 | 108 | fail: 109 | if (input != query) free(input); 110 | curl_free(query); 111 | return fd == -1 ? NULL : (void *)(intptr_t)fd; 112 | } 113 | 114 | 115 | const Protocol spartan = {"spartan", "300", tcp_read, tcp_peek, socket_error, tcp_close, spartan_download, set_query}; 116 | -------------------------------------------------------------------------------- /tcp.c: -------------------------------------------------------------------------------- 1 | /* 2 | ================================================================================ 3 | 4 | gplaces - a simple terminal Gemini client 5 | Copyright (C) 2022, 2023 Dima Krasner 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | ================================================================================ 21 | */ 22 | static int tcp_read(void *c, void *buffer, int length) { 23 | return (int)recv((int)(intptr_t)c, buffer, (size_t)length, 0); 24 | } 25 | 26 | 27 | static int tcp_peek(void *c, void *buffer, int length) { 28 | return (int)recv((int)(intptr_t)c, buffer, (size_t)length, MSG_PEEK); 29 | } 30 | 31 | 32 | static void tcp_close(void *c) { 33 | close((int)(intptr_t)c); 34 | } 35 | 36 | 37 | static ssize_t sendall(int sockfd, const void *buf, size_t len, int flags) { 38 | ssize_t sent = 0, total; 39 | for (total = 0; total < (ssize_t)len && (sent = send(sockfd, (char *)buf + total, len - total, flags)) > 0; total += sent); 40 | return sent <= 0 ? sent : total; 41 | } -------------------------------------------------------------------------------- /titan.c: -------------------------------------------------------------------------------- 1 | /* 2 | ================================================================================ 3 | 4 | gplaces - a simple terminal Gemini client 5 | Copyright (C) 2024 Dima Krasner 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | ================================================================================ 21 | */ 22 | typedef struct TitanParams { 23 | char *url; 24 | char *token; 25 | const char *mime; 26 | struct stat stbuf; 27 | void *body; 28 | } TitanParams; 29 | 30 | 31 | /*============================================================================*/ 32 | static int titan_request(const URL *url, SSL *ssl, void *p) { 33 | static char buffer[1024]; 34 | const TitanParams *params = (const TitanParams *)p; 35 | int len, err; 36 | 37 | (void)url; 38 | 39 | len = snprintf(buffer, sizeof(buffer), params->token == NULL || *params->token == '\0' ? "%s;mime=%s;size=%zu\r\n" : "%s;mime=%s;size=%zu;token=%s\r\n", params->url, params->mime, params->stbuf.st_size, params->token); 40 | if ((err = SSL_get_error(ssl, SSL_write(ssl, buffer, len >= (int)sizeof(buffer) ? (int)sizeof(buffer) - 1 : len))) != SSL_ERROR_NONE) return err; 41 | 42 | return params->stbuf.st_size > 0 ? SSL_get_error(ssl, SSL_write(ssl, params->body, params->stbuf.st_size)) : SSL_ERROR_NONE; 43 | } 44 | 45 | 46 | static void *titan_upload(const Selector *sel, URL *url, char **mime, Parser *parser, unsigned int redirs, int ask) { 47 | #ifdef GPLACES_USE_LIBMAGIC 48 | magic_t mag = NULL; 49 | #else 50 | char *tmp = NULL; 51 | #define magic_close(x) do {} while (0) 52 | #endif 53 | CURLU *cu; 54 | TitanParams params = {.mime = "application/octet-stream"}; 55 | char *fragment, *path = NULL; 56 | SSL *ssl = NULL; 57 | int fd, status = -1; 58 | 59 | (void)sel; 60 | 61 | if ((cu = curl_url_dup(url->cu)) == NULL || curl_url_set(cu, CURLUPART_FRAGMENT, NULL, CURLU_NON_SUPPORT_SCHEME) != CURLUE_OK || curl_url_get(cu, CURLUPART_URL, ¶ms.url, 0) != CURLUE_OK) { curl_url_cleanup(cu); return NULL; } 62 | curl_url_cleanup(cu); 63 | 64 | switch (curl_url_get(url->cu, CURLUPART_FRAGMENT, &fragment, 0)) { 65 | case CURLUE_OK: path = fragment; break; 66 | case CURLUE_NO_FRAGMENT: break; 67 | default: return NULL; 68 | } 69 | 70 | if (path == NULL || *path == '\0') { 71 | if (!ask || (params.token = bestline("Token> ")) == NULL) { curl_free(params.url); return NULL; } 72 | if (interactive) bestlineHistoryAdd(params.token); 73 | if ((path = bestline("File> ")) == NULL) { free(params.token); curl_free(params.url); return NULL; } 74 | if (interactive) bestlineHistoryAdd(path); 75 | } 76 | 77 | if ((fd = open(path, O_RDONLY)) == -1) { error(0, "cannot open `%s`: %s", path, strerror(errno)); free(path); free(params.token); curl_free(params.url); return NULL; } 78 | if (fstat(fd, ¶ms.stbuf) == -1) { error(0, "cannot open `%s`: %s", path, strerror(errno)); close(fd); free(path); free(params.token); curl_free(params.url); return NULL; } 79 | if (params.stbuf.st_size > 0 && (params.body = mmap(NULL, params.stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED) { error(0, "cannot open `%s`: %s", path, strerror(errno)); close(fd); free(path); free(params.token); curl_free(params.url); return NULL; } 80 | 81 | if (params.stbuf.st_size > 0) { 82 | #ifdef GPLACES_USE_LIBMAGIC 83 | if ((mag = magic_open(MAGIC_MIME_TYPE | MAGIC_NO_CHECK_COMPRESS | MAGIC_ERROR)) == NULL) { munmap(params.body, params.stbuf.st_size); close(fd); free(path); free(params.token); curl_free(params.url); return NULL; } 84 | if (magic_load(mag, NULL) != 0) { munmap(params.body, params.stbuf.st_size); close(fd); free(path); free(params.token); magic_close(mag); curl_free(params.url); return NULL; } 85 | if ((params.mime = magic_buffer(mag, params.body, params.stbuf.st_size)) == NULL) { error(0, "cannot open `%s`: %s", path, magic_error(mag)); munmap(params.body, params.stbuf.st_size); close(fd); free(path); free(params.token); magic_close(mag); curl_free(params.url); return NULL; } 86 | #else 87 | if ((tmp = bestline("File type> ")) == NULL) { munmap(params.body, params.stbuf.st_size); close(fd); free(path); free(params.token); curl_free(params.url); return NULL; } 88 | if (interactive) bestlineHistoryAdd(tmp); 89 | params.mime = tmp; 90 | #endif 91 | } 92 | 93 | do { 94 | status = ssl_download(url, &ssl, mime, titan_request, ¶ms, ask); 95 | if (status >= 20 && status <= 29) break; 96 | } while ((status >= 10 && status <= 19) || (status >= 60 && status <= 69) || (status >= 30 && status <= 39 && ++redirs < 5 && url->proto->download == titan_upload)); 97 | 98 | if (params.stbuf.st_size > 0) munmap(params.body, params.stbuf.st_size); 99 | close(fd); 100 | free(params.token); 101 | if (path != fragment) free(path); 102 | #ifdef GPLACES_USE_LIBMAGIC 103 | if (mag != NULL) magic_close(mag); 104 | #else 105 | free(tmp); 106 | #endif 107 | curl_free(fragment); 108 | curl_free(params.url); 109 | 110 | if (redirs < 5 && url->proto->download != titan_upload) return url->proto->download(sel, url, mime, parser, redirs, ask); 111 | 112 | if (ssl != NULL && strncmp(*mime, "text/gemini", 11) == 0) *parser = parse_gemtext_line; 113 | else if (ssl != NULL && (!interactive || strncmp(*mime, "text/plain", 10) == 0)) *parser = parse_plaintext_line; 114 | 115 | if (redirs == 5) error(0, "too many redirects from `%s`", url->url); 116 | return ssl; 117 | } 118 | 119 | 120 | const Protocol titan = {"titan", "1965", ssl_read, ssl_peek, ssl_error, ssl_close, titan_upload, set_fragment}; 121 | --------------------------------------------------------------------------------