diff --git a/coder-apps/common/auth/app/app.js b/coder-apps/common/auth/app/app.js index dacd9034..93cc8af8 100644 --- a/coder-apps/common/auth/app/app.js +++ b/coder-apps/common/auth/app/app.js @@ -362,7 +362,7 @@ exports.api_addpassword_handler = function( req, res ) { //setpass.addListener( 'exit', function( code, signal ) { var completed = function( code, signal ) { - err = code; + err = code; if ( err ) { @@ -440,16 +440,17 @@ exports.api_changepassword_handler = function( req, res ) { //device_settings.device_name = devicename; var erroutput = ""; var output = ""; - var setpipass = process.cwd() + '/sudo_scripts/setpipass'; - var setpass = spawn( '/usr/bin/sudo', [setpipass] ); - setpass.stdout.on( 'data', function( d ) { - output += d; - }); - setpass.stderr.on( 'data', function( d ) { - erroutput += d; - }); + //var setpipass = process.cwd() + '/sudo_scripts/setpipass'; + //var setpass = spawn( '/usr/bin/sudo', [setpipass] ); + //setpass.stdout.on( 'data', function( d ) { + // output += d; + //}); + //setpass.stderr.on( 'data', function( d ) { + // erroutput += d; + //}); - setpass.addListener( 'exit', function( code, signal ) { + //setpass.addListener( 'exit', function( code, signal ) { + var completed = function( code, signal ) { err = code; @@ -479,11 +480,13 @@ exports.api_changepassword_handler = function( req, res ) { }); } - }); - setpass.stdin.write(pass + '\n'); - setpass.stdin.write(pass + '\n'); - setpass.stdin.end(); + }; + completed(); + + //setpass.stdin.write(pass + '\n'); + //setpass.stdin.write(pass + '\n'); + //setpass.stdin.end(); }; diff --git a/coder-base/.gitignore b/coder-base/.gitignore new file mode 100644 index 00000000..3343905d --- /dev/null +++ b/coder-base/.gitignore @@ -0,0 +1,2 @@ +config.js + diff --git a/coder-base/apps/.gitignore b/coder-base/apps/.gitignore index e69de29b..72e8ffc0 100644 --- a/coder-base/apps/.gitignore +++ b/coder-base/apps/.gitignore @@ -0,0 +1 @@ +* diff --git a/coder-base/config.js b/coder-base/config.js deleted file mode 100644 index 19052a53..00000000 --- a/coder-base/config.js +++ /dev/null @@ -1,28 +0,0 @@ - -exports.listenIP = null; //Defaults to * -exports.listenPort = '8081'; //the SSL port things run on -exports.httpListenPort = '8080'; //this will all be redirected to SSL -exports.cacheApps = true; -exports.httpVisiblePort = '80'; //forwarded http port the user sees -exports.httpsVisiblePort = '443'; //forwarded https port the user sees - - -//SSL Info -exports.country = "US"; -exports.state = "New York"; -exports.locale = "New York"; -exports.commonName = "coder.local"; -exports.subjectAltName = "DNS:192.168.0.1"; - - -//Experimental -// -//Status Server -// This can be used in conjundtion with the sample findcoder -// appengine project. It allows multiple Coders on the same -// NAT network to be discoverable. Coder devices will ping the -// external server with their internal IP, and the server -// will list the devices for any requesting machine that -// originates from the same external IP. -exports.statusServer = '[yourpingserver].appspot.com'; -exports.enableStatusServer = false; diff --git a/coder-base/config.js.default b/coder-base/config.js.default index 19052a53..01dbc10d 100644 --- a/coder-base/config.js.default +++ b/coder-base/config.js.default @@ -1,19 +1,16 @@ +// Listen can take different values : +// - port number +// - [port number, bind address] array +// - unix socket path +// - "systemd" for socket activation +exports.listen = 80; -exports.listenIP = null; //Defaults to * -exports.listenPort = '8081'; //the SSL port things run on -exports.httpListenPort = '8080'; //this will all be redirected to SSL -exports.cacheApps = true; -exports.httpVisiblePort = '80'; //forwarded http port the user sees -exports.httpsVisiblePort = '443'; //forwarded https port the user sees - - -//SSL Info -exports.country = "US"; -exports.state = "New York"; -exports.locale = "New York"; -exports.commonName = "coder.local"; -exports.subjectAltName = "DNS:192.168.0.1"; +// Automatically stop the server if idle for a long amount of time. +// Designed to be used in conjunction with listen = "systemd". +// Disabled if timeout is 0 +exports.idleTimeout = 0; +exports.cacheApps = true; //Experimental // @@ -26,3 +23,4 @@ exports.subjectAltName = "DNS:192.168.0.1"; // originates from the same external IP. exports.statusServer = '[yourpingserver].appspot.com'; exports.enableStatusServer = false; + diff --git a/coder-base/config.js.localhost b/coder-base/config.js.localhost index 3aa5890b..82f3df35 100644 --- a/coder-base/config.js.localhost +++ b/coder-base/config.js.localhost @@ -1,19 +1,16 @@ +// Listen can take different values : +// - port number +// - [port number, bind address] array +// - unix socket path +// - "systemd" for socket activation +exports.listen = [8080, '127.0.0.1']; -exports.listenIP = '127.0.0.1'; //Defaults to * -exports.listenPort = '8081'; //the SSL port things run on -exports.httpListenPort = '8080'; //this will all be redirected to SSL -exports.cacheApps = true; -exports.httpVisiblePort = '8080'; //forwarded http port the user sees -exports.httpsVisiblePort = '8081'; //forwarded https port the user sees - - -//SSL Info -exports.country = "US"; -exports.state = "New York"; -exports.locale = "New York"; -exports.commonName = "coder.local"; -exports.subjectAltName = "DNS:192.168.0.1"; +// Automatically stop the server if idle for a long amount of time. +// Designed to be used in conjunction with listen = "systemd". +// Disabled if timeout is 0 +exports.idleTimeout = 0; +exports.cacheApps = true; //Experimental // @@ -26,3 +23,4 @@ exports.subjectAltName = "DNS:192.168.0.1"; // originates from the same external IP. exports.statusServer = '[yourpingserver].appspot.com'; exports.enableStatusServer = false; + diff --git a/coder-base/localserver.js b/coder-base/localserver.js deleted file mode 100644 index 1ef8034f..00000000 --- a/coder-base/localserver.js +++ /dev/null @@ -1,177 +0,0 @@ -/** - * Coder for Raspberry Pi - * A simple platform for experimenting with web stuff. - * http://goo.gl/coder - * - * Copyright 2013 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -var express = require('express'); -var io = require('socket.io'); -var net = require('http'); -var http = require('http'); -var https = require('https'); -var crypto = require('crypto'); -var path = require('path'); -var config = require('./config'); -var fs = require('fs'); -var util = require('util'); -var cons = require('consolidate'); -var params = require('express-params'); -var querystring = require('querystring'); - -var loadApp = function( loadpath ) { - - var userapp = null; - if ( config.cacheApps ) { - userapp = require(loadpath); - } else { - - var cached = require.cache[loadpath + '.js']; - if ( cached ) { - userapp = require(loadpath); - if ( userapp.on_destroy ) { - userapp.on_destroy(); - } - delete require.cache[loadpath + ".js"]; - } - userapp = require(loadpath); - } - return userapp; -}; - - -var apphandler = function( req, res, appdir ) { - - var appname = req.params[0]; - var apppath = req.params[1]; - var modpath = appdir + appname; - var userapp = loadApp( modpath + "/app" ); - - - util.log( "GET: " + apppath + " " + appname ); - - //Redirect to sign-in for unauthenticated users - publicAllowed = ["auth"]; //apps that are exempt from any login (should only be auth) - auth = require(appdir + "auth" + "/app"); - user = auth.isAuthenticated(req, res); - if ( !user && publicAllowed.indexOf( appname ) < 0) { - util.log("redirect: " + "http://" + getHost(req) + ":" + config.httpVisiblePort + '/app/auth'); - res.redirect("http://" + getHost(req) + ":" + config.httpVisiblePort + '/app/auth' ); - return; - } - - - if ( !apppath ) { - apppath = "/"; - } else { - apppath = "/" + apppath; - } - - userapp.settings.appname = appname; - userapp.settings.viewpath="apps/" + appname; - userapp.settings.appurl="/app/" + appname; - userapp.settings.staticurl = "/static/apps/" + appname; - userapp.settings.device_name = auth.getDeviceName(); - userapp.settings.coder_owner = auth.getCoderOwner(); - userapp.settings.coder_color = auth.getCoderColor(); - if ( userapp.settings.device_name === "" ) { - userapp.settings.device_name = "Coder"; - } - if ( userapp.settings.coder_color === "" ) { - userapp.settings.coder_color = "#3e3e3e"; - } - - var routes = []; - if ( req.route.method === 'get' ) { - routes = userapp.get_routes; - } else if ( req.route.method === 'post' ) { - routes = userapp.post_routes; - } - - if ( routes ) { - var found = false; - for ( var i in routes ) { - route = routes[i]; - if ( route['path'] instanceof RegExp ) { - var m = route['path'].exec( apppath ); - if ( m ) { - userapp[route['handler']]( req, res, m ); - found = true; - break; - } - - } else if ( route['path'] === apppath ) { - userapp[route['handler']]( req, res ); - found = true; - break; - } - - } - - if ( !found ) { - res.status( 404 ); - res.render('404', { - title: 'error' - }); - } - } -}; - - -var startLocal = function() { - http.createServer(localapp).listen( config.httpListenPort, '127.0.0.1' ); -}; - -var getHost = function( req ) { - var host = req.connection.address().address; - if ( typeof req.headers.host !== "undefined" ) { - host = req.headers.host; - if ( host.match(/:/g) ) { - host = host.slice( 0, host.indexOf(":") ); - } - } - return host; -}; - -//Traffic on 127.0.0.1 (localhost) only -var localapp = express(); -params.extend( localapp ); -localapp.engine( 'html', cons.mustache ); -localapp.set( 'view engine', 'html' ); -localapp.set( 'views', __dirname + '/views' ); -localapp.use( express.bodyParser() ); -localapp.use( express.cookieParser() ); -localapp.use( express.session({ - secret: crypto.randomBytes(16).toString('utf-8'), - store: new express.session.MemoryStore() -})); -localapp.use( '/static', express.static( __dirname + '/static' ) ); -localapp.get( '/', function( req, res ) { - util.log( 'GET: /' ); - res.redirect( '/app/auth' ); -}); -localapp.all( /^\/app\/(\w+)\/(.*)$/, function( req, res ) { apphandler( req, res, __dirname + '/apps/'); } ); -localapp.all( /^\/app\/(\w+)\/$/, function( req, res ) { apphandler( req, res, __dirname + '/apps/'); } ); -localapp.all( /^\/app\/(\w+)$/, function( req, res ) { apphandler( req, res, __dirname + '/apps/'); } ); - - -startLocal(); - -process.on('uncaughtException', function(err) { - console.log('WARNING: unhandled exception: ' + err ); -}); - diff --git a/coder-base/package.json b/coder-base/package.json index e42be37a..e32c6fed 100644 --- a/coder-base/package.json +++ b/coder-base/package.json @@ -1,17 +1,20 @@ { - "name": "coder-base", - "description": "kid-friendly web programming environment for pi", - "version": "0.0.1", - "private": true, - "dependencies": { - "express": "3.1.0", - "redis": "0.8.2", - "mustache": "0.7.2", - "consolidate": "0.8.0", - "socket.io": "0.9.13", - "express-params": "0.0.3", - "bcrypt": "0.7.4", - "connect": "*", - "cookie": "*" - } + "name": "coder-base", + "description": "kid-friendly web programming environment for pi", + "version": "0.0.1", + "private": true, + "dependencies": { + "express": "~4.0", + "express-session": "~1.0", + "body-parser": "~1.0", + "cookie-parser": "~1.0", + "mustache": "~0.8", + "consolidate": "~0.10", + "socket.io": "~0.9", + "bcrypt": "~0.7", + "connect": "~3.0", + "cookie": "~0.1", + "systemd": "git+https://github.com/plietar/node-systemd.git", + "autoquit": "~0.1.6" + } } diff --git a/coder-base/server.js b/coder-base/server.js index 10c8f049..0e45b696 100644 --- a/coder-base/server.js +++ b/coder-base/server.js @@ -23,21 +23,25 @@ var express = require('express'); var socketio = require('socket.io'); var net = require('http'); var http = require('http'); -var https = require('https'); var crypto = require('crypto'); var path = require('path'); -var config = require('./config'); var fs = require('fs'); var util = require('util'); var cons = require('consolidate'); -var params = require('express-params'); var querystring = require('querystring'); -var path = require('path'); var cookie = require('cookie'); var connect = require('connect'); +var session = require('express-session'); +var bodyParser = require('body-parser'); +var cookieParser = require('cookie-parser'); +var systemd = require('systemd') +require('autoquit'); +global.config = require('./config'); +global.coderlib = require('./apps/coderlib/app'); -var loadApp = function( loadpath ) { +var loadApp = function( path, appname, auth ) { + var loadpath = path + appname + "/app"; var userapp = null; if ( config.cacheApps ) { @@ -54,45 +58,35 @@ var loadApp = function( loadpath ) { } userapp = require(loadpath); } - return userapp; -}; -var applyAppSettings = function( userapp, appname, auth ) { - userapp.settings.appname = appname; - userapp.settings.viewpath="apps/" + appname; - userapp.settings.appurl="/app/" + appname; - userapp.settings.staticurl = "/static/apps/" + appname; - userapp.settings.device_name = auth.getDeviceName(); - userapp.settings.coder_owner = auth.getCoderOwner(); - userapp.settings.coder_color = auth.getCoderColor(); - if ( userapp.settings.device_name === "" ) { - userapp.settings.device_name = "Coder"; - } - if ( userapp.settings.coder_color === "" ) { - userapp.settings.coder_color = "#3e3e3e"; + if (userapp) + { + userapp.settings.appname = appname; + userapp.settings.viewpath="apps/" + appname; + userapp.settings.appurl="/app/" + appname; + userapp.settings.staticurl = "/static/apps/" + appname; + userapp.settings.device_name = auth.getDeviceName(); + userapp.settings.coder_owner = auth.getCoderOwner(); + userapp.settings.coder_color = auth.getCoderColor(); + + if ( userapp.settings.device_name === "" ) { + userapp.settings.device_name = "Coder"; + } + if ( userapp.settings.coder_color === "" ) { + userapp.settings.coder_color = "#3e3e3e"; + } } -}; + + return userapp; +} var apphandler = function( req, res, appdir ) { var appname = req.params[0]; var apppath = req.params[1]; - var modpath = appdir + appname; - var userapp = loadApp( modpath + "/app" ); - - - util.log( "GET: " + apppath + " " + appname ); - //Redirect to sign-in for unauthenticated users - publicAllowed = ["auth"]; //apps that are exempt from any login (should only be auth) auth = require(appdir + "auth" + "/app"); - user = auth.isAuthenticated(req, res); - if ( !user && publicAllowed.indexOf( appname ) < 0) { - util.log( "redirect: " + "https://" + getHost(req) + ":" + config.httpsVisiblePort + '/app/auth' ); - res.redirect("https://" + getHost(req) + ":" + config.httpsVisiblePort + '/app/auth' ); - return; - } - + var userapp = loadApp( appdir, appname, auth ); if ( !apppath ) { apppath = "/"; @@ -100,15 +94,24 @@ var apphandler = function( req, res, appdir ) { apppath = "/" + apppath; } - applyAppSettings( userapp, appname, auth ); + util.log( "GET: " + apppath + " " + appname ); + + //Redirect to sign-in for unauthenticated users + publicAllowed = ["auth"]; //apps that are exempt from any login (should only be auth) + user = auth.isAuthenticated(req, res); + if ( !user && publicAllowed.indexOf( appname ) < 0) { + util.log( "redirect: " + '/app/auth' ); + res.redirect('/app/auth'); + return; + } var routes = []; - if ( req.route.method === 'get' ) { + if ( req.method === 'GET' ) { routes = userapp.get_routes; - } else if ( req.route.method === 'post' ) { + } else if ( req.method === 'POST' ) { routes = userapp.post_routes; } - + if ( routes ) { var found = false; for ( var i in routes ) { @@ -120,7 +123,7 @@ var apphandler = function( req, res, appdir ) { found = true; break; } - + } else if ( route['path'] === apppath ) { userapp[route['handler']]( req, res ); found = true; @@ -138,99 +141,38 @@ var apphandler = function( req, res, appdir ) { } }; -var startSSLRedirect = function() { - http.createServer( redirectapp ).listen( config.httpListenPort, config.listenIP ); -}; - -var server; -var startSSL = function() { - - privateKeyFile=path.normalize('certs/server.key'); - certificateFile=path.normalize('certs/server.cert'); - var privateKey=""; - var certificate=""; - try { - privateKey = fs.readFileSync(privateKeyFile).toString(); - certificate = fs.readFileSync(certificateFile).toString(); - } catch ( e ) { - util.print( "no certificate found. generating self signed cert.\n" ); - } - - if ( privateKey !== "" && certificate !== "" ) { - server = https.createServer({ key: privateKey, cert: certificate }, sslapp); - server.listen( config.listenPort, config.listenIP ); - initSocketIO( server ); - } else { - var spawn = require('child_process').spawn; - - var genSelfSignedCert = function(keyFile, certFile) { - var genkey = spawn( 'openssl', [ - 'req', '-x509', '-nodes', - '-days', '365', - '-newkey', 'rsa:2048', - '-keyout', keyFile, - '-out', certFile, - '-subj', - '/C=' + config.country + '/ST=' + config.state + "/L=" + config.locale + "/CN=" + config.commonName + "/subjectAltName=" + config.subjectAltName - ]); - genkey.stdout.on('data', function(d) { util.print(d) } ); - genkey.stderr.on('data', function(d) { util.print(d) } ); - genkey.addListener( 'exit', function( code, signal ) { - fs.chmodSync(privateKeyFile, '600'); - loadServer(); - }); - }; - var loadServer = function() { - privateKey = fs.readFileSync(privateKeyFile).toString(); - certificate = fs.readFileSync(certificateFile).toString(); - server = https.createServer({ key: privateKey, cert: certificate }, sslapp); - server.listen( config.listenPort, config.listenIP ); - initSocketIO( server ); - }; - - genSelfSignedCert(privateKeyFile, certificateFile); - } -}; +var storeSecret = crypto.randomBytes(16).toString('utf-8'); +var sessionStore = new session.MemoryStore(); var io; var socketMap={}; var initSocketIO = function( server ) { io = socketio.listen( server ); + var sioCookieParser = cookieParser(storeSecret); + io.set('log level', 1); //TODO: hack to fix recursion problem since we are piping log info to a socket - // sync session data with socket - // via https://github.com/DanielBaulig/sioe-demo/blob/master/app.js io.set('authorization', function (handshake, accept) { - if (!handshake.headers.cookie) { - console.log('no cookie sent with socket connection'); - return accept('No cookie transmitted.', false); - } - - handshake.cookie = cookie.parse(handshake.headers.cookie); - handshake.sessionID = connect.utils.parseSignedCookie(handshake.cookie['connect.sid'], storesecret); - - if (handshake.cookie['connect.sid'] == handshake.sessionID) { - return accept('Cookie is invalid', false ); - } - - handshake.sessionStore = sslapp.sessionStore; - - if (!handshake.sessionID) { - return accept('Session cookie could not be found', false); - } - - handshake.sessionStore.get(handshake.sessionID, function (err, session) { + sioCookieParser(handshake, {}, function(err) { if (err) { - console.log( 'error loading session' ); - return accept('Error', false); + accept(err, false); + } + else { + sessionStore.get(handshake.signedCookies["connect.sid"], function(err, sessionData) { + if (err || !sessionData) { + accept('Session error', false); + } + else { + handshake.sessionStore = sessionStore; + handshake.session = new session.Session(handshake, sessionData); + accept(null, true); + } + }); } - - var s = handshake.session = new express.session.Session(handshake, session ); - return accept(null, true); }); }); - + var genRandomID = function() { var id = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; @@ -244,10 +186,10 @@ var initSocketIO = function( server ) { io.sockets.on('connection', function (socket) { - var sess = socket.handshake.session; + socket.session = socket.handshake.session; socket.socketID = genRandomID(); - socketMap[socket.socketID] = socket; + socketMap[socket.socketID] = socket; socket.emit('SOCKETID', socket.socketID); socket.on('disconnect', function() { @@ -255,15 +197,14 @@ var initSocketIO = function( server ) { }); socket.on('appdata', function(data) { - if ( !sess.authenticated ) { + if ( !socket.session.authenticated ) { return; } if ( data.appid !== undefined && data.appid.match(/^\w+$/) && data.key !== undefined ) { var appname = data.appid; - var userapp = loadApp( __dirname + '/apps/' + appname + "/app" ); - var auth = require( __dirname + "/apps/auth/app" ); - applyAppSettings( userapp, appname, auth ); - + var auth = require( __dirname + "/apps/auth/app" ); + var userapp = loadApp( __dirname + '/apps/', appname, auth ); + var route; var key = data.key; var routes = userapp.socketio_routes; @@ -278,7 +219,7 @@ var initSocketIO = function( server ) { found = true; break; } - + } else if ( route['key'] === key ) { userapp[route['handler']]( socket, data.data ); found = true; @@ -291,17 +232,18 @@ var initSocketIO = function( server ) { }); }); }; + // Allow front end console to receive server logs over a socket connection. // Note that util.log will still only go to stdout var origlog = console.log; -console.log = function(d) { - origlog.call( console, d ); +console.log = function() { + origlog.apply( console, arguments ); if ( io ) { io.set('log level', 1); var clients = io.sockets.clients(); for ( var x=0; x