├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── auth.go ├── cryptography.go ├── data └── settings.json ├── database.go ├── docker-compose.yaml ├── expiration.go ├── fileWriters.go ├── go.mod ├── go.sum ├── handlers.go ├── main.go ├── random.go ├── settings.go ├── static ├── auth.html ├── helper.js ├── index.html ├── qrcode.js ├── script.js ├── style.css └── theme.css └── templates ├── authTemplate.html ├── notFound.html └── pasteTemplate.html /.gitignore: -------------------------------------------------------------------------------- 1 | *.exe 2 | *.bat 3 | *.db 4 | .vscode 5 | .idea 6 | uploads/ 7 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:latest 2 | 3 | RUN apk add --no-cache git go 4 | 5 | WORKDIR /app 6 | 7 | COPY . /app 8 | 9 | RUN go build -ldflags="-s -w" 10 | 11 | CMD ["./app"] 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SuperBin 2 | File sharing, url shortener and pastebin all in one place with QR code and curl support. Uses stream based cryptography and data processing that can handle gigabytes of data with fixed memory and cpu usage. It can run on anything including PaaS like repl.it or Render and is very easy to customize. 3 | **Please star this project if you find it useful, thank you!** 4 | 5 | | ![](https://github.com/user-attachments/assets/d75999e5-736a-4ef4-80e8-c9a77079ed45) | ![](https://github.com/user-attachments/assets/80bab1ca-0685-4939-a999-8392d7c1bc8b) | 6 | |--------------------------------|--------------------------------| 7 | | ![](https://github.com/user-attachments/assets/34997223-8a08-4707-8490-9c9941f59141) | ![](https://github.com/user-attachments/assets/a54146fb-9c5f-46f2-a79b-c338e9272b53) | 8 | 9 | 10 | # Why it's better than other similar apps :zap: 11 | - works in mobile browsers, can upload file / text with ctrl+v, drag and drop, browse file or through terminal 12 | - Support password authentication (for both upload & download) 13 | - Extremely easy to set up, all you need is `go build .` or use the docker-compose.yaml and it's done 14 | - Very easy for modifications, don't like the style? pick a .css file from [here](https://github.com/dbohdan/classless-css) and replace the `static/theme.css`, don't like the layout? the html page is well commented and structured 15 | - Can run on any OS or deployment platforms like repl.it, render, fly.io, etc 16 | - Encryption done right, password protected data are secured with AES & pbkdf2 17 | - Decryption is done on the fly, the encrypted data is never decrypted to the disk 18 | - Short & unambiguous URL generation (with letters like ilI1 omitted) with collision detection 19 | - QR code support to quickly share files to / between mobile devices 20 | 21 | # URL shortener 🔗 22 | simply paste any valid url (must start with `http://` or `https://`) to the textbox and upload 23 | 24 | # Dont like how it looks? 🎨 25 | pick a .css file from [here](https://github.com/dbohdan/classless-css) and replace the `static/theme.css`, or search for "classless css" 26 | 27 | # How to build with docker :whale2: 28 | 1. Download / clone this repo 29 | 2. Make a folder called `uploads` 30 | 3. Run `docker compose up` 31 | 32 | # How to build without docker 📟 33 | 1. Download / clone this repo 34 | 2. Make sure that x64_86 gcc is installed 35 | 3. Open terminal 36 | 4. Run `go build .` 37 | 38 | # Settings ⚙️ 39 | You can modify the variables inside `data/settings.json` 40 | - `fileSizeLimitMB` = limit file size (in megabytes) 41 | - `textSizeLimitMB` = limit text size (in megabytes) 42 | - `streamSizeLimitKB` = limit file encryption, decryption, upload & download buffer stream size (in kb) to limit memory usage 43 | - `streamThrottleMS` = add throttle to the encryption, decryption, upload & download buffer to limit cpu usage 44 | - `pbkdf2Iterations` = key derivation algorithm iteration, the higher the better, but 100000 should be enough 45 | - `cmdUploadDefaultDurationMinute` = default file duration if you upload file through curl if duration is not specified 46 | - `enablePassword` = whether to enable password or not for site authentication 47 | - `password` = password value for site authentication, use a long password to deter attacks or use an external authentication server 48 | 49 | You can modify CPU/memory usage by calculating the memory usage / sec with `streamSizeLimitKB * (1000/streamThrottleMS)`, the default setting can handle 40 MB of data/second on file upload, download, encryption & decryption, you can tune this down if needed 50 | 51 | # Curl upload ⬆️ 52 | example: `curl -F file=@main.go -F duration=10 -F pass=123 -F burn=true https://yoursite.com` 53 | Note that the duration, password, and burn is totally optional, you can just write `curl -F file=@file.txt https://yoursite.com` for quick upload. If your site is protected with a password, you also need to add `-F auth=yourpassword` 54 | 55 | # Security 🔒 56 | For maximum security, it is recommended to encrypt your file before uploading 57 | 58 | # Contribution 🤝 59 | Feel free to open an issue if you have a feature idea / send me a PR. 60 | -------------------------------------------------------------------------------- /auth.go: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of GigaPaste. 3 | 4 | GigaPaste is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 5 | 6 | GigaPaste is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 7 | 8 | You should have received a copy of the GNU General Public License along with GigaPaste. If not, see . 9 | */ 10 | 11 | package main 12 | 13 | import ( 14 | "crypto/rand" 15 | "encoding/base64" 16 | "encoding/json" 17 | "fmt" 18 | "io" 19 | "net/http" 20 | "slices" 21 | "time" 22 | ) 23 | 24 | type Session struct { 25 | Timer *time.Timer 26 | SessionString string 27 | } 28 | 29 | var Sessions []Session = []Session{} 30 | 31 | func AuthHandler(w http.ResponseWriter, r *http.Request) { 32 | 33 | var jsonData struct { 34 | Key string `json:"key"` 35 | } 36 | 37 | decoder := json.NewDecoder(r.Body) 38 | err := decoder.Decode(&jsonData) 39 | if err != nil { 40 | fmt.Println(err) 41 | return 42 | } 43 | 44 | if jsonData.Key == Global.Password { 45 | 46 | randomBytes := make([]byte, 32) 47 | _, err := rand.Read(randomBytes) 48 | if err != nil { 49 | fmt.Println(err) 50 | } 51 | 52 | randomBytesString := base64.StdEncoding.EncodeToString(randomBytes) 53 | 54 | timer := time.AfterFunc(24*time.Hour, func() { 55 | 56 | for i, v := range Sessions { 57 | 58 | if v.SessionString == randomBytesString { 59 | 60 | Sessions = slices.Delete(Sessions, i, i+1) 61 | 62 | } 63 | 64 | } 65 | 66 | }) 67 | 68 | Sessions = append(Sessions, Session{timer, randomBytesString}) 69 | http.SetCookie(w, &http.Cookie{ 70 | 71 | Name: "session", 72 | Value: randomBytesString, 73 | Expires: time.Now().Add(24 * time.Hour), 74 | HttpOnly: true, 75 | Secure: false, 76 | Path: "/", 77 | }) 78 | 79 | _, err = io.WriteString(w, "done") 80 | if err != nil { 81 | fmt.Println(err) 82 | } 83 | 84 | } else { 85 | 86 | _, err = io.WriteString(w, "wrong") 87 | if err != nil { 88 | fmt.Println(err) 89 | } 90 | 91 | } 92 | 93 | } 94 | 95 | func ValidateSession(w http.ResponseWriter, r *http.Request) bool { 96 | 97 | if !Global.EnablePassword { 98 | 99 | return true 100 | 101 | } 102 | 103 | cookie, err := r.Cookie("session") 104 | if err != nil { 105 | 106 | return false 107 | 108 | } 109 | 110 | for _, v := range Sessions { 111 | 112 | if v.SessionString == cookie.Value { 113 | 114 | return true 115 | 116 | } 117 | 118 | } 119 | 120 | return false 121 | 122 | } 123 | 124 | func DeleteSession(w http.ResponseWriter, r *http.Request) { 125 | 126 | cookie, err := r.Cookie("session") 127 | if err != nil { 128 | return 129 | } 130 | 131 | for i, v := range Sessions { 132 | 133 | if v.SessionString == cookie.Value { 134 | 135 | v.Timer.Stop() 136 | Sessions = slices.Delete(Sessions, i, i+1) 137 | 138 | } 139 | 140 | } 141 | 142 | } 143 | -------------------------------------------------------------------------------- /cryptography.go: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of GigaPaste. 3 | 4 | GigaPaste is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 5 | 6 | GigaPaste is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 7 | 8 | You should have received a copy of the GNU General Public License along with GigaPaste. If not, see . 9 | */ 10 | 11 | package main 12 | 13 | import ( 14 | "crypto/aes" 15 | "crypto/cipher" 16 | "crypto/rand" 17 | "crypto/sha256" 18 | "golang.org/x/crypto/pbkdf2" 19 | "io" 20 | "os" 21 | "time" 22 | ) 23 | 24 | func EncryptFile(srcPath string, aesKey []byte) error { 25 | 26 | srcFile, err := os.Open(srcPath) 27 | if err != nil { 28 | return err 29 | } 30 | defer srcFile.Close() 31 | 32 | dstFile, err := os.Create(srcPath + ".tmp") 33 | if err != nil { 34 | return err 35 | } 36 | defer dstFile.Close() 37 | 38 | block, err := aes.NewCipher(aesKey) 39 | if err != nil { 40 | return err 41 | } 42 | 43 | //make nonce 44 | nonce := make([]byte, aes.BlockSize) 45 | if _, err := io.ReadFull(rand.Reader, nonce); err != nil { 46 | return err 47 | } 48 | 49 | //write nonce 50 | if _, err := dstFile.Write(nonce); err != nil { 51 | return err 52 | } 53 | 54 | stream := cipher.NewCTR(block, nonce) 55 | 56 | //create stream writer that can encrypt in real time 57 | streamWriter := &cipher.StreamWriter{S: stream, W: dstFile} 58 | buffer := make([]byte, 1024*Global.StreamSizeLimit) 59 | for { 60 | n, err := srcFile.Read(buffer) 61 | if err != nil && err != io.EOF { 62 | return err 63 | } 64 | if n == 0 { 65 | break 66 | } 67 | 68 | streamWriter.Write(buffer[:n]) 69 | if Global.StreamThrottle > 0 { 70 | time.Sleep(time.Duration(Global.StreamThrottle) * time.Millisecond) 71 | } 72 | } 73 | 74 | srcFile.Close() 75 | err = os.Remove(srcPath) 76 | if err != nil { 77 | return err 78 | } 79 | 80 | dstFile.Close() 81 | err = os.Rename(srcPath+".tmp", srcPath) 82 | if err != nil { 83 | return err 84 | } 85 | 86 | return nil 87 | } 88 | 89 | func GetDecryptInfo(srcPath string, aesKey []byte) (error, []byte, cipher.Stream, int) { 90 | 91 | srcFile, err := os.Open(srcPath) 92 | if err != nil { 93 | return err, nil, nil, -1 94 | } 95 | defer srcFile.Close() 96 | 97 | block, err := aes.NewCipher(aesKey) 98 | if err != nil { 99 | return err, nil, nil, -1 100 | } 101 | 102 | iv := make([]byte, aes.BlockSize) 103 | if _, err := io.ReadFull(srcFile, iv); err != nil { 104 | return err, nil, nil, -1 105 | } 106 | 107 | stream := cipher.NewCTR(block, iv) 108 | return nil, iv, stream, aes.BlockSize 109 | 110 | } 111 | 112 | func DecryptFileStream(buffer []byte, size int, iv []byte, stream cipher.Stream) (error, []byte) { 113 | 114 | decrypted := make([]byte, size) 115 | stream.XORKeyStream(decrypted, buffer[:size]) 116 | 117 | return nil, decrypted 118 | 119 | } 120 | 121 | func GenerateSalt() ([]byte, error) { 122 | 123 | salt := make([]byte, 16) 124 | _, err := rand.Read(salt) 125 | if err != nil { 126 | return nil, err 127 | } 128 | return salt, nil 129 | 130 | } 131 | 132 | func GeneratePasswordHash(password string, salt []byte) []byte { 133 | 134 | return pbkdf2.Key([]byte(password), (salt), Global.Pbkdf2Iteraions, 32, sha256.New) 135 | 136 | } 137 | -------------------------------------------------------------------------------- /data/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "fileSizeLimitMB": 9999999, 3 | "textSizeLimitMB": 10, 4 | "streamSizeLimitKB": 1024, 5 | "streamThrottleMS": 25, 6 | 7 | "pbkdf2Iterations": 10000, 8 | 9 | "cmdUploadDefaultDurationMinute" : 10, 10 | 11 | "enablePassword" : false, 12 | "password" : "password" 13 | } 14 | -------------------------------------------------------------------------------- /database.go: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of GigaPaste. 3 | 4 | GigaPaste is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 5 | 6 | GigaPaste is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 7 | 8 | You should have received a copy of the GNU General Public License along with GigaPaste. If not, see . 9 | */ 10 | 11 | package main 12 | 13 | import ( 14 | "database/sql" 15 | "fmt" 16 | _ "github.com/mattn/go-sqlite3" 17 | ) 18 | 19 | func InitDatabase() *sql.DB { 20 | 21 | db, err := sql.Open("sqlite3", "file:./data/database.db?cache=shared") 22 | if err != nil { 23 | fmt.Println(err) 24 | return nil 25 | } 26 | 27 | db.SetMaxOpenConns(1) 28 | 29 | // Create a table 30 | createTableSQL := `CREATE TABLE IF NOT EXISTS data ( 31 | id TEXT NOT NULL, 32 | type TEXT NOT NULL, 33 | fileName TEXT NOT NULL, 34 | filePath TEXT NOT NULL, 35 | burn TEXT NOT NULL, 36 | expire TEXT NOT NULL, 37 | passwordHash TEXT NOT NULL, 38 | passwordSalt TEXT NOT NULL, 39 | encryptSalt TEXT NOT NULL 40 | );` 41 | 42 | _, err = db.Exec(createTableSQL) 43 | if err != nil { 44 | fmt.Println(err) 45 | return nil 46 | } 47 | 48 | return db 49 | 50 | } 51 | -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | services: 2 | superbin: 3 | build: . 4 | ports: 5 | - "80:80" 6 | volumes: 7 | - ./data:/app/data 8 | - ./uploads:/app/uploads 9 | -------------------------------------------------------------------------------- /expiration.go: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of GigaPaste. 3 | 4 | GigaPaste is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 5 | 6 | GigaPaste is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 7 | 8 | You should have received a copy of the GNU General Public License along with GigaPaste. If not, see . 9 | */ 10 | 11 | package main 12 | 13 | import ( 14 | "database/sql" 15 | "fmt" 16 | "os" 17 | "strconv" 18 | "time" 19 | ) 20 | 21 | func CheckExpiration(db *sql.DB) { 22 | 23 | for { 24 | 25 | tx, err := db.Begin() 26 | if err != nil { 27 | fmt.Println(err) 28 | } 29 | 30 | //Sqlite doesn't support select for update, instead when we begin transaction it locks the whole db file 31 | rows, err := tx.Query("SELECT id, filePath FROM data WHERE expire <= ?", strconv.FormatInt(time.Now().Unix(), 10)) 32 | if err != nil { 33 | tx.Rollback() 34 | fmt.Print(err) 35 | return 36 | } 37 | 38 | var toDelete = []struct { 39 | Id string 40 | FilePath string 41 | }{} 42 | 43 | for rows.Next() { 44 | 45 | var id string 46 | var filePath string 47 | 48 | err = rows.Scan(&id, &filePath) 49 | if err != nil { 50 | tx.Rollback() 51 | fmt.Println(err) 52 | rows.Close() 53 | return 54 | } 55 | 56 | //dont wanna clutter the file with type struct 57 | //we cant' directly remove the rows from database because it will be locked before we call rows.Close() 58 | //so we just put things we want to delete into array 59 | toDelete = append(toDelete, struct { 60 | Id string 61 | FilePath string 62 | }{Id: id, FilePath: filePath}) 63 | 64 | } 65 | 66 | rows.Close() 67 | 68 | for _, v := range toDelete { 69 | 70 | _, err = tx.Exec("DELETE FROM data WHERE id = ?", v.Id) 71 | if err != nil { 72 | tx.Rollback() 73 | fmt.Println(err) 74 | return 75 | } 76 | 77 | err = os.Remove(v.FilePath) 78 | if err != nil { 79 | fmt.Println(err) 80 | } 81 | 82 | } 83 | 84 | if err := tx.Commit(); err != nil { 85 | fmt.Println(err) 86 | return 87 | } 88 | 89 | time.Sleep(10 * time.Second) 90 | 91 | } 92 | 93 | } 94 | -------------------------------------------------------------------------------- /fileWriters.go: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of GigaPaste. 3 | 4 | GigaPaste is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 5 | 6 | GigaPaste is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 7 | 8 | You should have received a copy of the GNU General Public License along with GigaPaste. If not, see . 9 | */ 10 | 11 | package main 12 | 13 | import ( 14 | "archive/zip" 15 | "fmt" 16 | "io" 17 | "mime/multipart" 18 | "os" 19 | "time" 20 | ) 21 | 22 | func MultipleFileWriter(files []*multipart.FileHeader, path string, aesKey []byte, callback func()) { 23 | 24 | outFile, err := os.Create(path) 25 | if err != nil { 26 | fmt.Println(err) 27 | return 28 | } 29 | defer outFile.Close() 30 | 31 | //make new zip file 32 | zipWriter := zip.NewWriter(outFile) 33 | defer zipWriter.Close() 34 | 35 | for _, fileHeader := range files { 36 | 37 | file, err := fileHeader.Open() 38 | if err != nil { 39 | fmt.Println(err) 40 | return 41 | } 42 | defer file.Close() 43 | 44 | //create file inside the zip 45 | writer, err := zipWriter.Create(fileHeader.Filename) 46 | if err != nil { 47 | fmt.Println(err) 48 | return 49 | } 50 | 51 | buffer := make([]byte, 1024*Global.StreamSizeLimit) 52 | for { 53 | 54 | n, err := file.Read(buffer) 55 | if err != nil && err != io.EOF { 56 | fmt.Println(err) 57 | return 58 | } 59 | if n == 0 { 60 | break 61 | } 62 | 63 | // Write the chunk to the ZIP file 64 | _, err = writer.Write(buffer[:n]) 65 | if err != nil { 66 | fmt.Println(err) 67 | return 68 | } 69 | 70 | //need to add check for > 0 because Sleep(0) will just trigger context switch 71 | if Global.StreamThrottle > 0 { 72 | time.Sleep(time.Duration(Global.StreamThrottle) * time.Millisecond) 73 | } 74 | 75 | } 76 | 77 | } 78 | 79 | zipWriter.Close() 80 | outFile.Close() 81 | 82 | if aesKey != nil { 83 | 84 | err = EncryptFile(path, aesKey) 85 | if err != nil { 86 | fmt.Println(err) 87 | } 88 | 89 | } 90 | 91 | callback() 92 | 93 | } 94 | 95 | func SingleFileWriter(files []*multipart.FileHeader, path string, aesKey []byte, callback func()) { 96 | 97 | outFile, err := os.Create(path) 98 | if err != nil { 99 | fmt.Println(err) 100 | return 101 | } 102 | defer outFile.Close() 103 | 104 | file, err := files[0].Open() 105 | if err != nil { 106 | fmt.Println(err) 107 | return 108 | } 109 | 110 | defer file.Close() 111 | 112 | // Use a buffered reader to read the file in chunks 113 | buffer := make([]byte, 1024*Global.StreamSizeLimit) 114 | for { 115 | n, err := file.Read(buffer) 116 | if err != nil && err != io.EOF { 117 | fmt.Println(err) 118 | return 119 | } 120 | if n == 0 { 121 | break 122 | } 123 | 124 | // Write the chunk to the output file 125 | _, err = outFile.Write(buffer[:n]) 126 | if err != nil { 127 | fmt.Println(err) 128 | return 129 | } 130 | 131 | //need to add check for > 0 because Sleep(0) will just trigger context switch 132 | if Global.StreamThrottle > 0 { 133 | time.Sleep(time.Duration(Global.StreamThrottle) * time.Millisecond) 134 | } 135 | 136 | } 137 | 138 | outFile.Close() 139 | if aesKey != nil { 140 | 141 | err = EncryptFile(path, aesKey) 142 | if err != nil { 143 | fmt.Println(err) 144 | } 145 | 146 | } 147 | 148 | callback() 149 | 150 | } 151 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module app 2 | 3 | go 1.21.6 4 | 5 | require ( 6 | github.com/mattn/go-sqlite3 v1.14.27 7 | golang.org/x/crypto v0.27.0 8 | ) 9 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/mattn/go-sqlite3 v1.14.27 h1:drZCnuvf37yPfs95E5jd9s3XhdVWLal+6BOK6qrv6IU= 2 | github.com/mattn/go-sqlite3 v1.14.27/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= 3 | golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A= 4 | golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70= 5 | -------------------------------------------------------------------------------- /handlers.go: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of GigaPaste. 3 | 4 | GigaPaste is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 5 | 6 | GigaPaste is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 7 | 8 | You should have received a copy of the GNU General Public License along with GigaPaste. If not, see . 9 | */ 10 | 11 | package main 12 | 13 | import ( 14 | "bytes" 15 | "crypto/cipher" 16 | "database/sql" 17 | "embed" 18 | "encoding/hex" 19 | "encoding/json" 20 | "fmt" 21 | "html/template" 22 | "io" 23 | "io/fs" 24 | "net/http" 25 | "net/url" 26 | "os" 27 | "strconv" 28 | "time" 29 | ) 30 | 31 | //go:embed templates/* 32 | var templateFiles embed.FS 33 | 34 | func FileHandler(w http.ResponseWriter, r *http.Request, db *sql.DB) { 35 | 36 | // Retrieve data from the form 37 | var duration string 38 | var password string 39 | var burnStr string 40 | 41 | //we do these checks for curl support 42 | if len(r.MultipartForm.Value["duration"]) > 0 { 43 | duration = r.MultipartForm.Value["duration"][0] 44 | } else { 45 | duration = strconv.FormatInt(Global.CmdUploadDefaultDurationMinute, 10) 46 | } 47 | if len(r.MultipartForm.Value["pass"]) > 0 { 48 | password = r.MultipartForm.Value["pass"][0] 49 | } else { 50 | password = "" 51 | } 52 | if len(r.MultipartForm.Value["burn"]) > 0 { 53 | burnStr = r.MultipartForm.Value["burn"][0] 54 | } else { 55 | burnStr = "" 56 | } 57 | 58 | if burnStr == "" { 59 | burnStr = "false" 60 | } 61 | burn, err := strconv.ParseBool(burnStr) 62 | if err != nil { 63 | fmt.Println(err) 64 | } 65 | 66 | minutes, err := strconv.ParseInt(duration, 10, 64) 67 | if err != nil { 68 | fmt.Println(err) 69 | return 70 | } 71 | 72 | seconds := minutes * 60 73 | 74 | //if anyone manipulates the number to weird value 75 | if seconds <= 0 { 76 | return 77 | } 78 | 79 | //if over 200 years just set it to 200 80 | if seconds > 6311520000 { 81 | seconds = 6311520000 82 | } 83 | 84 | files := r.MultipartForm.File["file"] 85 | 86 | if len(files) == 0 { 87 | fmt.Println("file length == 0") 88 | return 89 | } 90 | 91 | passwordHash := "" 92 | passwordSalt := "" 93 | var encryptKey []byte = nil 94 | encryptSalt := "" 95 | 96 | if password != "" { 97 | 98 | salt, err := GenerateSalt() 99 | if err != nil { 100 | fmt.Println(err) 101 | return 102 | } 103 | 104 | passwordSalt = hex.EncodeToString(salt) 105 | passwordHash = hex.EncodeToString(GeneratePasswordHash(password, salt)) 106 | 107 | salt2, err := GenerateSalt() 108 | if err != nil { 109 | fmt.Println(err) 110 | return 111 | } 112 | 113 | encryptSalt = hex.EncodeToString(salt2) 114 | encryptKey = GeneratePasswordHash(password, salt2) 115 | 116 | } 117 | 118 | //create unique file name + some random string as a protection in case there are 2 file uploads at the exact same time 119 | if len(files) == 1 { 120 | 121 | filePath := GenRandFileName("./uploads/", "") 122 | SingleFileWriter(files, filePath, encryptKey, func() { 123 | randUrl := GenRandPath(6, db) 124 | _, err = db.Exec("INSERT INTO data (id, type, fileName, filePath, burn, expire, passwordHash, passwordSalt, encryptSalt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", randUrl, "file", files[0].Filename, filePath, burn, strconv.FormatInt(time.Now().Unix()+seconds, 10), passwordHash, passwordSalt, encryptSalt) 125 | if err != nil { 126 | fmt.Println(err) 127 | return 128 | } 129 | 130 | _, err = io.WriteString(w, r.Host+"/"+randUrl) 131 | if err != nil { 132 | fmt.Println(err) 133 | return 134 | } 135 | 136 | }) 137 | 138 | } 139 | 140 | if len(files) >= 2 { 141 | 142 | filePath := GenRandFileName("./uploads/", ".zip") 143 | MultipleFileWriter(files, filePath, encryptKey, func() { 144 | randUrl := GenRandPath(6, db) 145 | _, err = db.Exec("INSERT INTO data (id, type, fileName, filePath, burn, expire, passwordHash, passwordSalt, encryptSalt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", randUrl, "file", "files.zip", filePath, burn, strconv.FormatInt(time.Now().Unix()+seconds, 10), passwordHash, passwordSalt, encryptSalt) 146 | if err != nil { 147 | fmt.Println(err) 148 | return 149 | } 150 | 151 | _, err = io.WriteString(w, r.Host+"/"+randUrl) 152 | if err != nil { 153 | fmt.Println(err) 154 | return 155 | } 156 | 157 | }) 158 | 159 | } 160 | 161 | } 162 | 163 | func TextHandler(w http.ResponseWriter, r *http.Request, db *sql.DB) { 164 | 165 | var jsonData struct { 166 | Duration int64 `json:"duration"` 167 | Text string `json:"text"` 168 | Password string `json:"pass"` 169 | Burn bool `json:"burn"` 170 | } 171 | 172 | decoder := json.NewDecoder(r.Body) 173 | err := decoder.Decode(&jsonData) 174 | if err != nil { 175 | fmt.Println(err) 176 | return 177 | } 178 | 179 | seconds := jsonData.Duration * 60 180 | 181 | if seconds <= 0 { 182 | return 183 | } 184 | 185 | //if over 200 years just set it to 200 186 | if seconds > 6311520000 { 187 | seconds = 6311520000 188 | } 189 | 190 | filePath := GenRandFileName("./uploads/", "") 191 | file, err := os.Create(filePath) 192 | if err != nil { 193 | fmt.Println(err) 194 | return 195 | } 196 | defer file.Close() 197 | 198 | password := jsonData.Password 199 | passwordHash := "" 200 | passwordSalt := "" 201 | var encryptKey []byte = nil 202 | encryptSalt := "" 203 | if password != "" { 204 | 205 | salt, err := GenerateSalt() 206 | if err != nil { 207 | fmt.Println(err) 208 | return 209 | } 210 | 211 | passwordSalt = hex.EncodeToString(salt) 212 | passwordHash = hex.EncodeToString(GeneratePasswordHash(password, salt)) 213 | 214 | salt2, err := GenerateSalt() 215 | if err != nil { 216 | fmt.Println(err) 217 | return 218 | } 219 | 220 | encryptSalt = hex.EncodeToString(salt2) 221 | encryptKey = GeneratePasswordHash(password, salt2) 222 | 223 | } 224 | 225 | _, err = file.Write([]byte(jsonData.Text)) 226 | if err != nil { 227 | fmt.Println(err) 228 | return 229 | } 230 | 231 | file.Close() 232 | 233 | randUrl := GenRandPath(6, db) 234 | _, err = db.Exec("INSERT INTO data (id, type, fileName, filePath, burn, expire, passwordHash, passwordSalt, encryptSalt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", randUrl, "text", "", filePath, jsonData.Burn, strconv.FormatInt(time.Now().Unix()+seconds, 10), passwordHash, passwordSalt, encryptSalt) 235 | if err != nil { 236 | fmt.Println(err) 237 | return 238 | } 239 | 240 | if passwordHash != "" { 241 | 242 | err = EncryptFile(filePath, encryptKey) 243 | if err != nil { 244 | fmt.Println(err) 245 | return 246 | } 247 | 248 | } 249 | 250 | _, err = io.WriteString(w, r.Host+"/"+randUrl) 251 | if err != nil { 252 | fmt.Println(err) 253 | return 254 | } 255 | 256 | } 257 | 258 | func DownloadHandler(w http.ResponseWriter, r *http.Request, db *sql.DB) { 259 | 260 | path := r.URL.Path[1:] //dont include the '/' 261 | 262 | var fType string 263 | var fFileName string 264 | var fFilePath string 265 | var fBurn string 266 | var fPasswordHash string 267 | var fPasswordSalt string 268 | var fEncryptSalt string 269 | 270 | decryptKey := r.URL.Query().Get("key") 271 | raw := r.URL.Query().Get("raw") 272 | 273 | err := db.QueryRow("SELECT type, fileName, filePath, burn, passwordHash, passwordSalt, encryptSalt FROM data WHERE id = ?", path).Scan(&fType, &fFileName, &fFilePath, &fBurn, &fPasswordHash, &fPasswordSalt, &fEncryptSalt) 274 | if err != nil { 275 | 276 | //path not found 277 | data, err := fs.ReadFile(templateFiles, "templates/notFound.html") 278 | if err != nil { 279 | fmt.Println(err) 280 | return 281 | } 282 | 283 | w.Header().Set("Content-Type", "text/html") 284 | w.WriteHeader(http.StatusOK) 285 | w.Write(data) 286 | return 287 | } 288 | 289 | //doesn't exist 290 | if fType == "" { 291 | return 292 | } 293 | 294 | //if link is password protected and no password is given 295 | if fPasswordHash != "" && decryptKey == "" { 296 | 297 | tmpl, err := template.ParseFS(templateFiles, "templates/authTemplate.html") 298 | if err != nil { 299 | fmt.Println(err) 300 | return 301 | } 302 | 303 | err = tmpl.Execute(w, struct{ Path string }{Path: path}) 304 | 305 | if err != nil { 306 | fmt.Println(err) 307 | return 308 | } 309 | 310 | return 311 | 312 | } 313 | 314 | var decryptFileHash []byte 315 | if fPasswordHash != "" { 316 | 317 | passwordSalt, err := hex.DecodeString(fPasswordSalt) 318 | if err != nil { 319 | fmt.Println(err) 320 | return 321 | } 322 | 323 | decryptKeyHash := GeneratePasswordHash(decryptKey, passwordSalt) 324 | 325 | passwordHash, err := hex.DecodeString(fPasswordHash) 326 | if err != nil { 327 | fmt.Println(err) 328 | return 329 | } 330 | 331 | //if wrong password 332 | if !bytes.Equal(decryptKeyHash, passwordHash) { 333 | 334 | referer := r.Header.Get("Referer") 335 | if referer == "" { 336 | return 337 | } 338 | 339 | // Redirect to the referer URL 340 | http.Redirect(w, r, referer, http.StatusFound) 341 | return 342 | 343 | } 344 | 345 | encryptSalt, err := hex.DecodeString(fEncryptSalt) 346 | if err != nil { 347 | fmt.Println(err) 348 | return 349 | } 350 | 351 | decryptFileHash = GeneratePasswordHash(decryptKey, encryptSalt) 352 | 353 | } 354 | 355 | if fType == "file" { 356 | 357 | file, err := os.Open(fFilePath) 358 | if err != nil { 359 | fmt.Println(err) 360 | return 361 | } 362 | defer file.Close() 363 | 364 | // Get the file stats to determine the size 365 | fileInfo, err := file.Stat() 366 | if err != nil { 367 | fmt.Println(err) 368 | return 369 | } 370 | 371 | var ( 372 | iv []byte 373 | aesCTR cipher.Stream 374 | nonceSize int 375 | ) 376 | 377 | if fPasswordHash != "" { 378 | 379 | err, iv, aesCTR, nonceSize = GetDecryptInfo(fFilePath, decryptFileHash) 380 | if err != nil { 381 | 382 | fmt.Println(err) 383 | 384 | } 385 | 386 | } 387 | 388 | // Set the appropriate headers 389 | w.Header().Set("Content-Disposition", "attachment; filename="+fFileName) 390 | w.Header().Set("Content-Type", "application/octet-stream") 391 | if fPasswordHash != "" { 392 | w.Header().Set("Content-Length", strconv.FormatInt(fileInfo.Size()-int64(nonceSize), 10)) 393 | } else { 394 | w.Header().Set("Content-Length", strconv.FormatInt(fileInfo.Size(), 10)) 395 | } 396 | 397 | buffer := make([]byte, 1024*Global.StreamSizeLimit) 398 | 399 | //skip the IV 400 | if fPasswordHash != "" { 401 | file.Seek(int64(nonceSize), 0) 402 | } 403 | 404 | for { 405 | 406 | n, err := file.Read(buffer) 407 | if err != nil && err != io.EOF { 408 | fmt.Println(err) 409 | return 410 | } 411 | 412 | if n == 0 { 413 | 414 | if fBurn == "1" { 415 | 416 | file.Close() 417 | _, err = db.Exec("DELETE FROM data WHERE id = ?", path) 418 | if err != nil { 419 | fmt.Println(err) 420 | return 421 | } 422 | 423 | err = os.Remove(fFilePath) 424 | if err != nil { 425 | fmt.Println(err) 426 | return 427 | } 428 | 429 | } 430 | 431 | break 432 | } 433 | 434 | if fPasswordHash != "" { 435 | 436 | err, decrypted := DecryptFileStream(buffer[:n], n, iv, aesCTR) 437 | if err != nil { 438 | fmt.Println(err) 439 | return 440 | } 441 | 442 | if _, err := w.Write(decrypted); err != nil { 443 | fmt.Println(err) 444 | return 445 | } 446 | 447 | } else { 448 | 449 | if _, err := w.Write(buffer[:n]); err != nil { 450 | fmt.Println(err) 451 | return 452 | } 453 | 454 | } 455 | 456 | // Ensure that the client receives the data immediately 457 | if flusher, ok := w.(http.Flusher); ok { 458 | flusher.Flush() 459 | } 460 | 461 | //need to add check for > 0 because Sleep(0) will just trigger context switch 462 | if Global.StreamThrottle > 0 { 463 | time.Sleep(time.Duration(Global.StreamThrottle) * time.Millisecond) 464 | } 465 | 466 | } 467 | 468 | } 469 | 470 | if fType == "text" { 471 | 472 | file, err := os.Open(fFilePath) 473 | if err != nil { 474 | fmt.Println(err) 475 | return 476 | } 477 | defer file.Close() 478 | 479 | content, err := io.ReadAll(file) 480 | 481 | if err != nil { 482 | fmt.Println(err) 483 | return 484 | } 485 | 486 | var text string 487 | 488 | if fPasswordHash != "" { 489 | 490 | err, iv, aesCTR, nonceSize := GetDecryptInfo(fFilePath, decryptFileHash) 491 | if err != nil { 492 | 493 | fmt.Println(err) 494 | 495 | } 496 | 497 | err, decrypted := DecryptFileStream(content[nonceSize:], len(content)-nonceSize, iv, aesCTR) 498 | if err != nil { 499 | fmt.Println(err) 500 | return 501 | } 502 | 503 | text = string(decrypted) 504 | 505 | } else { 506 | 507 | text = string(content) 508 | 509 | } 510 | 511 | //URL shortener 512 | _, err = url.ParseRequestURI(text) 513 | //if it's valid url 514 | if err == nil { 515 | 516 | http.Redirect(w, r, text, http.StatusSeeOther) 517 | 518 | } else { 519 | 520 | tmpl, err := template.ParseFS(templateFiles, "templates/pasteTemplate.html") 521 | if err != nil { 522 | fmt.Println(err) 523 | return 524 | } 525 | 526 | if raw == "1" { 527 | 528 | w.Header().Set("Content-Type", "text/plain") 529 | w.Write([]byte(text)) 530 | 531 | } else { 532 | 533 | err = tmpl.Execute(w, struct { 534 | Text string 535 | Burn string 536 | }{Text: text, Burn: fBurn}) 537 | if err != nil { 538 | fmt.Println(err) 539 | return 540 | } 541 | 542 | } 543 | 544 | } 545 | 546 | if fBurn == "1" { 547 | 548 | file.Close() 549 | _, err = db.Exec("DELETE FROM data WHERE id = ?", path) 550 | if err != nil { 551 | fmt.Println(err) 552 | return 553 | } 554 | 555 | err = os.Remove(fFilePath) 556 | if err != nil { 557 | fmt.Println(err) 558 | return 559 | } 560 | 561 | } 562 | 563 | } 564 | 565 | } 566 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of GigaPaste. 3 | 4 | GigaPaste is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 5 | 6 | GigaPaste is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 7 | 8 | You should have received a copy of the GNU General Public License along with GigaPaste. If not, see . 9 | */ 10 | 11 | package main 12 | 13 | import ( 14 | "embed" 15 | "fmt" 16 | "log" 17 | "mime" 18 | "net/http" 19 | "os" 20 | "os/signal" 21 | "path/filepath" 22 | "strconv" 23 | "strings" 24 | "syscall" 25 | ) 26 | 27 | //go:embed static/* 28 | var staticFiles embed.FS 29 | 30 | //go:embed data/settings.json 31 | var settingsFile string 32 | 33 | // Theoretically won't ever conflict with generated URL, because generated URL won't contain a dot "." 34 | func serveFile(w http.ResponseWriter, r *http.Request, next func(w2 http.ResponseWriter, r2 *http.Request)) { 35 | // Remove leading slash from the URL path 36 | path := strings.TrimPrefix(r.URL.Path, "/") 37 | 38 | if path == "" { 39 | http.Redirect(w, r, "/index.html", http.StatusFound) 40 | return 41 | } 42 | 43 | // Open the file from the embedded file system 44 | file, err := staticFiles.ReadFile("static/" + path) 45 | if err != nil { 46 | // If GET URL is not found in static files, then we pass the request to the next handler (file download handler) 47 | next(w, r) 48 | return 49 | } 50 | 51 | // Detect the MIME type based on file extension 52 | ext := filepath.Ext(path) 53 | contentType := mime.TypeByExtension(ext) 54 | if contentType == "" { 55 | contentType = "application/octet-stream" 56 | } 57 | 58 | // Set headers and write the file to the response 59 | w.Header().Set("Content-Type", contentType) 60 | w.Header().Set("Content-Length", strconv.Itoa(len(file))) 61 | w.WriteHeader(http.StatusOK) 62 | w.Write(file) 63 | 64 | } 65 | 66 | func main() { 67 | 68 | if _, err := os.Stat("./uploads/"); os.IsNotExist(err) { 69 | err := os.MkdirAll("./uploads", os.ModePerm) 70 | if err != nil { 71 | fmt.Println(err) 72 | } 73 | } 74 | 75 | if _, err := os.Stat("./data/"); os.IsNotExist(err) { 76 | err := os.MkdirAll("./data", os.ModePerm) 77 | if err != nil { 78 | fmt.Println(err) 79 | } 80 | 81 | err = os.WriteFile("./data/settings.json", []byte(settingsFile), 0644) 82 | if err != nil { 83 | fmt.Println(err) 84 | return 85 | } 86 | 87 | } 88 | 89 | db := InitDatabase() 90 | InitSettings() 91 | 92 | http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 93 | 94 | if r.Method == http.MethodGet { 95 | 96 | if (r.URL.Path == "/" || r.URL.Path == "/index.html") && !ValidateSession(w, r) { 97 | 98 | http.Redirect(w, r, "/auth.html", http.StatusFound) 99 | return 100 | } 101 | 102 | serveFile(w, r, func(w2 http.ResponseWriter, r2 *http.Request) { 103 | 104 | DownloadHandler(w2, r2, db) 105 | 106 | }) 107 | 108 | } 109 | 110 | //Post files 111 | if r.Method == http.MethodPost { 112 | 113 | r.Body = http.MaxBytesReader(w, r.Body, 1024*1024*Global.FileSizeLimit) //Limit file size 114 | err := r.ParseMultipartForm(1024 * Global.StreamSizeLimit) //Limit memory usage 115 | 116 | defer func() { 117 | 118 | // Before the multipart form is parsed, it will be written to a temporary folder, make sure to clean it after we are done 119 | if r.MultipartForm != nil { 120 | 121 | err := r.MultipartForm.RemoveAll() 122 | if err != nil { 123 | fmt.Println(err) 124 | } 125 | 126 | } 127 | 128 | }() 129 | 130 | if err != nil { 131 | 132 | if err.Error() == "http: request body too large" { 133 | 134 | //Can't seem to get this to work 135 | http.Error(w, "SizeExceeded", http.StatusInternalServerError) 136 | return 137 | 138 | } 139 | fmt.Println(err) 140 | return 141 | } 142 | 143 | //if session is not valid, the uploader might be uploading through terminal, in that case, we check for password 144 | if !ValidateSession(w, r) { 145 | 146 | if len(r.MultipartForm.Value["auth"]) > 0 { 147 | 148 | auth := r.MultipartForm.Value["auth"][0] 149 | if auth != Global.Password { 150 | 151 | return 152 | 153 | } 154 | 155 | } else { 156 | 157 | return 158 | 159 | } 160 | 161 | } 162 | 163 | FileHandler(w, r, db) 164 | 165 | } 166 | 167 | }) 168 | 169 | http.HandleFunc("/postText", func(w http.ResponseWriter, r *http.Request) { 170 | 171 | if r.Method == http.MethodPost { 172 | 173 | if !ValidateSession(w, r) { 174 | return 175 | } 176 | 177 | r.Body = http.MaxBytesReader(w, r.Body, 1024*1024*Global.TextSizeLimit) //Limit text size 178 | TextHandler(w, r, db) 179 | 180 | } 181 | 182 | }) 183 | 184 | http.HandleFunc("/auth", func(w http.ResponseWriter, r *http.Request) { 185 | 186 | if r.Method == http.MethodPost { 187 | 188 | AuthHandler(w, r) 189 | 190 | } 191 | 192 | }) 193 | 194 | http.HandleFunc("/deleteSession", func(w http.ResponseWriter, r *http.Request) { 195 | 196 | if r.Method == http.MethodPost { 197 | 198 | DeleteSession(w, r) 199 | 200 | } 201 | 202 | }) 203 | 204 | go CheckExpiration(db) 205 | 206 | server := &http.Server{Addr: ":80"} 207 | go func() { 208 | sigChan := make(chan os.Signal, 1) 209 | signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) 210 | <-sigChan 211 | 212 | fmt.Println("Shutting down") 213 | if err := server.Close(); err != nil { 214 | fmt.Println(err) 215 | } 216 | if err := db.Close(); err != nil { 217 | fmt.Println(err) 218 | } 219 | }() 220 | 221 | log.Println("Server running") 222 | log.Fatal(server.ListenAndServe()) 223 | } 224 | -------------------------------------------------------------------------------- /random.go: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of GigaPaste. 3 | 4 | GigaPaste is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 5 | 6 | GigaPaste is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 7 | 8 | You should have received a copy of the GNU General Public License along with GigaPaste. If not, see . 9 | */ 10 | 11 | package main 12 | 13 | import ( 14 | "database/sql" 15 | "math/rand" 16 | "os" 17 | "strconv" 18 | "time" 19 | ) 20 | 21 | // we want to avoid ambiguous characters like i, I, l, 1, etc 22 | const charset = "abcdefghkmnpqrstwxyzABCDEFGHJKLMNPQRSTWXYZ23456789" 23 | 24 | var seed rand.Source 25 | var random *rand.Rand 26 | 27 | func init() { 28 | 29 | seed = rand.NewSource(time.Now().UnixNano()) 30 | random = rand.New(seed) 31 | 32 | } 33 | 34 | func GenRandFileName(basePath string, extension string) string { 35 | 36 | for { 37 | fileName := strconv.FormatInt(time.Now().UnixMilli(), 10) + genRandString(5) + extension 38 | filePath := basePath + fileName 39 | 40 | if _, err := os.Stat(filePath); os.IsNotExist(err) { 41 | return filePath 42 | } 43 | } 44 | } 45 | 46 | func GenRandPath(length int, db *sql.DB) string { 47 | 48 | for { 49 | 50 | randPath := genRandString(6) 51 | var id string 52 | 53 | db.QueryRow("SELECT id FROM data WHERE id = ?", randPath).Scan(&id) 54 | 55 | if id == "" { 56 | return randPath 57 | } 58 | 59 | } 60 | 61 | } 62 | 63 | func genRandString(length int) string { 64 | result := make([]byte, length) 65 | for i := range result { 66 | result[i] = charset[random.Intn(len(charset))] 67 | } 68 | return string(result) 69 | } 70 | -------------------------------------------------------------------------------- /settings.go: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of GigaPaste. 3 | 4 | GigaPaste is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 5 | 6 | GigaPaste is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 7 | 8 | You should have received a copy of the GNU General Public License along with GigaPaste. If not, see . 9 | */ 10 | 11 | package main 12 | 13 | import ( 14 | "encoding/json" 15 | "fmt" 16 | "os" 17 | ) 18 | 19 | type Setting struct { 20 | FileSizeLimit int64 `json:"FileSizeLimitMB"` 21 | TextSizeLimit int64 `json:"TextSizeLimitMB"` 22 | StreamSizeLimit int64 `json:"StreamSizeLimitKB"` 23 | StreamThrottle int64 `json:"StreamThrottleMS"` 24 | Pbkdf2Iteraions int `json:"Pbkdf2Iteraions"` 25 | CmdUploadDefaultDurationMinute int64 `json:"CmdUploadDefaultDurationMinute"` 26 | EnablePassword bool `json:"enablePassword"` 27 | Password string `json:"password"` 28 | } 29 | 30 | var Global Setting 31 | 32 | func InitSettings() { 33 | 34 | file, err := os.Open("./data/settings.json") 35 | if err != nil { 36 | fmt.Println(err) 37 | return 38 | } 39 | defer file.Close() 40 | 41 | decoder := json.NewDecoder(file) 42 | err = decoder.Decode(&Global) 43 | if err != nil { 44 | fmt.Println("Error decoding JSON:", err) 45 | return 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /static/auth.html: -------------------------------------------------------------------------------- 1 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 60 | 61 | 62 | 63 | 64 | 65 |
66 | 67 |
68 | 69 | 70 | 71 | 72 | 73 |
74 | 75 |
76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /static/helper.js: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of GigaPaste. 3 | 4 | GigaPaste is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 5 | 6 | GigaPaste is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 7 | 8 | You should have received a copy of the GNU General Public License along with GigaPaste. If not, see . 9 | */ 10 | function copyToClipboard(text){ 11 | 12 | if (navigator.clipboard && navigator.clipboard.writeText) { 13 | 14 | navigator.clipboard.writeText(text) 15 | 16 | }else{ 17 | 18 | //sometimes clipboard api has problems on mobile browsers or won't work unless https connection, fallback 19 | //into this method instead 20 | let element = document.createElement("textarea"); 21 | element.value = text; 22 | document.body.appendChild(element); 23 | element.select(); 24 | document.execCommand("copy"); 25 | document.body.removeChild(element); 26 | 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /static/index.html: -------------------------------------------------------------------------------- 1 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 |
30 | 31 | 32 |
33 | 36 | 37 |
38 | 39 | 40 |
41 |
42 | 43 |
44 | 45 | 46 | 53 |
54 |
55 | 56 | 57 |
58 |
59 |
60 | 61 | 62 |
63 | 64 |
65 | 66 | 67 |
68 | 69 |
70 | 71 |
72 | 73 |
74 | 75 | 76 |
77 | 78 |
79 |
80 | 81 |
82 | 93 | 94 |
95 | 96 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /static/qrcode.js: -------------------------------------------------------------------------------- 1 | //original author: https://github.com/davidshimjs/qrcodejs 2 | var QRCode;!function(){function a(a){this.mode=c.MODE_8BIT_BYTE,this.data=a,this.parsedData=[];for(var b=[],d=0,e=this.data.length;e>d;d++){var f=this.data.charCodeAt(d);f>65536?(b[0]=240|(1835008&f)>>>18,b[1]=128|(258048&f)>>>12,b[2]=128|(4032&f)>>>6,b[3]=128|63&f):f>2048?(b[0]=224|(61440&f)>>>12,b[1]=128|(4032&f)>>>6,b[2]=128|63&f):f>128?(b[0]=192|(1984&f)>>>6,b[1]=128|63&f):b[0]=f,this.parsedData=this.parsedData.concat(b)}this.parsedData.length!=this.data.length&&(this.parsedData.unshift(191),this.parsedData.unshift(187),this.parsedData.unshift(239))}function b(a,b){this.typeNumber=a,this.errorCorrectLevel=b,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}function i(a,b){if(void 0==a.length)throw new Error(a.length+"/"+b);for(var c=0;c=f;f++){var h=0;switch(b){case d.L:h=l[f][0];break;case d.M:h=l[f][1];break;case d.Q:h=l[f][2];break;case d.H:h=l[f][3]}if(h>=e)break;c++}if(c>l.length)throw new Error("Too long data");return c}function s(a){var b=encodeURI(a).toString().replace(/\%[0-9a-fA-F]{2}/g,"a");return b.length+(b.length!=a?3:0)}a.prototype={getLength:function(){return this.parsedData.length},write:function(a){for(var b=0,c=this.parsedData.length;c>b;b++)a.put(this.parsedData[b],8)}},b.prototype={addData:function(b){var c=new a(b);this.dataList.push(c),this.dataCache=null},isDark:function(a,b){if(0>a||this.moduleCount<=a||0>b||this.moduleCount<=b)throw new Error(a+","+b);return this.modules[a][b]},getModuleCount:function(){return this.moduleCount},make:function(){this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(a,c){this.moduleCount=4*this.typeNumber+17,this.modules=new Array(this.moduleCount);for(var d=0;d=7&&this.setupTypeNumber(a),null==this.dataCache&&(this.dataCache=b.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,c)},setupPositionProbePattern:function(a,b){for(var c=-1;7>=c;c++)if(!(-1>=a+c||this.moduleCount<=a+c))for(var d=-1;7>=d;d++)-1>=b+d||this.moduleCount<=b+d||(this.modules[a+c][b+d]=c>=0&&6>=c&&(0==d||6==d)||d>=0&&6>=d&&(0==c||6==c)||c>=2&&4>=c&&d>=2&&4>=d?!0:!1)},getBestMaskPattern:function(){for(var a=0,b=0,c=0;8>c;c++){this.makeImpl(!0,c);var d=f.getLostPoint(this);(0==c||a>d)&&(a=d,b=c)}return b},createMovieClip:function(a,b,c){var d=a.createEmptyMovieClip(b,c),e=1;this.make();for(var f=0;f=g;g++)for(var h=-2;2>=h;h++)this.modules[d+g][e+h]=-2==g||2==g||-2==h||2==h||0==g&&0==h?!0:!1}},setupTypeNumber:function(a){for(var b=f.getBCHTypeNumber(this.typeNumber),c=0;18>c;c++){var d=!a&&1==(1&b>>c);this.modules[Math.floor(c/3)][c%3+this.moduleCount-8-3]=d}for(var c=0;18>c;c++){var d=!a&&1==(1&b>>c);this.modules[c%3+this.moduleCount-8-3][Math.floor(c/3)]=d}},setupTypeInfo:function(a,b){for(var c=this.errorCorrectLevel<<3|b,d=f.getBCHTypeInfo(c),e=0;15>e;e++){var g=!a&&1==(1&d>>e);6>e?this.modules[e][8]=g:8>e?this.modules[e+1][8]=g:this.modules[this.moduleCount-15+e][8]=g}for(var e=0;15>e;e++){var g=!a&&1==(1&d>>e);8>e?this.modules[8][this.moduleCount-e-1]=g:9>e?this.modules[8][15-e-1+1]=g:this.modules[8][15-e-1]=g}this.modules[this.moduleCount-8][8]=!a},mapData:function(a,b){for(var c=-1,d=this.moduleCount-1,e=7,g=0,h=this.moduleCount-1;h>0;h-=2)for(6==h&&h--;;){for(var i=0;2>i;i++)if(null==this.modules[d][h-i]){var j=!1;g>>e));var k=f.getMask(b,d,h-i);k&&(j=!j),this.modules[d][h-i]=j,e--,-1==e&&(g++,e=7)}if(d+=c,0>d||this.moduleCount<=d){d-=c,c=-c;break}}}},b.PAD0=236,b.PAD1=17,b.createData=function(a,c,d){for(var e=j.getRSBlocks(a,c),g=new k,h=0;h8*l)throw new Error("code length overflow. ("+g.getLengthInBits()+">"+8*l+")");for(g.getLengthInBits()+4<=8*l&&g.put(0,4);0!=g.getLengthInBits()%8;)g.putBit(!1);for(;;){if(g.getLengthInBits()>=8*l)break;if(g.put(b.PAD0,8),g.getLengthInBits()>=8*l)break;g.put(b.PAD1,8)}return b.createBytes(g,e)},b.createBytes=function(a,b){for(var c=0,d=0,e=0,g=new Array(b.length),h=new Array(b.length),j=0;j=0?p.get(q):0}}for(var r=0,m=0;mm;m++)for(var j=0;jm;m++)for(var j=0;j=0;)b^=f.G15<=0;)b^=f.G18<>>=1;return b},getPatternPosition:function(a){return f.PATTERN_POSITION_TABLE[a-1]},getMask:function(a,b,c){switch(a){case e.PATTERN000:return 0==(b+c)%2;case e.PATTERN001:return 0==b%2;case e.PATTERN010:return 0==c%3;case e.PATTERN011:return 0==(b+c)%3;case e.PATTERN100:return 0==(Math.floor(b/2)+Math.floor(c/3))%2;case e.PATTERN101:return 0==b*c%2+b*c%3;case e.PATTERN110:return 0==(b*c%2+b*c%3)%2;case e.PATTERN111:return 0==(b*c%3+(b+c)%2)%2;default:throw new Error("bad maskPattern:"+a)}},getErrorCorrectPolynomial:function(a){for(var b=new i([1],0),c=0;a>c;c++)b=b.multiply(new i([1,g.gexp(c)],0));return b},getLengthInBits:function(a,b){if(b>=1&&10>b)switch(a){case c.MODE_NUMBER:return 10;case c.MODE_ALPHA_NUM:return 9;case c.MODE_8BIT_BYTE:return 8;case c.MODE_KANJI:return 8;default:throw new Error("mode:"+a)}else if(27>b)switch(a){case c.MODE_NUMBER:return 12;case c.MODE_ALPHA_NUM:return 11;case c.MODE_8BIT_BYTE:return 16;case c.MODE_KANJI:return 10;default:throw new Error("mode:"+a)}else{if(!(41>b))throw new Error("type:"+b);switch(a){case c.MODE_NUMBER:return 14;case c.MODE_ALPHA_NUM:return 13;case c.MODE_8BIT_BYTE:return 16;case c.MODE_KANJI:return 12;default:throw new Error("mode:"+a)}}},getLostPoint:function(a){for(var b=a.getModuleCount(),c=0,d=0;b>d;d++)for(var e=0;b>e;e++){for(var f=0,g=a.isDark(d,e),h=-1;1>=h;h++)if(!(0>d+h||d+h>=b))for(var i=-1;1>=i;i++)0>e+i||e+i>=b||(0!=h||0!=i)&&g==a.isDark(d+h,e+i)&&f++;f>5&&(c+=3+f-5)}for(var d=0;b-1>d;d++)for(var e=0;b-1>e;e++){var j=0;a.isDark(d,e)&&j++,a.isDark(d+1,e)&&j++,a.isDark(d,e+1)&&j++,a.isDark(d+1,e+1)&&j++,(0==j||4==j)&&(c+=3)}for(var d=0;b>d;d++)for(var e=0;b-6>e;e++)a.isDark(d,e)&&!a.isDark(d,e+1)&&a.isDark(d,e+2)&&a.isDark(d,e+3)&&a.isDark(d,e+4)&&!a.isDark(d,e+5)&&a.isDark(d,e+6)&&(c+=40);for(var e=0;b>e;e++)for(var d=0;b-6>d;d++)a.isDark(d,e)&&!a.isDark(d+1,e)&&a.isDark(d+2,e)&&a.isDark(d+3,e)&&a.isDark(d+4,e)&&!a.isDark(d+5,e)&&a.isDark(d+6,e)&&(c+=40);for(var k=0,e=0;b>e;e++)for(var d=0;b>d;d++)a.isDark(d,e)&&k++;var l=Math.abs(100*k/b/b-50)/5;return c+=10*l}},g={glog:function(a){if(1>a)throw new Error("glog("+a+")");return g.LOG_TABLE[a]},gexp:function(a){for(;0>a;)a+=255;for(;a>=256;)a-=255;return g.EXP_TABLE[a]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)},h=0;8>h;h++)g.EXP_TABLE[h]=1<h;h++)g.EXP_TABLE[h]=g.EXP_TABLE[h-4]^g.EXP_TABLE[h-5]^g.EXP_TABLE[h-6]^g.EXP_TABLE[h-8];for(var h=0;255>h;h++)g.LOG_TABLE[g.EXP_TABLE[h]]=h;i.prototype={get:function(a){return this.num[a]},getLength:function(){return this.num.length},multiply:function(a){for(var b=new Array(this.getLength()+a.getLength()-1),c=0;cf;f++)for(var g=c[3*f+0],h=c[3*f+1],i=c[3*f+2],k=0;g>k;k++)e.push(new j(h,i));return e},j.getRsBlockTable=function(a,b){switch(b){case d.L:return j.RS_BLOCK_TABLE[4*(a-1)+0];case d.M:return j.RS_BLOCK_TABLE[4*(a-1)+1];case d.Q:return j.RS_BLOCK_TABLE[4*(a-1)+2];case d.H:return j.RS_BLOCK_TABLE[4*(a-1)+3];default:return void 0}},k.prototype={get:function(a){var b=Math.floor(a/8);return 1==(1&this.buffer[b]>>>7-a%8)},put:function(a,b){for(var c=0;b>c;c++)this.putBit(1==(1&a>>>b-c-1))},getLengthInBits:function(){return this.length},putBit:function(a){var b=Math.floor(this.length/8);this.buffer.length<=b&&this.buffer.push(0),a&&(this.buffer[b]|=128>>>this.length%8),this.length++}};var l=[[17,14,11,7],[32,26,20,14],[53,42,32,24],[78,62,46,34],[106,84,60,44],[134,106,74,58],[154,122,86,64],[192,152,108,84],[230,180,130,98],[271,213,151,119],[321,251,177,137],[367,287,203,155],[425,331,241,177],[458,362,258,194],[520,412,292,220],[586,450,322,250],[644,504,364,280],[718,560,394,310],[792,624,442,338],[858,666,482,382],[929,711,509,403],[1003,779,565,439],[1091,857,611,461],[1171,911,661,511],[1273,997,715,535],[1367,1059,751,593],[1465,1125,805,625],[1528,1190,868,658],[1628,1264,908,698],[1732,1370,982,742],[1840,1452,1030,790],[1952,1538,1112,842],[2068,1628,1168,898],[2188,1722,1228,958],[2303,1809,1283,983],[2431,1911,1351,1051],[2563,1989,1423,1093],[2699,2099,1499,1139],[2809,2213,1579,1219],[2953,2331,1663,1273]],o=function(){var a=function(a,b){this._el=a,this._htOption=b};return a.prototype.draw=function(a){function g(a,b){var c=document.createElementNS("http://www.w3.org/2000/svg",a);for(var d in b)b.hasOwnProperty(d)&&c.setAttribute(d,b[d]);return c}var b=this._htOption,c=this._el,d=a.getModuleCount();Math.floor(b.width/d),Math.floor(b.height/d),this.clear();var h=g("svg",{viewBox:"0 0 "+String(d)+" "+String(d),width:"100%",height:"100%",fill:b.colorLight});h.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xlink","http://www.w3.org/1999/xlink"),c.appendChild(h),h.appendChild(g("rect",{fill:b.colorDark,width:"1",height:"1",id:"template"}));for(var i=0;d>i;i++)for(var j=0;d>j;j++)if(a.isDark(i,j)){var k=g("use",{x:String(i),y:String(j)});k.setAttributeNS("http://www.w3.org/1999/xlink","href","#template"),h.appendChild(k)}},a.prototype.clear=function(){for(;this._el.hasChildNodes();)this._el.removeChild(this._el.lastChild)},a}(),p="svg"===document.documentElement.tagName.toLowerCase(),q=p?o:m()?function(){function a(){this._elImage.src=this._elCanvas.toDataURL("image/png"),this._elImage.style.display="block",this._elCanvas.style.display="none"}function d(a,b){var c=this;if(c._fFail=b,c._fSuccess=a,null===c._bSupportDataURI){var d=document.createElement("img"),e=function(){c._bSupportDataURI=!1,c._fFail&&_fFail.call(c)},f=function(){c._bSupportDataURI=!0,c._fSuccess&&c._fSuccess.call(c)};return d.onabort=e,d.onerror=e,d.onload=f,d.src="data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==",void 0}c._bSupportDataURI===!0&&c._fSuccess?c._fSuccess.call(c):c._bSupportDataURI===!1&&c._fFail&&c._fFail.call(c)}if(this._android&&this._android<=2.1){var b=1/window.devicePixelRatio,c=CanvasRenderingContext2D.prototype.drawImage;CanvasRenderingContext2D.prototype.drawImage=function(a,d,e,f,g,h,i,j){if("nodeName"in a&&/img/i.test(a.nodeName))for(var l=arguments.length-1;l>=1;l--)arguments[l]=arguments[l]*b;else"undefined"==typeof j&&(arguments[1]*=b,arguments[2]*=b,arguments[3]*=b,arguments[4]*=b);c.apply(this,arguments)}}var e=function(a,b){this._bIsPainted=!1,this._android=n(),this._htOption=b,this._elCanvas=document.createElement("canvas"),this._elCanvas.width=b.width,this._elCanvas.height=b.height,a.appendChild(this._elCanvas),this._el=a,this._oContext=this._elCanvas.getContext("2d"),this._bIsPainted=!1,this._elImage=document.createElement("img"),this._elImage.style.display="none",this._el.appendChild(this._elImage),this._bSupportDataURI=null};return e.prototype.draw=function(a){var b=this._elImage,c=this._oContext,d=this._htOption,e=a.getModuleCount(),f=d.width/e,g=d.height/e,h=Math.round(f),i=Math.round(g);b.style.display="none",this.clear();for(var j=0;e>j;j++)for(var k=0;e>k;k++){var l=a.isDark(j,k),m=k*f,n=j*g;c.strokeStyle=l?d.colorDark:d.colorLight,c.lineWidth=1,c.fillStyle=l?d.colorDark:d.colorLight,c.fillRect(m,n,f,g),c.strokeRect(Math.floor(m)+.5,Math.floor(n)+.5,h,i),c.strokeRect(Math.ceil(m)-.5,Math.ceil(n)-.5,h,i)}this._bIsPainted=!0},e.prototype.makeImage=function(){this._bIsPainted&&d.call(this,a)},e.prototype.isPainted=function(){return this._bIsPainted},e.prototype.clear=function(){this._oContext.clearRect(0,0,this._elCanvas.width,this._elCanvas.height),this._bIsPainted=!1},e.prototype.round=function(a){return a?Math.floor(1e3*a)/1e3:a},e}():function(){var a=function(a,b){this._el=a,this._htOption=b};return a.prototype.draw=function(a){for(var b=this._htOption,c=this._el,d=a.getModuleCount(),e=Math.floor(b.width/d),f=Math.floor(b.height/d),g=[''],h=0;d>h;h++){g.push("");for(var i=0;d>i;i++)g.push('');g.push("")}g.push("
"),c.innerHTML=g.join("");var j=c.childNodes[0],k=(b.width-j.offsetWidth)/2,l=(b.height-j.offsetHeight)/2;k>0&&l>0&&(j.style.margin=l+"px "+k+"px")},a.prototype.clear=function(){this._el.innerHTML=""},a}();QRCode=function(a,b){if(this._htOption={width:256,height:256,typeNumber:4,colorDark:"#000000",colorLight:"#ffffff",correctLevel:d.H},"string"==typeof b&&(b={text:b}),b)for(var c in b)this._htOption[c]=b[c];"string"==typeof a&&(a=document.getElementById(a)),this._android=n(),this._el=a,this._oQRCode=null,this._oDrawing=new q(this._el,this._htOption),this._htOption.text&&this.makeCode(this._htOption.text)},QRCode.prototype.makeCode=function(a){this._oQRCode=new b(r(a,this._htOption.correctLevel),this._htOption.correctLevel),this._oQRCode.addData(a),this._oQRCode.make(),this._el.title=a,this._oDrawing.draw(this._oQRCode),this.makeImage()},QRCode.prototype.makeImage=function(){"function"==typeof this._oDrawing.makeImage&&(!this._android||this._android>=3)&&this._oDrawing.makeImage()},QRCode.prototype.clear=function(){this._oDrawing.clear()},QRCode.CorrectLevel=d}(); 3 | -------------------------------------------------------------------------------- /static/script.js: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of GigaPaste. 3 | 4 | GigaPaste is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 5 | 6 | GigaPaste is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 7 | 8 | You should have received a copy of the GNU General Public License along with GigaPaste. If not, see . 9 | */ 10 | 11 | //elements in main page 12 | let fileInput; 13 | let customFileUpload; 14 | let password; 15 | let duration; 16 | let durationModifiers; 17 | let burn; 18 | let textArea; 19 | let uploadButton; 20 | 21 | let files; 22 | 23 | //elements in upload progress page 24 | let progressPage; 25 | let uploadPercent; 26 | let uploadInfo; 27 | let qrCode; 28 | let link; 29 | 30 | 31 | let convertMinutes = { 32 | "minutes": 1, 33 | "hours": 60, 34 | "days": 1440, 35 | "months" : 43800, 36 | "years": 525960 37 | } 38 | 39 | window.onbeforeunload = () => { 40 | 41 | fetch('/deleteSession', {method: 'POST'}) 42 | 43 | } 44 | 45 | window.onload = () => { 46 | 47 | //elements in main page 48 | fileInput = document.getElementById('fileInput'); 49 | customFileUpload = document.getElementById('customUpload'); 50 | password = document.getElementById("password"); 51 | burn = document.getElementById("burn"); 52 | duration = document.getElementById("duration"); 53 | durationModifiers = document.getElementById("durationModifiers"); 54 | textArea = document.getElementById("textarea"); 55 | uploadButton = document.getElementById("upload") 56 | 57 | //elements in upload progress page 58 | progressPage = document.getElementById("progressPage"); 59 | uploadPercent = document.getElementById("uploadPercent"); 60 | uploadInfo = document.getElementById("uploadInfo"); 61 | link = document.getElementById("link"); 62 | qrCode = document.getElementById("qrcode"); 63 | 64 | duration.value = localStorage.getItem("duration") || 5; 65 | durationModifiers.value = localStorage.getItem("durationModifiers") || "minutes"; 66 | 67 | duration.addEventListener('input', (e)=>{ 68 | 69 | localStorage.setItem('duration', e.target.value); 70 | 71 | }) 72 | 73 | durationModifiers.addEventListener('change', (e)=>{ 74 | 75 | localStorage.setItem('durationModifiers', e.target.value); 76 | 77 | }) 78 | 79 | textArea.addEventListener('input', ()=>{ 80 | 81 | files = null; 82 | customFileUpload.innerHTML = "Click here, drag & drop, or Ctrl + v anywhere to select file" 83 | uploadButton.innerHTML = "Upload text (Ctrl + Enter)"; 84 | 85 | }) 86 | 87 | textArea.addEventListener('keydown', (e)=>{ 88 | 89 | if(e.key == 'Tab'){ 90 | 91 | e.preventDefault(); 92 | 93 | let start = textArea.selectionStart; 94 | let end = textArea.selectionEnd; 95 | 96 | textArea.value = textArea.value.substring(0, start) + "\t" + textArea.value.substring(end); 97 | textArea.selectionStart = textArea.selectionEnd = start + 1; 98 | 99 | 100 | } 101 | }) 102 | 103 | textArea.addEventListener('paste', (event) => { 104 | 105 | event.preventDefault(); 106 | const pasteData = (event.clipboardData || window.clipboardData).getData('text'); 107 | 108 | textArea.value = textArea.value + pasteData; 109 | textArea.selectionStart = textArea.selectionEnd = textArea.selectionStart + pasteData.length; 110 | 111 | }); 112 | 113 | customFileUpload.addEventListener('click', ()=>{ 114 | 115 | fileInput.click() 116 | 117 | }) 118 | 119 | fileInput.addEventListener('change', function(){ 120 | handleFiles(this.files); 121 | }); 122 | 123 | document.addEventListener('drop', function(event) { 124 | event.preventDefault(); 125 | handleFiles(event.dataTransfer.files); 126 | }); 127 | 128 | document.addEventListener('paste', function(event) { 129 | event.preventDefault(); 130 | if (event.clipboardData && event.clipboardData.files.length > 0) { 131 | handleFiles(event.clipboardData.files); 132 | } 133 | }); 134 | 135 | document.addEventListener('keydown', function(event) { 136 | if (event.ctrlKey && event.key === 'Enter') { 137 | upload(); 138 | event.preventDefault(); 139 | } 140 | }); 141 | 142 | textArea.focus() 143 | 144 | } 145 | 146 | function copyLink(){ 147 | 148 | copyToClipboard(link.innerHTML) 149 | 150 | } 151 | 152 | function handleFiles(f) { 153 | 154 | if (f && f.length > 0) { 155 | 156 | textArea.value = ""; 157 | customFileUpload.innerHTML = f.length + " files selected"; 158 | uploadButton.innerHTML = "Upload file"; 159 | files = f; 160 | 161 | } 162 | } 163 | 164 | function upload() { 165 | 166 | if (files || textArea.value.trim () !== "") { 167 | 168 | const xhr = new XMLHttpRequest(); 169 | 170 | xhr.onloadstart = function () { 171 | 172 | progressPage.style.display = "flex"; 173 | 174 | }; 175 | 176 | xhr.upload.addEventListener('progress', function(event) { 177 | if (event.lengthComputable) { 178 | const percentComplete = Math.round((event.loaded / event.total) * 100); 179 | if(percentComplete != 100){ 180 | uploadPercent.innerHTML = percentComplete + "%"; 181 | }else{ 182 | uploadPercent.innerHTML = percentComplete + "% (waiting for link...)"; 183 | 184 | } 185 | console.log(`Upload progress: ${percentComplete}%`); 186 | } 187 | }); 188 | 189 | // Handle successful upload 190 | xhr.addEventListener('load', function() { 191 | 192 | if (xhr.status === 200) { 193 | 194 | uploadPercent.innerHTML = "100%"; 195 | link.innerHTML = xhr.responseText; 196 | uploadInfo.style.display = "flex"; 197 | 198 | let qrcode = new QRCode(qrCode, { 199 | 200 | text: xhr.responseText, 201 | width: 128, 202 | height: 128, 203 | colorDark : "#000000", 204 | colorLight : "#ffffff", 205 | correctLevel : QRCode.CorrectLevel.H 206 | 207 | }); 208 | 209 | } else { 210 | console.log('Upload failed with status:', xhr.status); 211 | } 212 | }); 213 | 214 | // Handle upload errors 215 | xhr.addEventListener('error', function() { 216 | document.getElementById("uploadPercent").innerHTML = "Upload error"; 217 | }); 218 | 219 | // Handle aborts 220 | xhr.addEventListener('abort', function() { 221 | console.log('Upload aborted'); 222 | }); 223 | 224 | let minutes = duration.value * convertMinutes[durationModifiers.value] 225 | 226 | if(files){ 227 | 228 | const formData = new FormData(); 229 | formData.append("duration", minutes); 230 | formData.append("pass", password.value); 231 | formData.append("burn", burn.checked); 232 | 233 | // Append all files to the FormData object 234 | for (let i = 0; i < files.length; i++) { 235 | formData.append('file', files[i]); //'file' as the key 236 | } 237 | 238 | xhr.open('POST', '/'); 239 | xhr.send(formData); 240 | 241 | }else{ 242 | 243 | if(textArea.value.trim () !== ""){ 244 | 245 | xhr.open('POST', '/postText'); 246 | xhr.send(JSON.stringify({duration: minutes, pass: password.value, burn: burn.checked, text: textArea.value})); 247 | 248 | } 249 | 250 | } 251 | 252 | } 253 | 254 | } 255 | 256 | 257 | -------------------------------------------------------------------------------- /static/style.css: -------------------------------------------------------------------------------- 1 | /* Style the custom file upload button */ 2 | html, body{ 3 | 4 | margin: 0; 5 | padding: 0; 6 | width: 100%; 7 | height: 100%; 8 | max-width: none; 9 | 10 | } 11 | 12 | /*some themes love to add padding to input elements for no reason*/ 13 | /*disabling it so that it will be cross compatible with other themes*/ 14 | fieldset,input,select,textarea,button,label { 15 | margin: 0 16 | } 17 | 18 | textarea{ 19 | 20 | resize: none; 21 | width: min(1000px, calc(100% - 20px)); 22 | height: auto; 23 | font-size: 1.5em; 24 | bottom: 0; 25 | padding: 0; 26 | } 27 | 28 | 29 | .rspText{ 30 | 31 | font-size: 1em; 32 | 33 | } 34 | 35 | .progress{ 36 | 37 | width: 100%; 38 | height: 100%; 39 | position: absolute; 40 | background: inherit; 41 | top: 0; 42 | left: 0; 43 | display: none; 44 | justify-content: center; 45 | align-items: center; 46 | flex-direction: column; 47 | gap: 10px; 48 | 49 | } 50 | 51 | #burn{ 52 | width: 20px; 53 | height: 20px; 54 | } 55 | 56 | -------------------------------------------------------------------------------- /static/theme.css: -------------------------------------------------------------------------------- 1 | /*! concrete.css v2.1.1 | MIT License | github.com/louismerlin/concrete.css */:root{--fg:#111;--bg:#fff}@media(prefers-color-scheme:dark){:root{--fg:#fff;--bg:#111}}html{font-size:62.5%;box-sizing:border-box}*,::after,::before{box-sizing:inherit;text-decoration-thickness:.2rem}body{font-size:2rem;font-weight:400;background:var(--bg);color:var(--fg);font-family:Helvetica,Arial,sans-serif}a{color:var(--fg)}img{max-width:100%;height:auto}main{margin:auto;max-width:66rem;padding:0 1rem;width:100%}header{padding:16rem 0;font-size:1.2em}footer{text-align:center}section{padding:4rem 0}button,input[type="button"],input[type="reset"],input[type="submit"]{display:inline-block;vertical-align:middle;padding:.4rem 1rem;font-size:2rem;font-weight:normal;margin-bottom:1rem;background:var(--bg);color:var(--fg);border:.2rem solid var(--fg);border-radius:0;cursor:pointer}button:disabled,input[type="button"]:disabled,input[type="reset"]:disabled,input[type="submit"]:disabled{border-style:dashed;cursor:not-allowed}ul{list-style:square}fieldset{border:.2rem solid var(--fg)}label,legend{display:block;font-weight:bold;margin-bottom:.8rem}input[type="email"],input[type="number"],input[type="password"],input[type="search"],input[type="tel"],input[type="text"],input[type="url"],textarea,select{-webkit-appearance:none;-moz-appearance:none;appearance:none;box-shadow:none;box-sizing:inherit;padding:.4rem 1rem;width:100%;font-size:2rem;color:var(--fg);background-color:var(--bg);border:.2rem solid var(--fg);border-radius:0}fieldset,input,select,textarea{margin:0 0 1.6rem 0}input::placeholder,textarea::placeholder{color:var(--fg);font-style:italic}table{width:100%;border-spacing:0}td,th{padding:.8rem}td:first-child,th:first-child{padding-left:0}td:last-child,th:last-child{padding-right:0}th{border-bottom:.2rem solid var(--fg);text-align:left}td{border-bottom:.1rem solid var(--fg)}blockquote,pre{margin-left:0;margin-right:0;padding:1rem 1.6rem;border-left:.2rem solid var(--fg);overflow-y:hidden}pre{border:.1rem dotted var(--fg);border-left:.2rem solid var(--fg)}pre>code{white-space:pre;display:block;font-size:1.6rem}progress{-moz-appearance:none;-webkit-appearance:none;display:block;height:1rem;overflow:hidden;padding:0;width:100%;background:var(--bg);color:var(--fg);border:.2rem solid var(--fg);border-radius:0}progress::-webkit-progress-bar{background-color:var(--bg)}progress::-webkit-progress-value{background-color:var(--fg)}progress::-moz-progress-bar{background-color:var(--fg)}hr{border:.1rem solid var(--fg)} 2 | -------------------------------------------------------------------------------- /templates/authTemplate.html: -------------------------------------------------------------------------------- 1 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 |
26 | 27 |
28 | 29 | 30 |
31 | 32 |
33 | 34 |
35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /templates/notFound.html: -------------------------------------------------------------------------------- 1 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | Not found 24 |
25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /templates/pasteTemplate.html: -------------------------------------------------------------------------------- 1 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 39 | 40 | 41 | 42 | 43 |
44 | 45 |
46 | 47 |
{{ .Text }}
48 | 49 |
50 | 51 |
52 | 53 | 54 | {{ if ne .Burn "1" }} 55 | 56 | {{ end }} 57 |
58 | 59 | 60 | 61 |
62 | 63 | 64 | 65 | 66 | --------------------------------------------------------------------------------