{"id":15557766,"url":"https://github.com/fgasper/zmodemjs","last_synced_at":"2025-04-06T22:11:00.082Z","repository":{"id":26017831,"uuid":"102979430","full_name":"FGasper/zmodemjs","owner":"FGasper","description":"zmodem.js - ZMODEM in JavaScript","archived":false,"fork":false,"pushed_at":"2022-12-06T20:21:30.000Z","size":676,"stargazers_count":130,"open_issues_count":16,"forks_count":25,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-03-30T21:08:11.077Z","etag":null,"topics":["javascript","shell","terminal","websocket","xmodem","ymodem","zmodem"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/FGasper.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-09-09T19:21:04.000Z","updated_at":"2025-01-07T03:24:14.000Z","dependencies_parsed_at":"2023-01-14T09:00:34.247Z","dependency_job_id":null,"html_url":"https://github.com/FGasper/zmodemjs","commit_stats":null,"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FGasper%2Fzmodemjs","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FGasper%2Fzmodemjs/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FGasper%2Fzmodemjs/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FGasper%2Fzmodemjs/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/FGasper","download_url":"https://codeload.github.com/FGasper/zmodemjs/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247557767,"owners_count":20958047,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["javascript","shell","terminal","websocket","xmodem","ymodem","zmodem"],"created_at":"2024-10-02T15:20:35.937Z","updated_at":"2025-04-06T22:11:00.063Z","avatar_url":"https://github.com/FGasper.png","language":"JavaScript","readme":"# zmodem.js - ZMODEM for JavaScript\n\n[![build status](https://api.travis-ci.org/FGasper/zmodemjs.svg?branch=master)](http://travis-ci.org/FGasper/zmodemjs)\n\n# SYNOPSIS\n\n    let zsentry = new Zmodem.Sentry( {\n        to_terminal(octets) { .. },  //i.e. send to the terminal\n\n        sender(octets) { .. },  //i.e. send to the ZMODEM peer\n\n        on_detect(detection) { .. },  //for when Sentry detects a new ZMODEM\n\n        on_retract() { .. },  //for when Sentry retracts a Detection\n    } );\n\n    //We have to configure whatever gives us new input to send that\n    //input to zsentry.\n    //\n    //EXAMPLE: From web browsers that use WebSocket …\n    //\n    ws.addEventListener(\"message\", function(evt) {\n        zsentry.consume(evt.data);\n    } );\n\nThe `on_detect(detection)` function call is probably the most complex\npiece of the above; one potential implementation might look like:\n\n    on_detect(detection) {\n\n        //Do this if we determine that what looked like a ZMODEM session\n        //is actually not meant to be ZMODEM.\n        if (no_good) {\n            detection.deny();\n            return;\n        }\n\n        zsession = detection.confirm();\n\n        if (zsession.type === \"send\") {\n\n            //Send a group of files, e.g., from an \u003cinput\u003e’s “.files”.\n            //There are events you can listen for here as well,\n            //e.g., to update a progress meter.\n            Zmodem.Browser.send_files( zsession, files_obj );\n        }\n        else {\n            zsession.on(\"offer\", (xfer) =\u003e {\n\n                //Do this if you don’t want the offered file.\n                if (no_good) {\n                    xfer.skip();\n                    return;\n                }\n\n                xfer.accept().then( () =\u003e {\n\n                    //Now you need some mechanism to save the file.\n                    //An example of how you can do this in a browser:\n                    Zmodem.Browser.save_to_disk(\n                        xfer.get_payloads(),\n                        xfer.get_details().name\n                    );\n                } );\n            });\n\n            zsession.start();\n        }\n    }\n\n# DESCRIPTION\n\nzmodem.js is a JavaScript implementation of the ZMODEM\nfile transfer protocol, which facilitates file transfers via a terminal.\n\n# STATUS\n\nThis library is BETA quality. It should be safe for general use, but\nbreaking changes may still happen.\n\n# HOW TO USE THIS LIBRARY\n\nThe basic workflow is:\n\n1. Create a `Zmodem.Sentry` object. This object must scan all input for\na ZMODEM initialization string. See `zsentry.js`’s documentation for more\ndetails.\n\n2. Once that initialization is found, the `on_detect` event is fired\nwith a `Detection` object as parameter. At this point you can `deny()`\nthat Detection or `confirm()` it; the latter will return a Session\nobject.\n\n3. Now you do the actual file transfer(s):\n\n    * If the session is a receive session, do something like this:\n\n            zsession.on(\"offer\", (offer) =\u003e { ... });\n                let { name, size, mtime, mode, serial, files_remaining, bytes_remaining } = offer.get_details();\n\n                offer.skip();\n\n                //...or:\n\n                offer.on(\"input\", (octets) =\u003e { ... });\n\n                //accept()’s return resolves when the transfer is complete.\n                offer.accept().then(() =\u003e { ... });\n            });\n            zsession.on(\"session_end\", () =\u003e { ... });\n            zsession.start();\n\n        The `offer` handler receives an Offer object. This object exposes the details\n    about the transfer offer. The object also exposes controls for skipping or\n    accepting the offer.\n\n    * Otherwise, your session is a send session. Now the user chooses\nzero or more files to send. For each of these you should do:\n\n            zsession.send_offer( { ... } ).then( (xfer) =\u003e {\n                if (!xfer) ... //skipped\n\n                else {\n                    xfer.send( chunk );\n                    xfer.end( chunk ).then(after_end);\n                }\n            } );\n\n        Note that `xfer.end()`’s return is a Promise. The resolution of this\nPromise is the point at which either to send another offer or to do:\n\n            zsession.close().then( () =\u003e { ... } );\n\n        The `close()` Promise’s resolution is the point at which the session\nhas ended successfully.\n\nThat should be all you need. If you want to go deeper, though, each module\nin this distribution has JSDoc and unit tests.\n\n# RATIONALE\n\nZMODEM facilitates terminal-based file transfers.\nThis was an important capability in the 1980s and early 1990s because\nmost modem use was for terminal applications, especially\n[BBS](https://en.wikipedia.org/wiki/Bulletin_board_system)es.\n(This was how, for example,\npopular shareware games like [Wolfenstein 3D](http://3d.wolfenstein.com)\nwere often distributed.) The World Wide Web in the\nmid-1990s, however, proved a more convenient way to accomplish most of\nwhat BBSes were useful for, as a result of which the problem that ZMODEM\nsolved became a much less important one.\n\nZMODEM stuck around, though, as it remained a convenient solution\nfor terminal users who didn’t want open a separate session to transfer a\nfile. [Uwe Ohse](https://uwe.ohse.de/)’s\n[lrzsz](https://ohse.de/uwe/software/lrzsz.html) package\nprovided a portable C implementation of the protocol (reworked from\nthe last public domain release of the original code) that is installed on\nmany systems today.\n\nWhere `lrzsz` can’t reach, though, is terminals that don’t have command-line\naccess—such as terminals that run in JavaScript. Now that\n[WebSocket](https://en.wikipedia.org/wiki/WebSocket) makes real-time\napplications like terminals possible in a web browser,\nthere is a use case for a JavaScript\nimplementation of ZMODEM to allow file transfers in this context.\n\n# GENERAL FLOW OF A ZMODEM SESSION:\n\nThe following is an overview of an error-free ZMODEM session.\n\n0. If you call the `sz` command (or equivalent), that command will send\na special ZRQINIT “pre-header” to signal your terminal to be a ZMODEM\nreceiver.\n\n1. The receiver, upon recognizing the ZRQINIT header, responds with\na ZRINIT header.\n\n2. The sender sends a ZFILE header along with information about the file.\n(This may also include the size and file count for the entire batch of files.)\n\n3. The recipient either accepts the file or skips it.\n\n4. If the recipient did not skip the file, then the sender sends the file\ncontents. At the end the sender sends a ZEOF header to let the recipient\nknow this file is done.\n\n5. The recipient sends another ZRINIT header. This lets the sender know that\nthe recipient confirms receipt of the entire file.\n\n6. Repeat steps 2-5 until the sender has no more files to send.\n\n7. Once the sender has no more files to send, the sender sends a ZEOF header,\nwhich the recipient echoes back. The sender closes the session by sending\n`OO` (“over and out”).\n\n# PROTOCOL NOTES AND ASSUMPTIONS\n\nHere are some notes about this particular implementation.\n\nParticular notes:\n\n* We send with a maximum data subpacket size of 8 KiB (8,192 bytes). While\nthe ZMODEM specification stipulates a maximum of 1 KiB, `lrzsz` accepts\nthe larger size, and it seems to have become a de facto standard extension\nto the protocol.\n\n* Remote command execution (i.e., ZCOMMAND) is unimplemented. It probably\nwouldn’t work in browsers, which is zmodem.js’s principal use case.\n\n* No file translations are done. (Unix/Windows line endings are a\nfuture feature possibility.)\n\n* It is assumed that no error correction will be needed. All connections\nare assumed to be **“reliable”**; i.e.,\ndata is received exactly as sent. We take this for granted today,\nbut ZMODEM’s original application was over raw modem connections that\noften didn’t have reliable hardware error correction. TCP also wasn’t\nin play to do software error correction as generally happens\ntoday over remote connections. Because the forseeable use of zmodem.js\nis either over TCP or a local socket—both of which are reliable—it seems\nsafe to assume that zmodem.js will not need to implement error correction.\n\n* zmodem.js sends with CRC-16 by default. Ideally we would just use CRC-16\nfor everything, but lsz 0.12.20 has a [buffer overflow bug](https://github.com/gooselinux/lrzsz/blob/master/lrzsz-0.12.20.patch) that rears its\nhead when you try to abort a ZMODEM session in the middle of a CRC-16 file\ntransfer. To avoid this bug, zmodem.js advertises CRC-32 support when it\nreceives a file, which makes lsz avoid the buffer overflow bug by using\nCRC-32.\n\n    The bug is reported, incidentally, and a fix is expected (nearly 20 years\n    after the last official lrzsz release!).\n\n* There is no XMODEM/YMODEM fallback.\n\n* Occasionally lrzsz will output things to the console that aren’t\nactual ZMODEM—for example, if you skip an offered file, `sz` will write a\nmessage about it to the console. For the most part we can accommodate these\nbecause they happen between ZMODEM headers; however, it’s possible to\n“poison” such messages, e.g., by sending a file whose name includes a\nZMODEM header. So don’t do that. :-P\n\n# IMPLEMENTATION NOTES\n\n* I initially had success integrating zmodem.js with\n[xterm.js](https://xtermjs.org); however, that library’s plugin interface\nchanged dramatically, and I haven’t created a new plugin to replace the\nold one. (It should be relatively straightforward if someone else wants to\npick it up.)\n\n* Browsers don’t have an easy way to download only part of a file;\nas a result, anything the browser saves to disk must be the entire file.\n\n* ZMODEM is a _binary_ protocol. (There was an extension planned\nto escape everything down to 7-bit ASCII, but it doesn’t seem to have\nbeen implemented?) Hence, **if you use WebSocket, you’ll need to use\nbinary messages, not text**.\n\n* lrzsz is the only widely-distributed ZMODEM implementation nowadays,\nwhich makes it a de facto standard in its\nown right. Thus far all end-to-end testing has been against it. It is\nthus possible that resolutions to disparities between `lrzsz` and the\nprotocol specification may need to favor the implementation.\n\n* It is a generally-unavoidable byproduct of how ZMODEM works that\nthe first header in a ZMODEM session will echo to the terminal. This\nexplains the unsightly `**B0000…` stuff that you’ll see when you run\neither `rz` or `sz`.\n\n    That header\n    will include some form of line break. (From `lrzsz` means bytes 0x0d\n    and 0x8a—**not** 0x0a). Your terminal might react oddly to that;\n    if it does, try stripping out one or the other line ending character.\n\n# PROTOCOL CHOICE\n\nBoth XMODEM and YMODEM (including the latter’s many variants) require the\nreceiver to initiate the session by sending a “magic character” (ASCII SOH);\nthe problem is that there’s nothing in the protocol to prompt the receiver\nto do so. ZMODEM is sender-driven, so the terminal can show a notice that\nsays, “Do you want to receive a file?”\n\nThis is a shame because these other two protocols are a good deal simpler\nthan ZMODEM. The YMODEM-g variant in particular would be better-suited to\nour purpose because it doesn’t “litter” the transfer with CRCs.\n\nThere is also [Kermit](http://www.columbia.edu/kermit/kermit.html), which\nseems to be more standardized than ZMODEM but **much** more complex.\n\n# DESIGN NOTES\n\nzmodem.js tries to avoid “useless” states:\neither we fail completely, or we succeed. To that end, some callbacks are\nrequired arguments (e.g., the Sentry constructor’s `to_terminal` argument),\nwhile others are registered separately.\n\nLikewise, for this reason some of the session-level logic is exposed only\nthrough the Transfer and Offer objects. The Session creates these\ninternally then exposes them via callback\n\n# SOURCES\n\nZMODEM is not standardized in a nice, clean, official RFC like DNS or HTTP;\nrather, it was one guy’s solution to a particular problem. There is\ndocumentation, but it’s not as helpful as it might be; for example,\nthere’s only one example workflow given, and it’s a “happy-path”\ntransmission of a single file.\n\nAs part of writing zmodem.js I’ve culled together various resources\nabout the protocol. As far as I know these are the best sources for\ninformation on ZMODEM.\n\nTwo documents that describe ZMODEM are saved in the repository for reference.\nThe first is the closest there is to an official ZMODEM specification:\na description of the protocol from its author, Chuck Forsberg. The second\nseems to be based on the first and comes from\n[Jacques Mattheij](https://jacquesmattheij.com).\n\n**HISTORICAL:** The included `rzsz.zip` file (fetched from [ftp://archives.thebbs.org/file_transfer_protocols/](ftp://archives.thebbs.org/file_transfer_protocols/) on 16 October 2017)\nis the last public domain release\nfrom Forsberg. [http://freeware.nekochan.net/source/rzsz/](http://freeware.nekochan.net/source/rzsz/) has what is supposedly Forsberg’s last shareware release;\nI have not looked at it except for the README. I’m not sure of the\ncopyright status of this software: Forsberg is deceased, and his company\nappears to be defunct. Regardless, neither it nor its public domain\npredecessor is likely in widespread use.\n\nHere are some other available ZMODEM implementations:\n\n* [lrzsz](https://ohse.de/uwe/software/lrzsz.html)\n\n    A widely-deployed adaptation of Forsberg’s last public domain ZMODEM\n    code. This is the de facto “reference” implementation, both by virtue\n    of its wide availability and its derivation from Forsberg’s original.\n    If your server has the `rz` and `sz` commands, they’re probably\n    from this package.\n\n* [SyncTERM](http://syncterm.bbsdev.net)\n\n    Based on Jacques Mattheij’s ZMODEM implementation, originally called\n    zmtx/zmrx. This is a much more readable implementation than lrzsz\n    but lamentably one that doesn’t seem to compile as readily.\n\n* [Qodem](https://github.com/klamonte/qodem)\n\n    This terminal emulator package appears to contain its own ZMODEM\n    implementation.\n\n* [PD Zmodem](http://pcmicro.com/netfoss/pdzmodem.html)\n\n    I know nothing of this one.\n\n* [zmodem (Rust)](https://github.com/lexxvir/zmodem)\n\n    A pure [Rust](http://rust-lang.org) implementation of ZMODEM.\n\n# REQUIREMENTS\n\nThis library only supports modern browsers. There is no support for\nInternet Explorer or other older browsers planned.\n\nThe tests have run successfully against node.js version 8.\n\n# DOCUMENTATION\n\nBesides this document, each module has inline [jsdoc](http://usejsdoc.org).\nYou can see it by running `yarn` in the repository’s root directory;\nthe documentation will build in a newly-created `documentation` directory.\n\n# CONTRIBUTING\n\nSubmit pull requests via\n[GitHub](https://github.com/FGasper/zmodemjs/pulls).\n\n# TROUBLESHOOTING\n\nBefore you do anything else, set `Zmodem.DEBUG` to true. This will log\nuseful information about the ZMODEM session to your JavaScript console. That\nmay give you all you need to fix your problem.\n\nIf you have trouble transferring files, try these diagnostics:\n\n1. Transfer an empty file. (Run `touch empty.bin` to create one named `empty.bin`.)\n\n2. Transfer a small file. (`echo hello \u003e small.txt`)\n\n3. Transfer a file that contains all possible octets. (`perl -e 'print chr for 0 .. 255' \u003e all_bytes.bin`)\n\n4. If a specific file fails, does it still fail if you `truncate` a copy of\nthe file down to, say, half size and transfer that truncated file? Does it\nwork if you truncate the file down to 1 byte? If so, then use this method\nto determine which specific place in the file triggers the transfer error.\n\n**IF YOU HAVE DONE THE ABOVE** and still think the problem is with zmodem.js,\nyou can file a bug report. Note that, historically, most bug reports have\nreflected implementation errors rather than bugs in zmodem.js.\n\nIf you just want help using zmodem.js, try [Gitter](https://gitter.im/zmodemjs/community).\n\n# TODO\n\n* Teach send sessions to “fast-forward” so as to honor requests for\nappend-style sessions.\n\n* Implement newline conversions.\n\n* Teach Session how to do and to handle pre-CRC checks.\n\n* Possible: command-line `rz`, if there’s demand for it, e.g., in\nenvironments where `lrzsz` can’t run. (NB: The distribution includes\na bare-bones, proof-of-concept `sz` replacement.)\n\n# KNOWN ISSUES\n\n* In testing, Microsoft Edge appeared not to care what string was given\nto `\u003ca\u003e`’s `download` attribute; the saved filename was based on the\nbrowser’s internal Blob object URL instead.\n\n# USERS\n\nThe following are projects I’m aware of that use this library:\n\n* [electerm](https://github.com/electerm/electerm)\n\n* [ttyd](https://github.com/tsl0922/ttyd)\n\n* [gowebssh](https://github.com/leffss/gowebssh)\n\n[Send a pull request](https://github.com/FGasper/zmodemjs/pulls)\nif you’d like your project listed.\n\n# COPYRIGHT\n\nCopyright 2017 Gasper Software Consulting\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nParts of the CRC-16 logic are adapted from crc-js by Johannes Rudolph.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffgasper%2Fzmodemjs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffgasper%2Fzmodemjs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffgasper%2Fzmodemjs/lists"}