master dea7292195bc cached
321 files
1.8 MB
553.5k tokens
572 symbols
1 requests
Download .txt
Showing preview only (1,947K chars total). Download the full file or copy to clipboard to get everything.
Repository: octave-online/octave-online-server
Branch: master
Commit: dea7292195bc
Files: 321
Total size: 1.8 MB

Directory structure:
gitextract_lv487tfw/

├── .dockerignore
├── .editorconfig
├── .eslintignore
├── .eslintrc.yml
├── .gcloudignore
├── .github/
│   └── workflows/
│       └── build-test.yml
├── .gitignore
├── .npmrc
├── COPYING
├── Makefile
├── README.md
├── back-filesystem/
│   ├── .eslintrc.yml
│   ├── .npmrc
│   ├── README.md
│   ├── app.js
│   ├── git/
│   │   ├── create-repo-service.js
│   │   ├── create-repo.service
│   │   └── gitd.service
│   ├── package.json
│   └── src/
│       ├── controller.js
│       ├── fake-socket.js
│       ├── git-util.js
│       ├── logger.js
│       ├── mime.types
│       └── working-util.js
├── back-master/
│   ├── .eslintrc.yml
│   ├── .npmrc
│   ├── README.md
│   ├── app.js
│   ├── package.json
│   └── src/
│       ├── capped-file-system.js
│       ├── docker-handler.js
│       ├── main-flavor.js
│       ├── main-pool.js
│       ├── maintenance-request-manager.js
│       ├── maintenance.js
│       ├── message-translator.js
│       ├── octave-session.js
│       ├── process-handler.js
│       ├── session-impl.js
│       └── session-manager.js
├── back-octave/
│   ├── Makefile
│   ├── README.md
│   ├── host.c
│   └── oo-changesets/
│       ├── 000-README.md
│       ├── 001-d38b7c534496.hg.txt
│       ├── 002-d3de6023e846.hg.txt
│       ├── 003-4d28376c34a8.hg.txt
│       ├── 004-6ff3e34eea77.hg.txt
│       ├── 005-9e73fe0d92d5.hg.txt
│       ├── 006-15d21ceec728.hg.txt
│       ├── 007-4d778d6ebbd0.hg.txt
│       ├── 008-e8ef7f3333bf.hg.txt
│       ├── 009-05f7272c001e.hg.txt
│       ├── 010-4a1afb661c55.hg.txt
│       ├── 011-7327936fa23e.hg.txt
│       ├── 012-84390db50239.hg.txt
│       ├── 013-f4110d638cdb.hg.txt
│       ├── 014-21fd506b7530.hg.txt
│       ├── 100-2d1fd5fdd1d5.hg.txt
│       ├── 100-README.md
│       ├── 101-bc8cd93feec5.hg.txt
│       ├── 102-30d8ba0fbc32.hg.txt
│       ├── 103-352b599bc533.hg.txt
│       ├── 104-9475120a3110.hg.txt
│       ├── 105-ccbef5c9b050.hg.txt
│       ├── 106-91cb270ffac0.hg.txt
│       ├── 107-80081f9d8ff7.hg.txt
│       ├── 108-9b39ca8bcbfd.hg.txt
│       ├── 200-84cbf166497f.hg.txt
│       ├── 200-README.md
│       ├── 201-b993253f19d0.hg.txt
│       ├── 202-d9d23f97ba78.hg.txt
│       ├── 203-d6b5ffb8e4cc.hg.txt
│       ├── 204-e61d7b8918e2.hg.txt
│       ├── 300-d78448f9c483.hg.txt
│       ├── 301-97f7d1f4fe83.hg.txt
│       ├── 302-8900d7cf8554.hg.txt
│       ├── 310-1e1c91e6cddc.hg.txt
│       ├── 320-8d4683a83238.hg.txt
│       ├── 321-faad58416a3a.hg.txt
│       ├── 400-7ade2492e023.hg.txt
│       ├── 401-1b33dc797ec9.hg.txt
│       ├── 402-b01fa2864d4d.hg.txt
│       ├── 403-2813cb96e10f.hg.txt
│       ├── 404-acb523f25bb9.hg.txt
│       ├── 405-6ad34b0b69e1.hg.txt
│       ├── 406-d0df6f16f41e.hg.txt
│       ├── 407-df206dd11399.hg.txt
│       ├── 408-8184a51579f3.hg.txt
│       ├── 420-4c3d80dd9e65.hg.txt
│       ├── 421-de16dd99ab0e.hg.txt
│       ├── 422-de16dd99ab0e.hg.txt
│       └── 430-d2250ae9bddd.hg.patch
├── client/
│   ├── .bowerrc
│   ├── .gitignore
│   ├── .npmrc
│   ├── COPYING
│   ├── Gruntfile.js
│   ├── README.md
│   ├── app/
│   │   ├── .eslintrc.yml
│   │   ├── colab.html
│   │   ├── eula.txt
│   │   ├── fonts/
│   │   │   └── dejavusansmono_book/
│   │   │       ├── DejaVuSansMono-demo.html
│   │   │       ├── specimen_files/
│   │   │       │   ├── easytabs.js
│   │   │       │   ├── grid_12-825-55-15.css
│   │   │       │   └── specimen_stylesheet.css
│   │   │       └── stylesheet.css
│   │   ├── images/
│   │   │   ├── flaticons/
│   │   │   │   └── download-svg.ai
│   │   │   ├── logo_collections/
│   │   │   │   ├── official/
│   │   │   │   │   └── favicon_package/
│   │   │   │   │       ├── README.md
│   │   │   │   │       ├── browserconfig.xml
│   │   │   │   │       └── site.webmanifest
│   │   │   │   └── server/
│   │   │   │       └── favicon_package/
│   │   │   │           ├── README.md
│   │   │   │           ├── browserconfig.xml
│   │   │   │           └── site.webmanifest
│   │   │   └── sanscons/
│   │   │       └── license.txt
│   │   ├── js/
│   │   │   ├── ace-adapter.js
│   │   │   ├── ace-extras.js
│   │   │   ├── anal.js
│   │   │   ├── app.js
│   │   │   ├── base64-toBlob.js
│   │   │   ├── base64v1.module.js
│   │   │   ├── bucket.js
│   │   │   ├── client.js
│   │   │   ├── detectmobilebrowser.js
│   │   │   ├── download.js
│   │   │   ├── flex-resize.js
│   │   │   ├── ko-ace.js
│   │   │   ├── ko-flash.js
│   │   │   ├── ko-takeArray.js
│   │   │   ├── modernizr-201406b.js
│   │   │   ├── octfile.js
│   │   │   ├── onboarding.js
│   │   │   ├── ot-client.js
│   │   │   ├── ot-handler.js
│   │   │   ├── polyfill.js
│   │   │   ├── runtime.js
│   │   │   ├── utils.js
│   │   │   ├── vars.js
│   │   │   └── ws-shared.js
│   │   ├── main.js
│   │   ├── privacy.txt
│   │   ├── privacy_standalone.txt
│   │   └── styl/
│   │       ├── all.styl
│   │       ├── callouts.styl
│   │       ├── editor.styl
│   │       ├── flexbox.styl
│   │       ├── hamburger.styl
│   │       ├── header.styl
│   │       ├── mixins.styl
│   │       ├── modals.styl
│   │       ├── output_panel.styl
│   │       ├── print.styl
│   │       └── themes/
│   │           ├── official/
│   │           │   ├── fire.styl
│   │           │   ├── ice.styl
│   │           │   ├── lava.styl
│   │           │   └── sun.styl
│   │           └── server/
│   │               ├── fire.styl
│   │               ├── ice.styl
│   │               ├── lava.styl
│   │               └── sun.styl
│   ├── bower.json
│   └── package.json
├── config.sample.hjson
├── config_defaults.hjson
├── containers/
│   ├── README.md
│   ├── octave-deps/
│   │   ├── Dockerfile
│   │   └── cloudbuild.yaml
│   ├── octave-oo/
│   │   ├── Dockerfile
│   │   ├── cloudbuild.yaml
│   │   └── java.opts
│   ├── octave-pkg/
│   │   ├── Dockerfile
│   │   ├── README.md
│   │   ├── cloudbuild.yaml
│   │   ├── ltfat.patch
│   │   └── octaverc.m
│   ├── octave-stable/
│   │   ├── Dockerfile
│   │   └── cloudbuild.yaml
│   ├── oo-back/
│   │   ├── Dockerfile
│   │   └── cloudbuild.yaml
│   ├── oo-front/
│   │   ├── Dockerfile
│   │   └── cloudbuild.yaml
│   ├── oo-gith/
│   │   ├── Dockerfile
│   │   ├── cloudbuild.yaml
│   │   ├── nginx.conf
│   │   └── supervisord.conf
│   ├── oo-redirect/
│   │   └── cloudbuild.yaml
│   ├── oos-quick-start/
│   │   └── docker-compose.yaml
│   ├── utils-admin/
│   │   └── cloudbuild.yaml
│   ├── utils-gitd/
│   │   ├── Dockerfile
│   │   ├── cloudbuild.yaml
│   │   └── supervisord.conf
│   └── utils-gith/
│       ├── Dockerfile
│       ├── cloudbuild.yaml
│       └── supervisord.conf
├── entrypoint/
│   ├── .eslintrc.yml
│   ├── README.md
│   ├── back-selinux.js
│   ├── exit.js.sample
│   ├── oo-front.service
│   ├── oo-no-restart.service
│   ├── oo-reinstall.service
│   ├── oo.service
│   └── policy/
│       ├── octave_online.fc
│       ├── octave_online.if
│       ├── octave_online.te
│       ├── octave_online_supplement.if
│       └── octave_online_supplement.te
├── front/
│   ├── .eslintrc.yml
│   ├── .npmrc
│   ├── README.md
│   ├── locales/
│   │   ├── README.md
│   │   ├── en.yaml
│   │   └── qqq.yaml
│   ├── package.json
│   ├── src/
│   │   ├── app.ts
│   │   ├── back_server_handler.ts
│   │   ├── bucket_model.ts
│   │   ├── email.ts
│   │   ├── express_setup.ts
│   │   ├── flavor_record_model.ts
│   │   ├── mongo.ts
│   │   ├── octave_session_helper.ts
│   │   ├── ot_document.ts
│   │   ├── passport_setup.ts
│   │   ├── patreon.ts
│   │   ├── program_model.ts
│   │   ├── session_middleware.ts
│   │   ├── shared_wrap.ts
│   │   ├── socket_connect.ts
│   │   ├── socketio.ts
│   │   ├── user_model.ts
│   │   ├── utils.ts
│   │   ├── views/
│   │   │   ├── captcha_error.ejs
│   │   │   ├── incorrect_page.ejs
│   │   │   ├── index.ejs
│   │   │   ├── login_error.ejs
│   │   │   ├── partials/
│   │   │   │   ├── foot.ejs
│   │   │   │   └── head.ejs
│   │   │   ├── patreon_link_error.ejs
│   │   │   └── token_page.ejs
│   │   ├── workspace_normal.ts
│   │   └── workspace_shared.ts
│   ├── tsconfig.json
│   └── typings/
│       ├── easy-no-password.d.ts
│       ├── i18next-fs-backend.d.ts
│       ├── i18next-http-middleware.d.ts
│       ├── ot.d.ts
│       ├── pseudo-localization.d.ts
│       ├── socketio-file-upload.d.ts
│       └── socketio-wildcard.d.ts
├── package.json
├── redirect/
│   ├── README.md
│   ├── app.js
│   ├── bin/
│   │   └── server.js
│   ├── package.json
│   ├── src/
│   │   └── db.js
│   └── views/
│       └── error.ejs
├── shared/
│   ├── .eslintrc.yml
│   ├── .npmrc
│   ├── README.md
│   ├── async-cache.js
│   ├── config-helper.js
│   ├── config.js
│   ├── gcp/
│   │   ├── .npmrc
│   │   ├── fetch_translations.js
│   │   ├── index.js
│   │   ├── package.json
│   │   └── reboot_or_remove_self.js
│   ├── gitarchive.js
│   ├── hostname.js
│   ├── index.d.ts
│   ├── index.js
│   ├── json-stream-safe.js
│   ├── logger.js
│   ├── lua/
│   │   ├── get-sesscode.lua
│   │   ├── ot.lua
│   │   ├── ot_apply.lua
│   │   ├── ot_set.lua
│   │   └── ot_test.lua
│   ├── metrics.js
│   ├── once-message.js
│   ├── online-offline.js
│   ├── package.json
│   ├── queue.js
│   ├── redis-messenger.js
│   ├── redis-queue.js
│   ├── redis-util.js
│   ├── silent.js
│   ├── stackdriver/
│   │   ├── index.js
│   │   └── package.json
│   ├── stdio-messenger.js
│   └── time-limit.js
├── test/
│   ├── package.json
│   └── small-unit.js
├── utils-admin/
│   ├── .npmrc
│   ├── README.md
│   ├── app.js
│   ├── bin/
│   │   ├── repo-cleanup.js
│   │   └── server.js
│   ├── package.json
│   ├── public/
│   │   └── stylesheets/
│   │       └── style.css
│   ├── routes/
│   │   ├── index.js
│   │   └── users.js
│   ├── src/
│   │   ├── db.js
│   │   └── repo.js
│   └── views/
│       ├── error.ejs
│       ├── find.ejs
│       ├── index.ejs
│       ├── partials/
│       │   ├── footer.ejs
│       │   └── header.ejs
│       ├── user-list.ejs
│       └── user.ejs
└── utils-auth/
    ├── .eslintrc.yml
    ├── .npmrc
    ├── README.md
    ├── app.js
    ├── configs/
    │   ├── custom_4xx.html
    │   ├── gitlist.ini
    │   └── oo-utils-auth.service
    └── package.json

================================================
FILE CONTENTS
================================================

================================================
FILE: .dockerignore
================================================
.git/
**/_old
**/node_modules
**/tmp
**/vendor


================================================
FILE: .editorconfig
================================================
root = true

[*]
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true
charset = utf-8

# Default to tab indentation (narrow 2-column size)
indent_style = tab
indent_size = 2

# Specific exceptions using space indentation
[*.{json,yml}]
indent_style = space
indent_size = 2


================================================
FILE: .eslintignore
================================================
node_modules/
node_modules_1/
vendor/
dist/
build/
client/app/fonts/
_old/
front/
front2/
*.d.ts


================================================
FILE: .eslintrc.yml
================================================
env:
  es6: true
  node: true
extends: 'eslint:recommended'
parserOptions:
  ecmaVersion: 2018
rules:
  indent:
    - error
    - tab
    - SwitchCase: 1
  linebreak-style:
    - error
    - unix
  quotes:
    - error
    - double
  semi:
    - error
    - always


================================================
FILE: .gcloudignore
================================================
#!include:.gitignore

.git/


================================================
FILE: .github/workflows/build-test.yml
================================================
name: Node.js CI

on: [push]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - uses: actions/setup-node@v1
      with:
        node-version: 10.x
    - name: Install
      run: |
        touch config.hjson
        npm ci
        (cd test && npm ci)
    - name: Test
      run: |
        (cd test && npm test)
      env:
        CI: true
    - name: Lint
      run: npm run lint


================================================
FILE: .gitignore
================================================
# Copyright © 2018, Octave Online LLC
#
# This file is part of Octave Online Server.
#
# Octave Online Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Octave Online Server is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Octave Online Server.  If not, see
# <https://www.gnu.org/licenses/>.

# Directory names that should not be tracked
_old/
bundle/
dist/
node_modules/
node_modules_1/
vendor/
tmp/
front/static/

# File extensions that should not be tracked
*.bak
*.log
*.o
*.out
*.pem
*.pub
*.pp

# Specific files to omit
.env
config.hjson
back-octave/octave-host
back-octave/bin/cwd/
entrypoint/exit.js
entrypoint/front_setup.js


================================================
FILE: .npmrc
================================================
# Please keep this in sync with all other .npmrc files
# SEE: https://github.com/npm/feedback/discussions/864
install-links=false


================================================
FILE: COPYING
================================================
                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU Affero General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time.  Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.


================================================
FILE: Makefile
================================================
# Copyright © 2018, Octave Online LLC
#
# This file is part of Octave Online Server.
#
# Octave Online Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Octave Online Server is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Octave Online Server.  If not, see
# <https://www.gnu.org/licenses/>.

SHELL := /bin/bash
NODE = node

# Read options from config file
# \n is replaced with \1 because gnumake removes \n from ${shell}. See: https://stackoverflow.com/q/54067438/1407170
get_config = ${shell $(NODE) -e "console.log(require('./shared').config.$(1))" | tr '\n' '\1'}
GIT_HOST      = $(call get_config,git.hostname)
GIT_DIR       = $(call get_config,docker.gitdir)
WORK_DIR      = $(call get_config,docker.cwd)
OCTAVE_SUFFIX = $(call get_config,docker.images.octaveSuffix)
FILES_SUFFIX  = $(call get_config,docker.images.filesystemSuffix)
JSON_MAX_LEN  = $(call get_config,session.jsonMaxMessageLength)
CGROUP_CONF   = $(call get_config,selinux.cgroup.conf)


install-selinux-policy:
	# yum install -y selinux-policy-devel policycoreutils-sandbox selinux-policy-sandbox
	cd entrypoint/policy && make -f /usr/share/selinux/devel/Makefile octave_online.pp
	semodule -i entrypoint/policy/octave_online.pp
	restorecon -R -v /usr/local/lib/octave
	restorecon -R -v /tmp
	restorecon -R -v /srv/oo
	setenforce enforcing
	echo "For maximum security, make sure to put SELinux in enforcing mode by default in /etc/selinux/config."

install-selinux-bin:
	cp entrypoint/back-selinux.js /usr/local/bin/oo-back-selinux
	# TODO: Put in /etc instead of /usr/lib?
	cp entrypoint/oo.service /usr/lib/systemd/system/oo.service
	systemctl daemon-reload
	echo "$(CGROUP_CONF)" | tr '\1' '\n' > /etc/cgconfig.d/oo.conf
	echo "Run `systemctl restart cgconfig.service` to load changes to cgroup configurations."
	systemctl enable cgconfig
	ln -sf $$PWD /usr/local/share/oo

install-site-m:
	echo "This command is no longer supported. See containers/octave-pkg/Dockerfile."

enable-graceful-shutdown:
	cp entrypoint/oo-no-restart.service /usr/lib/systemd/system/oo.service;
	systemctl daemon-reload;
	echo "Tip 1: Consider removing entrypoint/exit.js if it could cause disruption";
	echo "Tip 2: Consider sending SIGUSR1 to the server process to start a graceful shutdown";

lint:
	cd back-filesystem && npm run lint
	cd back-master && npm run lint
	cd shared && npm run lint
	cd utils-auth && npm run lint

clean:
	if [[ -e bundle ]]; then rm -rf bundle; fi


================================================
FILE: README.md
================================================
Octave Online Server
====================

This repository contains the full stack of code to run Octave Online Server, the infrastructure that powers [Octave Online](https://octave-online.net).

[![Node.js CI](https://github.com/octave-online/octave-online-server/workflows/Node.js%20CI/badge.svg)](https://github.com/octave-online/octave-online-server/actions)

## High-Level Overview

There are three separate components of Octave Online Server:

1. **Client**: Code that runs in the browser.
2. **Front Server**: Authentication, client session handling.
3. **Back Server**: File I/O, Octave process handling.

*Communication:* The Client and Front Server communicate primarily with WebSockets via [socket.io](https://socket.io); the Front Server and Back Server communicate primarily with [Redis PubSub](https://redis.io/topics/pubsub).  User account information is stored in [MongoDB](https://www.mongodb.com) and is accessed primarily from the Front Server.  User files are stored in [Git on the Server](https://git-scm.com/book/en/v1/Git-on-the-Server) and are accessed primarily from the Back Server.

*Scaling:* Front Servers and Back Servers can be scaled independently (in general, you need more Back Servers than Front Servers).  It is also possible to run both the Front Server and the Back Server on the same computer.

*Languages:* All code is written with JavaScript technologies, although for historical reasons, the three components use different flavors of JavaScript.  The Client uses ES5; the Front Server uses TypeScript; and the Back Server uses ES6.

## Quick Start

Read [containers/README.md](containers/README.md) for details on running a containerized version of all of Octave Online Server for use with trusted users.  This is the fastest way to get off the ground.

## Manual Installation

*Note:* Octave Online Server has a lot of moving parts.  It is recommended that you feel comfortable with basic system administration before attempting an installation.

For more details on operating each of the three components, see the respective README files:

- [back-master/README.md](back-master/README.md) (back server)
- [front/README.md](front/README.md) (front server)
- [client/README.md](client/README.md) (client)

There are also a few more directories for other components:

- [back-filesystem/README.md](back-filesystem/README.md) for filesystem I/O on the back server
- [back-octave/README.md](back-octave/README.md) for GNU Octave bindings for the back server
- [entrypoint/README.md](entrypoint/README.md) for helper scripts to run Octave Online Server
- [shared/README.md](shared/README.md) for code shared by multiple components
- [utils-admin/README.md](utils-admin/README.md) for an optional admin panel
- [utils-auth/README.md](utils-auth/README.md) for an optional standalone user authentication service

Every subdirectory of the top-level Octave Online Server directory has a README file that explains what the contents of the directory is for.

### Prerequisites

[Required] *Operating System:* Octave Online Server is built and tested exclusively on GNU/Linux.  It is recommended that you use CentOS 8, although other modern distributions should work also.  Most of Octave Online Server should work on macOS, but this has not been tested.

[Required] *Node.js:* Octave Online Server is built and tested with Node.js LTS version 10.  This is the default version on CentOS 8.

	# Install Node.js 10.x LTS on CentOS 8:
	$ sudo yum install nodejs

[Required] *Redis:* Install and run a local Redis instance.  Enable expiration events in `redis.conf`:

	$ sudo yum install redis
	$ sudo emacs redis.conf
	# Search for "notify-keyspace-events"
	# Set the value to "Ex"

Although it is possible to use a third-party hosted Redis instance, this is not recommended because Redis latency is amplified due to its central role in the Octave Online Server architecture.

[Recommended] *Git Server:* In order to persist user files between sessions, you need to set up a Git file server.  It boils down to a server, which could be the current server, with a low-privileged user usually named "git".  For more information, see [Git on the Server](https://git-scm.com/book/en/v1/Git-on-the-Server).  Also see [back-filesystem/README.md](back-filesystem/README.md) for instructions on how to configure a Git file server for Octave Online Server.

[Recommended] *MongoDB:* Install and run a MongoDB instance.  Unlike Redis, MongoDB is not as central of a piece in the infrastructure, so it is possible to use a remotely hosted MongoDB if you do not want to host it locally.  My experience is that it takes some time to correctly configure a fast and secure MongoDB installation.  Keep in mind that MongoDB will contain personally identifiable information for user accounts.

[Recommended] *Email SaaS:* If you want Octave Online Server to be able to send transactional emails, such as for email-based login, you need a [Mailgun](https://www.mailgun.com) or [Postmark](https://postmarkapp.com) account.  Mailgun has a free tier that should cover most experimental and low-traffic usage.

[Recommended] *ReCAPTCHA:* Certain actions, such as when email is sent, require a CAPTCHA to prevent abuse. You should register for a [ReCAPTCHA](https://www.google.com/recaptcha/) v2 Checkbox and put your credentials into your config.hjson file.

[Optional] *Google Analytics:* For aggregated statistics about traffic to your site, you can enable [Google Analytics](https://www.google.com/analytics/) integration.

[Optional] *Nginx:* For better performance with serving static files and easier HTTPS setup, I recommend installing and configuring [Nginx](https://www.nginx.com).  However, this is not an essential piece, and it can be done after the rest of the infrastructure is up and running.

### Configuration File

Read `config_defaults.hjson` to learn more about the array of settings available for Octave Online Server.  When ready, copy `config.sample.hjson` into `config.hjson`, and fill in the required details.  Your own `config.hjson` is ignored by source control.

### Installing Depencencies and Building

In each of the five directories containing Node.js projects, go in and run `npm install`:

	$ (cd shared && npm install)
	$ (cd back-filesystem && npm install)
	$ (cd back-master && npm install)
	$ (cd front && npm install)
	$ (cd client && npm install)

You also need to install the Bower (client-side) dependencies for the client project:

	$ (cd client && npm run bower install)

Finally, build the client and front server projects (the back server runs without needing to be built):

	$ (cd client && npm run grunt)
	$ (cd front && npm run grunt)

### Configuring GNU Octave

Octave Online Server requires a special version of GNU Octave, which needs to be built.  *This is a required step.*  For more information, see [back-master/README.md](back-master/README.md).

### Running Octave Online Server

To run the code manually, just open up two terminals and run each of the following two commands:

	$ (cd back-master && DEBUG=* node app.js)
	$ (cd front && node app.js)

To run the code as a service, you can install the systemd service provided in this repository and enable the code to be automatically run at startup; see *entrypoint/oo.service* and `make install-selinux-bin`.

**Tip:** When debugging, you can modify your hosts file (on macOS, /private/etc/hosts) to create a stable URL that you can add to your Google developer console to allow Google services to work.

## Contributing

You are welcome to send pull requests for consideration for addition to Octave Online Server.  Pull requests are not guaranteed to be accepted; if in doubt, you should open an issue to discuss your idea before spending time writing your pull request.

### Contributor License Agreement

Like many projects distributed with copyleft licenses such as AGPL, contributors to Octave Online Server must sign a Contributor License Agreement (CLA).  The terms of the [Octave Online CLA](https://cla-assistant.io/octave-online/octave-online-server) are taken from [The Apache Software Foundation CLA](https://www.apache.org/licenses/contributor-agreements.html).  Having a CLA in place enables Octave Online Server to be distributed with alternate licensing schemes, including commercial licenses that help keep the project afloat.

### Style

If in doubt on style, follow the convention of the file you are editing.

**Wrapping and Indentation:** Use tab indentation, unless in a file format such as *.yml* that requires space indentation.  There is no limit on line length.  This gives you full control to configure your editor to your desired width and tab size.

**Naming:** In general, use camelCase for variable names and MACRO_CASE for constants.  Prefix private members with an underscore (`_`).

**Quotes:** Use double-quoted strings, unless you are in a context where you need a different quotation style, such as backtick strings in JavaScript.

**Internationalization (i18n/l10n):** If possible, all new UI strings should be extracted into *en.yaml* so that they can be translated.  For more details, see [front/locales/README.md](front/locales/README.md).

**Upstream/Downstream:** Throughout the code, there are comments and function names indicating "upstream" and "downstream".  "Upstream", or "U", means toward the Octave process, away from the client.  "Downstream", or "D", means toward the client, away from the Octave process.  So, for example, a message sent from the back server to the front server is considered downstream, and a message sent from the back server to the Octave process is considered upstream.

**ECMAScript Versions:** JavaScript code in the *client* project should conform to the ECMAScript 5 standard, in order to have broad browser support.  JavaScript in all other projects can use the latest ECMAScript standard supported by Node.js 6.x LTS.  By design, all JavaScript code in Octave Online Server server should be able to be run natively without transcompilation to a different ECMAScript version.

### Linting

The *eslint* tool will catch most style and compatibility issues in JavaScript files.  Execute `npm run lint` in the top-level directory to check for errors.  If your code does not pass *eslint*, you will also trigger a Travis failure on GitHub.

### Manual Testing

Due to the complexity of Octave Online Server, there is not currently an automated test suite.  As a contributor, you are expected to perform some manual testing to ensure that your feature does not accidentally break something else in Octave Online Server.

Here are some critical user journeys that test a fairly wide cross-section of the code base.  **Please make sure that all of these journeys continue working after your change.**

1. The core file editor
	1. Sign in if necessary
	1. Create a new file
	1. Open the new file in the editor and make some changes
	1. The file should appear dirty (unsaved): its name should be italic and underlined
	1. Save the file; it should no longer appear dirty
	1. Press the "Refresh Files" button; your file should go away and reappear a few seconds later with the same changes you had made
	1. Click the following the buttons in the file toolbar, and make sure they behave as expected:
		- "Download File"
		- "Print File"
		- "Toggle Word Wrap"
		- "Save File" (make some changes first)
		- "Run Script"
	1. Create a file named `.octaverc` with the following content:
	```rcx = 5;```
	1. Run the `exit` command, then click the reconnect link
	1. Once the workspace loads, check that the variable `rcx` exists and has value 5
1. Collaborative workspaces
	1. Sign in if necessary
	1. Open the side bar menu and enable workspace sharing if necessary
	1. Open the sharing link in another window
	1. Repeat all of the steps from the "core file editor" journey, mixed between the two windows, and make sure that all state gets updated as expected
1. Plotting and image processing
	1. In the main command prompt, make some standard plots like `sombrero()` and `fplot(@sin, [-pi pi])`, and ensure they appear as expected
	1. Open the plot window.  You should be able to scroll through your plots.  Ensure that the two download buttons work as expected (download as PNG and as SVG)
	1. Sign in if necessary
	1. Download a full-color image from [PNGNQ](http://pngnq.sourceforge.net/pngnqsamples.html); I usually use mandrill.png
	1. Drag the PNG file onto the file list until it turns yellow; drop the file to upload it
	1. Select the file in the list; make sure "Download File" and "Rename File" work
	1. Click the "DELETE File" button to delete the file
	1. Upload the file again, this time using the "Upload file" button in the file list toolbar
	1. In the command prompt, run the following command: `imshow(imread("mandrill.png"))`; you should see the full-color image appear in the console output window (there is a surprisingly large amount of code that is needed to make this happen)
1. Buckets and Projects
	1. Sign in if necessary
	1. Create or upload multiple files if you don't already have files in your workspace
	1. Open a script file that runs by itself (not a function file)
	1. Click the "Share File in new Bucket" button
	1. Play around with the options, adding new files and selecting a main file
	1. Click "Create Bucket"
	1. Ensure that the bucket creates successfully and that the main file runs
	1. Click the bucket ID in the title bar. An information panel should appear with details about the bucket. Make sure they look correct
	1. Click the pencil icon to edit the shortlink; change it to "test999"
	1. Go to "octav.onl/test999"; the redirect should work and the same bucket page should open
	1. Click "Fork This Bucket"
	1. Enter "test999" as the custom URL in the "Create Project" screen. Click "Create Project"; a second or two later, you should see an alert box saying that there is a duplicate link
	1. Change the shortlink so that it contains illegal characters, like "$". Click "Create Project" again; a second or two later, you should see an alert saying that the shortlink has invalid characters
	1. Close the "Customize Project" dialog box, then reopen it by clicking "Fork This Bucket" again
	1. This time, click "Create Project" without changing any other settings. Your browser should refresh into the new project
	1. Ensure that you can edit and save files in the project
	1. Open the info panel for the project by clicking it in the title bar. You should see the bucket name under "Forked From"
	1. Close the info bar, then open the side bar menu
	1. Find the bucket and project you created; ensure that the timestamps is correct
	1. Save the links to both the bucket and the project
	1. Press the "⌫" button to delete the bucket and then the project
	1. Once deleted, go back to the bucket and the project with the links you saved, and ensure that the bucket and project are actaully deleted
1. Small interpreter features
	1. Run a few lines of code and then run `clc`; it should clear all output from the console window
	1. Run `doc fplot`; it should produce a working link
	1. Run `char(randi(256, 1000, 1)' .- 1)`; it should print a nonsense string with a lot of replacement characters
	1. Run `O = urlread("http://example.com")`; it should finish without error and print the HTML content of that page
	1. Run `O = urlread("https://example.com")`; it should print the same HTML as the previous line (http vs https)
	1. Run `O = urlread("http://cnn.com")`; it should print an error saying that the domain is not in the whitelist (unless you added that domain to your custom whitelist)
	1. Run `ping`; you should see a response like "Ping time: 75ms"
	1. Run `pause; disp("done")`; you should see a message "press enter to continue".  Press enter, and then you should see "done" printed out to the console
1. Octave feature coverage
	1. Run `gf`; you should see a message "Run 'pkg load communications' to use 'gf'"
	1. Run `pkg load communications` and then `help gf`; you should get a help page
	1. Run `audioread("dummy.wav")`; you should get an error that the file does not exist (but you should NOT get an error that says libsndfile was not installed)
	1. Run `fork`; you should see a message "error: 'fork' undefined near line 1, column 1"
1. Student / instructor features
	1. Create two accounts if you do not already have two accounts
	1. In one account, add a string to the `instructor` field in mongodb; for example, `"test-course"`
	1. Sign in to Octave Online Server using the other account
	1. Run `enroll("test-course")` and follow the onscreen instructions
	1. Sign out and sign into the first account, the one with the instructor field
	1. Ensure that the student is listed in the menu bar
	1. Sign out and back into the student account
	1. Open the menu and try disabling sharing; it should deny permission
	1. Run `enroll("default")` and follow the onscreen instructions
	1. Open the menu and try disabling sharing again; it should work this time
1. Network connection and reconnecting to a session
	1. Open your Octave Online Server as a guest user (not signed in)
	1. Type `x = 5` and press Enter, followed by `x` and Enter, to ensure that the variable is set correctly
	1. Terminate (Ctrl-C) your front server process and quickly restart it
	1. The loading animation should appear on the browser window, and the animation should go away once the front server has finished restarting.  In addition, the phrase "Connection lost.  Attempting to reconnect..." should be printed to the console window.  When the server reconnects, the prompt should activate
	1. Type `x` and Enter; the variable should still have the value 5
	1. Type `exit`; it should say "Octave Exited. Message: Shell Exited", and you should get a link that says "Click Here to Reconnect"
	1. Terminate (Ctrl-C) your front server process and quickly restart it
	1. The loading animation should appear on the browser window, and the animation should go away once the front server has finished restarting.  However, you should NOT get the "Connection lost" message printed to the console, and you should NOT get an active prompt automatically after the animation goes away
	1. Press the "Click Here to Reconnect" button; you should now get an active command prompt.  Run a command or two to make sure the session is working normally
	1. For an exhaustive test, repeate this section as (i) a signed-in user, (ii) a session with sharing enabled, and (iii) a bucket session.
1. Reconnecting to and expiring collaborative workspaces
	1. Sign in to a user that has sharing enabled
	1. *Ensure that no one else is viewing the user's workspace* (for example, there should be no red cursors at the command prompt)
	1. Set a variable like `x = 99`
	1. Reload the browser window; it should be the same session.  Check that `x` is still `99`
	1. Close the browser window without exiting explicitly
	1. Wait for `config.redis.expire.timeout` milliseconds to ellapse, then open up a new tab for that user; it should be a new session.  Check that `x` is no longer set to `99`
1. GUI: Flexbox panels and CSS
	1. Hover over the border between panels; a slider should appear.  Drag the slider around to resize the panels
	1. Open the menu and click "Change/Reset Layout"; the panel sizes should reset to the defaults
	1. Open the menu and click "Change Theme"; you should get a dark theme.  Clicking the button again should change the theme back
1. GUI: Function arguments and filenames
	1. Run the command `edit demo_fn.m`; it should create a new file with that name and open it in the editor
	1. Enter the following content for that file:
	```
	function [o] = demo_fn(x)
	o = x*2;
	endfunction
	```
	1. Click the "Run" button.  You should get a prompt asking you for the value of x.  Enter a value such as 3.  You should now see `ans = 6` in the console output window
	1. Press Command+R or Control+R.  The same prompt should appear
	1. Attempt to create another new file with the same name, `demo_fn.m`, using the "Create empty file" button.  You should not be able to create a file with that name since it already exists
1. GUI: Command prompt features
	1. Type `fpl` into the prompt box, then hit TAB.  You should get a menu of auto-completions like `fplot`
	1. Run several commands, such as `x=1` then `x=2` then `x=3`.  Press the up arrow.  You should be able to scroll through your command history
	1. You should see "x" in the Vars menu.  Click on the x.  A dialog should open telling you the current value of x
	1. Within the command output panel, click on command text, to the right of the "octave:#>".  That command should appear in the URL bar
	1. Reload the page.  The command you clicked (the one now in the URL) should be automatically executed after the page loads
1. GUI: Legal and account management
	1. Open the side bar menu.  Click on "Privacy Policy and EULA".  A dialog should open showing that content
	1. Make sure you are signed in
	1. Click "Change Password".  Follow the instructions to change the password
	1. Sign out and sign back in using your new password to make sure it worked
1. GUI: Folders
	1. Use the "Create empty file" button to create a file named "dir1/foo.m".  It should create a file in that subdirectory, "dir1", shown in the file list panel
	1. Enter the command `cd dir1`; you should now be changed into that directory and there should be a small window reminding you in the top left of the console output window
1. Pushing the limits: File Size
	1. Make sure you are *not* signed in
	1. Run the following command line; it should finish without any errors:
	```A = rand(500); save A.mat; load A.mat```
	1. Run the following command line; it should produce the error "load: failed to load matrix constant", due to hitting the 20 MB file size limit per workspace:
	```A = rand(5000); save A.mat; load A.mat```
1. Pushing the limits: Message Size
	1. Run the following command line; it should finish without any errors and produce a busy line plot:
	```plot(rand(100));```
	1. Run the following command line; it should produce the error "Warning: Suppressed a large plot", due to hitting the 1 MB limit on message size and therefore plot size:
	```plot(rand(300));```
1. Pushing the limits: Countdown / Time Limit
	1. Run the following command:
	```pause(12)```
	1. When the "Add 15 Seconds" link appears, click it
	1. Ensure that the time runs out after 12 seconds from the original entry of the command
1. Pushing the limits: Payload and signals
	1. Run the following command:
	```x = 0; while(true), x += 1, end```
	1. The variable `x` should get to somewhere between 1500 and 2000 before being paused for payload
	1. Click the "Resume Execution" button, and `x` should climb by approximately the same amount
	1. Click the x button to stop execution.  There may be a bit more output, but you should soon be returned to the command prompt
	1. Repeat the above steps, but instead of clicking the x button, wait for the payload timeout to finish on its own and return you to the command prompt

Tip: A community member like you could implement an automated end-to-end test suite.  If this is your area of expertise, please open an issue and engage!

## License

Octave Online Server is licensed under the [GNU Affero General Public License](https://en.wikipedia.org/wiki/Affero_General_Public_License).

> Octave Online Server is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
>
> Octave Online Server is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.

A copy of the license can be found in COPYING.

Note: You may contact webmaster@octave-online.net to inquire about other options for licensing Octave Online Server.


================================================
FILE: back-filesystem/.eslintrc.yml
================================================


================================================
FILE: back-filesystem/.npmrc
================================================
# Please keep this in sync with all other .npmrc files
# SEE: https://github.com/npm/feedback/discussions/864
install-links=false


================================================
FILE: back-filesystem/README.md
================================================
Octave Online Server: Back Server, Filesystem Utilities
=======================================================

This directory contains the source code dealing with the filesystem for the Octave Online Server back server.  It also contains scripts for interacting with the Git file server.

## Git File Server

The subdirectory *git* contains files for running a Git file server for Octave Online Server.

*gitd.service* is a systemd service that enables the Git daemon with the repository root at */srv/oo/git*, which is expected to contain *repos* and *buckets* subdirectories that are read/write to the *git* user.

*create-repo.service* is a systemd service that runs a tiny server for creating empty repositories.  It has the same path expectations as *gitd.service*.  It invokes the path */usr/local/bin/create-repo-service*, which is expected to be a copy of *create-repo-service.js* from this project.

**CAUTION:** Neither *gitd.service* nor *create-repo.service* require any authentication.  You should therefore run these services behind a firewall.

## History

When using the SELinux backend, the code in this directory is run in the main event loop (Node.js process) along with the *back-master* code.  When the Docker backend is used, however, this code runs inside of a Docker container, while *back-master* runs outside of a Docker container.

This separation was done in order to make file permissions work correctly.  However, this separation is one reason why the Docker implementation is not able to handle as many concurrent sessions as the SELinux implementation.


================================================
FILE: back-filesystem/app.js
================================================
/*
 * Copyright © 2018, Octave Online LLC
 *
 * This file is part of Octave Online Server.
 *
 * Octave Online Server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Octave Online Server is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Octave Online Server.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

"use strict";

// This is the entrypoint for a standalone version of back-filesystem, used by the Docker mode but NOT the SELinux mode.

const messenger = new (require("@oo/shared").StdioMessenger)();
const log = require("@oo/shared").logger("app");
const FilesController = require("./src/controller");

// Customize options on the logger
require("./src/logger");

// Read command-line arguments
const GIT_DIR = process.argv[2];
const WORK_DIR = process.argv[3];
log.info("Dirs:", GIT_DIR, WORK_DIR);

// Make an instance of controller
var controller = new FilesController(GIT_DIR, WORK_DIR, "");

// Set up the STDIO messenger instance so we can talk to the master
messenger._log = require("@oo/shared").logger("messenger");
messenger.setReadStream(process.stdin);
messenger.setWriteStream(process.stdout);
messenger.on("message", (name, content) => {
	controller.receiveMessage(name, content);
});
controller.on("message", (name, content) => {
	messenger.sendMessage(name, content);
});
messenger.on("error", (err) => {
	log.error("messenger:", err);
});

// Send acknowledgement message downstream
messenger.sendMessage("ack", true);




================================================
FILE: back-filesystem/git/create-repo-service.js
================================================
#!/usr/bin/env node

/*
 * Copyright © 2019, Octave Online LLC
 *
 * This file is part of Octave Online Server.
 *
 * Octave Online Server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Octave Online Server is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Octave Online Server.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

"use strict";

/* eslint-disable no-console */

const child_process = require("child_process");
const fs = require("fs");
const http = require("http");
const path = require("path");
const url = require("url");

if (process.argv.length !== 4) {
	console.error("Usage: node create-repo-service.js /path/to/git/root PORT");
	process.exit(1);
}

const gitRoot = process.argv[2];
const port = parseInt(process.argv[3]);

http.createServer((req, res) => {
	const { query } = url.parse(req.url, true);
	const isoTime = new Date().toISOString();
	if (["buckets", "repos"].indexOf(query.type) === -1) {
		res.writeHead(400, "Invalid type");
		console.log(`create-repo-service: ${isoTime} Invalid type`);
		return res.end();
	}
	if (!query.name || !/^[\w]+$/.test(query.name)) {
		res.writeHead(400, "Invalid name");
		console.log(`create-repo-service: ${isoTime} Invalid name`);
		return res.end();
	}
	const bareRepoPath = path.join(gitRoot, query.type, query.name + ".git");
	fs.stat(bareRepoPath, (err) => {
		const exists = !err;
		let process;
		if (query.action === "delete") {
			if (exists) {
				process = child_process.spawn("rm", ["-rf", bareRepoPath]);
			} else {
				res.writeHead(200, { "Content-Type": "text/plain" });
				res.end("Already Deleted\n");
				console.log(`create-repo-service: ${isoTime} Already Deleted: ${bareRepoPath}`);
				return;
			}
		} else {
			if (exists) {
				res.writeHead(200, { "Content-Type": "text/plain" });
				res.end("Already Created\n");
				console.log(`create-repo-service: ${isoTime} Already Created: ${bareRepoPath}`);
				return;
			} else {
				process = child_process.spawn("git", ["init", "--bare", bareRepoPath]);
			}
		}
		let resData = Buffer.alloc(0);
		process.stdout.on("data", (chunk) => {
			resData = Buffer.concat([resData, chunk]);
		});
		process.stderr.on("data", (chunk) => {
			resData = Buffer.concat([resData, chunk]);
		});
		process.on("exit", (code /* , signal */) => {
			const operation = (query.action === "delete") ? "Delete" : "Init";
			if (code === 0) {
				res.writeHead(200, { "Content-Type": "text/plain" });
				res.write(`${operation} Success\n`);
				console.log(`create-repo-service: ${isoTime} ${operation} Success: ${bareRepoPath}`);
			} else {
				res.writeHead(500, { "Content-Type": "text/plain" });
				res.write(`${operation} Error\n`);
				console.log(`create-repo-service: ${isoTime} ${operation} Error: ${bareRepoPath}`);
				console.log(`create-repo-service: ${resData.toString("utf-8")}`);
			}
			res.write(resData);
			res.end();
		});
	});
}).listen(port);

console.log("create-repo-service: Listening on port", port);


================================================
FILE: back-filesystem/git/create-repo.service
================================================
# Copyright © 2019, Octave Online LLC
#
# This file is part of Octave Online Server.
#
# Octave Online Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Octave Online Server is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Octave Online Server.  If not, see
# <https://www.gnu.org/licenses/>.

###############################################################
# NOTE: This systemd service file is here for reference only; #
# it is not currently being used in Octave Online Server.     #
###############################################################

[Unit]
Description=Service to create and delete bare git repos

[Service]
ExecStart=/usr/local/bin/create-repo-service /srv/oo/git 3003
Environment=NODE_ENV=production

Restart=always

StandardOutput=syslog
StandardError=syslog

User=git
Group=git

[Install]
WantedBy=multi-user.target


================================================
FILE: back-filesystem/git/gitd.service
================================================
# Copyright © 2019, Octave Online LLC
#
# This file is part of Octave Online Server.
#
# Octave Online Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Octave Online Server is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Octave Online Server.  If not, see
# <https://www.gnu.org/licenses/>.

###############################################################
# NOTE: This systemd service file is here for reference only; #
# it is not currently being used in Octave Online Server.     #
###############################################################

[Unit]
Description=Start Read-Write Git Daemon

[Service]
ExecStart=/usr/bin/git -c daemon.receivepack=true daemon --verbose --reuseaddr --export-all --base-path=/srv/oo/git /srv/oo/git

Restart=always
RestartSec=500ms

StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=git-daemon

User=git
Group=git

[Install]
WantedBy=multi-user.target


================================================
FILE: back-filesystem/package.json
================================================
{
  "name": "@oo/files",
  "version": "0.0.0",
  "description": "Reads and writes to an Octave session working directory",
  "main": "app.js",
  "scripts": {},
  "author": "Octave Online LLC",
  "license": "AGPL-3.0",
  "private": true,
  "engines": {
    "node": "18.x"
  },
  "dependencies": {
    "@oo/shared": "file:../shared",
    "async": "^1.5.2",
    "charset-detector": "0.0.2",
    "debug-logger": "^0.4.1",
    "iconv": "^3",
    "mime": "^1.3.4",
    "socketio-file-upload": "^0.4.4",
    "sprintf-js": "^1.0.3"
  }
}


================================================
FILE: back-filesystem/src/controller.js
================================================
/*
 * Copyright © 2018, Octave Online LLC
 *
 * This file is part of Octave Online Server.
 *
 * Octave Online Server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Octave Online Server is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Octave Online Server.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

"use strict";

const async = require("async");
const GitUtil = require("./git-util");
const WorkingUtil = require("./working-util");
const path = require("path");
const SocketIOFileUploadServer = require("socketio-file-upload");
const config = require("@oo/shared").config;
const FakeSocket = require("./fake-socket");
const logger = require("@oo/shared").logger;
const EventEmitter = require("events");

class FilesController extends EventEmitter {
	constructor(gitDir, workDir, logMemo) {
		super();
		this._log = logger(`files-controller:${logMemo}`);
		this._mlog = logger(`files-controller:${logMemo}:minor`);

		this.gitUtil = new GitUtil(gitDir, logMemo);
		this.workingUtil = new WorkingUtil(workDir, logMemo);
		this.workDir = workDir;
		this.user = null;
		this.bucketId = null;
		this.ready = false;
		this.destroyed = false;

		this.fakeSocket = new FakeSocket();
		this.fakeSocket.on("_emit", this._sendMessage.bind(this));
		this._setupUploader();
	}

	// Returns whether Git operations are safe to perform.
	// Check this.ready for whether file operations (without git) are safe.
	_isInitialized() {
		return this.ready && (this.user !== null || this.bucketId !== null);
	}

	// Returns whether either "user-info" or "bucket-info" has been called
	_isSetUp() {
		return this.user || this.bucketId || this.ready;
	}

	receiveMessage(name, content) {
		switch (name) {
			case "user-info": {
				if (this._isSetUp()) {
					this._log.error("user-info called, but already set up:", content);
					return;
				}
				this.user = content.user;
				if (this.user) {
					this._log.info("Received user:", this.user.consoleText);
					this._legalTime = content.legalTime; // FIXME: For backwards compatibility
				} else {
					this._log.info("No user this session");
					this.ready = true;
					this._sendMessage("files-ready", {});
					return;
				}

				async.waterfall([
					(_next) => {
						this.gitUtil.initialize(this.user, this.workDir, _next);
					},
					(results, _next) => {
						this.workingUtil.hasOctaverc(_next);
					},
					(hasOctaverc, _next) => {
						this.ready = true;
						this._sendMessage("files-ready", { hasOctaverc });
						_next(null);
					},
					(_next) => {
						this.workingUtil.listAll(_next);
					}
				], (err, fileData) => {
					if (err) {
						if (/unable to write file/.test(err.message)) {
							return this._fail("filelist", "warn", `Whoops! You are currently exceeding your space limit of ${config.docker.diskQuotaKiB} KiB.\nPlease open a support ticket and we will help you resolve the\nissue. Sorry for the inconvenience!`);
						} else {
							if (this._logError("initialize", err)) {
								this._fail("filelist", "warn", "Unable to load your files from the server: please try again.");
							}
							return;
						}
					}
					this._mlog.debug("User successfully initialized");
					this._sendMessage("filelist", {
						success: true,
						legalTime: this._legalTime, // FIXME: for backwards compatibility
						files: fileData,
						refresh: false
					});
				});
				break;
			}

			case "bucket-info": {
				if (this._isSetUp()) {
					this._log.error("bucket-info called, but already set up:", content);
					return;
				}
				this.bucketId = content.id;
				this._legalTime = content.legalTime; // FIXME: For backwards compatibility
				// If content.readonly is false, this request is for a project or for creating the bucket.  If content.readonly is true, this request is for reading from the bucket.
				this._log.info("Received bucket:", this.bucketId, content.readonly);
				async.waterfall([
					(_next) => {
						this.gitUtil.initializeBucket(this.bucketId, this.workDir, content.readonly, _next);
					},
					(results, _next) => {
						this.workingUtil.hasOctaverc(_next);
					},
					(hasOctaverc, _next) => {
						this.ready = true;
						this._sendMessage("files-ready", { hasOctaverc });
						_next(null);
					},
					(_next) => {
						this.workingUtil.listAll(_next);
					}
				], (err, fileData) => {
					if (err) return this._logError("bucket", err);
					this._mlog.debug("Bucket successfully initialized");
					this._sendMessage("filelist", {
						success: true,
						legalTime: this._legalTime, // FIXME: for backwards compatibility
						files: fileData,
						refresh: false
					});
				});
				break;
			}

			case "list": {
				if (!this.ready) return this._mlog.warn("list: not ready");
				this._mlog.debug("Listing files...");
				async.waterfall([
					(_next) => {
						this.workingUtil.listAll(_next);
					}
				], (err, fileData) => {
					if (err) return this._logError("list", err);
					this._log.debug("Files successfully listed");
					this._sendMessage("filelist", {
						success: true,
						legalTime: this._legalTime, // FIXME: for backwards compatibility
						files: fileData,
						refresh: false
					});
				});
				break;
			}

			case "refresh": {
				if (!this._isInitialized()) return this._mlog.warn("refresh: not initialized");
				this._mlog.debug("Refreshing files...");
				async.waterfall([
					(_next) => {
						this.gitUtil.pullPush("Scripted user file commit", _next);
					},
					(results, _next) => {
						this.workingUtil.listAll(_next);
					}
				], (err, fileData) => {
					if (err) return this._logError("refresh", err);
					this._log.debug("Files successfully refreshed");
					this._sendMessage("filelist", {
						success: true,
						files: fileData,
						refresh: true
					});
				});
				break;
			}

			case "commit": {
				if (!this._isInitialized()) return this._fail("committed", "warn", "Not initialized");
				// NOTE: In a readonly repository (buckets), this is a no-op.
				const comment = content.comment;
				if (!comment) return this._fail("committed", "warn", "Empty comment:", comment);
				this._mlog.debug("Committing files...");
				async.waterfall([
					(_next) => {
						this.gitUtil.pullPush(comment, _next);
					}
				], (err) => {
					if (err) return this._fail("committed", "warn", err);
					this._log.debug("Files successfully committed (except for readonly)");
					return this._sendMessage("committed", { success: true });
				});
				break;
			}

			case "save": {
				if (!this.ready) return this._fail("save", "warn", "Not ready");
				const filename = content.filename;
				const value = content.content;
				this._mlog.debug("Saving file:", filename);
				if (!filename) return this._fail("saved", "warn", "Empty file name:", filename, value);
				async.waterfall([
					(_next) => {
						this.workingUtil.saveFile(filename, value, _next);
					}
				], (err, md5sum) => {
					if (err) {
						if (/ENOSPC/.test(err.message)) return this._fail("saved", "warn", `Whoops, you reached your space limit (${config.docker.diskQuotaKiB} KiB).\nYou should free up space to ensure that changes you make get committed.\nRunning the command "system('rm octave-workspace')" might help.`);
						else return this._fail("saved", "error", err);
					}
					this._log.debug("File successfully saved");
					return this._sendMessage("saved", {
						success: true,
						filename,
						md5sum
					});
				});
				break;
			}

			case "rename": {
				if (!this.ready) return this._fail("rename", "warn", "Not ready");
				const oldname = content.filename;
				const newname = content.newname;
				if (!oldname || !newname) return this._fail("renamed", "warn", "Empty file name or new name:", oldname, newname);
				this._mlog.debug("Renaming file:", oldname, newname);
				async.waterfall([
					(_next) => {
						this.workingUtil.renameFile(oldname, newname, _next);
					}
				], (err) => {
					if (err) return this._fail("renamed", "error", err);
					this._log.debug("File successfully renamed");
					return this._sendMessage("renamed", { oldname, newname, success: true });
				});
				break;
			}

			case "delete": {
				if (!this.ready) return this._fail("delete", "warn", "Not ready");
				const filename = content.filename;
				if (!filename) return this._fail("deleted", "warn", "Empty file name:", filename);
				this._mlog.debug("Deleting file:", filename);
				async.waterfall([
					(_next) => {
						this.workingUtil.deleteFile(filename, _next);
					}
				], (err) => {
					if (err) {
						if (/ENOENT/.test(err.message)) return this._fail("deleted", "warn", `Whoops, the file ${filename} does not exist any more.\nTry pressing the "refresh files" button in the file manager toolbar.`);
						else return this._fail("deleted", "error", err);
					}
					this._log.debug("File successfully deleted");
					return this._sendMessage("deleted", {
						success: true,
						filename
					});
				});
				break;
			}

			case "binary": {
				if (!this.ready) return this._mlog.warn("binary: not ready");
				const filename = content.filename;
				if (!filename) return this._fail("binary", "warn", "Empty file name:", filename);
				this._mlog.debug("Loading binary file:", filename);
				async.waterfall([
					(_next) => {
						this.workingUtil.readBinary(filename, _next);
					}
				], (err, base64data, mime) => {
					if (err) return this._fail("binary", "error", err);
					this._log.debug("File successfully loaded");
					return this._sendMessage("binary", {
						success: true,
						filename,
						base64data,
						mime
					});
				});
				break;
			}

			case "read-delete-binary": {
				if (!this.ready) return this._mlog.warn("read-delete-binary: not ready");
				const filename = content.filename;
				if (!filename) return this._fail("deleted-binary", "warn", "Empty file name:", filename);
				this._mlog.debug("Loading and deleting binary file:", filename);
				async.series([
					(_next) => {
						this.workingUtil.readBinary(filename, _next);
					}, (_next) => {
						this.workingUtil.deleteFile(filename, _next);
					}
				], (err, results) => {
					if (err) return this._fail("deleted-binary", "error", err);
					const base64data = results[0][0];
					const mime = results[0][1];
					this._log.debug("File successfully loaded and deleted");
					return this._sendMessage("deleted-binary", {
						success: true,
						filename,
						base64data,
						mime
					});
				});
				break;
			}

			case "multi-binary": {
				if (!this.ready) return this._mlog.warn("multi-binary: not ready");
				const filenames = content.filenames;
				const responseName = "multi-binary:" + content.id;
				if (!Array.isArray(filenames)) return this._fail(responseName, "warn", "Invalid filename array:", filenames);
				this._mlog.debug("Loading multiple files", responseName, filenames);
				async.map(filenames, (filename, _next) => {
					async.waterfall([
						(__next) => {
							this.workingUtil.readBinary(filename, __next);
						},
						(base64data, mime, __next) => {
							__next(null, base64data);
						}
					], _next);
				}, (err, results) => {
					if (err) return this._fail(responseName, "error", err);
					this._mlog.trace("Files finished loading", responseName);
					return this._sendMessage(responseName, {
						success: true,
						results
					});
				});
				break;
			}

			case "save-multi-binary": {
				if (!this.ready) return this._mlog.warn("save-multi-binary: not ready");
				const filenames = content.filenames;
				const base64datas = content.base64datas;
				const responseName = "multi-binary-saved:" + content.id;
				if (!Array.isArray(filenames) || !Array.isArray(base64datas) || filenames.length !== base64datas.length) return this._fail(responseName, "warn", "Invalid array:", filenames, base64datas);
				this._mlog.debug("Writing multiple files:", responseName, filenames);
				async.times(filenames.length, (i, _next) => {
					const buffer = new Buffer(base64datas[i], "base64");
					this.workingUtil.saveFile(filenames[i], buffer, _next);
				}, (err, results) => {
					if (err) return this._fail(responseName, "error", err);
					this._mlog.trace("Files finished writing", responseName);
					return this._sendMessage(responseName, {
						success: true,
						results
					});
				});
				break;
			}

			// Send remaining messages to the fakeSocket
			default: {
				this.fakeSocket.trigger(name, content);
				break;
			}
		}
	}

	destroy() {
		this.destroyed = true;
	}

	_logError(context, err) {
		if (this.destroyed) {
			this._mlog.trace("Ignoring git error:", context, err);
			return false;
		} else {
			this._log.error(context, err);
			return true;
		}
	}

	// Send messages downstream
	_sendMessage(name, content) {
		this.emit("message", name, content);
	}

	// Log and send failure messages
	_fail() {
		let args = Array.prototype.slice.call(arguments, 2);
		let messageString = args.join(" ");
		this._log[arguments[1]].apply(this, args);
		this._sendMessage(arguments[0], { success: false, message: messageString });
	}

	// Set up SIOFU
	_setupUploader() {
		const uploader = new SocketIOFileUploadServer();
		uploader.dir = this.workDir;
		uploader.emitChunkFail = true;
		uploader.on("saved", (event) => {
			const filename = path.basename(event.file.pathName);
			this.workingUtil.getFileInfo(filename, (err, fileInfo) => {
				if (err) return this._log.warn(err);
				if (!fileInfo) return this._fail("saved", "warn", "Your file uploaded, but it will not appear in the list due to an illegal file name.");
				this._log.debug("File successfully uploaded");
				return this._sendMessage("fileadd", fileInfo);
			});
		});
		uploader.on("error", (event) => {
			if (/ENOSPC/.test(event.error.message)) return this._fail("saved", "debug", `Uploading ${event.file.name}:\nIf your file is large and causes you to exceed your space limit\n(${config.docker.diskQuotaKiB} KiB), the file may be incomplete.`);
			this._log.error("siofu:", event);
		});
		uploader.listen(this.fakeSocket);
	}
}

module.exports = FilesController;


================================================
FILE: back-filesystem/src/fake-socket.js
================================================
/*
 * Copyright © 2018, Octave Online LLC
 *
 * This file is part of Octave Online Server.
 *
 * Octave Online Server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Octave Online Server is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Octave Online Server.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

"use strict";

const EventEmitter = require("events");

// Object to replicate the API of a server-side Socket.IO socket instance.
// 
// To trigger all local listeners with an emulated socket message, call
//   myFakeSocket.trigger(name,data)
// 
// To listen for when local methods want to send a message, listen for
// the "_emit" event on your FakeSocket instance.

class FakeSocket extends EventEmitter {
	constructor() {
		super();
	}
}

// Change around some of the methods
const oldEmit = FakeSocket.prototype.emit;
FakeSocket.prototype.trigger = oldEmit;
FakeSocket.prototype.emit = function(){
	const args = Array.prototype.slice.call(arguments);
	args.unshift("_emit");
	oldEmit.apply(this, args);
};

module.exports = FakeSocket;


================================================
FILE: back-filesystem/src/git-util.js
================================================
/*
 * Copyright © 2018, Octave Online LLC
 *
 * This file is part of Octave Online Server.
 *
 * Octave Online Server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Octave Online Server is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Octave Online Server.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

"use strict";

const async = require("async");
const child_process = require("child_process");
const logger = require("@oo/shared").logger;
const config = require("@oo/shared").config;
const silent = require("@oo/shared").silent;

class GitUtil {
	constructor(gitDir, logMemo) {
		this._log = logger(`git-util:${logMemo}`);
		this._mlog = logger(`git-util:${logMemo}:minor`);
		this.execOptions = { cwd: gitDir };
		this.readonly = false;
		this._initialized = false;
		// TODO: Prevent multiple git operations from taking place simultaneously.
	}

	initialize(user, workDir, next) {
		if (this._initialized) {
			this._log.error("Initializing a repository for a user that was already initialized");
			return;
		}
		const remote = this._userToRemote(user);
		async.series([
			(_next) => {
				this._createUserOnRemote(user, _next);
			},
			(_next) => {
				this._initialize(remote, workDir, _next);
			}
		], next);
	}

	initializeBucket(bucketId, workDir, readonly, next) {
		if (this._initialized) {
			this._log.error("Initializing a repository for a bucket that was already initialized");
			return;
		}
		this.readonly = readonly;
		const remote = this._bucketToRemote(bucketId);
		async.series([
			(_next) => {
				if (!readonly) {
					this._createBucketOnRemote(bucketId, _next);
				} else {
					_next(null);
				}
			},
			(_next) => {
				this._initialize(remote, workDir, _next);
			}
		], next);
	}

	_initialize(remote, workDir, next) {
		async.series([
			(_next) => {
				this._mlog.trace("Running git init...");
				child_process.execFile("git", ["--git-dir=.", `--work-tree=${workDir}`, "init"], this.execOptions, _next);
			},
			(_next) => {
				// May 2018: Do not log email-based Git URL
				const idx = remote.indexOf("_");
				const safeOrigin = (idx === -1) ? remote : remote.substr(0, idx) + "_…";
				this._mlog.info("Setting origin:", safeOrigin);
				child_process.execFile("git", ["remote", "add", "origin", remote], this.execOptions, _next);
			},
			(_next) => {
				this._pull(_next);
			},
			(_next) => {
				this._initialized = true;
				_next(null);
			}
		], next);
	}

	pullPush(message, next) {
		if (!this._initialized) {
			// Trying to sync the repo before it has been initialized; do not attempt to push, because no local changes are possible.
			return next(null);
		}
		if (this.readonly) {
			return this._pull(next);
		} else {
			return this._pullPush(message, next);
		}
	}

	_pullPush(message, next) {
		async.series([
			(_next) => {
				this._mlog.debug("Preparing to pull-push...");
				_next();
			},
			(_next) => {
				this._commit(message, _next);
			},
			(_next) => {
				// Perform a shallow clone to avoid wasting time and resources downloading old refs from the server
				// This command can fail silently for the case when the remote repo is empty
				child_process.execFile("git", ["fetch", "--depth=1"], this.execOptions, silent(/no matching remote head/, _next));
			},
			(_next) => {
				// Resolve merge conflicts by committing all the conflicts into the repository, and let the user manually fix the conflict next time the log in.
				// This command can fail silently for the case when origin/master does not exist
				const mergeArgs = config.git.supportsAllowUnrelatedHistories ? ["merge", "--no-commit", "--allow-unrelated-histories", "origin/master"] : ["merge", "--no-commit", "origin/master"];
				child_process.execFile("git", this._gitConfigArgs().concat(mergeArgs), this.execOptions, silent(/fix conflicts|not something we can merge/, _next).stdout);
			},
			(_next) => {
				this._commit("Scripted merge", _next);
			},
			(_next) => {
				// Push the changes up
				// This command can fail silently for the case when the local branch "master" is empty
				child_process.execFile("git", ["push", "origin", "master"], this.execOptions, silent(/src refspec master does not match any/, _next));
			},
			(_next) => {
				this._mlog.debug("Finished pull-push");
				_next(null);
			}
		], next);
	}

	_pull(next) {
		async.series([
			(_next) => {
				this._mlog.debug("Preparing to pull...");
				_next();
			},
			(_next) => {
				// Perform a shallow clone to avoid wasting time and resources downloading old refs from the server
				// This command can fail silently for the case when the remote repo is empty
				child_process.execFile("git", ["fetch", "--depth=1"], this.execOptions, silent(/no matching remote head/, _next));
			},
			(_next) => {
				child_process.execFile("git", this._gitConfigArgs().concat(["merge", "origin/master"]), this.execOptions, silent(/not something we can merge/, _next));
			},
			(_next) => {
				this._mlog.debug("Finished pull");
				_next();
			}
		], next);
	}

	_commit(message, next) {
		async.series([
			(_next) => {
				child_process.execFile("git", ["add", "--all"], this.execOptions, _next);
			},
			// Remove the following check since the new "capped file system" should take care of this for us
			// (_next) => {
			// 	// Do not commit files greater than 1MB in size
			// 	child_process.exec("find . -size +1M -type f -exec git reset {} \\;", this.execOptions, _next);
			// },
			(_next) => {
				// This command can safely fail silently for the case when there are no files to commit (in that case, the error is empty)
				// Note that specifying --author here does not seem to work; I have to do -c ... instead
				child_process.execFile("git", this._gitConfigArgs().concat(["commit", "-m", message]), this.execOptions, silent(/nothing to commit/, _next).stdout);
			}
		], next);
	}

	_createUserOnRemote(user, next) {
		async.series([
			(_next) => {
				this._mlog.debug("Preparing remote repo...");
				_next();
			},
			(_next) => {
				fetch(`http://${config.git.hostname}:${config.git.createRepoPort}/?` + new URLSearchParams({
					type: "repos",
					name: user.parametrized
				})).then((response) => {
					if (!response.ok) {
						return _next(new Error("Not 2xx response", { cause: response }));
					}
					_next();
				}).catch(_next);
			}
		], next);
	}

	_createBucketOnRemote(bucketId, next) {
		async.series([
			(_next) => {
				this._mlog.debug("Preparing remote bucket...");
				_next();
			},
			(_next) => {
				fetch(`http://${config.git.hostname}:${config.git.createRepoPort}/?` + new URLSearchParams({
					type: "buckets",
					name: bucketId
				})).then((response) => {
					if (!response.ok) {
						return _next(new Error("Not 2xx response", { cause: response }));
					}
					_next();
				}).catch(_next);
			}
		], next);
	}

	_userToRemote(user) {
		return `git://${config.git.hostname}:${config.git.gitDaemonPort}/repos/${user.parametrized}.git`;
	}

	_bucketToRemote(bucketId) {
		return `git://${config.git.hostname}:${config.git.gitDaemonPort}/buckets/${bucketId}.git`;
	}

	_gitConfigArgs() {
		return ["-c", `user.name="${config.git.author.name}"`, "-c", `user.email="${config.git.author.email}"`];
	}
}

module.exports = GitUtil;


================================================
FILE: back-filesystem/src/logger.js
================================================
/*
 * Copyright © 2018, Octave Online LLC
 *
 * This file is part of Octave Online Server.
 *
 * Octave Online Server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Octave Online Server is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Octave Online Server.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

"use strict";

const logger = require("@oo/shared").logger;

// Enable all log levels by default
logger.debug.enable("*");

// Customize formatArgs
// Based on https://github.com/visionmedia/debug/blob/master/node.js
logger.debug.formatArgs = function formatArgs() {
	var args = arguments;
	var useColors = this.useColors;
	var name = this.namespace;

	if (useColors) {
		var c = this.color;

		args[0] = "  \u001b[3" + c + ";1m" + name + " "	+ "\u001b[0m"	+ args[0] + "\u001b[3" + c + "m" + " +" + logger.debug.humanize(this.diff) + "\u001b[0m";
	} else {
		args[0] = name + " " + args[0];
	}
	return args;
};


================================================
FILE: back-filesystem/src/mime.types
================================================
# Copyright © 2018, Octave Online LLC
#
# This file is part of Octave Online Server.
#
# Octave Online Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Octave Online Server is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Octave Online Server.  If not, see
# <https://www.gnu.org/licenses/>.


# Additional MIME Types used by the Octave Online application

# GNU Octave Types
# If these haven't ben defined before, then they are now!
text/x-octave	m
application/x-octave-data	mat
text/plain	octaverc


================================================
FILE: back-filesystem/src/working-util.js
================================================
/*
 * Copyright © 2018, Octave Online LLC
 *
 * This file is part of Octave Online Server.
 *
 * Octave Online Server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Octave Online Server is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Octave Online Server.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

"use strict";

const async = require("async");
const fs = require("fs");
const path = require("path");
const mime = require("mime");
const charsetDetector = require("charset-detector");
const Iconv = require("iconv").Iconv;
const logger = require("@oo/shared").logger;
const config = require("@oo/shared").config;
const crypto = require("crypto");

// Load extra MIME types
mime.load(path.join(__dirname, "mime.types"));

const ACCEPTABLE_MIME_REGEX = /^(text\/.*)$/;
const UNACCEPTABLE_FILENAME_REGEX = /^(\..*|octave-\w+)$/;

class WorkingUtil {
	constructor(workDir, logMemo) {
		this._log = logger(`working-util:${logMemo}`);
		this._mlog = logger(`working-util:${logMemo}:minor`);
		this.cwd = workDir;
	}

	listAll(next) {
		async.waterfall([
			(_next) => {
				this._recursiveReaddir(this.cwd, 0, _next);
			},
			(fileInfos, _next) => {
				const dict = {};
				fileInfos.forEach((fileInfo) => {
					if (!fileInfo) return;
					let filename = fileInfo.filename;
					delete fileInfo.filename;
					dict[filename] = fileInfo;
				});
				_next(null, dict);
			}
		], next);
	}

	hasOctaverc(next) {
		fs.access(path.join(this.cwd, ".octaverc"), (err) => {
			if (err) {
				this._mlog.trace(".octaverc does not exist");
				return next(null, false);
			} else {
				this._mlog.trace(".octaverc exists");
				return next(null, true);
			}
		});
	}

	_recursiveReaddir(directory, depth, next) {
		// Don't recurse more than 3 levels deep
		if (depth > 3) {
			return next(null, []);
		}

		async.waterfall([
			(_next) => {
				this._mlog.trace("Entering directory", directory);
				fs.readdir(directory, _next);
			},
			(files, _next) => {
				async.map(files, (filename, __next) => {
					let pathname = path.join(directory, filename);
					let relname = path.relative(this.cwd, pathname);
					// TODO: Can the following be removed?
					if (pathname === path.join(this.cwd, ".git")) {
						this._mlog.debug("Skipping .git in _recursiveReaddir");
						return;
					}
					async.waterfall([
						(___next) => {
							// lstat to prevent following symlinks
							fs.lstat(pathname, ___next);
						},
						(stats, ___next) => {
							this._mlog.trace("Got lstats", relname, stats.isDirectory(), stats.isFile());
							if (stats.isDirectory()) {
								return this._recursiveReaddir(pathname, depth+1, ___next);
							} else if (stats.isFile()) {
								return this._getFileInfo(filename, pathname, relname, stats, ___next);
							} else {
								return ___next(null, []);
							}
						}
					], __next);
				}, (err, results) => {
					if (err) return _next(err);
					this._mlog.trace("Leaving directory", directory);
					_next(null, Array.prototype.concat.apply([], results));
				});
			}
		], next);
	}

	// Endpoint for standalone getFileInfo (used by SIOFU)
	getFileInfo(filename, next) {
		let pathname = this._safePath(filename);
		let relname = path.relative(this.cwd, pathname);
		async.waterfall([
			(_next) => {
				fs.lstat(pathname, _next);
			},
			(stats, _next) => {
				this._getFileInfo(filename, pathname, relname, stats, _next);
			},
			(arr, _next) => {
				_next(null, arr[0]);
			}
		], next);
	}

	_getFileInfo(filename, pathname, relname, stats, next) {
		this._mlog.trace("Getting file info for", relname);
		let _mime = mime.lookup(filename);
		if (ACCEPTABLE_MIME_REGEX.test(_mime)) {
			if (stats.size > config.session.textFileSizeLimit) {
				// This file is too big.  Do not perform any further processing on this file.
				// FIXME: Show a nice message to the end user to let them know why their file isn't being loaded
				this._log.debug("Skipping text file that is too big:", stats.size, filename);
				next(null, [{
					filename: relname,
					isText: false
				}]);
			} else {
				fs.readFile(pathname, (err, buf) => {
					if (err) return next(err);
					buf = this._convertCharset(buf);
					next(null, [{
						filename: relname,
						isText: true,
						content: buf.toString("base64")
					}]);
				});
			}
		} else if (!UNACCEPTABLE_FILENAME_REGEX.test(filename)) {
			next(null, [{
				filename: relname,
				isText: false
			}]);
		} else {
			next(null, []);
		}
	}

	_convertCharset(buf) {
		var encoding;

		// Detect and attempt to convert charset
		if (buf.length > 0) {
			try {
				let charsetResults = charsetDetector(buf);
				this._log.debug("Top charset match:", charsetResults?.[0]);
				encoding = charsetResults?.[0]?.charsetName || "UTF-8";
				if (encoding !== "UTF-8"){
					this._log.trace("Converting charset:", encoding);
					buf = new Iconv(encoding, "UTF-8").convert(buf);
				}
			} catch(err) {
				this._log.warn("Could not convert encoding:", encoding);
			}
		}

		// Convert line endings
		// TODO: Is there a better way than converting to a string here?
		buf = new Buffer(buf.toString("utf8").replace(/\r\n/g, "\n"));

		return buf;
	}

	saveFile(filename, value, next) {
		// Create backup of file in memory in case there are any I/O errors
		async.waterfall([
			(_next) => {
				let dirname = path.dirname(this._safePath(filename));
				// Callback to a function to remove/normalize extra arguments
				fs.mkdir(dirname, { recursive: true }, (e) => _next(e));
			},
			(_next) => {
				fs.readFile(
					this._safePath(filename),
					(err, buf) => {
						if (!err) return _next(null, buf);
						if (/ENOENT/.test(err.message)) {
							this._log.info("Creating new file:", filename);
							return _next(null, new Buffer(0));
						}
						return _next(err);
					}
				);
			},
			(buf, _next) => {
				fs.writeFile(
					this._safePath(filename),
					value,
					(err) => {
						_next(null, buf, err);
					});
			},
			(buf, err, _next) => {
				if (err) {
					fs.writeFile(
						this._safePath(filename),
						buf,
						() => {
							_next(err);
						});
				} else {
					async.nextTick(() => {
						_next(null);
					});
				}
			},
			(_next) => {
				return _next(null, crypto.createHash("md5").update(value, "utf-8").digest("hex"));
			}
		], next);
	}

	renameFile(oldname, newname, next) {
		fs.rename(
			this._safePath(oldname),
			this._safePath(newname),
			next);
	}

	deleteFile(filename, next) {
		fs.unlink(
			this._safePath(filename),
			next);
	}

	readBinary(filename, next) {
		async.waterfall([
			(_next) => {
				fs.readFile(this._safePath(filename), _next);
			},
			(buf, _next) => {
				const base64data = buf.toString("base64");
				const _mime = mime.lookup(filename);
				_next(null, base64data, _mime);
			}
		], next);
	}

	_safePath(filename) {
		// Filenames must descend from the working directory.  Forbids filenames starting with '..' or similar.
		let candidate = path.join(this.cwd, filename);
		if (candidate.substring(0, this.cwd.length) !== this.cwd) {
			this._log.warn("Processed a fishy filename:", filename);
			return path.join(this.cwd, "octave-workspace"); // an arbitrary legal path
		}
		return candidate;
	}
}

module.exports = WorkingUtil;


================================================
FILE: back-master/.eslintrc.yml
================================================


================================================
FILE: back-master/.npmrc
================================================
# Please keep this in sync with all other .npmrc files
# SEE: https://github.com/npm/feedback/discussions/864
install-links=false


================================================
FILE: back-master/README.md
================================================
Octave Online Server: Back Server
=================================

This directory contains the source code for the Octave Online Server back server.  This is the "master" process that communicates with the downstream user via Redis and with the GNU Octave subprocess.  Commands dealing with the filesystem are in the *back-filesystem* directory parallel to this directory.

## Setup

There are three modes for the back server.

1. SELinux: Fast, and able to handle many concurrent sessions.
2. Unsafe: Fast and easy, but not recommended with untrusted users. Every Octave process is run without any sandboxing or resource limitations.

Previously, a third mode, "docker", worked by creating a new Docker container for each session. This is no longer supported. Instead, if running with trusted users, you can use a single Docker container and Unsafe mode.

### Option 1: SELinux

Ensure that you are running on CentOS or another distribution of Linux that supports SELinux.  SELinux should come pre-installed on CentOS.

Make and build Octave from source.  Follow a procedure similar to the one put forth in *dockerfiles/build-octave.dockerfile*.

Run `sudo yum install -y selinux-policy-devel policycoreutils-sandbox selinux-policy-sandbox libcgroup-tools`

Ensure that Node.js is installed and the dependencies are downloaded for the shared project:

	$ (cd shared && npm install)

Run all of the following make commands from the projects directory.

- `sudo make install-cgroup`
- `sudo make install-selinux-policy`
- `sudo make install-selinux-bin`
- `sudo make install-site-m`

### Option 2: Unsafe

Follow the Option 2 instructions to build and install Octave from source.  Stop before installing selinux-policy-devel and other selinux packages.

## Running the Back Server

### Debugging

Go to the *back-master* directory and run `DEBUG=* node app.js` to start the back server.  The `DEBUG=*` enables debug logging.

### Production

`node app.js` can be run directly, but consider using `oo.service` in the *entrypoint* directory parallel to this directory.

## Stopping the Back Server

By default, after the back server receives a successful maintenance request, it will wait for all sessions to close, and then cleanup and exit with code 0.

If you wish to cause the back server process to gracefully release all sessions without exiting, you can send the signal SIGUSR1 to the process.

## To-do list

- Update /usr/bin/sandbox according to https://github.com/SELinuxProject/selinux/commit/0f4620d6111838ce78bf5a591bb80c99c9d88730
- If using RHEL, the line "Defaults requiretty" must be commented out.


================================================
FILE: back-master/app.js
================================================
/*
 * Copyright © 2018, Octave Online LLC
 *
 * This file is part of Octave Online Server.
 *
 * Octave Online Server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Octave Online Server is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Octave Online Server.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

"use strict";

const log = require("@oo/shared").logger("app");
const mlog = require("@oo/shared").logger("app:minor");
const hostname = require("@oo/shared").hostname();
const MessageTranslator = require("./src/message-translator");
const RedisMessenger = require("@oo/shared").RedisMessenger;
const SessionManager = require("./src/session-manager");
const config = require("@oo/shared").config;
const gcStats = (require("@sematext/gc-stats"))();
const fs = require("fs");
const path = require("path");
const async = require("async");
const http = require("http");

process.stdout.write("Process ID: " + process.pid + "\n");
process.stderr.write("Process ID: " + process.pid + "\n");
log.info("Process ID:", process.pid);
log.info("Hostname:", hostname);
log.log(process.env);

var sessionManager, mainImpl, personality;
if (fs.existsSync(config.rackspace.personality_filename)) {
	personality = JSON.parse(fs.readFileSync(config.rackspace.personality_filename, "utf8"));
	log.info("Personality:", personality.flavor, personality);
	sessionManager = new SessionManager(true);
	mainImpl = require("./src/main-flavor");
} else if (process.env["OO_FLAVOR_OVERRIDE"]) {
	personality = { flavor: process.env["OO_FLAVOR_OVERRIDE"] };
	log.info("Flavor override:", personality.flavor);
	sessionManager = new SessionManager(true);
	mainImpl = require("./src/main-flavor");
} else {
	log.info("No personality file found");
	personality = null;
	sessionManager = new SessionManager(false);
	mainImpl = require("./src/main-pool");
}

let sessionLogDirCount = 0;
function makeSessionLogDir(tokens) {
	if (tokens.length === config.worker.sessionLogs.depth) {
		const dirname = path.join(config.worker.logDir, config.worker.sessionLogs.subdir, ...tokens);
		if (sessionLogDirCount % 1000 === 0) {
			mlog.trace(dirname);
		}
		sessionLogDirCount++;
		fs.mkdirSync(dirname, { recursive: true });
	} else {
		for (let a of "0123456789abcdef") {
			makeSessionLogDir(tokens.concat([a]));
		}
	}
}
log.info("Creating session log dirs…");
makeSessionLogDir([]);
log.info(sessionLogDirCount, "dirs touched");

const redisInputHandler = new RedisMessenger().subscribeToInput();
const redisDestroyDHandler = new RedisMessenger().subscribeToDestroyD();
const redisExpireHandler = new RedisMessenger().subscribeToExpired();
const redisScriptHandler = new RedisMessenger().enableSessCodeScriptsSync();
const redisMessenger = new RedisMessenger();
const translator = new MessageTranslator();

redisInputHandler.on("message", translator.fromDownstream.bind(translator));
sessionManager.on("message", translator.fromUpstream.bind(translator));

translator.on("for-upstream", (sessCode, name, getData) => {
	const session = sessionManager.get(sessCode);

	// Stop processing this message if it doesn't have to do with a session running on this node.
	if (!session) return;

	// Now we can safely continue.  The following method will download the data from Redis.
	session.enqueueMessage(name, getData);
});

translator.on("for-downstream", (sessCode, name, content) => {
	log.trace("Sending Downstream:", sessCode, name);
	redisMessenger.output(sessCode, name, content);
});

translator.on("destroy", (sessCode, reason) => {
	log.debug("Received Destroy:", sessCode);
	sessionManager.destroy(sessCode, reason);
});

translator.on("ping", (code) => {
	// Not currently used
	log.debug("Received Ping:", code);
	redisMessenger.output(code, "pong", { hostname });
});

redisDestroyDHandler.on("destroy-d", (sessCode, reason) => {
	if (!sessionManager.get(sessCode)) return;
	log.info("Received Destroy-D:", sessCode, reason);
	sessionManager.destroy(sessCode, reason);
});

redisExpireHandler.on("expired", (sessCode, channel) => {
	if (!sessionManager.get(sessCode)) return;
	log.info("Received Expire:", sessCode, channel);
	sessionManager.destroy(sessCode, "Octave Session Expired (downstream)");
});

sessionManager.on("touch", (sessCode, start) => {
	redisMessenger.touchOutput(sessCode);
	if (personality) {
		redisMessenger.output(sessCode, "oo.touch-flavor", {
			start,
			current: new Date().valueOf(),
			flavor: personality.flavor
		});
	}
});

sessionManager.on("live", (sessCode) => {
	redisMessenger.setLive(sessCode);
});

sessionManager.on("destroy-u", (sessCode, reason) => {
	log.info("Sending Destroy-U:", reason, sessCode);
	redisMessenger.destroyU(sessCode, reason);
});

gcStats.on("stats", (stats) => {
	mlog.trace(`Garbage Collected (type ${stats.gctype}, ${stats.pause/1e6} ms)`);
});

const healthServer = http.createServer((req, res) => {
	if (sessionManager.isHealthy()) {
		res.writeHead(200);
	} else {
		res.writeHead(503);
	}
	res.end();
}).listen(config.gcp.health_check_port);

mainImpl.start({
	sessionManager,
	redisScriptHandler,
	redisMessenger,
	personality
}, (err) => {
	log.error("Main-impl ended", err);
	doExit();
});

function doExit() {
	sessionManager.terminate("Server Maintenance");
	mainImpl.doExit();

	setTimeout(() => {
		redisInputHandler.close();
		redisDestroyDHandler.close();
		redisExpireHandler.close();
		redisScriptHandler.close();
		redisMessenger.close();
		healthServer.close();
	}, 5000);
}

function doGracefulExit() {
	log.info("RECEIVED SIGUSR1.  Will not accept any further sessions.");
	mainImpl.doExit();
	sessionManager.disablePool();
	async.series([
		(_next) => {
			async.whilst(
				() => { return sessionManager.numActiveSessions() > 0; },
				(next) => { setTimeout(next, config.maintenance.pauseDuration); },
				_next
			);
		},
		(_next) => {
			log.info("All user sessions are closed. Send SIGINT to fully terminate.");
			_next(null);
		}
	], (err) => {
		if (err) log.error("Error during graceful exit:", err);
	});
}

function doFastExit() {
	log.info("RECEIVED SIGNAL.  Starting exit procedure.");
	doExit();
}

process.on("SIGINT", doFastExit);
process.on("SIGHUP", doFastExit);
process.on("SIGTERM", doFastExit);
process.on("SIGUSR1", doGracefulExit);

//const heapdump = require("heapdump");
//setInterval(() => { heapdump.writeSnapshot("/srv/oo/logs/heap/" + hostname + "." + process.pid + "." + Date.now() + ".heapsnapshot"); }, 30000);


================================================
FILE: back-master/package.json
================================================
{
  "name": "@oo/back",
  "version": "0.0.0",
  "description": "Spawns Octave sessions and passes messages",
  "main": "app.js",
  "scripts": {},
  "author": "Octave Online LLC",
  "license": "AGPL-3.0",
  "private": true,
  "engines": {
    "node": "18.x"
  },
  "dependencies": {
    "@oo/shared": "file:../shared",
    "@sematext/gc-stats": "^1.5.8",
    "async": "^1.5.2",
    "base-x": "^3.0.8",
    "ps-tree": "^1.2.0",
    "temp": "^0.8.4",
    "tmp": "0.0.28",
    "uuid": "^2.0.1"
  }
}


================================================
FILE: back-master/src/capped-file-system.js
================================================
/*
 * Copyright © 2018, Octave Online LLC
 *
 * This file is part of Octave Online Server.
 *
 * Octave Online Server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Octave Online Server is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Octave Online Server.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

"use strict";

const async = require("async");
const temp = require("temp");
const child_process = require("child_process");
const fs = require("fs");
const path = require("path");
const logger = require("@oo/shared").logger;
const OnlineOffline = require("@oo/shared").OnlineOffline;
const config = require("@oo/shared").config;

// This file is based on http://souptonuts.sourceforge.net/quota_tutorial.html

const IMG_FILE_NAME = "img.ext3";
const IMG_MNT_DIR = "mnt";
const IMG_DATA_DIR = "data";

class CappedFileSystem extends OnlineOffline {
	constructor(sessCode, size) {
		super();
		this.sessCode = sessCode;
		this._log = logger("capped-file-system:" + sessCode);
		this._mlog = logger("capped-file-system:" + sessCode + ":minor");

		this._size = size;
	}

	_doCreate(next) {
		this._cleanups = [];

		async.series([
			(_next) => {
				this._mlog.trace("Making temp dir...");
				temp.mkdir("oo-", (err, tmpdir) => {
					if (tmpdir) this._tmpdir = tmpdir;
					if (!err) this._cleanups.unshift((__next) => {
						this._mlog.trace("Removing temp dir...");
						fs.rmdir(tmpdir, __next);
					});
					_next(err);
				});
			},
			(_next) => {
				this._mlog.debug("Created temp dir:", this._tmpdir);
				this._mlog.trace("Allocating space for filesystem...");
				const imgFileName = path.join(this._tmpdir, IMG_FILE_NAME);
				// eslint-disable-next-line no-unused-vars
				child_process.execFile("dd", ["if=/dev/zero", `of=${imgFileName}`, "bs=1k", `count=${this._size}`], (err, stdout, stderr) => {
					if (!err) this._cleanups.unshift((__next) => {
						this._mlog.trace("Removing file system...");
						fs.unlink(imgFileName, __next);
					});
					_next(err);
				});
			},
			(_next) => {
				this._mlog.trace("Formatting file system...");
				const imgFileName = path.join(this._tmpdir, IMG_FILE_NAME);
				child_process.execFile("mkfs", ["-t", "ext3", "-q", imgFileName, "-F"], (err, stdout, stderr) => {
					if (stderr) err = new Error(stderr);
					_next(err);
				});
			},
			(_next) => {
				this._mlog.trace("Creating mount directory...");
				const imgMntDir = path.join(this._tmpdir, IMG_MNT_DIR);
				fs.mkdir(imgMntDir, 0o700, (err) => {
					if (!err) this._cleanups.unshift((__next) => {
						this._mlog.trace("Removing mount directory...");
						fs.rmdir(imgMntDir, __next);
					});
					_next(err);
				});
			},
			(_next) => {
				this._mlog.trace("Mounting file system...");
				const imgFileName = path.join(this._tmpdir, IMG_FILE_NAME);
				const imgMntDir = path.join(this._tmpdir, IMG_MNT_DIR);
				child_process.execFile("sudo", ["mount", "-o", "loop,rw", imgFileName, imgMntDir], (err, stdout, stderr) => {
					if (stderr) err = new Error(stderr);
					if (!err) this._cleanups.unshift((__next) => {
						this._mlog.trace("Unmounting file system...");
						child_process.execFile("sudo", ["umount", imgMntDir], __next);
					});
					_next(err);
				});
			},
			(_next) => {
				this._mlog.trace("Claiming ownership of file system root...");
				const imgMntDir = path.join(this._tmpdir, IMG_MNT_DIR);
				child_process.execFile("sudo", ["chown", config.worker.uid+":"+config.worker.uid, imgMntDir], (err, stdout, stderr) => {
					if (stderr) err = new Error(stderr);
					_next(err);
				});
			},
			(_next) => {
				this._mlog.trace("Creating data directory...");
				const imgDataDir = path.join(this._tmpdir, IMG_MNT_DIR, IMG_DATA_DIR);
				fs.mkdir(imgDataDir, 0o700, (err) => {
					// Cleanup function not necessary here because the directory resides in the guest filesystem
					_next(err);
				});
			}
		], (err) => {
			const imgDataDir = path.join(this._tmpdir, IMG_MNT_DIR, IMG_DATA_DIR);
			this.dir = imgDataDir;
			return next(err, imgDataDir);
		});
	}

	_doDestroy(next) {
		async.series(this._cleanups, (err) => {
			if (err) return next(err);
			this._enabled = false;
			this._cleanups = null;
			this._tmpdir = null;
			this.dir = null;
			return next(null);
		});
	}
}

/// An alternative to CappedFileSystem when sudo is unavailable.
/// This class does *not* limit file sizes.
class TmpWorkDirectory extends OnlineOffline {
	constructor(sessCode) {
		super();
		this.sessCode = sessCode;
		this._mlog = logger("tmp-work-directory:" + sessCode + ":minor");
	}

	_doCreate(next) {
		this._cleanups = [];

		async.series([
			(_next) => {
				this._mlog.trace("Making directory...");
				temp.mkdir("oo-", (err, tmpdir) => {
					if (tmpdir) this.dir = tmpdir;
					if (!err) this._cleanups.unshift((__next) => {
						this._mlog.trace("Removing directory...");
						child_process.execFile("rm", ["-rf", tmpdir], __next);
					});
					this._mlog.debug("Created directory:", this.dir);
					_next(err);
				});
			},
		], (err) => {
			return next(err, this.dir);
		});
	}

	_doDestroy(next) {
		async.series(this._cleanups, (err) => {
			if (err) return next(err);
			this._enabled = false;
			this._cleanups = null;
			this.dir = null;
			return next(null);
		});
	}
}

module.exports = {
	CappedFileSystem,
	TmpWorkDirectory
};


================================================
FILE: back-master/src/docker-handler.js
================================================
/*
 * Copyright © 2018, Octave Online LLC
 *
 * This file is part of Octave Online Server.
 *
 * Octave Online Server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Octave Online Server is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Octave Online Server.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

"use strict";

const async = require("async");
const child_process = require("child_process");
const logger = require("@oo/shared").logger;
const StdioMessenger = require("@oo/shared").StdioMessenger;

class DockerHandler extends StdioMessenger {
	constructor(sessCode, dockerImage) {
		super();
		this._log = logger(`docker-handler:${dockerImage}:${sessCode}`);
		this.sessCode = sessCode;
	}

	_doCreate(next, dockerArgs) {
		async.series([
			(_next) => {
				// Create the session
				this._spwn = child_process.spawn("docker", dockerArgs);
				this._log.trace("Docker args:", dockerArgs.join(" "));
				this._log.debug("Launched process with ID:", this._spwn.pid);

				// Create stderr listener
				this._spwn.stderr.on("data", this._handleLog.bind(this));

				// Create exit listener
				this._spwn.on("exit", this._handleExit.bind(this));

				// Listen to main read stream
				this.setReadStream(this._spwn.stdout);

				// Wait until we get an acknowledgement before continuing.  Two conditions: receipt of the acknowledgement message, and premature exit.
				var ack = false;
				this.once("message", (name /*,  content */) => {
					if (ack) return;
					ack = true;

					// Error if the message is docker-exit
					if (name === "docker-exit") return _next(new Error("Process exited prematurely"));

					// Don't enable the write stream until down here because we don't want to write messages to the child's STDIN until we've acknowledged that it is online
					this.setWriteStream(this._spwn.stdin);
					_next(null);
				});
			}
		], (err) => {
			if (err) return next(err);
			this._log.debug("Finished creating");
			return next(null);
		});
	}

	_doDestroy(next) {
		// Since the child process is actually the docker client and not the daemon, the SIGKILL will never get forwarded to the actual octave host process.  We need to delegate the task to docker.
		child_process.execFile("docker", ["stop", "-t", 0, this._dockerName], (err, stdout, stderr) => {
		// child_process.execFile("docker", ["rm", "-f", this._dockerName], (err, stdout, stderr) => {
			if (err) this._log.warn(err, stderr);
			this._log.debug("Finished destroying");
			return next(null);
		});
	}

	signal(name) {
		if (this._state !== "ONLINE") return this._log.warn("Will not send SIGINT to child process: process not online");

		// Although the child process is actually the docker client and not the daemon, the client will forward simple signals like SIGINT to the actual octave host process.
		this._spwn.kill(name);
		this._log.debug("Sent " + name + " to child process");
	}

	_handleLog(data) {
		// Log message to console
		data.toString().trim().split("\n").forEach((line) => {
			this._log.log(line);
		});

		// Special handling of certain messages
		// TODO: Make this message get sent from host.c instead of from here
		if (/Process exited with status 0, signal 9/.test(data)) {
			this.emit("message", "octave-killed");
		}
	}

	_handleExit(code, signal) {
		this._log.debug("Docker Exit:", code, signal);
		this.emit("message", "docker-exit", { code, signal });
	}
}

module.exports = DockerHandler;


================================================
FILE: back-master/src/main-flavor.js
================================================
/*
 * Copyright © 2019, Octave Online LLC
 *
 * This file is part of Octave Online Server.
 *
 * Octave Online Server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Octave Online Server is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Octave Online Server.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

// This file contains the main loop for flavor (dedicated) servers.

const log = require("@oo/shared").logger("main-flavor");
const mlog = require("@oo/shared").logger("main-flavor:minor");
const config = require("@oo/shared").config;
const config2 = require("@oo/shared").config2;
const RedisMessenger = require("@oo/shared").RedisMessenger;
const MaintenanceRequestFlavorManager = require("./maintenance-request-manager");
const runMaintenance = require("./maintenance");
const async = require("async");
const rackOperations = require("@oo/shared/rack/operations");

var redisFlavorStatusHandler,
	flavorStatusManager;

var ACCEPT_CONS = true;
var statusTimer;

function start(globals, next) {
	async.parallel([
		(_next) => {
			startConnectionAcceptLoop(globals, _next);
		},
		(_next) => {
			startLifetimeLoop(globals, _next);
		}
	], next);
}

function startConnectionAcceptLoop(globals, next) {
	let { sessionManager, redisScriptHandler, personality } = globals;
	async.during(
		(_next) => {
			if (!ACCEPT_CONS) return _next(null, false);
			async.waterfall([
				(__next) => {
					if (sessionManager.canAcceptNewSessions()) {
						redisScriptHandler.getSessCodeFlavor(personality.flavor, (err, sessCode, content) => {
							if (err) log.error("Error getting sessCode:", err);
							__next(null, sessCode, content);
						});
					} else {
						process.nextTick(() => {
							__next(null, null, null);
						});
					}
				},
				(sessCode, content, __next) => {
					if (sessCode) {
						async.waterfall([
							(___next) => {
								log.info("Received Session:", sessCode);
								content.tier = "_maxima";
								sessionManager.attach(sessCode, content);
								sessionManager.disablePool();
								flavorStatusManager.stop();
								flavorStatusManager.ignoreAll();
								clearTimeout(statusTimer);
								sessionManager.once("destroy-done", (_sessCode) => {
									___next(null, _sessCode);
								});
							},
							(_sessCode, ___next) => {
								if (sessionManager.numActiveSessions() !== 0) {
									log.error("Active sessions when session was closed");
								}
								if (sessCode !== _sessCode) {
									log.error("sessCode changed:", sessCode, _sessCode);
								}
								sessionManager.terminate("Server Maintenance");
								setTimeout(___next, config.maintenance.pauseDuration);
							},
							(___next) => {
								runMaintenance(___next);
							}
						], (err) => {
							__next(err, false);
						});
					} else {
						__next(null, true);
					}
				},
			], _next);
		},
		(_next) => {
			let delay = Math.floor(config.worker.clockInterval.min + Math.random()*(config.worker.clockInterval.max-config.worker.clockInterval.min));
			setTimeout(_next, delay);
		},
		(err) => {
			mlog.info("Connection-accepting loop ended");
			return next(err);
		}
	);
}

function startLifetimeLoop(globals, next) {
	let { sessionManager, redisMessenger, personality } = globals;
	const flavorConfig = config2.flavor(personality.flavor);
	flavorStatusManager = new MaintenanceRequestFlavorManager(flavorConfig.defaultClusterSize);
	redisFlavorStatusHandler = new RedisMessenger().subscribeToFlavorStatus(personality.flavor);
	redisFlavorStatusHandler.on("flavor-status", (...args) => {
		flavorStatusManager.onMessage(...args);
	});
	flavorStatusManager.on("request-maintenance", (...args) => {
		redisMessenger.requestFlavorStatus(personality.flavor, ...args);
	});
	flavorStatusManager.on("reply-to-maintenance-request", (...args) => {
		redisMessenger.replyToFlavorStatus(personality.flavor, ...args);
	});

	// In a flavor cluster, when we get approval from peers, we remove ourself from the cluster permanently in order to save on idle time costs. New servers will be added to the cluster when needed (on demand).
	async.forever(
		(_next) => {
			async.series([
				(__next) => {
					statusTimer = setTimeout(__next, flavorConfig.idleTime);
				},
				(__next) => {
					flavorStatusManager.beginRequesting(flavorConfig.statusInterval);
					flavorStatusManager.once("maintenance-accepted", __next);
				},
				(__next) => {
					sessionManager.disablePool();
					if (sessionManager.numActiveSessions() !== 0) {
						log.warn("Active sessions when flavor maintenance was approved");
						return;
					}
					sessionManager.terminate("Server Maintenance");
					statusTimer = setTimeout(__next, config.maintenance.pauseDuration);
				},
				(__next) => {
					// TODO: Move this call somewhere it could be configurable.
					rackOperations.deleteSelf(personality, __next);
				}
			], (err) => {
				_next(err);
			});
		},
		(err) => {
			log.info("Lifetime loop ended");
			return next(err);
		}
	);
}

function doExit() {
	clearTimeout(statusTimer);
	flavorStatusManager.stop();
	ACCEPT_CONS = false;

	setTimeout(() => {
		redisFlavorStatusHandler.close();
	}, 5000);
}

module.exports = {
	start,
	doExit
};


================================================
FILE: back-master/src/main-pool.js
================================================
/*
 * Copyright © 2019, Octave Online LLC
 *
 * This file is part of Octave Online Server.
 *
 * Octave Online Server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Octave Online Server is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Octave Online Server.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

// This file contains the main loop for normal pool servers.

const log = require("@oo/shared").logger("main-pool");
const config = require("@oo/shared").config;
const RedisMessenger = require("@oo/shared").RedisMessenger;
const MaintenanceRequestFlavorManager = require("./maintenance-request-manager");
const runMaintenance = require("./maintenance");
const async = require("async");

const redisMaintenanceHandler = new RedisMessenger().subscribeToRebootRequests();
const maintenanceRequestManager = new MaintenanceRequestFlavorManager();

var ACCEPT_CONS = true;
var maintenanceTimer;

// Main loops
function start(globals, next) {
	async.parallel([
		(_next) => {
			startConnectionAcceptLoop(globals, _next);
		},
		(_next) => {
			startMaintenanceLoop(globals, _next);
		}
	], next);
}

function startConnectionAcceptLoop(globals, next) {
	let { sessionManager, redisScriptHandler } = globals;
	async.forever(
		(_next) => {
			if (!ACCEPT_CONS) return;
			async.waterfall([
				(__next) => {
					let fraction;
					if (config.worker.clockStrategy === "random") {
						fraction = Math.random();
					} else {
						fraction = sessionManager.usagePercent();
					}
					let delay = Math.floor(config.worker.clockInterval.min + fraction * (config.worker.clockInterval.max-config.worker.clockInterval.min));
					setTimeout(__next, delay);
				},
				(__next) => {
					if (sessionManager.canAcceptNewSessions()) {
						redisScriptHandler.getSessCode((err, sessCode, content) => {
							if (err) log.error("Error getting sessCode:", err);
							__next(null, sessCode, content);
						});
					} else {
						process.nextTick(() => {
							__next(null, null, null);
						});
					}
				},
				(sessCode, content, __next) => {
					if (sessCode) {
						log.info("Received Session:", sessCode);
						sessionManager.attach(sessCode, content);
					}

					__next(null);
				}
			], _next);
		},
		(err) => {
			log.error("Connection-accepting loop ended");
			return next(err);
		}
	);
}

function startMaintenanceLoop(globals, next) {
	let { sessionManager, redisMessenger } = globals;
	redisMaintenanceHandler.on("reboot-request", maintenanceRequestManager.onMessage.bind(maintenanceRequestManager));
	maintenanceRequestManager.on("request-maintenance", redisMessenger.requestReboot.bind(redisMessenger));
	maintenanceRequestManager.on("reply-to-maintenance-request", redisMessenger.replyToRebootRequest.bind(redisMessenger));
	async.forever(
		(_next) => {
			async.series([
				(__next) => {
					maintenanceTimer = setTimeout(__next, config.maintenance.interval);
				},
				(__next) => {
					maintenanceRequestManager.beginRequesting(config.maintenance.requestInterval);
					maintenanceRequestManager.once("maintenance-accepted", __next);
				},
				(__next) => {
					sessionManager.disablePool();
					async.whilst(
						() => { return sessionManager.numActiveSessions() > 0; },
						(__next) => { maintenanceTimer = setTimeout(__next, config.maintenance.pauseDuration); },
						__next
					);
				},
				(__next) => {
					sessionManager.terminate();
					maintenanceTimer = setTimeout(__next, config.maintenance.pauseDuration);
				},
				(__next) => {
					runMaintenance(__next);
				},
				(__next) => {
					sessionManager.restart();
					maintenanceTimer = setTimeout(__next, config.maintenance.pauseDuration);
				},
				(__next) => {
					maintenanceRequestManager.reset();
					__next();
				}
			], (err) => {
				_next(err);
			});
		},
		(err) => {
			log.error("Maintenance loop ended");
			return next(err);
		}
	);
}

function doExit() {
	clearTimeout(maintenanceTimer);
	maintenanceRequestManager.stop();
	ACCEPT_CONS = false;

	setTimeout(() => {
		redisMaintenanceHandler.close();
	}, 5000);
}

module.exports = {
	start,
	doExit
};


================================================
FILE: back-master/src/maintenance-request-manager.js
================================================
/*
 * Copyright © 2018, Octave Online LLC
 *
 * This file is part of Octave Online Server.
 *
 * Octave Online Server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Octave Online Server is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Octave Online Server.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

"use strict";

const uuid = require("uuid");
const EventEmitter = require("events");
const log = require("@oo/shared").logger("maint-req-manager");
const config = require("@oo/shared").config;

class MaintenanceRequestFlavorManager extends EventEmitter {
	constructor(clusterSize) {
		super();
		if (clusterSize) {
			this._forFlavor = true;
			this._clusterSize = clusterSize;
			this._priority = Math.random();
			log.debug("Flavor Priority:", this._priority);
		}
		this.reset();
	}

	reset() {
		this._responses = {};
		this._ignoreAll = false;
		if (!this._forFlavor) {
			this._priority = 0;
		}
	}

	ignoreAll() {
		this._ignoreAll = true;
	}

	beginRequesting(intervalTime) {
		log.info("Beginning maintenance requests");
		this.reset();
		this._requestInterval = setInterval(this._requestMaintenance.bind(this), intervalTime);
	}

	onMessage(id, isRequest, message) {
		// Has the server has removed itself from the actively responding cluster?
		if (this._ignoreAll) {
			return;
		}

		let isOwnRequest = Object.keys(this._responses).indexOf(id) !== -1;

		if (isRequest && !isOwnRequest) {
			// Reply to the maintenance request.  Reply "yes" only if the requester's priority is higher than our own priority.
			let response = (message.priority > this._priority);
			this.emit("reply-to-maintenance-request", id, response);
		} else if (!isRequest && isOwnRequest) {
			// Someone replied to our own maintenance request.
			this._responses[id].push(message.response);
		}
	}

	stop() {
		if (this._requestInterval) {
			clearInterval(this._requestInterval);
		}
		this._requestInterval = null;
	}

	_requestMaintenance() {
		let id = uuid.v4();
		if (!this._forFlavor) {
			// In flavor status mode, keep a fixed priority at all times. This creates stability and uniqueness that is easy to reason about.
			// In maintenance request mode, make the priority grow as time goes on. This means older servers get first priority to maintenance.
			this._priority += 1;
		}
		this._responses[id] = [];
		this.emit("request-maintenance", id, this._priority);
		log.trace("Sent maintenance request:", id, this._priority);

		setTimeout(() => {
			// Count the number of yeses and nos.
			let numYes = this._responses[id].reduce((s,v) => {
				return s + (v ? 1 : 0);
			}, 0);
			let numNo = this._responses[id].length - numYes;

			let success;
			if (this._forFlavor) {
				// Policy: Guarantee at least _clusterSize online nodes
				success = numYes >= this._clusterSize;
			} else {
				// Policy: Guarantee at least minNodesInCluster online nodes and no more than maxNodesInMaintenance maintenance nodes.
				success = numNo < config.maintenance.maxNodesInMaintenance && numYes >= config.maintenance.minNodesInCluster;
			}

			// Were we successful?
			if (success) {
				log.info("Maintenance request was approved");
				this.emit("maintenance-accepted");
				this._priority = Number.MAX_VALUE;
				clearInterval(this._requestInterval);
			}
			else {
				log.trace("Maintenance request failed; trying again:", id);
			}

			// Dereference responses array
			delete this._responses[id];
		}, config.maintenance.responseWaitTime);
	}
}

module.exports = MaintenanceRequestFlavorManager;


================================================
FILE: back-master/src/maintenance.js
================================================
/*
 * Copyright © 2018, Octave Online LLC
 *
 * This file is part of Octave Online Server.
 *
 * Octave Online Server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Octave Online Server is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Octave Online Server.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

"use strict";

const child_process = require("child_process");
const log = require("@oo/shared").logger("maintenance");
const config = require("@oo/shared").config;

function runMaintenance(next) {
	log.info("Starting Maintenance Routine");

	switch (config.session.implementation) {
		case "docker": {
			let MAINTENANCE_COMMAND = "docker ps -a --filter \"status=exited\" --filter \"ancestor=oo/" + config.docker.images.octaveSuffix + "\" | cut -c -12 | xargs -n 1 docker rm -f; docker ps -a --filter \"status=exited\" --filter \"ancestor=oo/" + config.docker.images.filesystemSuffix + "\" | cut -c -12 | xargs -n 1 docker rm -f";
			log.trace("Running command:", MAINTENANCE_COMMAND);
			child_process.exec(MAINTENANCE_COMMAND, (err, stdout, stderr) => {
				log.info("Finished Maintenance Routine");
				if (err) log.warn(err);
				log.trace(stdout);
				log.trace(stderr);
				next();
			});
			break;
		}

		case "selinux":
		case "unsafe":
			// Exit this process and let the daemon running it clean up and restart
			process.exit(0);
			break;

		default: {
			log.error("Please provide a maintenance command for your implementation");
			break;
		}
	}
}

module.exports = runMaintenance;


================================================
FILE: back-master/src/message-translator.js
================================================
/*
 * Copyright © 2018, Octave Online LLC
 *
 * This file is part of Octave Online Server.
 *
 * Octave Online Server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Octave Online Server is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Octave Online Server.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

"use strict";

const EventEmitter = require("events");
const log = require("@oo/shared").logger("message-translator");
const crypto = require("crypto");
const uuid = require("uuid");
const config = require("@oo/shared").config;

// This class "translates" messages between the older format expected by the downstream front end and the newer format expected by the upstream back ends (Octave host and file manager).

class MessageTranslator extends EventEmitter {

	// When the upstream back ends send us a message:
	fromUpstream(sessCode, name, content) {
		switch(name) {
			// MESSAGES NEEDING TRANSLATION:

			// "request-input" is the newer version of "prompt", which provided a line number as an integer.  The line number needs to be extracted via regex for backwards compatibility.
			case "request-input": {
				let match = content.match(/^octave:(\d+)>\s+$/);
				let line_number = -1;
				if (match) {
					line_number = parseInt(match[1]);
				} else {
					this._forDownstream(sessCode, "data", {
						type: "stdout",
						data: content
					});
				}
				this._forDownstream(sessCode, "prompt", { line_number, prompt: content });
				break;
			}

			// "out" and "err" need to be translated to "data" events
			case "out": {
				this._forDownstream(sessCode, "data", {
					type: "stdout",
					data: content
				});
				break;
			}

			case "err": {
				// Send the error text doenstream
				this._forDownstream(sessCode, "data", {
					type: "stderr",
					data: content
				});
				break;
			}

			// We need only the "ws" part of the "set-workspace" message
			case "set-workspace": {
				this._forDownstream(sessCode, "workspace", {
					vars: content.ws
				});
				break;
			}

			// The new "show-static-plot" needs to be broken into "plotd" (plot data) and "plote" (plot finished)
			case "show-static-plot": {
				let id = uuid.v4();
				this._forDownstream(sessCode, "plotd", {
					id: id,
					content: content.content
				});
				this._forDownstream(sessCode, "plote", {
					id: id,
					md5: crypto.createHash("md5").update(content.content).digest("hex"),
					command_number: content.command_number
				});
				break;
			}

			// "clc" control command:
			case "clear-screen": {
				this._forDownstream(sessCode, "ctrl", {
					command: "clc"
				});
				break;
			}

			// "doc" control command:
			case "show-doc": {
				var url = content ? `https://octave.sourceforge.io/list_functions.php?q=${encodeURIComponent(content)}` : "https://octave.sourceforge.io/octave/overview.html";
				this._forDownstream(sessCode, "ctrl", {
					command: `url=${url}`
				});
				break;
			}

			// When come other command was suppressed due to length:
			case "message-too-long": {
				if (content.name === "show-static-plot") {
					log.trace("Plot message too long:", content);
					this._forDownstream(sessCode, "data", {
						type: "stderr",
						data: `Warning: Suppressed a large plot (${content.length} bytes).\nMaximum allowable length is ${content.max_length} bytes.\nTip: Try running "clf".  If that does not work,\ntry generating a rasterized plot (e.g., imagesc)\ninstead of a vector plot.\n`
					});
				} else {
					log.warn("Unknown message too long:", content);
				}
				break;
			}

			// The "exit" event from octave_link:
			case "exit": {
				this._forDownstream(sessCode, "data", {
					type: "exit",
					code: content
				});
				break;
			}

			// The "exit" event from the child process:
			case "docker-exit":
			case "process-exit": {
				this.emit("destroy", sessCode, "Shell Exited");
				break;
			}

			// The event for when the Octave process is killed:
			case "octave-killed": {
				this._forDownstream(sessCode, "data", {
					type: "stderr",
					data: "Error: Octave process killed.\nYou may have been using too much memory.\nYour memory cap is: " + config.docker.memoryShares + "\n"
				});
				break;
			}

			// Turn "destroy" into "destroy" on this instance
			case "destroy": {
				this.emit("destroy", sessCode, content);
				break;
			}

			// Filesystem events: if any of them fail, do not let the events bubble up, but show their error messages on stderr
			case "saved":
			case "renamed":
			case "deleted": {
				// FIXME: The rendering of error messages should occur on the client side, not here.
				if (content && !content.success) {
					this._forDownstream(sessCode, "data", {
						type: "stderr",
						data: content.message+"\n"
					});
					break;
				} else {
					this._forDownstream(sessCode, name, content);
					break;
				}
			}

			// File list event (change name from "filelist" to "user")
			case "filelist": {
				this._forDownstream(sessCode, "user", content);
				break;
			}

			// MESSAGES THAT CAN BE IGNORED:
			case "ack":
			case "set-history": {
				break;
			}

			// REMAINING MESSAGES:
			default: {
				this._forDownstream(sessCode, name, content);
				break;
			}
		}
	}

	// When the downstream client sends us a message:
	fromDownstream(sessCode, name, getData) {
		switch(name) {
			// MESSAGES NEEDING TRANSLATION:

			// "data" needs to be translated to the "cmd" event (which is a synonym for "request-input-answer")
			case "data":
				this._forUpstream(sessCode, "cmd", getData);
				break;

			// Translate "signal" to "interrupt"
			case "signal":
				this._forUpstream(sessCode, "interrupt", getData);
				break;

			// Emit ping/pong as an event
			case "oo.ping":
				this.emit("ping", sessCode, getData);
				break;
			case "oo.pong":
				this.emit("pong", sessCode, getData);
				break;

			// MESSAGES THAT CAN BE IGNORED:
			case "init":
			case "ot.cursor":
			case "ot.change":
			case "oo.reconnect":
				break;

			// REMAINING MESSAGES:
			default:
				this._forUpstream(sessCode, name, getData);
				break;
		}
	}

	_forDownstream(sessCode, name, content) {
		this.emit("for-downstream", sessCode, name, content);
	}

	_forUpstream(sessCode, name, getData) {
		this.emit("for-upstream", sessCode, name, getData);
	}
}

module.exports = MessageTranslator;


================================================
FILE: back-master/src/octave-session.js
================================================
/*
 * Copyright © 2018, Octave Online LLC
 *
 * This file is part of Octave Online Server.
 *
 * Octave Online Server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Octave Online Server is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Octave Online Server.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

"use strict";

// The code in this file is shared among all implementations of the Octave session.  See session-impl.js for examples of implementations.

const logger = require("@oo/shared").logger;
const OnlineOffline = require("@oo/shared").OnlineOffline;
const config = require("@oo/shared").config;
const config2 = require("@oo/shared").config2;
const timeLimit = require("@oo/shared").timeLimit;
const fs = require("fs");
const path = require("path");
const async = require("async");
const url = require("url");
const http = require("http");
const https = require("https");
const querystring = require("querystring");
const uuid = require("uuid");
const RedisQueue = require("@oo/shared").RedisQueue;
const base58 = require("base-x")("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
const temp = require("temp");
const onceMessage = require("@oo/shared").onceMessage;
const child_process = require("child_process");

class OctaveSession extends OnlineOffline {
	constructor(sessCode, options) {
		super();
		this.sessCode = sessCode;
		this._options = options;
		this._log = logger("octave-session:" + sessCode);
		this._mlog = logger("octave-session:" + sessCode + ":minor");

		this._log.debug("Tier:", this._options.tier);

		this._extraTime = 0;
		this._countdownExtraTime = config2.tier(this._options.tier)["session.countdownExtraTime"];
		this._countdownRequestTime = config2.tier(this._options.tier)["session.countdownRequestTime"];

		this._legalTime = config.session.legalTime.guest;
		this._payloadLimit = config.session.payloadLimit.guest;
		this._resetPayload();

		this._plotPngStore = {};
		this._plotSvgStore = {};

		this._suppressedWarningsStore = {};

		this._redisQueue = new RedisQueue(sessCode);
		this._redisQueue.on("message", this.sendMessage.bind(this));

		this._throttleCounter = 0;
		this._throttleTime = process.hrtime();

		this.on("error", this._handleError.bind(this));
	}

	_doCreate(next) {
		let subdir = path.join(config.worker.logDir, config.worker.sessionLogs.subdir);
		for (let i=0; i<config.worker.sessionLogs.depth; i++) {
			subdir = path.join(subdir, this.sessCode[i]);
		}
		let sessionLogPath = path.join(subdir, `${this.sessCode}.log`);
		this._mlog.trace("Storing session log in:", sessionLogPath);
		this._sessionLogStream = fs.createWriteStream(sessionLogPath);
		this._doCreateImpl(next);
	}

	_doDestroy(next, reason) {
		this._mlog.trace("Starting Destroy Procedure:", reason);
		async.series([
			(_next) => {
				if (this._countdownTimer) clearTimeout(this._countdownTimer);
				if (this._timewarnTimer) clearTimeout(this._timewarnTimer);
				if (this._timeoutTimer) clearTimeout(this._timeoutTimer);
				if (this._autoCommitTimer) clearInterval(this._autoCommitTimer);
				if (this._payloadInterruptTimer) clearTimeout(this._payloadInterruptTimer);
				_next(null);
			},
			(_next) => {
				this._doDestroyImpl(_next, reason);
			},
			(_next) => {
				if (this._sessionLogStream) this._sessionLogStream.end(reason);
				_next(null);
			}
		], next);
	}

	interrupt() {
		this._signal("SIGINT");
	}

	enqueueMessage(name, getData) {
		this._redisQueue.enqueueMessage(name, getData);
	}

	// COUNTDOWN METHODS: For interrupting the Octave kernel after a fixed number of seconds to ensure a fair distribution of CPU time.
	// Use an interval to signal Octave once after the first timeout and then repeatedly after that, until the kernel sends us a "request-input" event to signal that it is done processing commands.
	_startCountdown() {
		if (this._countdownTimer) return;
		if (this._state !== "ONLINE") return;

		this._countdownTimer = setTimeout(this._onCountdownEnd.bind(this), this._legalTime);
	}
	_endCountdown() {
		if (this._countdownTimer) {
			clearTimeout(this._countdownTimer);
			this._countdownTimer = null;
		}
	}
	_onCountdownEnd() {
		if (new Date().valueOf() - this._extraTime < this._countdownRequestTime + config.session.countdownRequestTimeBuffer) {
			// Add 15 seconds and don't send an interrupt signal
			this._log.trace("Extending countdown with extra time");
			this._countdownTimer = setTimeout(this._onCountdownEnd.bind(this), this._countdownExtraTime);
		} else {
			// Send an interrupt signal now and again in 5 seconds
			this._log.trace("Interrupting execution due to countdown");
			this.interrupt();
			this.emit("message", "err", "!!! OUT OF TIME !!!\n");
			this._countdownTimer = setTimeout(this._onCountdownEnd.bind(this), 5000);
		}
	}
	_addTime() {
		// This method gets called when the user clicks the "Add 15 Seconds" button on the front end.
		this._extraTime = new Date().valueOf();
	}

	// TIMEOUT METHODS: For killing the Octave kernel after a fixed number of seconds to clear server resources when the client is inactive.
	resetTimeout() {
		if (this._state !== "ONLINE") return;
		if (this._timewarnTimer) clearTimeout(this._timewarnTimer);
		if (this._timeoutTimer) clearTimeout(this._timeoutTimer);
		const timewarnTime = config2.tier(this._options.tier)["session.timewarnTime"];
		const timeoutTime = config2.tier(this._options.tier)["session.timeoutTime"];
		this._mlog.trace("Resetting timeout:", timewarnTime, timeoutTime);
		this._timewarnTimer = setTimeout(() => {
			this.emit("message", "err", config.session.timewarnMessage+"\n");
		}, timewarnTime);
		this._timeoutTimer = setTimeout(() => {
			this._log.info("Session Timeout");
			this.emit("message", "destroy", "Session Timeout");
		}, timeoutTime);
	}

	// PAYLOAD METHODS: For interrupting the Octave kernel after a large amount of stdout/stderr data to prevent infinite loops from using too much bandwidth.
	_resetPayload() {
		this._payloadSize = 0;
		this._payloadInterrupted = false;
	}
	_appendToPayload(content) {
		this._payloadSize += content.length;
		if (this._payloadSize > this._payloadLimit && !this._payloadInterrupted) {
			this._payloadInterrupted = true;

			// End the countdown, and instead give the user a specified amount of time to allow the process to continue from where it left off.
			this._signal("SIGSTOP");
			this._endCountdown();
			let payloadDelay = config.session.payloadAcknowledgeDelay;
			this._payloadInterruptTimer = setTimeout(() => {
				this._signal("SIGCONT");
				this._signal("SIGINT");

				// Send the error message after a small delay in order to let the output buffers flush first
				setTimeout(() => {
					this.emit("message", "err", "!!! PAYLOAD TOO LARGE !!!\n");

					// Octave sometimes gets confused with the interrupt signal, so send an empty command to reset things.
					this._sendMessageToHost("cmd", "");
				}, config.session.payloadMessageDelay);
			}, payloadDelay);

			// Tell the user how much time they have.
			this.emit("message", "payload-paused", {
				delay: payloadDelay
			});
		}
	}
	_acknowledgePayload() {
		if (!this._payloadInterrupted) return this._log.warn("Attempting to acknowledge payload, but process is not currently paused");
		this._log.trace("User manually acknowledged payload");
		this._continueIfPaused();
		this._resetPayload();
	}
	_continueIfPaused() {
		if (!this._payloadInterrupted) return;
		this._log.trace("Continuing execution");
		clearTimeout(this._payloadInterruptTimer);
		this._signal("SIGCONT");
		this._startCountdown();
	}

	// AUTO-COMMIT METHODS: For auto-committing the user's files on a fixed interval.
	_startAutoCommitLoop() {
		this._autoCommitTimer = setInterval(() => {
			this._log.debug("Requesting auto-commit...");
			this._commit("Scripted auto-commit", this._handleError.bind(this));
		}, config.git.autoCommitInterval);
	}

	_commit(comment, next) {
		// Set a 60-second time limit
		let _next = timeLimit(config.git.commitTimeLimit, [new Error("Out of time")], next);

		// Call the callback when a "committed" message is received
		this._onceMessageFromFiles("committed", () => { _next(null); });

		// Request the commit
		this._sendMessageToFiles("commit", { comment });
	}

	// SESSION LOG: Log all commands, input, and output to a log file
	_appendToSessionLog(type, content) {
		if (!this._sessionLogStream) return this._log.warn("Cannot log before created", { type, content });
		if (this._sessionLogStream.closed) return this._log.warn("Cannot log to a closed stream:", { type, content });
		this._sessionLogStream.write(type + ": " + content.replace(/\n/g, "\n" + type + ": ") + "\n");
	}

	// PLOTTED PNG IMAGE METHODS: Convert image links to base-64 data URIs
	// TODO: A better way to do this would be to modify GNUPlot to directly save PNG images as base-64 URIs.  I did it this way because I wanted to avoid having to maintain a fork from another major project.
	_convertPlotImages(content) {
		// Search the plot SVG for local PNG files that we need to load
		let imageNames = [];
		let regex = /xlink:href='(\w+).png'/g;
		let match;
		while ((match = regex.exec(content.content))) {
			imageNames.push(match[1]);
		}
		if (imageNames.length === 0) return false;

		// Enqueue the images for loading
		let id = uuid.v4();
		let svgObj = {
			content: content.content,
			command_number: (content.command_number || -1),
			waitCount: 0
		};
		imageNames.forEach((name) => {
			let filename = name + ".png";
			if (filename in this._plotPngStore) {
				return this._log.error("Plot image is already in the queue:", filename);
			}
			this._plotPngStore[filename] = id;
			svgObj.waitCount++;
			// Actually send the read-image job upstream:
			this._sendMessageToFiles("read-delete-binary", { filename });
		});
		this._plotSvgStore[id] = svgObj;
		this._log.debug(`Loading ${svgObj.waitCount} images for plot`, id);
		return true;
	}
	_onDeletedBinary(content) {
		if (content.filename in this._plotPngStore) {
			this._resolvePng(content);
			return true;
		} else if (!content.success) {
			// TODO: Implement a better way to resolve load errors.
			this._log.warn("Failed loading a plot image; discarding all pending plots");
			this._plotPngStore = {};
			this._plotSvgStore = {};
		} else {
			return false;
		}
	}
	_resolvePng(content) {
		let filename = content.filename;
		let base64data = content.base64data;
		let id = this._plotPngStore[filename];
		delete this._plotPngStore[filename];
		let svgObj = this._plotSvgStore[id];
		this._log.trace(`Loaded image '${filename}' for plot`, id);

		// Perform the substitution
		svgObj.content = svgObj.content.replace(`xlink:href='${filename}'`, `xlink:href='data:image/png;base64,${base64data}'`);

		// Have we loaded all of the images we need to replace?
		svgObj.waitCount--;
		if (svgObj.waitCount === 0) {
			this._log.debug("Loaded all images for plot", id);
			this.emit("message", "show-static-plot", {
				content: svgObj.content,
				command_number: svgObj.command_number
			});
			delete this._plotSvgStore[id];
		}
	}

	// URL METHODS: Perform URL requests on behalf of the user.  Uses a hard-coded whitelist in the config file for filtering out legal URLs.
	_handleRequestUrl(content) {
		try {
			let urlObj = url.parse(content.url);

			// Check if the hostname is legal
			if (urlObj.hostname === null) {
				this._sendMessageToHost("request-url-answer", [false, "You must specify a URL of the form http://example.com/"]);
				return;
			}
			let isLegal = false;
			for (let pattern of config.session.urlreadPatterns) {
				if (new RegExp(pattern).test(urlObj.hostname)) {
					isLegal = true;
					break;
				}
			}
			if (!isLegal) {
				this._sendMessageToHost("request-url-answer", [false, `The hostname ${urlObj.hostname} is not whitelisted\nfor access by Octave Online. If you think this hostname\nshould be whitelisted, please open a support ticket.`]);
				return;
			}

			// Convert from the query param list to a query string
			let paramObj = {};
			for (let i=0; i<content.param.length; i+=2) {
				paramObj[content.param[i]] = content.param[i+1];
			}
			let encodedParams = querystring.stringify(paramObj);

			// Set up and perform the request
			let payload = "";
			if (content.action.toLowerCase() === "post") {
				urlObj.method = "POST";
				urlObj.headers = {
					"Content-Type": "application/x-www-form-urlencoded",
					"Content-Length": Buffer.byteLength(encodedParams)
				};
				payload = encodedParams;
			} else {
				urlObj.method = "GET";
				if (urlObj.query) {
					urlObj.query += "&" + encodedParams;
				} else {
					urlObj.query = encodedParams;
				}
				// shouldn't updating the path and href be automatic inside the url module? :/
				urlObj.path = urlObj.pathname + (urlObj.query ? "?" + urlObj.query : "") + (urlObj.hash ? urlObj.hash : "");
				urlObj.href = urlObj.protocol  + "//" + (urlObj.auth ? urlObj.auth + "@" : "") + urlObj.hostname + (urlObj.port ? ":" + urlObj.port : "") + urlObj.path;
			}

			this._log.info("Successfully matched URL", content.url, urlObj);
			this._log.trace("Sending URL request:", urlObj.href);
			let httpLib = (urlObj.protocol === "https:") ? https : http;
			let req = httpLib.request(urlObj, (res) => {
				this._log.trace("Received URL response:", res.statusCode, urlObj.href);
				res.setEncoding("base64");
				let fullResult = "";
				let errmsg = "";
				res.on("data", (chunk) => {
					if (chunk.length + fullResult.length > config.session.urlreadMaxBytes) {
						errmsg = `Requested URL exceeds maximum of ${config.session.urlreadMaxBytes} bytes`;
					} else {
						fullResult += chunk;
					}
				});
				res.on("end", () => {
					this._log.trace("URL response after processing:", errmsg, fullResult.length);
					if (errmsg) {
						this._sendMessageToHost("request-url-answer", [false, errmsg]);
					} else {
						this._sendMessageToHost("request-url-answer", [true, fullResult]);
					}
				});
			});
			req.on("error", (err) => {
				this._log.trace("Problem with URL request:", err.message);
				this._sendMessageToHost("request-url-answer", [false, err.message]);
			});
			req.write(payload);
			req.end();
		} catch(err) {
			this._sendMessageToHost("request-url-answer", [false, err.message]);
		}
	}

	// BUCKET METHODS: Create (and destroy) buckets with snapshots of static files that can be published.
	_createBucket(bucketInfo) {
		let filenames = bucketInfo.filenames;
		if (!Array.isArray(filenames)) return;

		// Create the bucket ID.
		// Note: Starting 2021-08-07, the bucket ID is generated on the front server instead. The if statement here is for backwards compatibility.
		let bucketId = bucketInfo.bucket_id;
		if (!bucketId) {
			const bucketIdBuffer = new Buffer(16);
			uuid.v4({}, bucketIdBuffer, 0);
			bucketId = base58.encode(bucketIdBuffer);
			bucketInfo.bucket_id = bucketId;
		}

		this._log.debug("Creating new bucket:", bucketId, filenames);
		async.auto({
			"read_files": (_next) => {
				// Load the bucket files into memory.
				this._mlog.trace("Reading files for bucket");
				let jobId = uuid.v4();
				this._onceMessageFromFiles("multi-binary:" + jobId, (err, data) => {
					if (!data.success) return _next(new Error("Unsuccessful call to multi-binary"));
					_next(null, data.results);
				}, _next);
				this._sendMessageToFiles("multi-binary", {
					id: jobId,
					filenames: filenames
				});
			},
			"tmpdir": (_next) => {
				// We need to create a working directory for the bucket git
				this._mlog.trace("Creating tmpdir for bucket");
				temp.mkdir("oo-", _next);
			},
			"session": (_next) => {
				// Create a Git session for the new bucket.
				const session = this._makeNewFileSession("create-bucket:" + bucketId);
				session.on("message", (name /*, content */) => {
					this._mlog.trace("Bucket file session message:", name);
				});
				session.on("error", (err) => {
					this._log.error("Bucket file session error:", err);
				});
				_next(null, session);
			},
			// NOTE: In Async 1.5.x, the version used here, the argument order is (_next, results), but in Async 2.x, the argument order changed to (results, _next).
			"session_create": ["tmpdir", "session", (_next, results) => {
				this._mlog.trace("Creating session for bucket");
				results.session.create(_next, results.tmpdir);
			}],
			"session_init": ["session_create", (_next, results) => {
				this._mlog.trace("Initializing session for bucket");
				onceMessage(results.session, "filelist", _next);
				results.session.sendMessage("bucket-info", {
					id: bucketId,
					readonly: false
				});
			}],
			"write_files": ["read_files", "session_init", (_next, results) => {
				this._mlog.trace("Writing files for bucket");
				let jobId = uuid.v4();
				onceMessage(results.session, "multi-binary-saved:" + jobId, (err, data) => {
					if (!data.success) return _next(new Error("Unsuccessful call to save-multi-binary"));
					_next(null);
				});
				results.session.sendMessage("save-multi-binary", {
					id: jobId,
					filenames: filenames,
					base64datas: results.read_files
				});
			}],
			"commit": ["write_files", (_next, results) => {
				this._mlog.trace("Committing files for bucket");
				onceMessage(results.session, "committed", _next);
				results.session.sendMessage("commit", {
					comment: "Scripted bucket creation: " + bucketId
				});
			}],
			"destroy_session": ["commit", (_next, results) => {
				this._mlog.trace("Destroying session for bucket");
				results.session.destroy(_next);
			}],
			"destroy_tmpdir": ["destroy_session", (_next, results) => {
				this._mlog.trace("Destroying working dir bucket");
				child_process.exec(`rm -rf ${results.tmpdir}`, _next);
			}]
		}, (err) => {
			if (err) {
				this._log.error("Error creating bucket:", err);
				this.emit("message", "err", "Encountered an error creating the bucket.\n");
			} else {
				this._log.info("Finished creating new bucket:", bucketId);
				this.emit("message", "bucket-repo-created", bucketInfo);
			}
		});
	}

	// Prevent spammy messages from clogging up the server.
	// TODO: It would be better if this were done deeper in the stack, such as host.c, so that message spamming doesn't reach all the way into the main event loop.
	_checkThrottle() {
		// FIXME: Make these config values.
		// Nominal values: 100 messages per 100 milliseconds (1000 messages/second) = spam.
		// INTERVAL_DURATION should be less than 1e9.
		let MSGS_PER_INTERVAL = 100;
		let INTERVAL_DURATION = 1e8;

		if (++this._throttleCounter < MSGS_PER_INTERVAL) return;

		this._throttleCounter = 0;
		let diff = process.hrtime(this._throttleTime);
		this._throttleTime = process.hrtime();

		if (diff[0] === 0 && diff[1] < INTERVAL_DURATION) {
			this._log.warn("Messages too rapid!  Killing process!", diff);
			this.emit("message", "destroy", "Too Many Packets");
		}
	}

	sendMessage(name, content) {
		switch (name) {
			// Messages requiring special handling
			case "interrupt":
				this._continueIfPaused();
				this.interrupt();
				break;

			case "oo.add_time":
				this._addTime();
				this.resetTimeout();
				break;

			case "oo.acknowledge_payload":
				this._acknowledgePayload();
				this.resetTimeout();
				break;

			case "cmd":
				// FIXME: The following translation (from content to content.data) should be performed in message-translator.js, but we're unable to do so because the data isn't downloaded from Redis until after message-translator is run.  Is there a more elegant place to put this?  Maybe all message translation should happen here in octave-session.js instead?
				content = content.data || "";
				if (typeof content !== "string") {
					this._log.error("content is not a string:", content);
					break;
				}
				this._startCountdown();
				this.resetTimeout();
				this._appendToSessionLog(name, content);
				// Split the command into individual lines and send them to Octave one-by-one.
				content.split("\n").forEach((line) => {
					this._sendMessageToHost(name, line);
				});
				break;

			case "user-info":
				if (content && content.user) {
					this._startAutoCommitLoop();
					this._legalTime = content.user.legalTime;
					this._payloadLimit = content.user.payloadLimit;
					this._countdownExtraTime = content.user.countdownExtraTime;
					this._countdownRequestTime = content.user.countdownRequestTime;
				}
				if (content.bucketId && !content.bucket) {
					// For backwards compatibility
					content.bucket = {
						bucket_id: content.bucketId,
						butype: "readonly",
					};
				}
				if (content.bucket) {
					if (!content.bucket.butype) {
						this._log.error("butype not present in bucket", content);
						content.butype = "readonly";
					}
					this._sendMessageToFiles("bucket-info", {
						id: content.bucket.bucket_id,
						legalTime: this._legalTime, // For backwards compatibility
						readonly: content.bucket.butype === "readonly",
					});
				} else {
					this._sendMessageToFiles(name, content);
				}
				break;

			case "oo.create_bucket":
				this._createBucket(content);
				break;

			// Messages to forward to the file manager
			case "list":
			case "refresh":
			case "commit":
			case "save":
			case "rename":
			case "delete":
			case "binary":
			case "read-delete-binary":
			case "siofu_start":
			case "siofu_progress":
			case "siofu_done":
				this._sendMessageToFiles(name, content);
				break;

			// Messages to forward to the Octave host
			case "request-input-answer":
			case "request-url-answer":
			case "confirm-shutdown-answer":
			case "prompt-new-edit-file-answer":
			case "message-dialog-answer":
			case "question-dialog-answer":
			case "list-dialog-answer":
			case "input-dialog-answer":
			case "file-dialog-answer":
			case "debug-cd-or-addpath-error-answer":
				this._sendMessageToHost(name, content);
				break;

			// Unknown messages
			default:
				this._log.debug("Message ignored:", name);
				break;
		}
	}

	_handleMessage(name, content) {
		// Check for message throttling, except for "out" and "err" messages, which are throttled via payload.
		if (name !== "out" && name !== "err") this._checkThrottle();

		// Special pre-processing of a few events here
		switch (name) {
			case "show-static-plot":
				// Convert PNG file links to embedded base 64 data
				if (this._convertPlotImages(content)) return;
				break;

			case "deleted-binary":
				// If we're waiting for any binary files, capture them here rather than sending them downstream
				if (this._onDeletedBinary(content)) return;
				break;

			case "display-warning":
				let opWarningMatch = /(the '.*' operator)/.exec(content.message);
				if (opWarningMatch) {
					if (this._suppressedWarningsStore[opWarningMatch[0]]) {
						this._mlog.trace("Suppressed duplicate warning:", content.id);
						return;
					}
					this._suppressedWarningsStore[opWarningMatch[0]] = true;
				}
				name = "err";
				content = content.formatted;
				break;

			case "display-exception":
				name = "err";
				content = content.ee_str;
				break;

			default:
				break;
		}
		if (name === "err") {
			// Filter out some error messages
			if (/warning: readline is not linked/.test(content)) return;
			if (/warning: docstring file/.test(content)) return;
			if (/error: unable to open .+macros\.texi/.test(content)) return;
			if (/^\/tmp\/octave-help-/.test(content)) return;
			if (/built-in-docstrings' not found/.test(content)) return;
		}
		if (/^multi-binary:[\w-]+$/.test(name)) return;

		// Forward remaining events downstream
		this.emit("message", name, content);
		this.emit(`msg:${name}`, content);

		// Special post-processing of a few more events here
		switch (name) {
			case "request-input":
				this._endCountdown();
				this.resetTimeout();
				this._resetPayload();
				break;

			case "err":
			case "out":
				this._appendToPayload(content);
				this._appendToSessionLog(name, content);
				break;

			case "request-url":
				this._handleRequestUrl(content);
				break;

			// UNIMPLEMENTED FEATURES REQUIRING RESPONSE:
			case "confirm-shutdown":
				this._sendMessageToHost("confirm-shutdown-answer", true);
				break;
			case "prompt-new-edit-file":
				this._sendMessageToHost("prompt-new-edit-file-answer", true);
				break;
			case "message-dialog":
				this._sendMessageToHost("message-dialog-answer", 0);
				break;
			case "question-dialog":
				this._sendMessageToHost("question-dialog-answer", "");
				break;
			case "list-dialog":
				this._sendMessageToHost("list-dialog-answer", [[],0]);
				break;
			case "input-dialog":
				this._sendMessageToHost("input-dialog-answer", []);
				break;
			case "file-dialog":
				this._sendMessageToHost("file-dialog-answer", []);
				break;
			case "debug-cd-or-addpath-error":
				this._sendMessageToHost("debug-cd-or-addpath-error-answer", 0);
				break;

			default:
				break;
		}
	}

	_handleError(err) {
		if (err) this._log.error(err);
	}
}

module.exports = OctaveSession;


================================================
FILE: back-master/src/process-handler.js
================================================
/*
 * Copyright © 2018, Octave Online LLC
 *
 * This file is part of Octave Online Server.
 *
 * Octave Online Server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Octave Online Server is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Octave Online Server.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

"use strict";

const async = require("async");
const logger = require("@oo/shared").logger;
const StdioMessenger = require("@oo/shared").StdioMessenger;

class ProcessHandler extends StdioMessenger {
	constructor(sessCode) {
		super();
		this._log = logger(`process-handler:${sessCode}`);
		this._mlog = logger(`process-handler:${sessCode}:minor`);
		this.sessCode = sessCode;
	}

	_doCreate(next, fn) {
		async.series([
			(_next) => {
				// Spawn the process
				let args = Array.prototype.slice.call(arguments, 2);
				this._mlog.trace("Spawning process:", args[0], args[1].join(" "), args[2]);
				this._spwn = fn.apply(this, args);

				// Create all unexpected error listeners
				this._spwn.on("error", (err) => { this._log.error("spwn:", err); });
				this._spwn.stdin.on("error", (err) => { this._log.error("stdin:", err); });
				this._spwn.stdout.on("error", (err) => { this._log.error("stdout:", err); });
				this._spwn.stderr.on("error", (err) => { this._log.error("stderr:", err); });

				// Create stderr listener
				this._spwn.stderr.on("data", this._handleLog.bind(this));

				// Create exit listener
				this._spwn.on("exit", this._handleExit.bind(this));

				// Listen to main read stream
				this.setReadStream(this._spwn.stdout);

				// Wait until we get an acknowledgement before continuing.  Two conditions: receipt of the acknowledgement message, and premature exit.
				var ack = false;
				this.once("message", (name /*, content */) => {
					if (ack) return;
					ack = true;

					// Error if the message is process-exit
					if (name === "process-exit") return _next(new Error("Process exited prematurely"));

					// Don't enable the write stream until down here because we don't want to write messages to the child's STDIN until we've acknowledged that it is online
					this.setWriteStream(this._spwn.stdin);
					_next(null);
				});
			}
		], (err) => {
			if (err) return next(err);
			this._mlog.debug("Finished creating");
			return next(null);
		});
	}

	_doDestroy(next) {
		// This method wont't be called unless the process state is ONLINE, so we don't need to check.
		if (this._spwn) {
			// We can ignore the "next" callback because it will be implicitly called by _handleExit()
			this._mlog.trace("this._spwn exists");
			this._doDestroyProcess();
		} else {
			this._mlog.trace("this._spwn does not exist");
			next(null);
		}
	}

	signal(name) {
		if (!this._spwn) return this._log.warn("Tried to signal child process, but it does not exist");
		if (this._spwn.exitCode !== null || this._spwn.signalCode !== null) return this._log.warn("Tried to signal child process, but it is exited");
		this._signal(name);
		this._log.debug("Sent " + name + " to child process");
	}

	_signal(name) {
		this._spwn.kill(name);
	}

	_handleLog(data) {
		// Log message to console
		data.toString().trim().split("\n").forEach((line) => {
			this._mlog.log(line);
		});
	}

	_handleExit(code, signal) {
		this._log.debug("Process Exit:", code, signal);
		this._spwn = null;
		this.emit("message", "process-exit", { code, signal });
		this._internalDestroyed(null);

		// TODO: when to emit this.emit("message", "octave-killed") ?
	}
}

module.exports = ProcessHandler;


================================================
FILE: back-master/src/session-impl.js
================================================
/*
 * Copyright © 2018, Octave Online LLC
 *
 * This file is part of Octave Online Server.
 *
 * Octave Online Server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Octave Online Server is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Octave Online Server.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

"use strict";

const OctaveSession = require("./octave-session");
const { CappedFileSystem, TmpWorkDirectory } = require("./capped-file-system");
const DockerHandler = require("./docker-handler");
const ProcessHandler = require("./process-handler");
const config = require("@oo/shared").config;
const config2 = require("@oo/shared").config2;
const async = require("async");
const silent = require("@oo/shared").silent;
const child_process = require("child_process");
const logger = require("@oo/shared").logger;
const pstree = require("ps-tree");
const temp = require("temp");
const OnlineOffline = require("@oo/shared").OnlineOffline;
const Queue = require("@oo/shared").Queue;
const onceMessage = require("@oo/shared").onceMessage;
const FilesController = require("../../back-filesystem/src/controller");

class SessionImpl extends OctaveSession {
	constructor(sessCode, options) {
		super(sessCode, options);
		this.options = options;

		this._makeSessions();

		if (config.session.implementation === "unsafe") {
			this._cfs = new TmpWorkDirectory(this.sessCode);
		} else {
			this._cfs = new CappedFileSystem(this.sessCode, config.docker.diskQuotaKiB);
		}

		this._filesSession.on("message", this._handleMessage.bind(this));
		this._hostSession.on("message", this._handleMessage.bind(this));

		this._cfs.on("error", this._handleError.bind(this));
		this._filesSession.on("error", this._handleError.bind(this));
		this._hostSession.on("error", this._handleError.bind(this));
	}

	_doCreateImpl(next) {
		async.auto({
			"cfs": (_next) => {
				this._mlog.trace("Requesting creation of capped file system");
				this._cfs.create((err, dataDir) => {
					if (!err) this._dataDir = dataDir;
					_next(err);
				});
			},
			"files": ["cfs", (_next) => {
				this._mlog.trace("Requesting creation of file manager process");
				this._filesSession.create(_next, this._dataDir);
			}],
			"host": ["cfs", (_next) => {
				this._mlog.trace("Requesting creation of Octave host process");
				this._hostSession.create(_next, this._dataDir);
			}]
		}, (err) => {
			if (err) return next(err);
			this._log.info("Session successfully created");
			this.resetTimeout();
			return next(null);
		});
	}

	_doDestroyImpl(next, reason) {
		// TODO: Add an alternative destroy implementation that is synchronous, so that it can be run in an exit handler.
		async.auto({
			"commit": (_next) => {
				this._mlog.trace("Requesting to commit changes to Git");
				this._commit("Scripted user file commit", silent(/Out of time/, _next));
			},
			"host": ["commit", (_next) => {
				this._mlog.trace("Requesting termination of Octave host process");
				this._hostSession.destroy(_next);
			}],
			"files": ["commit", (_next) => {
				this._mlog.trace("Requesting termination of file manager process");
				this._filesSession.destroy(_next);
			}],
			"cfs": ["host", "files", (_next) => {
				this._mlog.trace("Requesting deletion of capped file system");
				this._cfs.destroy(_next);
			}]
		}, (err) => {
			if (err) return next(err);
			this._log.info("Session successfully destroyed:", reason);
			return next(null);
		});
	}

	_signal(name) {
		this._hostSession.signal(name);
	}

	_sendMessageToFiles(name, content) {
		this._filesSession.sendMessage(name, content);
	}

	_sendMessageToHost(name, content) {
		this._mlog.trace("Sending message to Octave host:", name, content);
		this._hostSession.sendMessage(name, content);
	}

	_onceMessageFromFiles(name, next) {
		onceMessage(this._filesSession, name, next);
	}
}

class HostProcessHandler extends ProcessHandler {
	constructor(sessCode, options) {
		super(sessCode);
		this.options = options;

		// Override default logger with something that says "host"
		this._log = logger(`host-handler:${sessCode}`);
		this._mlog = logger(`host-handler:${sessCode}:minor`);
	}

	_doCreate(next, dataDir) {
		const tier = this.options.tier;
		let cgroupName = config2.tier(tier)["selinux.cgroup.name"];
		let addressSpace = config2.tier(tier)["selinux.prlimit.addressSpace"];

		const envVars = [
			"env", "GNUTERM=svg",
			"env", "LD_LIBRARY_PATH=/usr/local/lib",
			"env", "OO_SESSCODE="+this.sessCode,
			"env", "OO_TIER="+this.options.tier
		];

		async.series([
			(_next) => {
				temp.mkdir("oo-", (err, tmpdir) => {
					this._mlog.debug("Created tmpdir:", tmpdir);
					this.tmpdir = tmpdir;
					_next(err);
				});
			},
			(_next) => {
				if (config.session.implementation === "unsafe") {
					// Spawn un-sandboxed process
					super._doCreate(_next, child_process.spawn, "env", [].concat(envVars.slice(1)).concat(["/usr/local/bin/octave-host", config.session.jsonMaxMessageLength]), {
						cwd: dataDir
					});
				} else {
					// Spawn sandboxed process
					// The CWD is set to /tmp in order to make the child process not hold a reference to the mount that the application happens to be running under.
					super._doCreate(_next, child_process.spawn, "/usr/bin/prlimit", [
						"--as="+addressSpace,
						"/usr/bin/cgexec",
						"-g", "cpu:"+cgroupName,
						"/usr/bin/sandbox",
						"-M",
						"-H", dataDir,
						"-T", this.tmpdir,
						"--level", "s0"]
						.concat(envVars)
						.concat([
							"/usr/local/bin/octave-host", config.session.jsonMaxMessageLength
						]),
					{
						cwd: "/tmp"
					});
				}
			},
			(_next) => {
				// We need to get the octave-cli PID for signalling, because sandbox handles signals strangely.
				this.octavePID = null;
				async.whilst(
					() => { return !this.octavePID && this._state !== "DESTROYED"; },
					(__next) => {
						async.waterfall([
							(___next) => {
								setTimeout(___next, 250);
							},
							(___next) => {
								this._mlog.trace("Attempting to get Octave PID...");
								pstree(this._spwn.pid, ___next);
							},
							(children, ___next) => {
								let child = children.find((_child) => { return /octave-cli/.test(_child.COMMAND); });
								if (child) {
									this.octavePID = child.PID;
									this._mlog.debug("Got Octave PID:", this.octavePID);
								}
								___next(null);
							}
						], __next);
					},
					_next
				);
			}
		], next);
	}

	_doDestroy(next) {
		async.series([
			super._doDestroy.bind(this),
			(_next) => {
				if (this.tmpdir) {
					this._mlog.trace("Destroying tmpdir");
					child_process.exec(`rm -rf ${this.tmpdir}`, _next);
				} else {
					process.nextTick(_next);
				}
			}
		], next);
	}

	_doDestroyProcess() {
		// Starting with Octave 4.4, sending SIGTERM is insufficient to make Octave exit.
		this._log.trace("Executing 'exit' in Octave process");
		this.sendMessage("cmd", "exit");
		setTimeout(() => {
			if (!this._spwn) {
				this._mlog.trace("Not sending SIGKILL: Process is already exited");
				return;
			}
			this._log.trace("Sending SIGKILL");
			this._signal("SIGKILL");
		}, 10000);
	}

	_signal(name) {
		if (!this.octavePID) return this._log.error("Cannot signal Octave process yet");
		child_process.exec(`kill -s ${name.slice(3)} ${this.octavePID}`, (err) => {
			if (err) this._log.error("signalling octave:", err);
		});
	}
}

class FilesControllerHandler extends OnlineOffline {
	constructor(sessCode) {
		super();
		this._log = logger(`files-handler:${sessCode}`);
		this._mlog = logger(`files-handler:${sessCode}:minor`);
		this.sessCode = sessCode;
		this._messageQueue = new Queue();
	}

	_doCreate(next, dataDir) {
		async.series([
			(_next) => {
				// Make the gitdir
				temp.mkdir("oo-", (err, tmpdir) => {
					this._mlog.debug("Created gitdir:", tmpdir);
					this.gitdir = tmpdir;
					_next(err);
				});
			},
			(_next) => {
				// Make the controller
				this.controller = new FilesController(this.gitdir, dataDir, this.sessCode);

				// Flush messages to the controller
				while (!this._messageQueue.isEmpty()) this._flush();
				this._messageQueue.on("enqueue", this._flush.bind(this));

				// Emit messages from the controller
				this.controller.on("message", (name, content) => {
					this.emit("message", name, content);
				});

				_next(null);
			}
		], next);
	}

	_doDestroy(next) {
		async.series([
			(_next) => {
				if (this.controller) {
					this.controller.destroy();
				}
				if (this.gitdir) {
					this._mlog.trace("Destroying gitdir");
					child_process.exec(`rm -rf ${this.gitdir}`, _next);
				} else {
					process.nextTick(_next);
				}
			}
		], next);
	}

	sendMessage(name, content) {
		this._messageQueue.enqueue([name, content]);
	}

	_flush() {
		this.controller.receiveMessage.apply(this.controller, this._messageQueue.dequeue());
	}
}

class SessionSELinux extends SessionImpl {
	_makeSessions() {
		this._filesSession = new FilesControllerHandler(this.sessCode);
		this._hostSession = new HostProcessHandler(this.sessCode, this.options);
	}

	_makeNewFileSession(sessCode) {
		return new FilesControllerHandler(sessCode);
	}
}

class HostDockerHandler extends DockerHandler {
	constructor(sessCode) {
		super(sessCode);
		this._dockerImage = config.docker.images.octaveSuffix;
		this._dockerName = `oo-host-${sessCode}`;

		// Override default logger with something that says "host"
		this._log = logger(`host-handler:${sessCode}`);
		this._mlog = logger(`host-handler:${sessCode}:minor`);
	}

	_doCreate(next, dataDir) {
		// More about resource management: https://goldmann.pl/blog/2014/09/11/resource-management-in-docker/
		const dockerArgs = [
			"run", "-i",
			"-v", `${dataDir}:${config.docker.cwd}`,
			"--cpu-shares", config.docker.cpuShares,
			"-m", config.docker.memoryShares,
			"--name", this._dockerName,
			`oo/${this._dockerImage}`
		];
		super._doCreate(next, dockerArgs);
	}
}

class FilesDockerHandler extends DockerHandler {
	constructor(sessCode) {
		super(sessCode);
		this._dockerImage = config.docker.images.filesystemSuffix;
		this._dockerName = `oo-files-${sessCode}`;

		// Override default logger with something that says "files"
		this._log = logger(`files-handler:${sessCode}`);
		this._mlog = logger(`files-handler:${sessCode}:minor`);
	}

	_doCreate(next, dataDir) {
		const dockerArgs = [
			"run", "-i",
			"-v", `${dataDir}:${config.docker.cwd}`,
			"--name", this._dockerName,
			`oo/${this._dockerImage}`
		];
		super._doCreate(next, dockerArgs);
	}
}

class SessionDocker extends SessionImpl {
	_makeSessions() {
		this._filesSession = new FilesDockerHandler(this.sessCode);
		this._hostSession = new HostDockerHandler(this.sessCode);
	}

	_makeNewFileSession(sessCode) {
		return new FilesDockerHandler(sessCode);
	}
}

module.exports = {
	docker: SessionDocker,
	selinux: SessionSELinux,
	docker_handler: HostDockerHandler,
	selinux_handler: HostProcessHandler
};


================================================
FILE: back-master/src/session-manager.js
================================================
/*
 * Copyright © 2018, Octave Online LLC
 *
 * This file is part of Octave Online Server.
 *
 * Octave Online Server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Octave Online Server is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Octave Online Server.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

"use strict";

const log = require("@oo/shared").logger("session-manager");
const mlog = require("@oo/shared").logger("session-manager:minor");
const EventEmitter = require("events");
const impls = require("./session-impl");
const uuid = require("uuid");
const Queue = require("@oo/shared").Queue;
const config = require("@oo/shared").config;
const config2 = require("@oo/shared").config2;
const metrics = require("@oo/shared").metrics;
const timeLimit = require("@oo/shared").timeLimit;

class SessionManager extends EventEmitter {
	constructor(maxOnly) {
		super();
		this._pool = {};
		this._poolSizes = {};

		let tiersEnabled;
		if (maxOnly) {
			tiersEnabled = ["_maxima"];
		} else {
			tiersEnabled = Object.keys(config.tiers);
			tiersEnabled.splice(tiersEnabled.indexOf("_maxima"), 1);
		}
		tiersEnabled.forEach((tier) => {
			if (config2.tier(tier)["sessionManager.poolTier"]) {
				mlog.info("Skipping tier with poolTier:", tier);
				// continue
			} else {
				mlog.info("Enabling tier:", tier);
				this._pool[tier] = {};
				this._poolSizes[tier] = config2.tier(tier)["sessionManager.poolSize"];
			}
		});
		log.info("Enabled tiers:", Object.keys(this._pool));

		this._online = {};
		this._monitor_session = null;
		this._setup();
		this.startPool();
		this.recordMetrics();
	}

	_setup() {
		// Log the session index on a fixed interval
		this._logInterval = setInterval(() => {
			Object.keys(this._pool).forEach((tier) => {
				log.debug("Current Number of Pooled Sessions, tier " + tier + ":", Object.keys(this._pool[tier]).length);
				log.trace(Object.keys(this._pool[tier]).join("; "));
			});
			log.debug("Current Number of Online Sessions:", Object.keys(this._online).length);
			log.trace(Object.keys(this._online).join("; "));

			// Time an arbitrary command to test server health
			if (this._monitor_session) {
				let t1 = new Date().valueOf();
				this._monitor_session.sendMessage("cmd", { data: "pinv(magic(500));" });
				this._monitor_session.once("msg:request-input", () => {
					const elapsed = new Date().valueOf() - t1;
					log.debug("Monitor Time (ms):", elapsed);
					metrics
Download .txt
gitextract_lv487tfw/

├── .dockerignore
├── .editorconfig
├── .eslintignore
├── .eslintrc.yml
├── .gcloudignore
├── .github/
│   └── workflows/
│       └── build-test.yml
├── .gitignore
├── .npmrc
├── COPYING
├── Makefile
├── README.md
├── back-filesystem/
│   ├── .eslintrc.yml
│   ├── .npmrc
│   ├── README.md
│   ├── app.js
│   ├── git/
│   │   ├── create-repo-service.js
│   │   ├── create-repo.service
│   │   └── gitd.service
│   ├── package.json
│   └── src/
│       ├── controller.js
│       ├── fake-socket.js
│       ├── git-util.js
│       ├── logger.js
│       ├── mime.types
│       └── working-util.js
├── back-master/
│   ├── .eslintrc.yml
│   ├── .npmrc
│   ├── README.md
│   ├── app.js
│   ├── package.json
│   └── src/
│       ├── capped-file-system.js
│       ├── docker-handler.js
│       ├── main-flavor.js
│       ├── main-pool.js
│       ├── maintenance-request-manager.js
│       ├── maintenance.js
│       ├── message-translator.js
│       ├── octave-session.js
│       ├── process-handler.js
│       ├── session-impl.js
│       └── session-manager.js
├── back-octave/
│   ├── Makefile
│   ├── README.md
│   ├── host.c
│   └── oo-changesets/
│       ├── 000-README.md
│       ├── 001-d38b7c534496.hg.txt
│       ├── 002-d3de6023e846.hg.txt
│       ├── 003-4d28376c34a8.hg.txt
│       ├── 004-6ff3e34eea77.hg.txt
│       ├── 005-9e73fe0d92d5.hg.txt
│       ├── 006-15d21ceec728.hg.txt
│       ├── 007-4d778d6ebbd0.hg.txt
│       ├── 008-e8ef7f3333bf.hg.txt
│       ├── 009-05f7272c001e.hg.txt
│       ├── 010-4a1afb661c55.hg.txt
│       ├── 011-7327936fa23e.hg.txt
│       ├── 012-84390db50239.hg.txt
│       ├── 013-f4110d638cdb.hg.txt
│       ├── 014-21fd506b7530.hg.txt
│       ├── 100-2d1fd5fdd1d5.hg.txt
│       ├── 100-README.md
│       ├── 101-bc8cd93feec5.hg.txt
│       ├── 102-30d8ba0fbc32.hg.txt
│       ├── 103-352b599bc533.hg.txt
│       ├── 104-9475120a3110.hg.txt
│       ├── 105-ccbef5c9b050.hg.txt
│       ├── 106-91cb270ffac0.hg.txt
│       ├── 107-80081f9d8ff7.hg.txt
│       ├── 108-9b39ca8bcbfd.hg.txt
│       ├── 200-84cbf166497f.hg.txt
│       ├── 200-README.md
│       ├── 201-b993253f19d0.hg.txt
│       ├── 202-d9d23f97ba78.hg.txt
│       ├── 203-d6b5ffb8e4cc.hg.txt
│       ├── 204-e61d7b8918e2.hg.txt
│       ├── 300-d78448f9c483.hg.txt
│       ├── 301-97f7d1f4fe83.hg.txt
│       ├── 302-8900d7cf8554.hg.txt
│       ├── 310-1e1c91e6cddc.hg.txt
│       ├── 320-8d4683a83238.hg.txt
│       ├── 321-faad58416a3a.hg.txt
│       ├── 400-7ade2492e023.hg.txt
│       ├── 401-1b33dc797ec9.hg.txt
│       ├── 402-b01fa2864d4d.hg.txt
│       ├── 403-2813cb96e10f.hg.txt
│       ├── 404-acb523f25bb9.hg.txt
│       ├── 405-6ad34b0b69e1.hg.txt
│       ├── 406-d0df6f16f41e.hg.txt
│       ├── 407-df206dd11399.hg.txt
│       ├── 408-8184a51579f3.hg.txt
│       ├── 420-4c3d80dd9e65.hg.txt
│       ├── 421-de16dd99ab0e.hg.txt
│       ├── 422-de16dd99ab0e.hg.txt
│       └── 430-d2250ae9bddd.hg.patch
├── client/
│   ├── .bowerrc
│   ├── .gitignore
│   ├── .npmrc
│   ├── COPYING
│   ├── Gruntfile.js
│   ├── README.md
│   ├── app/
│   │   ├── .eslintrc.yml
│   │   ├── colab.html
│   │   ├── eula.txt
│   │   ├── fonts/
│   │   │   └── dejavusansmono_book/
│   │   │       ├── DejaVuSansMono-demo.html
│   │   │       ├── specimen_files/
│   │   │       │   ├── easytabs.js
│   │   │       │   ├── grid_12-825-55-15.css
│   │   │       │   └── specimen_stylesheet.css
│   │   │       └── stylesheet.css
│   │   ├── images/
│   │   │   ├── flaticons/
│   │   │   │   └── download-svg.ai
│   │   │   ├── logo_collections/
│   │   │   │   ├── official/
│   │   │   │   │   └── favicon_package/
│   │   │   │   │       ├── README.md
│   │   │   │   │       ├── browserconfig.xml
│   │   │   │   │       └── site.webmanifest
│   │   │   │   └── server/
│   │   │   │       └── favicon_package/
│   │   │   │           ├── README.md
│   │   │   │           ├── browserconfig.xml
│   │   │   │           └── site.webmanifest
│   │   │   └── sanscons/
│   │   │       └── license.txt
│   │   ├── js/
│   │   │   ├── ace-adapter.js
│   │   │   ├── ace-extras.js
│   │   │   ├── anal.js
│   │   │   ├── app.js
│   │   │   ├── base64-toBlob.js
│   │   │   ├── base64v1.module.js
│   │   │   ├── bucket.js
│   │   │   ├── client.js
│   │   │   ├── detectmobilebrowser.js
│   │   │   ├── download.js
│   │   │   ├── flex-resize.js
│   │   │   ├── ko-ace.js
│   │   │   ├── ko-flash.js
│   │   │   ├── ko-takeArray.js
│   │   │   ├── modernizr-201406b.js
│   │   │   ├── octfile.js
│   │   │   ├── onboarding.js
│   │   │   ├── ot-client.js
│   │   │   ├── ot-handler.js
│   │   │   ├── polyfill.js
│   │   │   ├── runtime.js
│   │   │   ├── utils.js
│   │   │   ├── vars.js
│   │   │   └── ws-shared.js
│   │   ├── main.js
│   │   ├── privacy.txt
│   │   ├── privacy_standalone.txt
│   │   └── styl/
│   │       ├── all.styl
│   │       ├── callouts.styl
│   │       ├── editor.styl
│   │       ├── flexbox.styl
│   │       ├── hamburger.styl
│   │       ├── header.styl
│   │       ├── mixins.styl
│   │       ├── modals.styl
│   │       ├── output_panel.styl
│   │       ├── print.styl
│   │       └── themes/
│   │           ├── official/
│   │           │   ├── fire.styl
│   │           │   ├── ice.styl
│   │           │   ├── lava.styl
│   │           │   └── sun.styl
│   │           └── server/
│   │               ├── fire.styl
│   │               ├── ice.styl
│   │               ├── lava.styl
│   │               └── sun.styl
│   ├── bower.json
│   └── package.json
├── config.sample.hjson
├── config_defaults.hjson
├── containers/
│   ├── README.md
│   ├── octave-deps/
│   │   ├── Dockerfile
│   │   └── cloudbuild.yaml
│   ├── octave-oo/
│   │   ├── Dockerfile
│   │   ├── cloudbuild.yaml
│   │   └── java.opts
│   ├── octave-pkg/
│   │   ├── Dockerfile
│   │   ├── README.md
│   │   ├── cloudbuild.yaml
│   │   ├── ltfat.patch
│   │   └── octaverc.m
│   ├── octave-stable/
│   │   ├── Dockerfile
│   │   └── cloudbuild.yaml
│   ├── oo-back/
│   │   ├── Dockerfile
│   │   └── cloudbuild.yaml
│   ├── oo-front/
│   │   ├── Dockerfile
│   │   └── cloudbuild.yaml
│   ├── oo-gith/
│   │   ├── Dockerfile
│   │   ├── cloudbuild.yaml
│   │   ├── nginx.conf
│   │   └── supervisord.conf
│   ├── oo-redirect/
│   │   └── cloudbuild.yaml
│   ├── oos-quick-start/
│   │   └── docker-compose.yaml
│   ├── utils-admin/
│   │   └── cloudbuild.yaml
│   ├── utils-gitd/
│   │   ├── Dockerfile
│   │   ├── cloudbuild.yaml
│   │   └── supervisord.conf
│   └── utils-gith/
│       ├── Dockerfile
│       ├── cloudbuild.yaml
│       └── supervisord.conf
├── entrypoint/
│   ├── .eslintrc.yml
│   ├── README.md
│   ├── back-selinux.js
│   ├── exit.js.sample
│   ├── oo-front.service
│   ├── oo-no-restart.service
│   ├── oo-reinstall.service
│   ├── oo.service
│   └── policy/
│       ├── octave_online.fc
│       ├── octave_online.if
│       ├── octave_online.te
│       ├── octave_online_supplement.if
│       └── octave_online_supplement.te
├── front/
│   ├── .eslintrc.yml
│   ├── .npmrc
│   ├── README.md
│   ├── locales/
│   │   ├── README.md
│   │   ├── en.yaml
│   │   └── qqq.yaml
│   ├── package.json
│   ├── src/
│   │   ├── app.ts
│   │   ├── back_server_handler.ts
│   │   ├── bucket_model.ts
│   │   ├── email.ts
│   │   ├── express_setup.ts
│   │   ├── flavor_record_model.ts
│   │   ├── mongo.ts
│   │   ├── octave_session_helper.ts
│   │   ├── ot_document.ts
│   │   ├── passport_setup.ts
│   │   ├── patreon.ts
│   │   ├── program_model.ts
│   │   ├── session_middleware.ts
│   │   ├── shared_wrap.ts
│   │   ├── socket_connect.ts
│   │   ├── socketio.ts
│   │   ├── user_model.ts
│   │   ├── utils.ts
│   │   ├── views/
│   │   │   ├── captcha_error.ejs
│   │   │   ├── incorrect_page.ejs
│   │   │   ├── index.ejs
│   │   │   ├── login_error.ejs
│   │   │   ├── partials/
│   │   │   │   ├── foot.ejs
│   │   │   │   └── head.ejs
│   │   │   ├── patreon_link_error.ejs
│   │   │   └── token_page.ejs
│   │   ├── workspace_normal.ts
│   │   └── workspace_shared.ts
│   ├── tsconfig.json
│   └── typings/
│       ├── easy-no-password.d.ts
│       ├── i18next-fs-backend.d.ts
│       ├── i18next-http-middleware.d.ts
│       ├── ot.d.ts
│       ├── pseudo-localization.d.ts
│       ├── socketio-file-upload.d.ts
│       └── socketio-wildcard.d.ts
├── package.json
├── redirect/
│   ├── README.md
│   ├── app.js
│   ├── bin/
│   │   └── server.js
│   ├── package.json
│   ├── src/
│   │   └── db.js
│   └── views/
│       └── error.ejs
├── shared/
│   ├── .eslintrc.yml
│   ├── .npmrc
│   ├── README.md
│   ├── async-cache.js
│   ├── config-helper.js
│   ├── config.js
│   ├── gcp/
│   │   ├── .npmrc
│   │   ├── fetch_translations.js
│   │   ├── index.js
│   │   ├── package.json
│   │   └── reboot_or_remove_self.js
│   ├── gitarchive.js
│   ├── hostname.js
│   ├── index.d.ts
│   ├── index.js
│   ├── json-stream-safe.js
│   ├── logger.js
│   ├── lua/
│   │   ├── get-sesscode.lua
│   │   ├── ot.lua
│   │   ├── ot_apply.lua
│   │   ├── ot_set.lua
│   │   └── ot_test.lua
│   ├── metrics.js
│   ├── once-message.js
│   ├── online-offline.js
│   ├── package.json
│   ├── queue.js
│   ├── redis-messenger.js
│   ├── redis-queue.js
│   ├── redis-util.js
│   ├── silent.js
│   ├── stackdriver/
│   │   ├── index.js
│   │   └── package.json
│   ├── stdio-messenger.js
│   └── time-limit.js
├── test/
│   ├── package.json
│   └── small-unit.js
├── utils-admin/
│   ├── .npmrc
│   ├── README.md
│   ├── app.js
│   ├── bin/
│   │   ├── repo-cleanup.js
│   │   └── server.js
│   ├── package.json
│   ├── public/
│   │   └── stylesheets/
│   │       └── style.css
│   ├── routes/
│   │   ├── index.js
│   │   └── users.js
│   ├── src/
│   │   ├── db.js
│   │   └── repo.js
│   └── views/
│       ├── error.ejs
│       ├── find.ejs
│       ├── index.ejs
│       ├── partials/
│       │   ├── footer.ejs
│       │   └── header.ejs
│       ├── user-list.ejs
│       └── user.ejs
└── utils-auth/
    ├── .eslintrc.yml
    ├── .npmrc
    ├── README.md
    ├── app.js
    ├── configs/
    │   ├── custom_4xx.html
    │   ├── gitlist.ini
    │   └── oo-utils-auth.service
    └── package.json
Download .txt
SYMBOL INDEX (572 symbols across 81 files)

FILE: back-filesystem/app.js
  constant GIT_DIR (line 33) | const GIT_DIR = process.argv[2];
  constant WORK_DIR (line 34) | const WORK_DIR = process.argv[3];

FILE: back-filesystem/src/controller.js
  class FilesController (line 33) | class FilesController extends EventEmitter {
    method constructor (line 34) | constructor(gitDir, workDir, logMemo) {
    method _isInitialized (line 54) | _isInitialized() {
    method _isSetUp (line 59) | _isSetUp() {
    method receiveMessage (line 63) | receiveMessage(name, content) {
    method destroy (line 384) | destroy() {
    method _logError (line 388) | _logError(context, err) {
    method _sendMessage (line 399) | _sendMessage(name, content) {
    method _fail (line 404) | _fail() {
    method _setupUploader (line 412) | _setupUploader() {

FILE: back-filesystem/src/fake-socket.js
  class FakeSocket (line 33) | class FakeSocket extends EventEmitter {
    method constructor (line 34) | constructor() {

FILE: back-filesystem/src/git-util.js
  class GitUtil (line 29) | class GitUtil {
    method constructor (line 30) | constructor(gitDir, logMemo) {
    method initialize (line 39) | initialize(user, workDir, next) {
    method initializeBucket (line 55) | initializeBucket(bucketId, workDir, readonly, next) {
    method _initialize (line 76) | _initialize(remote, workDir, next) {
    method pullPush (line 99) | pullPush(message, next) {
    method _pullPush (line 111) | _pullPush(message, next) {
    method _pull (line 146) | _pull(next) {
    method _commit (line 167) | _commit(message, next) {
    method _createUserOnRemote (line 185) | _createUserOnRemote(user, next) {
    method _createBucketOnRemote (line 205) | _createBucketOnRemote(bucketId, next) {
    method _userToRemote (line 225) | _userToRemote(user) {
    method _bucketToRemote (line 229) | _bucketToRemote(bucketId) {
    method _gitConfigArgs (line 233) | _gitConfigArgs() {

FILE: back-filesystem/src/working-util.js
  constant ACCEPTABLE_MIME_REGEX (line 36) | const ACCEPTABLE_MIME_REGEX = /^(text\/.*)$/;
  constant UNACCEPTABLE_FILENAME_REGEX (line 37) | const UNACCEPTABLE_FILENAME_REGEX = /^(\..*|octave-\w+)$/;
  class WorkingUtil (line 39) | class WorkingUtil {
    method constructor (line 40) | constructor(workDir, logMemo) {
    method listAll (line 46) | listAll(next) {
    method hasOctaverc (line 64) | hasOctaverc(next) {
    method _recursiveReaddir (line 76) | _recursiveReaddir(directory, depth, next) {
    method getFileInfo (line 122) | getFileInfo(filename, next) {
    method _getFileInfo (line 138) | _getFileInfo(filename, pathname, relname, stats, next) {
    method _convertCharset (line 171) | _convertCharset(buf) {
    method saveFile (line 196) | saveFile(filename, value, next) {
    method renameFile (line 245) | renameFile(oldname, newname, next) {
    method deleteFile (line 252) | deleteFile(filename, next) {
    method readBinary (line 258) | readBinary(filename, next) {
    method _safePath (line 271) | _safePath(filename) {

FILE: back-master/app.js
  function makeSessionLogDir (line 61) | function makeSessionLogDir(tokens) {
  function doExit (line 170) | function doExit() {
  function doGracefulExit (line 184) | function doGracefulExit() {
  function doFastExit (line 205) | function doFastExit() {

FILE: back-master/src/capped-file-system.js
  constant IMG_FILE_NAME (line 34) | const IMG_FILE_NAME = "img.ext3";
  constant IMG_MNT_DIR (line 35) | const IMG_MNT_DIR = "mnt";
  constant IMG_DATA_DIR (line 36) | const IMG_DATA_DIR = "data";
  class CappedFileSystem (line 38) | class CappedFileSystem extends OnlineOffline {
    method constructor (line 39) | constructor(sessCode, size) {
    method _doCreate (line 48) | _doCreate(next) {
    method _doDestroy (line 131) | _doDestroy(next) {
  class TmpWorkDirectory (line 145) | class TmpWorkDirectory extends OnlineOffline {
    method constructor (line 146) | constructor(sessCode) {
    method _doCreate (line 152) | _doCreate(next) {
    method _doDestroy (line 173) | _doDestroy(next) {

FILE: back-master/src/docker-handler.js
  class DockerHandler (line 28) | class DockerHandler extends StdioMessenger {
    method constructor (line 29) | constructor(sessCode, dockerImage) {
    method _doCreate (line 35) | _doCreate(next, dockerArgs) {
    method _doDestroy (line 73) | _doDestroy(next) {
    method signal (line 83) | signal(name) {
    method _handleLog (line 91) | _handleLog(data) {
    method _handleExit (line 104) | _handleExit(code, signal) {

FILE: back-master/src/main-flavor.js
  function start (line 39) | function start(globals, next) {
  function startConnectionAcceptLoop (line 50) | function startConnectionAcceptLoop(globals, next) {
  function startLifetimeLoop (line 116) | function startLifetimeLoop(globals, next) {
  function doExit (line 166) | function doExit() {

FILE: back-master/src/main-pool.js
  function start (line 37) | function start(globals, next) {
  function startConnectionAcceptLoop (line 48) | function startConnectionAcceptLoop(globals, next) {
  function startMaintenanceLoop (line 93) | function startMaintenanceLoop(globals, next) {
  function doExit (line 142) | function doExit() {

FILE: back-master/src/maintenance-request-manager.js
  class MaintenanceRequestFlavorManager (line 28) | class MaintenanceRequestFlavorManager extends EventEmitter {
    method constructor (line 29) | constructor(clusterSize) {
    method reset (line 40) | reset() {
    method ignoreAll (line 48) | ignoreAll() {
    method beginRequesting (line 52) | beginRequesting(intervalTime) {
    method onMessage (line 58) | onMessage(id, isRequest, message) {
    method stop (line 76) | stop() {
    method _requestMaintenance (line 83) | _requestMaintenance() {

FILE: back-master/src/maintenance.js
  function runMaintenance (line 27) | function runMaintenance(next) {

FILE: back-master/src/message-translator.js
  class MessageTranslator (line 31) | class MessageTranslator extends EventEmitter {
    method fromUpstream (line 34) | fromUpstream(sessCode, name, content) {
    method fromDownstream (line 195) | fromDownstream(sessCode, name, getData) {
    method _forDownstream (line 231) | _forDownstream(sessCode, name, content) {
    method _forUpstream (line 235) | _forUpstream(sessCode, name, getData) {

FILE: back-master/src/octave-session.js
  class OctaveSession (line 44) | class OctaveSession extends OnlineOffline {
    method constructor (line 45) | constructor(sessCode, options) {
    method _doCreate (line 76) | _doCreate(next) {
    method _doDestroy (line 87) | _doDestroy(next, reason) {
    method interrupt (line 108) | interrupt() {
    method enqueueMessage (line 112) | enqueueMessage(name, getData) {
    method _startCountdown (line 118) | _startCountdown() {
    method _endCountdown (line 124) | _endCountdown() {
    method _onCountdownEnd (line 130) | _onCountdownEnd() {
    method _addTime (line 143) | _addTime() {
    method resetTimeout (line 149) | resetTimeout() {
    method _resetPayload (line 166) | _resetPayload() {
    method _appendToPayload (line 170) | _appendToPayload(content) {
    method _acknowledgePayload (line 198) | _acknowledgePayload() {
    method _continueIfPaused (line 204) | _continueIfPaused() {
    method _startAutoCommitLoop (line 213) | _startAutoCommitLoop() {
    method _commit (line 220) | _commit(comment, next) {
    method _appendToSessionLog (line 232) | _appendToSessionLog(type, content) {
    method _convertPlotImages (line 240) | _convertPlotImages(content) {
    method _onDeletedBinary (line 271) | _onDeletedBinary(content) {
    method _resolvePng (line 284) | _resolvePng(content) {
    method _handleRequestUrl (line 308) | _handleRequestUrl(content) {
    method _createBucket (line 393) | _createBucket(bucketInfo) {
    method _checkThrottle (line 492) | _checkThrottle() {
    method sendMessage (line 511) | sendMessage(name, content) {
    method _handleMessage (line 615) | _handleMessage(name, content) {
    method _handleError (line 715) | _handleError(err) {

FILE: back-master/src/process-handler.js
  class ProcessHandler (line 27) | class ProcessHandler extends StdioMessenger {
    method constructor (line 28) | constructor(sessCode) {
    method _doCreate (line 35) | _doCreate(next, fn) {
    method _doDestroy (line 79) | _doDestroy(next) {
    method signal (line 91) | signal(name) {
    method _signal (line 98) | _signal(name) {
    method _handleLog (line 102) | _handleLog(data) {
    method _handleExit (line 109) | _handleExit(code, signal) {

FILE: back-master/src/session-impl.js
  class SessionImpl (line 40) | class SessionImpl extends OctaveSession {
    method constructor (line 41) | constructor(sessCode, options) {
    method _doCreateImpl (line 61) | _doCreateImpl(next) {
    method _doDestroyImpl (line 86) | _doDestroyImpl(next, reason) {
    method _signal (line 112) | _signal(name) {
    method _sendMessageToFiles (line 116) | _sendMessageToFiles(name, content) {
    method _sendMessageToHost (line 120) | _sendMessageToHost(name, content) {
    method _onceMessageFromFiles (line 125) | _onceMessageFromFiles(name, next) {
  class HostProcessHandler (line 130) | class HostProcessHandler extends ProcessHandler {
    method constructor (line 131) | constructor(sessCode, options) {
    method _doCreate (line 140) | _doCreate(next, dataDir) {
    method _doDestroy (line 217) | _doDestroy(next) {
    method _doDestroyProcess (line 231) | _doDestroyProcess() {
    method _signal (line 245) | _signal(name) {
  class FilesControllerHandler (line 253) | class FilesControllerHandler extends OnlineOffline {
    method constructor (line 254) | constructor(sessCode) {
    method _doCreate (line 262) | _doCreate(next, dataDir) {
    method _doDestroy (line 290) | _doDestroy(next) {
    method sendMessage (line 306) | sendMessage(name, content) {
    method _flush (line 310) | _flush() {
  class SessionSELinux (line 315) | class SessionSELinux extends SessionImpl {
    method _makeSessions (line 316) | _makeSessions() {
    method _makeNewFileSession (line 321) | _makeNewFileSession(sessCode) {
  class HostDockerHandler (line 326) | class HostDockerHandler extends DockerHandler {
    method constructor (line 327) | constructor(sessCode) {
    method _doCreate (line 337) | _doCreate(next, dataDir) {
  class FilesDockerHandler (line 351) | class FilesDockerHandler extends DockerHandler {
    method constructor (line 352) | constructor(sessCode) {
    method _doCreate (line 362) | _doCreate(next, dataDir) {
  class SessionDocker (line 373) | class SessionDocker extends SessionImpl {
    method _makeSessions (line 374) | _makeSessions() {
    method _makeNewFileSession (line 379) | _makeNewFileSession(sessCode) {

FILE: back-master/src/session-manager.js
  class SessionManager (line 34) | class SessionManager extends EventEmitter {
    method constructor (line 35) | constructor(maxOnly) {
    method _setup (line 66) | _setup() {
    method numActiveSessions (line 98) | numActiveSessions() {
    method canAcceptNewSessions (line 102) | canAcceptNewSessions() {
    method usagePercent (line 118) | usagePercent() {
    method isHealthy (line 122) | isHealthy() {
    method _create (line 126) | _create(next, options) {
    method attach (line 154) | attach(remoteCode, content) {		// Move pool session to online session
    method get (line 220) | get(sessCode) {
    method destroy (line 229) | destroy(sessCode, reason) {
    method startPool (line 261) | startPool() {
    method disablePool (line 305) | disablePool() {
    method terminate (line 319) | terminate(reason) {
    method restart (line 334) | restart() {
    method recordMetrics (line 339) | recordMetrics() {

FILE: back-octave/host.c
  type write_req_t (line 70) | typedef struct {
  type STD_STREAM (line 75) | enum STD_STREAM {
  function cb_walk (line 84) | void cb_walk(uv_handle_t* handle, void* arg) {
  function cleanup (line 88) | void cleanup() {
  function cb_cleanup_write_req (line 96) | void cb_cleanup_write_req(uv_write_t *req, int status) {
  function cb_alloc_buffer (line 102) | void cb_alloc_buffer(uv_handle_t* handle, size_t suggested_size, uv_buf_...
  function cb_sigfwd (line 106) | void cb_sigfwd(uv_signal_t *handle, int signum) {
  function cb_exit (line 111) | void cb_exit(uv_process_t* req, int64_t exit_status, int term_signal) {
  function write_to_socket (line 120) | void write_to_socket(const char* str, size_t len) {
  function write_to_stdout (line 127) | void write_to_stdout(const char* str, size_t len) {
  function print_json_msg_str (line 134) | void print_json_msg_str(const char* name, const char* str, size_t len) {
  function process_std_stream (line 155) | void process_std_stream(enum STD_STREAM type, uv_stream_t* stream, ssize...
  function cb_stdmsg (line 196) | void cb_stdmsg(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
  function cb_stdout (line 200) | void cb_stdout(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
  function cb_stderr (line 204) | void cb_stderr(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
  function cb_stdin (line 208) | void cb_stdin(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
  function cb_connect (line 212) | void cb_connect(uv_stream_t* comm, int status) {
  function main (line 232) | int main(int argc, char* argv[]) {

FILE: client/Gruntfile.js
  function getCssTimestamp (line 26) | function getCssTimestamp() {
  function getJsTimestamp (line 30) | function getJsTimestamp() {
  function getFileUtf8 (line 34) | function getFileUtf8(filepath) {

FILE: client/app/fonts/dejavusansmono_book/specimen_files/easytabs.js
  function hideAll (line 4) | function hideAll(){$(thisId+" .easytabs-tab-content").hide();}
  function changeContent (line 5) | function changeContent(tabId){hideAll();$(thisId+" .tabs li").removeClas...

FILE: client/app/js/ace-adapter.js
  function bind (line 27) | function bind(fn, me){
  function ACEAdapter (line 34) | function ACEAdapter(aceInstance) {

FILE: client/app/js/ace-extras.js
  function e (line 3) | function e(e,t,n){return e=e.substr(1),/^\d+$/.test(e)&&!n.inFormatStrin...
  function t (line 3) | function t(e){return"(?:[^\\\\"+e+"]|\\\\.)"}
  function o (line 3) | function o(t){var n=e.indexOf(t,r+1);n!=-1&&(r=n)}
  function l (line 3) | function l(e){var t=[];for(var n=0;n<e.length;n++){var r=e[n];if(typeof ...
  function o (line 3) | function o(e){return e&&!/^\^?\(.*\)\$?$|^\\b$/.test(e)&&(e="(?:"+e+")")...
  function u (line 3) | function u(e,t,n){return e=o(e),t=o(t),n?(e=t+e,e&&e[e.length-1]!="$"&&(...
  function a (line 3) | function a(e){e.scope||(e.scope=t||"_"),t=e.scope,n[t]||(n[t]=[],i[t]={}...
  function i (line 3) | function i(e){var i=r[e.scope||t];if(i&&i[e.name]){delete i[e.name];var ...
  function s (line 3) | function s(e,t){var n=e.getTextRange(r.fromPoints({row:0,column:0},t));r...
  function o (line 3) | function o(e,t){var n=s(e,t),r=e.getValue().split(i),o=Object.create(nul...
  function h (line 7) | function h(){var r=a.renderSync(e,t,n,i,s);return u?u(r):r}

FILE: client/app/js/anal.js
  function gtag (line 25) | function gtag(){ dataLayer.push(arguments); }
  function sendEvent (line 43) | function sendEvent(event_category, event_action, event_label, value) {

FILE: client/app/js/app.js
  function updateTheme (line 253) | function updateTheme(newValue) {
  function toggleTheme (line 262) | function toggleTheme(dark) {

FILE: client/app/js/bucket.js
  function Bucket (line 26) | function Bucket(){

FILE: client/app/js/client.js
  function Skin (line 35) | function Skin(name, aceTheme, iconColor){
  function PlotObject (line 72) | function PlotObject(id){
  function getOrMakePlotById (line 437) | function getOrMakePlotById(id){

FILE: client/app/js/flex-resize.js
  function cbmove (line 23) | function cbmove(e){
  function cbdown (line 80) | function cbdown(e, _obsArr){
  function cbup (line 91) | function cbup(){

FILE: client/app/js/modernizr-201406b.js
  function v (line 5) | function v(a){i.cssText=a}
  function w (line 5) | function w(a,b){return v(prefixes.join(a+";")+(b||""))}
  function x (line 5) | function x(a,b){return typeof a===b}
  function y (line 5) | function y(a,b){return!!~(""+a).indexOf(b)}
  function z (line 5) | function z(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a...

FILE: client/app/js/octfile.js
  function OctFile (line 28) | function OctFile(filename, content, editable){

FILE: client/app/js/ot-client.js
  function OTClientWrapper (line 22) | function OTClientWrapper(docId, observable){
  function ObservableAdapter (line 29) | function ObservableAdapter(observable){

FILE: client/app/js/ot-handler.js
  function findDocWithId (line 24) | function findDocWithId(docId){
  function create (line 83) | function create(docId, observable) {
  function destroy (line 94) | function destroy(docId) {

FILE: client/app/js/vars.js
  function Var (line 24) | function Var(){

FILE: client/app/js/ws-shared.js
  function clientForFilename (line 90) | function clientForFilename(filename) {
  function forEachDocClient (line 94) | function forEachDocClient(cb){

FILE: entrypoint/back-selinux.js
  function getExitFunction (line 61) | function getExitFunction() {
  function mkdirSyncNoError (line 77) | function mkdirSyncNoError(path) {
  function makeSessionLogDirsRecursive (line 92) | function makeSessionLogDirsRecursive(prefix, depth) {
  method transform (line 121) | transform(chunk, encoding, callback) {
  function doExit (line 168) | function doExit() {
  function runOnce (line 186) | function runOnce() {

FILE: front/src/app.ts
  function main (line 33) | async function main() {

FILE: front/src/back_server_handler.ts
  class BackServerHandler (line 38) | class BackServerHandler extends EventEmitter {
    method constructor (line 44) | constructor() {
    method setSessCode (line 49) | public setSessCode(sessCode: string|null) {
    method dataD (line 67) | public dataD(name: string, data: any) {
    method subscribe (line 79) | public subscribe() {
    method unsubscribe (line 91) | public unsubscribe() {
    method depend (line 103) | private depend(props: string[], log=false) {

FILE: front/src/bucket_model.ts
  type Err (line 27) | type Err = Error | null;
  type IBucketMethods (line 75) | interface IBucketMethods {
  type IBucket (line 84) | interface IBucket extends Mongoose.Document, IBucketMethods {
  class BucketMethods (line 103) | class BucketMethods implements IBucketMethods {
    method isValidAction (line 104) | isValidAction(this: IBucket, action: string): boolean {
    method checkAccessPermissions (line 114) | checkAccessPermissions(this: IBucket, user: IUser|null): boolean {
    method isOwnedBy (line 121) | isOwnedBy(this: IBucket, user: IUser|null): boolean {
    method touchLastActivity (line 128) | touchLastActivity(this: IBucket, next: (err: Err) => void): void {
    method removeRepo (line 134) | removeRepo(this: IBucket, next: (err: Err) => void): void {
    method logf (line 155) | logf(this: IBucket): ILogger {

FILE: front/src/email.ts
  function sendLoginToken (line 35) | async function sendLoginToken(email: string, token: string, url: string) {
  function sendZipArchive (line 54) | async function sendZipArchive(email: string, desc: string, url: string) {

FILE: front/src/express_setup.ts
  constant PORT (line 48) | const PORT = process.env.PORT || config.front.listen_port;
  constant STATIC_PATH_1 (line 49) | const STATIC_PATH_1 = Path.join(__dirname, "..", "..", config.front.stat...
  constant STATIC_PATH_2 (line 50) | const STATIC_PATH_2 = Path.join(__dirname, "..", "static");
  constant STATIC_OPTS (line 51) | const STATIC_OPTS: ServeStatic.ServeStaticOptions = {
  type BuildData (line 67) | interface BuildData {
  function getT (line 73) | function getT(req: Express.Request) {
  function getCurrentLanguage (line 85) | function getCurrentLanguage(req: Express.Request, buildData: BuildData) {
  function getJSTranslations (line 98) | function getJSTranslations(req: Express.Request, t: I18next.TFunction) {
  function init (line 119) | function init(buildData: BuildData){

FILE: front/src/flavor_record_model.ts
  type IFlavorRecord (line 34) | interface IFlavorRecord extends Mongoose.Document {

FILE: front/src/mongo.ts
  function connect (line 27) | async function connect(): Promise<Mongoose.Mongoose> {

FILE: front/src/octave_session_helper.ts
  type Err (line 26) | type Err = Error|null;
  type SessionState (line 28) | enum SessionState {
  class OctaveSessionHelper (line 36) | class OctaveSessionHelper extends EventEmitter {
    method constructor (line 39) | constructor() {
    method getNewSessCode (line 44) | public getNewSessCode(sessCodeGuess: string|null, next: (err: Err, ses...
    method askForOctave (line 72) | public askForOctave(sessCode: string, content: any, next: (err: Err) =...
    method sendDestroyD (line 95) | public sendDestroyD(sessCode: string, message: string) {
    method makeSessCode (line 100) | private makeSessCode(next: (err: Err, sessCode: string) => void) {
    method isValid (line 111) | private isValid(sessCode: string, next: (valid: SessionState) => void) {

FILE: front/src/ot_document.ts
  type Err (line 28) | type Err = Error|null;
  class OtDocument (line 39) | class OtDocument extends EventEmitter {
    method constructor (line 50) | constructor (id: string, safeId: string, initialContent: string) {
    method logFilename (line 59) | public logFilename(filename: string) {
    method subscribe (line 63) | public subscribe() {
    method unsubscribe (line 71) | public unsubscribe() {
    method dataD (line 76) | public dataD(name: string, value: any) {
    method changeDocId (line 93) | public changeDocId(newDocId: string) {
    method destroy (line 104) | public destroy() {
    method load (line 109) | private load() {
    method touch (line 132) | private touch() {
    method receiveOperation (line 201) | private receiveOperation(rev: number, op: Ot.ITextOperation) {
    method setContent (line 218) | private setContent(content: string) {

FILE: front/src/passport_setup.ts
  type Err (line 32) | type Err = Error | null;
  function findOrCreateUser (line 39) | async function findOrCreateUser(email: string, profile: any) {
  type PasswordStatus (line 61) | enum PasswordStatus { UNKNOWN, INCORRECT, VALID }
  type UserWithPasswordResponse (line 63) | interface UserWithPasswordResponse {
  function findWithPasswordPromise (line 68) | async function findWithPasswordPromise(email: string, password: string):...
  function findWithPassword (line 95) | function findWithPassword(email: string, password: string, done: (err: E...
  function init (line 181) | function init(){

FILE: front/src/patreon.ts
  type PatreonInfo (line 30) | interface PatreonInfo {
  type PatreonPhase1AsyncAuto (line 36) | interface PatreonPhase1AsyncAuto {
  type PatreonPhase2AsyncAuto (line 43) | interface PatreonPhase2AsyncAuto {
  type PatreonRevokeAsyncAuto (line 53) | interface PatreonRevokeAsyncAuto {
  function processMembership (line 79) | function processMembership(membership: any, user_id: string|null): Patre...
  function phase1 (line 101) | function phase1(req: any, res: any, next: any) {
  function phase2 (line 141) | function phase2(req: any, res: any, next: any) {
  function revoke (line 255) | function revoke(req: any, res: any, next: any) {
  function webhook (line 298) | function webhook(req: any, res: any, next: any) {

FILE: front/src/program_model.ts
  type ProgramModel (line 27) | type ProgramModel = Mongoose.Model<IProgram, {}, IProgramMethods>;
  type IProgramMethods (line 47) | interface IProgramMethods {
  type IProgram (line 51) | interface IProgram {

FILE: front/src/session_middleware.ts
  function init (line 33) | function init() {

FILE: front/src/shared_wrap.ts
  type IRedisMessenger (line 29) | interface IRedisMessenger extends Shared.RedisMessenger, EventEmitter {}
  function newRedisMessenger (line 30) | function newRedisMessenger(...args: any[]): IRedisMessenger {
  type IRedisQueue (line 34) | interface IRedisQueue extends Shared.RedisQueue, EventEmitter {}
  function newRedisQueue (line 35) | function newRedisQueue(...args: any[]): IRedisQueue {
  type ILogger (line 40) | interface ILogger {
  function logger (line 49) | function logger(id: string): ILogger {

FILE: front/src/socket_connect.ts
  constant TOKEN_REGEX (line 37) | const TOKEN_REGEX = /^\w*$/;
  constant SHORTLINK_REGEX (line 38) | const SHORTLINK_REGEX = /^[\p{L}\p{Nd}_-]{5,}$/u;
  type ISocketCustom (line 42) | interface ISocketCustom extends SocketIO.Socket {
  type InitData (line 47) | interface InitData {
  type SocketAsyncAuto (line 55) | interface SocketAsyncAuto {
  type DeleteBucketAsyncAuto (line 63) | interface DeleteBucketAsyncAuto {
  class SocketHandler (line 69) | class SocketHandler implements IDestroyable {
    method onConnection (line 80) | public static onConnection(socket: SocketIO.Socket) {
    method constructor (line 85) | constructor(socket: SocketIO.Socket) {
    method listen (line 254) | private listen(): void {
    method unlisten (line 279) | private unlisten(): void {
    method sendMessage (line 290) | private sendMessage(message: string): void {
    method onDestroyD (line 303) | private onDestroyD(): void {
    method onDestroyU (line 310) | private onDestroyU(message: string): void {
    method onDataD (line 318) | private onDataD(obj: any): void {
    method onDataU (line 388) | private onDataU(name: string, data: any): void {
    method onDataW (line 406) | private onDataW(name: string, data: any): void {
    method loadInstructor (line 412) | private async loadInstructor(): Promise<void> {
    method loadUserBuckets (line 425) | private async loadUserBuckets(): Promise<void> {
    method touchUser (line 432) | private touchUser(): void {
    method touchBucket (line 442) | private touchBucket(): void {
    method onSetPassword (line 452) | private onSetPassword(obj: any): void {
    method parseDuplicateKeyError (line 461) | private parseDuplicateKeyError(err: Error): object | void {
    method onCreateBucket (line 475) | private onCreateBucket(obj: any): void {
    method onBucketRepoCreated (line 526) | private onBucketRepoCreated(bucket: any): void {
    method onChangeBucketShortlink (line 530) | private onChangeBucketShortlink(obj: any): void {
    method onDeleteBucket (line 581) | private onDeleteBucket(obj: any): void {
    method onTouchFlavor (line 623) | private onTouchFlavor(obj: any): void {
    method onOoReconnect (line 651) | private onOoReconnect(): void {
    method setSessCode (line 659) | private setSessCode(sessCode: string): void {
    method onDataWtoU (line 669) | private onDataWtoU(name: string, value: any): void {
    method onEnroll (line 675) | private onEnroll(obj: any): void {
    method onUpdateStudents (line 687) | private onUpdateStudents(obj: any): void {
    method onUnenrollStudent (line 692) | private async onUnenrollStudent(obj: any): Promise<void> {
    method onReenrollStudent (line 705) | private async onReenrollStudent(obj: any): Promise<void> {
    method onPing (line 723) | private onPing(obj: any): void {
    method onToggleSharing (line 730) | private onToggleSharing(obj: any): void {
    method onFlavorUpgrade (line 781) | private onFlavorUpgrade(obj: any): void {
    method onGenerateZip (line 800) | private onGenerateZip(obj: any): void {

FILE: front/src/socketio.ts
  function init (line 34) | function init(){

FILE: front/src/user_model.ts
  type Err (line 31) | type Err = Error | null;
  type UserModel (line 32) | type UserModel = Mongoose.Model<IUser, {}, IUserMethods, IUserVirtuals>;
  type UserSchema (line 33) | type UserSchema = Mongoose.Schema<IUser, UserModel, IUserMethods, {}, IU...
  type HydratedUser (line 34) | type HydratedUser = Mongoose.HydratedDocument<IUser, IUserMethods, IUser...
  type IUserMethods (line 75) | interface IUserMethods {
  type IUserVirtuals (line 86) | interface IUserVirtuals {
  type IUser (line 94) | interface IUser {
  function v2Parametrize (line 132) | function v2Parametrize(id: Mongoose.Types.ObjectId, email: string) {
  function randomAlphaString (line 294) | function randomAlphaString(length: number): string {

FILE: front/src/utils.ts
  function emailHash (line 24) | function emailHash(email: string): string {
  type IDestroyable (line 28) | interface IDestroyable {
  type IWorkspace (line 32) | interface IWorkspace {

FILE: front/src/workspace_normal.ts
  type Err (line 31) | type Err = Error|null;
  class NormalWorkspace (line 36) | class NormalWorkspace
    method constructor (line 45) | constructor(sessCode: string|null, user: HydratedUser|null, bucket: IB...
    method destroyD (line 57) | public destroyD(message: string){
    method beginOctaveRequest (line 78) | public beginOctaveRequest(flavor: string) {
    method destroyU (line 130) | public destroyU(message: string){
    method dataD (line 134) | public dataD(name: string, val: any){
    method dataU (line 138) | public dataU(name: string, val: any){
    method subscribe (line 142) | public subscribe() {
    method unsubscribe (line 146) | public unsubscribe() {

FILE: front/src/workspace_shared.ts
  type BeginOctaveRequestAsyncAuto (line 34) | interface BeginOctaveRequestAsyncAuto {
  type Err (line 39) | type Err = Error|null;
  class SharedWorkspace (line 49) | class SharedWorkspace
    method constructor (line 68) | constructor(shareKey: string|null, user: HydratedUser|null, bucket: IB...
    method setWsId (line 87) | private setWsId(wsId: string, truncate: boolean) {
    method forEachDoc (line 111) | private forEachDoc(fn: (docId: string,doc: OtDocument) => void){
    method destroyD (line 117) | public destroyD(message: string){
    method destroyU (line 138) | public destroyU(message: string){
    method dataD (line 141) | public dataD(name: string, value: any) {
    method dataU (line 165) | public dataU(name: string, value: any) {
    method resolveFileList (line 191) | private resolveFileList(files: any){
    method resolveFileAdd (line 202) | private resolveFileAdd(file: any){
    method resolveFileSave (line 211) | private resolveFileSave(file: any){
    method resolveFile (line 216) | private resolveFile(filename: string, content: string) {
    method resolveFileRename (line 235) | private resolveFileRename(oldname: string, newname: string) {
    method resolveFileDelete (line 267) | private resolveFileDelete(filename: string) {
    method beginOctaveRequest (line 288) | public beginOctaveRequest(flavor: string) {
    method doBeginOctaveRequest (line 324) | private doBeginOctaveRequest(flavor: string) {
    method subscribe (line 381) | public subscribe() {
    method unsubscribe (line 395) | public unsubscribe() {

FILE: front/typings/easy-no-password.d.ts
  type Err (line 25) | type Err = Error | null;
  type Data (line 27) | interface Data {
  type Options (line 33) | interface Options {
  type VerifiedFn (line 39) | type VerifiedFn = (err: Err, user?: unknown, info?: any) => void;
  type VerifyFn (line 41) | type VerifyFn = ((username: string, verified: VerifiedFn) => void)
  class EasyNoPassword (line 45) | class EasyNoPassword {
  class Strategy (line 53) | class Strategy {

FILE: front/typings/i18next-fs-backend.d.ts
  type IHandleOptions (line 22) | interface IHandleOptions {

FILE: front/typings/i18next-http-middleware.d.ts
  type IHandleOptions (line 22) | interface IHandleOptions {

FILE: front/typings/ot.d.ts
  type ITextOperation (line 22) | interface ITextOperation {
  class Server (line 26) | class Server {
  class TextOperation (line 31) | class TextOperation {

FILE: redirect/bin/server.js
  function normalizePort (line 57) | function normalizePort(val) {
  function onError (line 75) | function onError(error) {
  function onListening (line 101) | function onListening() {

FILE: redirect/src/db.js
  function connect (line 26) | async function connect(url, dbName) {
  function close (line 32) | async function close() {
  function findBucketWithShortlink (line 36) | async function findBucketWithShortlink(shortlink) {

FILE: shared/async-cache.js
  function makePromise (line 30) | function makePromise() {

FILE: shared/gcp/index.js
  function getComputeClient (line 35) | function getComputeClient() {
  function getRecommendedSize (line 49) | async function getRecommendedSize(log) {
  function getTargetSize (line 58) | async function getTargetSize(log) {
  function getAutoscalerInfo (line 67) | async function getAutoscalerInfo(log) {
  function getSelfName (line 78) | async function getSelfName(log) {
  function removeSelfFromGroup (line 84) | async function removeSelfFromGroup(log) {
  function getStorageClient (line 110) | function getStorageClient() {
  function downloadFile (line 124) | async function downloadFile(log, bucketName, srcPath, destination) {
  function uploadRepoArchive (line 131) | async function uploadRepoArchive(log, tld, name) {
  function uploadRepoSnapshot (line 141) | async function uploadRepoSnapshot(log, tld, name) {
  function doUploadRepo (line 151) | async function doUploadRepo(log, tld, name, bucketName) {
  function restoreRepoFromCloudStorage (line 166) | async function restoreRepoFromCloudStorage(log, tld, name, bucketName, b...

FILE: shared/gcp/reboot_or_remove_self.js
  function reboot (line 36) | async function reboot() {
  function main (line 40) | async function main() {

FILE: shared/gitarchive.js
  function repoContainsRefs (line 35) | async function repoContainsRefs(tld, name) {
  function createRepoSnapshot (line 61) | async function createRepoSnapshot(tld, name, outStream) {
  function restoreRepoFromZipFile (line 82) | async function restoreRepoFromZipFile(log, tld, name, branchName, zipFil...
  function generateFilename (line 153) | function generateFilename(name) {

FILE: shared/index.d.ts
  class JSONStreamSafe (line 3) | class JSONStreamSafe {
  class OnlineOffline (line 34) | class OnlineOffline {
  class Queue (line 71) | class Queue {
  class RedisMessenger (line 114) | class RedisMessenger {
  class RedisQueue (line 223) | class RedisQueue {
  class StdioMessenger (line 258) | class StdioMessenger {
  class EventEmitter (line 614) | class EventEmitter {
  class EventEmitter (line 680) | class EventEmitter {
  class EventEmitter (line 746) | class EventEmitter {
  class EventEmitter (line 812) | class EventEmitter {
  class EventEmitter (line 878) | class EventEmitter {
  class EventEmitter (line 944) | class EventEmitter {

FILE: shared/json-stream-safe.js
  class JSONStreamSafe (line 30) | class JSONStreamSafe extends EventEmitter {
    method constructor (line 31) | constructor(stream) {
    method _run (line 37) | _run() {

FILE: shared/metrics.js
  function getClient (line 29) | function getClient() {

FILE: shared/online-offline.js
  class OnlineOffline (line 34) | class OnlineOffline extends EventEmitter {
    method constructor (line 35) | constructor() {
    method isOnline (line 43) | isOnline() {
    method create (line 47) | create(next) {
    method _afterCreate (line 83) | _afterCreate(err) {
    method destroy (line 128) | destroy(next) {
    method _afterDestroy (line 165) | _afterDestroy(err) {
    method _internalDestroyed (line 192) | _internalDestroyed(err) {

FILE: shared/queue.js
  class Queue (line 27) | class Queue extends EventEmitter {
    method constructor (line 28) | constructor() {
    method size (line 34) | size() {
    method enqueue (line 38) | enqueue(item) {
    method dequeue (line 45) | dequeue() {
    method peek (line 53) | peek() {
    method removeAll (line 61) | removeAll() {
    method isEmpty (line 65) | isEmpty() {

FILE: shared/redis-messenger.js
  class RedisMessenger (line 33) | class RedisMessenger extends EventEmitter {
    method constructor (line 34) | constructor() {
    method enableSessCodeScriptsSync (line 60) | enableSessCodeScriptsSync() {
    method enableOtScriptsSync (line 66) | enableOtScriptsSync() {
    method _makeScriptManager (line 83) | _makeScriptManager() {
    method input (line 89) | input(sessCode, name, content) {
    method subscribeToInput (line 98) | subscribeToInput() {
    method output (line 104) | output(sessCode, name, content) {
    method subscribeToOutput (line 113) | subscribeToOutput() {
    method putSessCode (line 119) | putSessCode(sessCode, millisecondBoost, content) {
    method putSessCodeFlavor (line 123) | putSessCodeFlavor(sessCode, millisecondBoost, flavor, content) {
    method _putSessCode (line 127) | _putSessCode(sessCode, millisecondBoost, channel, content) {
    method getSessCode (line 142) | getSessCode(next) {
    method getSessCodeFlavor (line 146) | getSessCodeFlavor(flavor, next) {
    method _getSessCode (line 150) | _getSessCode(channel, next) {
    method destroyD (line 164) | destroyD(sessCode, reason) {
    method subscribeToDestroyD (line 180) | subscribeToDestroyD() {
    method destroyU (line 188) | destroyU(sessCode, reason) {
    method subscribeToDestroyU (line 202) | subscribeToDestroyU() {
    method setLive (line 210) | setLive(sessCode) {
    method isValid (line 217) | isValid(sessCode, next) {
    method touchInput (line 223) | touchInput(sessCode, short) {
    method touchOutput (line 234) | touchOutput(sessCode) {
    method touchWorkspace (line 243) | touchWorkspace(wsId) {
    method touchOtDoc (line 250) | touchOtDoc(docId) {
    method subscribeToExpired (line 259) | subscribeToExpired() {
    method requestReboot (line 267) | requestReboot(id, priority) {
    method requestFlavorStatus (line 271) | requestFlavorStatus(flavor, id, priority) {
    method _requestReboot (line 275) | _requestReboot(channel, id, priority) {
    method replyToRebootRequest (line 289) | replyToRebootRequest(id, response) {
    method replyToFlavorStatus (line 293) | replyToFlavorStatus(flavor, id, response) {
    method _replyToRebootRequest (line 297) | _replyToRebootRequest(channel, id, response) {
    method subscribeToRebootRequests (line 311) | subscribeToRebootRequests() {
    method subscribeToFlavorStatus (line 315) | subscribeToFlavorStatus(flavor) {
    method _subscribeToRebootRequests (line 319) | _subscribeToRebootRequests(channel, eventName) {
    method workspaceMsg (line 327) | workspaceMsg(wsId, type, data) {
    method subscribeToWorkspaceMsgs (line 339) | subscribeToWorkspaceMsgs() {
    method getWorkspaceSessCode (line 347) | getWorkspaceSessCode(wsId, next) {
    method setWorkspaceSessCode (line 352) | setWorkspaceSessCode(wsId, newSessCode, oldSessCode, next) {
    method otMsg (line 361) | otMsg(docId, obj) {
    method subscribeToOtMsgs (line 370) | subscribeToOtMsgs() {
    method changeOtDocId (line 378) | changeOtDocId(oldDocId, newDocId) {
    method destroyOtDoc (line 389) | destroyOtDoc(docId) {
    method loadOtDoc (line 400) | loadOtDoc(docId, next) {
    method applyOtOperation (line 412) | applyOtOperation(docId, rev, message) {
    method setOtDocContent (line 430) | setOtDocContent(docId, content, message) {
    method close (line 448) | close() {
    method _subscribe (line 454) | _subscribe(channel) {
    method _psubscribe (line 472) | _psubscribe(chanFn) {
    method _epsubscribe (line 499) | _epsubscribe() {
    method _runScript (line 516) | _runScript(memo, keys, args, next) {
    method _serializeMessage (line 525) | _serializeMessage(name, content) {
    method _emitMessage (line 546) | _emitMessage(sessCode, message) {
    method _uploadAttachment (line 566) | _uploadAttachment(id, contentString, next) {
    method _downloadAttachment (line 583) | _downloadAttachment(id, next) {
    method _handleError (line 601) | _handleError() {
    method _ensureNotSubscribed (line 605) | _ensureNotSubscribed() {

FILE: shared/redis-queue.js
  class RedisQueue (line 28) | class RedisQueue extends EventEmitter {
    method constructor (line 29) | constructor(logId) {
    method enqueueMessage (line 36) | enqueueMessage(name, getData) {
    method reset (line 47) | reset() {
    method _flushMessageQueue (line 51) | _flushMessageQueue() {

FILE: shared/redis-util.js
  constant PORT (line 30) | const PORT = config.redis.port;
  constant HOSTNAME (line 31) | const HOSTNAME = config.redis.hostname;
  constant OPTIONS (line 32) | const OPTIONS = config.redis.options;
  class MockRedisClient (line 34) | class MockRedisClient extends EventEmitter {
    method psubscribe (line 35) | psubscribe(name, ...args) {
    method subscribe (line 38) | subscribe(name, ...args) {
    method multi (line 41) | multi() {
    method send_command (line 45) | send_command(name, ...args) {
    method del (line 48) | del(name, ...args) {
    method publish (line 51) | publish(name, ...args) {
    method zadd (line 54) | zadd(name, ...args) {
    method zrem (line 57) | zrem(name, ...args) {
    method hget (line 60) | hget(name, ...args) {
    method hset (line 63) | hset(name, ...args) {
    method set (line 66) | set(name, ...args) {
    method expire (line 69) | expire(name, ...args) {
    method exec (line 72) | exec() {

FILE: shared/silent.js
  function silent (line 24) | function silent(messageRegex, next) {

FILE: shared/stackdriver/index.js
  function reportError (line 33) | function reportError(label, message) {
  function writeLog (line 40) | function writeLog(level, label, args) {

FILE: shared/stdio-messenger.js
  class StdioMessenger (line 27) | class StdioMessenger extends OnlineOffline {
    method constructor (line 28) | constructor() {
    method setReadStream (line 39) | setReadStream(stream) {
    method setWriteStream (line 48) | setWriteStream(stream) {
    method sendMessage (line 55) | sendMessage(name, content) {
    method _flush (line 60) | _flush() {
    method _handleData (line 69) | _handleData(data) {

FILE: shared/time-limit.js
  function timeLimit (line 24) | function timeLimit(milliseconds, defaults, callback) {

FILE: utils-admin/bin/server.js
  function normalizePort (line 57) | function normalizePort(val) {
  function onError (line 75) | function onError(error) {
  function onListening (line 101) | function onListening() {

FILE: utils-admin/routes/users.js
  function randomString (line 35) | function randomString(length) {

FILE: utils-admin/src/db.js
  function connect (line 26) | async function connect(url, dbName) {
  function close (line 32) | async function close() {
  function find (line 36) | async function find(collectionName, query) {
  function findById (line 41) | async function findById(collectionName, id) {
  function findAll (line 52) | function findAll(collectionName, query, projection) {
  function updateById (line 58) | async function updateById(collectionName, id, update) {
  function replaceById (line 65) | async function replaceById(collectionName, id, newDoc) {
  function createDocument (line 72) | async function createDocument(collectionName, newDoc) {

FILE: utils-admin/src/repo.js
  function deleteRepo (line 25) | async function deleteRepo(user) {

FILE: utils-auth/app.js
  constant SOCKET_PATH (line 33) | const SOCKET_PATH = "/var/run/oosocks/auth.sock";
  function prompt (line 123) | function prompt(res, message) {
Condensed preview — 321 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (2,054K chars).
[
  {
    "path": ".dockerignore",
    "chars": 47,
    "preview": ".git/\n**/_old\n**/node_modules\n**/tmp\n**/vendor\n"
  },
  {
    "path": ".editorconfig",
    "chars": 297,
    "preview": "root = true\n\n[*]\nend_of_line = lf\ntrim_trailing_whitespace = true\ninsert_final_newline = true\ncharset = utf-8\n\n# Default"
  },
  {
    "path": ".eslintignore",
    "chars": 97,
    "preview": "node_modules/\nnode_modules_1/\nvendor/\ndist/\nbuild/\nclient/app/fonts/\n_old/\nfront/\nfront2/\n*.d.ts\n"
  },
  {
    "path": ".eslintrc.yml",
    "chars": 264,
    "preview": "env:\n  es6: true\n  node: true\nextends: 'eslint:recommended'\nparserOptions:\n  ecmaVersion: 2018\nrules:\n  indent:\n    - er"
  },
  {
    "path": ".gcloudignore",
    "chars": 28,
    "preview": "#!include:.gitignore\n\n.git/\n"
  },
  {
    "path": ".github/workflows/build-test.yml",
    "chars": 420,
    "preview": "name: Node.js CI\n\non: [push]\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    steps:\n    - uses: actions/checkout@v2\n    -"
  },
  {
    "path": ".gitignore",
    "chars": 1111,
    "preview": "# Copyright © 2018, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": ".npmrc",
    "chars": 130,
    "preview": "# Please keep this in sync with all other .npmrc files\n# SEE: https://github.com/npm/feedback/discussions/864\ninstall-li"
  },
  {
    "path": "COPYING",
    "chars": 34523,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "Makefile",
    "chars": 2912,
    "preview": "# Copyright © 2018, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "README.md",
    "chars": 24027,
    "preview": "Octave Online Server\n====================\n\nThis repository contains the full stack of code to run Octave Online Server, "
  },
  {
    "path": "back-filesystem/.eslintrc.yml",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "back-filesystem/.npmrc",
    "chars": 130,
    "preview": "# Please keep this in sync with all other .npmrc files\n# SEE: https://github.com/npm/feedback/discussions/864\ninstall-li"
  },
  {
    "path": "back-filesystem/README.md",
    "chars": 1588,
    "preview": "Octave Online Server: Back Server, Filesystem Utilities\n=======================================================\n\nThis di"
  },
  {
    "path": "back-filesystem/app.js",
    "chars": 1933,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "back-filesystem/git/create-repo-service.js",
    "chars": 3437,
    "preview": "#!/usr/bin/env node\n\n/*\n * Copyright © 2019, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Oc"
  },
  {
    "path": "back-filesystem/git/create-repo.service",
    "chars": 1313,
    "preview": "# Copyright © 2019, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "back-filesystem/git/gitd.service",
    "chars": 1376,
    "preview": "# Copyright © 2019, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "back-filesystem/package.json",
    "chars": 530,
    "preview": "{\n  \"name\": \"@oo/files\",\n  \"version\": \"0.0.0\",\n  \"description\": \"Reads and writes to an Octave session working directory"
  },
  {
    "path": "back-filesystem/src/controller.js",
    "chars": 14531,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "back-filesystem/src/fake-socket.js",
    "chars": 1536,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "back-filesystem/src/git-util.js",
    "chars": 7714,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "back-filesystem/src/logger.js",
    "chars": 1405,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "back-filesystem/src/mime.types",
    "chars": 977,
    "preview": "# Copyright © 2018, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "back-filesystem/src/working-util.js",
    "chars": 7713,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "back-master/.eslintrc.yml",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "back-master/.npmrc",
    "chars": 130,
    "preview": "# Please keep this in sync with all other .npmrc files\n# SEE: https://github.com/npm/feedback/discussions/864\ninstall-li"
  },
  {
    "path": "back-master/README.md",
    "chars": 2616,
    "preview": "Octave Online Server: Back Server\n=================================\n\nThis directory contains the source code for the Oct"
  },
  {
    "path": "back-master/app.js",
    "chars": 6893,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "back-master/package.json",
    "chars": 496,
    "preview": "{\n  \"name\": \"@oo/back\",\n  \"version\": \"0.0.0\",\n  \"description\": \"Spawns Octave sessions and passes messages\",\n  \"main\": \""
  },
  {
    "path": "back-master/src/capped-file-system.js",
    "chars": 5808,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "back-master/src/docker-handler.js",
    "chars": 3904,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "back-master/src/main-flavor.js",
    "chars": 5671,
    "preview": "/*\n * Copyright © 2019, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "back-master/src/main-pool.js",
    "chars": 4568,
    "preview": "/*\n * Copyright © 2019, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "back-master/src/maintenance-request-manager.js",
    "chars": 3990,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "back-master/src/maintenance.js",
    "chars": 1990,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "back-master/src/message-translator.js",
    "chars": 6778,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "back-master/src/octave-session.js",
    "chars": 25374,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "back-master/src/process-handler.js",
    "chars": 4001,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "back-master/src/session-impl.js",
    "chars": 11392,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "back-master/src/session-manager.js",
    "chars": 11033,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "back-octave/Makefile",
    "chars": 1090,
    "preview": "# Copyright © 2018, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "back-octave/README.md",
    "chars": 1136,
    "preview": "Octave Online Server: GNU Octave Utilities\n==========================================\n\nThis directory contains machinery"
  },
  {
    "path": "back-octave/host.c",
    "chars": 8837,
    "preview": "/*\r\n * Copyright © 2018, Octave Online LLC\r\n *\r\n * This file is part of Octave Online Server.\r\n *\r\n * Octave Online Serv"
  },
  {
    "path": "back-octave/oo-changesets/000-README.md",
    "chars": 160,
    "preview": "Patch files from `001` until `100` are based on commit `323e92c4589f` in the GNU Octave mercurial repository, which is i"
  },
  {
    "path": "back-octave/oo-changesets/001-d38b7c534496.hg.txt",
    "chars": 2195,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1453104462 21600\n#      Mon Jan 18 02:07:42 2016"
  },
  {
    "path": "back-octave/oo-changesets/002-d3de6023e846.hg.txt",
    "chars": 6696,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1453119478 21600\n#      Mon Jan 18 06:17:58 2016"
  },
  {
    "path": "back-octave/oo-changesets/003-4d28376c34a8.hg.txt",
    "chars": 2313,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1453120386 21600\n#      Mon Jan 18 06:33:06 2016"
  },
  {
    "path": "back-octave/oo-changesets/004-6ff3e34eea77.hg.txt",
    "chars": 2909,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1453120461 21600\n#      Mon Jan 18 06:34:21 2016"
  },
  {
    "path": "back-octave/oo-changesets/005-9e73fe0d92d5.hg.txt",
    "chars": 927,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1453121851 21600\n#      Mon Jan 18 06:57:31 2016"
  },
  {
    "path": "back-octave/oo-changesets/006-15d21ceec728.hg.txt",
    "chars": 36192,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1453127653 21600\n#      Mon Jan 18 08:34:13 2016"
  },
  {
    "path": "back-octave/oo-changesets/007-4d778d6ebbd0.hg.txt",
    "chars": 990,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1453275208 21600\n#      Wed Jan 20 01:33:28 2016"
  },
  {
    "path": "back-octave/oo-changesets/008-e8ef7f3333bf.hg.txt",
    "chars": 10788,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1458303601 18000\n#      Fri Mar 18 07:20:01 2016"
  },
  {
    "path": "back-octave/oo-changesets/009-05f7272c001e.hg.txt",
    "chars": 6511,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1458307337 18000\n#      Fri Mar 18 08:22:17 2016"
  },
  {
    "path": "back-octave/oo-changesets/010-4a1afb661c55.hg.txt",
    "chars": 1807,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1458312433 18000\n#      Fri Mar 18 09:47:13 2016"
  },
  {
    "path": "back-octave/oo-changesets/011-7327936fa23e.hg.txt",
    "chars": 7645,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1481411965 0\n#      Sat Dec 10 23:19:25 2016 +00"
  },
  {
    "path": "back-octave/oo-changesets/012-84390db50239.hg.txt",
    "chars": 2335,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1481412676 28800\n#      Sat Dec 10 15:31:16 2016"
  },
  {
    "path": "back-octave/oo-changesets/013-f4110d638cdb.hg.txt",
    "chars": 1191,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1481417641 28800\n#      Sat Dec 10 16:54:01 2016"
  },
  {
    "path": "back-octave/oo-changesets/014-21fd506b7530.hg.txt",
    "chars": 1658,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1481421015 28800\n#      Sat Dec 10 17:50:15 2016"
  },
  {
    "path": "back-octave/oo-changesets/100-2d1fd5fdd1d5.hg.txt",
    "chars": 62768,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1514199455 21600\n#      Mon Dec 25 04:57:35 2017"
  },
  {
    "path": "back-octave/oo-changesets/100-README.md",
    "chars": 240,
    "preview": "Patch file `100` contains all previous patch files combined and applied against commit `b9d482dd90f3` in the GNU Octave "
  },
  {
    "path": "back-octave/oo-changesets/101-bc8cd93feec5.hg.txt",
    "chars": 1389,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1514203589 21600\n#      Mon Dec 25 06:06:29 2017"
  },
  {
    "path": "back-octave/oo-changesets/102-30d8ba0fbc32.hg.txt",
    "chars": 3059,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1514234238 21600\n#      Mon Dec 25 14:37:18 2017"
  },
  {
    "path": "back-octave/oo-changesets/103-352b599bc533.hg.txt",
    "chars": 2273,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1514767734 21600\n#      Sun Dec 31 18:48:54 2017"
  },
  {
    "path": "back-octave/oo-changesets/104-9475120a3110.hg.txt",
    "chars": 2589,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1515058277 21600\n#      Thu Jan 04 03:31:17 2018"
  },
  {
    "path": "back-octave/oo-changesets/105-ccbef5c9b050.hg.txt",
    "chars": 1368,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1515058304 21600\n#      Thu Jan 04 03:31:44 2018"
  },
  {
    "path": "back-octave/oo-changesets/106-91cb270ffac0.hg.txt",
    "chars": 1286,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1515059962 21600\n#      Thu Jan 04 03:59:22 2018"
  },
  {
    "path": "back-octave/oo-changesets/107-80081f9d8ff7.hg.txt",
    "chars": 1200,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1515065941 21600\n#      Thu Jan 04 05:39:01 2018"
  },
  {
    "path": "back-octave/oo-changesets/108-9b39ca8bcbfd.hg.txt",
    "chars": 1567,
    "preview": "# HG changeset patch\n# User Octave Online <webmaster@octave-online.net>\n# Date 1555656254 0\n#      Fri Apr 19 06:44:14 2"
  },
  {
    "path": "back-octave/oo-changesets/200-84cbf166497f.hg.txt",
    "chars": 68695,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1577968674 21600\n#      Thu Jan 02 06:37:54 2020"
  },
  {
    "path": "back-octave/oo-changesets/200-README.md",
    "chars": 176,
    "preview": "Patch file `200` is the data on the oo-4.2.1 branch applied against Octave 5.2 RC and saved in a new branch oo-5.2.  It "
  },
  {
    "path": "back-octave/oo-changesets/201-b993253f19d0.hg.txt",
    "chars": 19553,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1578034524 21600\n#      Fri Jan 03 00:55:24 2020"
  },
  {
    "path": "back-octave/oo-changesets/202-d9d23f97ba78.hg.txt",
    "chars": 1725,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1578045495 21600\n#      Fri Jan 03 03:58:15 2020"
  },
  {
    "path": "back-octave/oo-changesets/203-d6b5ffb8e4cc.hg.txt",
    "chars": 756,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1578047258 21600\n#      Fri Jan 03 04:27:38 2020"
  },
  {
    "path": "back-octave/oo-changesets/204-e61d7b8918e2.hg.txt",
    "chars": 2948,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane@sffc.xyz>\n# Date 1578122988 21600\n#      Sat Jan 04 01:29:48 2020 -0600"
  },
  {
    "path": "back-octave/oo-changesets/300-d78448f9c483.hg.txt",
    "chars": 71358,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1593731318 18000\n#      Thu Jul 02 18:08:38 2020"
  },
  {
    "path": "back-octave/oo-changesets/301-97f7d1f4fe83.hg.txt",
    "chars": 34334,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1593748718 0\n#      Fri Jul 03 03:58:38 2020 +00"
  },
  {
    "path": "back-octave/oo-changesets/302-8900d7cf8554.hg.txt",
    "chars": 1412,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1593856818 18000\n#      Sat Jul 04 05:00:18 2020"
  },
  {
    "path": "back-octave/oo-changesets/310-1e1c91e6cddc.hg.txt",
    "chars": 73567,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1593894938 18000\n#      Sat Jul 04 15:35:38 2020"
  },
  {
    "path": "back-octave/oo-changesets/320-8d4683a83238.hg.txt",
    "chars": 73765,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1640589439 21600\n#      Mon Dec 27 01:17:19 2021"
  },
  {
    "path": "back-octave/oo-changesets/321-faad58416a3a.hg.txt",
    "chars": 1529,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1640591257 21600\n#      Mon Dec 27 01:47:37 2021"
  },
  {
    "path": "back-octave/oo-changesets/400-7ade2492e023.hg.txt",
    "chars": 73750,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1640564444 21600\n#      Sun Dec 26 18:20:44 2021"
  },
  {
    "path": "back-octave/oo-changesets/401-1b33dc797ec9.hg.txt",
    "chars": 6103,
    "preview": "# HG changeset patch\n# User Octave Online Team <webmaster@octave-online.net>\n# Date 1640567764 21600\n#      Sun Dec 26 1"
  },
  {
    "path": "back-octave/oo-changesets/402-b01fa2864d4d.hg.txt",
    "chars": 1393,
    "preview": "# HG changeset patch\n# User Octave Online Team <webmaster@octave-online.net>\n# Date 1640569694 21600\n#      Sun Dec 26 1"
  },
  {
    "path": "back-octave/oo-changesets/403-2813cb96e10f.hg.txt",
    "chars": 2378,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1640570532 21600\n#      Sun Dec 26 20:02:12 2021"
  },
  {
    "path": "back-octave/oo-changesets/404-acb523f25bb9.hg.txt",
    "chars": 6199,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1640575083 21600\n#      Sun Dec 26 21:18:03 2021"
  },
  {
    "path": "back-octave/oo-changesets/405-6ad34b0b69e1.hg.txt",
    "chars": 3125,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1640576162 21600\n#      Sun Dec 26 21:36:02 2021"
  },
  {
    "path": "back-octave/oo-changesets/406-d0df6f16f41e.hg.txt",
    "chars": 4769,
    "preview": "# HG changeset patch\n# User Octave Online Team <webmaster@octave-online.net>\n# Date 1640581133 21600\n#      Sun Dec 26 2"
  },
  {
    "path": "back-octave/oo-changesets/407-df206dd11399.hg.txt",
    "chars": 1477,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1640581766 21600\n#      Sun Dec 26 23:09:26 2021"
  },
  {
    "path": "back-octave/oo-changesets/408-8184a51579f3.hg.txt",
    "chars": 1523,
    "preview": "# HG changeset patch\n# User Shane F. Carr <shane.carr@wustl.edu>\n# Date 1640581778 21600\n#      Sun Dec 26 23:09:38 2021"
  },
  {
    "path": "back-octave/oo-changesets/420-4c3d80dd9e65.hg.txt",
    "chars": 77002,
    "preview": "# HG changeset patch\n# User username = Octave Online Team <webmaster@octave-online.net>\n# Date 1672382380 21600\n#      F"
  },
  {
    "path": "back-octave/oo-changesets/421-de16dd99ab0e.hg.txt",
    "chars": 11468,
    "preview": "# HG changeset patch\n# User Octave Online Team <webmaster@octave-online.net>\n# Date 1672385388 21600\n#      Fri Dec 30 0"
  },
  {
    "path": "back-octave/oo-changesets/422-de16dd99ab0e.hg.txt",
    "chars": 4088,
    "preview": "# HG changeset patch\n# User Octave Online Team <webmaster@octave-online.net>\n# Date 1673173830 21600\n#      Sun Jan 08 0"
  },
  {
    "path": "back-octave/oo-changesets/430-d2250ae9bddd.hg.patch",
    "chars": 78466,
    "preview": "# HG changeset patch\n# User username = Octave Online Team <webmaster@octave-online.net>\n# Date 1703965894 21600\n#      S"
  },
  {
    "path": "client/.bowerrc",
    "chars": 31,
    "preview": "{\n  \"directory\": \"app/vendor\"\n}"
  },
  {
    "path": "client/.gitignore",
    "chars": 829,
    "preview": "# Copyright © 2018, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "client/.npmrc",
    "chars": 130,
    "preview": "# Please keep this in sync with all other .npmrc files\n# SEE: https://github.com/npm/feedback/discussions/864\ninstall-li"
  },
  {
    "path": "client/COPYING",
    "chars": 34523,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "client/Gruntfile.js",
    "chars": 5964,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/README.md",
    "chars": 988,
    "preview": "Octave Online Server: Client\n============================\n\nThis directory contains the web frontend code for Octave Onli"
  },
  {
    "path": "client/app/.eslintrc.yml",
    "chars": 526,
    "preview": "# Don't inherit ESLint configs:\n# The JavaScript here runs in the browser environment\n# and is designed to be ES5 compat"
  },
  {
    "path": "client/app/colab.html",
    "chars": 2553,
    "preview": "<!DOCTYPE html>\n<!--\nCopyright © 2018, Octave Online LLC\n\nThis file is part of Octave Online Server.\n\nOctave Online Serv"
  },
  {
    "path": "client/app/eula.txt",
    "chars": 5410,
    "preview": "This copy of Octave Online (\"the Software Product\") and accompanying documentation is licensed and not sold. This Softwa"
  },
  {
    "path": "client/app/fonts/dejavusansmono_book/DejaVuSansMono-demo.html",
    "chars": 24093,
    "preview": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
  },
  {
    "path": "client/app/fonts/dejavusansmono_book/specimen_files/easytabs.js",
    "chars": 1082,
    "preview": "(function($){$.fn.easyTabs=function(option){var param=jQuery.extend({fadeSpeed:\"fast\",defaultContent:1,activeClass:'acti"
  },
  {
    "path": "client/app/fonts/dejavusansmono_book/specimen_files/grid_12-825-55-15.css",
    "chars": 4597,
    "preview": "/*Notes about grid:\nColumns:      12\nGrid Width:   825px\nColumn Width: 55px\nGutter Width: 15px\n-------------------------"
  },
  {
    "path": "client/app/fonts/dejavusansmono_book/specimen_files/specimen_stylesheet.css",
    "chars": 7310,
    "preview": "@import url('grid_12-825-55-15.css');\n\n/*  \n\tCSS Reset by Eric Meyer - Released under Public Domain\n    http://meyerweb."
  },
  {
    "path": "client/app/fonts/dejavusansmono_book/stylesheet.css",
    "chars": 428,
    "preview": "@font-face {\n    font-family: 'DejaVu Sans Mono';\n    src: url('DejaVuSansMono-webfont.eot');\n    src: url('DejaVuSansMo"
  },
  {
    "path": "client/app/images/flaticons/download-svg.ai",
    "chars": 45567,
    "preview": "%PDF-1.5\r%\r\n1 0 obj\r<</Metadata 2 0 R/OCProperties<</D<</ON[6 0 R]/Order 7 0 R/RBGroups[]>>/OCGs[6 0 R]>>/Pages 3 0 R/Ty"
  },
  {
    "path": "client/app/images/logo_collections/official/favicon_package/README.md",
    "chars": 1534,
    "preview": "# Your Favicon Package\n\nThis package was generated with [RealFaviconGenerator](https://realfavicongenerator.net/) [v0.16"
  },
  {
    "path": "client/app/images/logo_collections/official/favicon_package/browserconfig.xml",
    "chars": 267,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<browserconfig>\n    <msapplication>\n        <tile>\n            <square150x150logo"
  },
  {
    "path": "client/app/images/logo_collections/official/favicon_package/site.webmanifest",
    "chars": 450,
    "preview": "{\n    \"name\": \"Octave Online\",\n    \"short_name\": \"Octave Online\",\n    \"icons\": [\n        {\n            \"src\": \"android-c"
  },
  {
    "path": "client/app/images/logo_collections/server/favicon_package/README.md",
    "chars": 1530,
    "preview": "# Your Favicon Package\n\nThis package was generated with [RealFaviconGenerator](https://realfavicongenerator.net/) [v0.16"
  },
  {
    "path": "client/app/images/logo_collections/server/favicon_package/browserconfig.xml",
    "chars": 265,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<browserconfig>\n    <msapplication>\n        <tile>\n            <square150x150logo"
  },
  {
    "path": "client/app/images/logo_collections/server/favicon_package/site.webmanifest",
    "chars": 464,
    "preview": "{\n    \"name\": \"Octave Online Server\",\n    \"short_name\": \"Octave Online Server\",\n    \"icons\": [\n        {\n            \"sr"
  },
  {
    "path": "client/app/images/sanscons/license.txt",
    "chars": 146,
    "preview": "SANSCONS ICONS\n\nSource: http://somerandomdude.com/work/sanscons/\nCopyright: P.J. Onori\nLicense: http://creativecommons.o"
  },
  {
    "path": "client/app/js/ace-adapter.js",
    "chars": 10229,
    "preview": "/* eslint-disable */\n/*\nFrom https://github.com/firebase/firepad/blob/master/lib/ace-adapter.coffee\n\nCopyright (c) 2015 "
  },
  {
    "path": "client/app/js/ace-extras.js",
    "chars": 59226,
    "preview": "/* eslint-disable */\n// Additional Ace classes\ndefine(\"ace/ext/language_tools\",[\"require\",\"exports\",\"module\",\"ace/snippe"
  },
  {
    "path": "client/app/js/anal.js",
    "chars": 3284,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/js/app.js",
    "chars": 10272,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/js/base64-toBlob.js",
    "chars": 1304,
    "preview": "/* eslint-disable */\n/*\n * Copyright © 2013 Jeremy (@jeremy.ca)\n *\n * This work is licensed under the Creative Commons A"
  },
  {
    "path": "client/app/js/base64v1.module.js",
    "chars": 4911,
    "preview": "/* eslint-disable */\r\n/*\r\nCopyright Vassilis Petroulias [DRDigit]\r\n\r\nLicensed under the Apache License, Version 2.0 (th"
  },
  {
    "path": "client/app/js/bucket.js",
    "chars": 4532,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/js/client.js",
    "chars": 52733,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/js/detectmobilebrowser.js",
    "chars": 2161,
    "preview": "/* eslint-disable */\n// based on http://detectmobilebrowsers.com/\ndefine(function(){\n\tvar ua = navigator.userAgent || na"
  },
  {
    "path": "client/app/js/download.js",
    "chars": 1176,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/js/flex-resize.js",
    "chars": 4479,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/js/ko-ace.js",
    "chars": 2511,
    "preview": "// Much of this file originates from https://github.com/probonogeek/knockout-ace/blob/master/knockout-ace.js\n\ndefine([\"k"
  },
  {
    "path": "client/app/js/ko-flash.js",
    "chars": 1959,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/js/ko-takeArray.js",
    "chars": 1948,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/js/modernizr-201406b.js",
    "chars": 2549,
    "preview": "/* eslint-disable */\n/* Modernizr 2.6.2 (Custom Build) | MIT & BSD\n * Build: http://modernizr.com/download/#-fontface-ca"
  },
  {
    "path": "client/app/js/octfile.js",
    "chars": 5958,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/js/onboarding.js",
    "chars": 6007,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/js/ot-client.js",
    "chars": 5642,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/js/ot-handler.js",
    "chars": 2874,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/js/polyfill.js",
    "chars": 1531,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/js/runtime.js",
    "chars": 3267,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/js/utils.js",
    "chars": 4974,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/js/vars.js",
    "chars": 4828,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/js/ws-shared.js",
    "chars": 3241,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/main.js",
    "chars": 2073,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/privacy.txt",
    "chars": 189,
    "preview": "Privacy Policy\n==============\n\n<!-- Privacy TXT -->\n\n\nEnd User License Agreement (last updated January 2, 2015)\n========"
  },
  {
    "path": "client/app/privacy_standalone.txt",
    "chars": 2727,
    "preview": "Octave Online LLC values the privacy of our users.  In order to provide excellent software, we collect and save the foll"
  },
  {
    "path": "client/app/styl/all.styl",
    "chars": 1919,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/styl/callouts.styl",
    "chars": 4837,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/styl/editor.styl",
    "chars": 4283,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/styl/flexbox.styl",
    "chars": 3816,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/styl/hamburger.styl",
    "chars": 2193,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/styl/header.styl",
    "chars": 4294,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/styl/mixins.styl",
    "chars": 3069,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/styl/modals.styl",
    "chars": 8397,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/styl/output_panel.styl",
    "chars": 6528,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/styl/print.styl",
    "chars": 1783,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/styl/themes/official/fire.styl",
    "chars": 1422,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/styl/themes/official/ice.styl",
    "chars": 1422,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/styl/themes/official/lava.styl",
    "chars": 1445,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/styl/themes/official/sun.styl",
    "chars": 1423,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/styl/themes/server/fire.styl",
    "chars": 1344,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/styl/themes/server/ice.styl",
    "chars": 1344,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/styl/themes/server/lava.styl",
    "chars": 1363,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/app/styl/themes/server/sun.styl",
    "chars": 1345,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "client/bower.json",
    "chars": 421,
    "preview": "{\n  \"name\": \"octave-online\",\n  \"version\": \"1.0.0\",\n  \"dependencies\": {\n    \"requirejs\": \"latest\",\n    \"jquery\": \"#^1\",\n "
  },
  {
    "path": "client/package.json",
    "chars": 948,
    "preview": "{\n  \"name\": \"@oo/client\",\n  \"version\": \"0.0.0\",\n  \"description\": \"Web client front end for Octave Online\",\n  \"main\": \"ap"
  },
  {
    "path": "config.sample.hjson",
    "chars": 2279,
    "preview": "# Copyright © 2018, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "config_defaults.hjson",
    "chars": 21963,
    "preview": "# Copyright © 2018, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/README.md",
    "chars": 6867,
    "preview": "Containers for Octave Online Server\n===================================\n\nThis directory contains up-to-date container de"
  },
  {
    "path": "containers/octave-deps/Dockerfile",
    "chars": 3268,
    "preview": "# Copyright © 2019, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/octave-deps/cloudbuild.yaml",
    "chars": 1206,
    "preview": "# Copyright © 2019, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/octave-oo/Dockerfile",
    "chars": 5377,
    "preview": "# Copyright © 2019, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/octave-oo/cloudbuild.yaml",
    "chars": 1463,
    "preview": "# Copyright © 2019, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/octave-oo/java.opts",
    "chars": 84,
    "preview": "-Xms4m\n-Xmx32m\n-XX:MetaspaceSize=4m\n-XX:MaxMetaspaceSize=32m\n-XX:-TieredCompilation\n"
  },
  {
    "path": "containers/octave-pkg/Dockerfile",
    "chars": 8068,
    "preview": "# Copyright © 2019, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/octave-pkg/README.md",
    "chars": 784,
    "preview": "Packages for Octave Online Server\n=================================\n\n## Methodology\n\nThere are 70+ packages on Octave Fo"
  },
  {
    "path": "containers/octave-pkg/cloudbuild.yaml",
    "chars": 1341,
    "preview": "# Copyright © 2019, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/octave-pkg/ltfat.patch",
    "chars": 732,
    "preview": "diff -u -r ltfat/inst/nonstatgab/nsdgt.m ltfat/inst/nonstatgab/nsdgt.m\n--- ltfat/inst/nonstatgab/nsdgt.m\t2018-06-21 15:0"
  },
  {
    "path": "containers/octave-pkg/octaverc.m",
    "chars": 2745,
    "preview": "# Copyright © 2018, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/octave-stable/Dockerfile",
    "chars": 2545,
    "preview": "# Copyright © 2019, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/octave-stable/cloudbuild.yaml",
    "chars": 1387,
    "preview": "# Copyright © 2019, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/oo-back/Dockerfile",
    "chars": 1556,
    "preview": "# Copyright © 2020, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/oo-back/cloudbuild.yaml",
    "chars": 3137,
    "preview": "# Copyright © 2019, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/oo-front/Dockerfile",
    "chars": 1614,
    "preview": "# Copyright © 2020, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/oo-front/cloudbuild.yaml",
    "chars": 2863,
    "preview": "# Copyright © 2019, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/oo-gith/Dockerfile",
    "chars": 3543,
    "preview": "# Copyright © 2020, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/oo-gith/cloudbuild.yaml",
    "chars": 1692,
    "preview": "# Copyright © 2019, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/oo-gith/nginx.conf",
    "chars": 2551,
    "preview": "# Copyright © 2019, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/oo-gith/supervisord.conf",
    "chars": 1368,
    "preview": "# Copyright © 2020, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/oo-redirect/cloudbuild.yaml",
    "chars": 1918,
    "preview": "# Copyright © 2021, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/oos-quick-start/docker-compose.yaml",
    "chars": 4083,
    "preview": "# Copyright © 2020, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/utils-admin/cloudbuild.yaml",
    "chars": 1918,
    "preview": "# Copyright © 2020, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/utils-gitd/Dockerfile",
    "chars": 2407,
    "preview": "# Copyright © 2019, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/utils-gitd/cloudbuild.yaml",
    "chars": 1198,
    "preview": "# Copyright © 2019, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/utils-gitd/supervisord.conf",
    "chars": 1565,
    "preview": "# Copyright © 2020, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/utils-gith/Dockerfile",
    "chars": 2924,
    "preview": "# Copyright © 2019, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/utils-gith/cloudbuild.yaml",
    "chars": 1197,
    "preview": "# Copyright © 2019, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "containers/utils-gith/supervisord.conf",
    "chars": 1389,
    "preview": "# Copyright © 2020, Octave Online LLC\n#\n# This file is part of Octave Online Server.\n#\n# Octave Online Server is free so"
  },
  {
    "path": "entrypoint/.eslintrc.yml",
    "chars": 53,
    "preview": "rules:\n  # Allow console.log\n  no-console:\n    - off\n"
  },
  {
    "path": "entrypoint/README.md",
    "chars": 1093,
    "preview": "Octave Online Server: Back Server Entrypoint Scripts\n====================================================\n\nThis director"
  },
  {
    "path": "entrypoint/back-selinux.js",
    "chars": 6277,
    "preview": "#!/usr/bin/env node\n/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Oct"
  },
  {
    "path": "entrypoint/exit.js.sample",
    "chars": 1228,
    "preview": "/*\n * Copyright © 2018, Octave Online LLC\n *\n * This file is part of Octave Online Server.\n *\n * Octave Online Server is"
  },
  {
    "path": "entrypoint/oo-front.service",
    "chars": 264,
    "preview": "[Service]\nExecStart=/srv/oo/projects/front/app.js\nStandardOutput=journal\nStandardError=journal\n#SyslogIdentifier=oo-fron"
  }
]

// ... and 121 more files (download for full content)

About this extraction

This page contains the full source code of the octave-online/octave-online-server GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 321 files (1.8 MB), approximately 553.5k tokens, and a symbol index with 572 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!