Skip to content

Commit

Permalink
Merge branch 'beta'
Browse files Browse the repository at this point in the history
  • Loading branch information
gentee committed Oct 8, 2020
2 parents e6f11b3 + 5aec630 commit 5a64065
Show file tree
Hide file tree
Showing 14 changed files with 455 additions and 338 deletions.
14 changes: 13 additions & 1 deletion api.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ type CompileResponse struct {

type RunResponse struct {
Success bool `json:"success"`
Port int `json:"port"`
ID uint32 `json:"id"`
Error string `json:"error,omitempty"`
}
Expand Down Expand Up @@ -137,8 +138,10 @@ func runHandle(c echo.Context) error {
Title: title,
AssetsDir: cfg.AssetsDir,
LogDir: cfg.Log.Dir,
CDN: cfg.CDN,
Console: console,
IsPlayground: cfg.playground,
IP: c.RealIP(),
UserID: c.(*Auth).User.ID,
Constants: storage.Settings.Constants,
Lang: langCode,
Expand All @@ -154,6 +157,15 @@ func runHandle(c echo.Context) error {
}
if header.IsPlayground {
header.Playground = &cfg.Playground
tasksLimit := cfg.Playground.Tasks
for _, item := range tasks {
if item.Status < TaskFinished {
tasksLimit--
}
}
if tasksLimit <= 0 {
return jsonError(c, Lang(GetLangId(c.(*Auth).User), `errtasklimit`, cfg.Playground.Tasks))
}
}
if src, err = GenSource(item, &header); err != nil {
return jsonError(c, err)
Expand All @@ -173,7 +185,7 @@ func runHandle(c echo.Context) error {
if console {
return c.Blob(http.StatusOK, ``, data.Bytes())
}
return c.JSON(http.StatusOK, RunResponse{Success: true, ID: header.TaskID})
return c.JSON(http.StatusOK, RunResponse{Success: true, Port: header.HTTP.Port, ID: header.TaskID})
}

func pingHandle(c echo.Context) error {
Expand Down
647 changes: 335 additions & 312 deletions assets.go

Large diffs are not rendered by default.

42 changes: 38 additions & 4 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package main

import (
"eonza/lib"
"net"
"net/http"
"strings"
"time"
Expand Down Expand Up @@ -48,30 +49,63 @@ func getCookie(c echo.Context, name string) string {
return cookie.Value
}

func accessIP(curIP, originalIP string) bool {
return curIP == originalIP || net.ParseIP(curIP).IsLoopback()
}

func AuthHandle(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) (err error) {
var (
access string
isAccess bool
)
host := c.Request().Host[:strings.LastIndex(c.Request().Host, `:`)]
ip := c.RealIP()
if len(cfg.Whitelist) > 0 {
var matched bool
clientip := net.ParseIP(ip)
for _, item := range cfg.Whitelist {
_, network, err := net.ParseCIDR(item)
if err == nil && network.Contains(clientip) {
matched = true
break
}
}
if !matched {
return echo.NewHTTPError(http.StatusForbidden, "Access denied")
}
}
url := c.Request().URL.String()
if url == `/ping` {
return next(c)
}

host := c.Request().Host
if offPort := strings.LastIndex(c.Request().Host, `:`); offPort > 0 {
host = host[:offPort]
}
if IsScript {
access = scriptTask.Header.HTTP.Access
} else {
access = cfg.HTTP.Access
}
if access == AccessPrivate {
isAccess = lib.IsPrivate(host, c.RealIP())
isAccess = lib.IsPrivate(host, ip)
} else if access == AccessHost {
if IsScript {
isAccess = (host == scriptTask.Header.HTTP.Host && accessIP(ip, scriptTask.Header.IP)) ||
host == Localhost
} else {
isAccess = host == cfg.HTTP.Host || host == Localhost
}
} else {
isAccess = lib.IsLocalhost(host, c.RealIP())
isAccess = lib.IsLocalhost(host, ip)
}
if !isAccess {
return echo.NewHTTPError(http.StatusForbidden, "Access denied")
}
mutex.Lock()
defer mutex.Unlock()

url := c.Request().URL.String()
if len(storage.Settings.PasswordHash) > 0 && (url == `/` || strings.HasPrefix(url, `/api`) ||
strings.HasPrefix(url, `/ws`) || strings.HasPrefix(url, `/task`)) {
hashid := getCookie(c, "hashid")
Expand Down
26 changes: 19 additions & 7 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,17 @@ type UsersConfig struct {

// Config stores application's settings
type Config struct {
Version string `yaml:"version"` // Version of the application
Mode string `yaml:"mode"` // Mode: default, develop, playground
AssetsDir string `yaml:"assetsdir"` // Directory for assets file. empty - dir of cfg file
Log LogConfig `yaml:"log"` // Log settings
Users UsersConfig `yaml:"users"` // Users settings
HTTP lib.HTTPConfig `yaml:"http"` // Web-server settings
Playground lib.PlaygroundConfig `yaml:"playground"` // Playground settings
Version string `yaml:"version"` // Version of the application
Mode string `yaml:"mode"` // Mode: default, develop, playground
AssetsDir string `yaml:"assetsdir"` // Directory for assets file. empty - dir of cfg file
Log LogConfig `yaml:"log"` // Log settings
Users UsersConfig `yaml:"users"` // Users settings
HTTP lib.HTTPConfig `yaml:"http"` // Web-server settings
Playground lib.PlaygroundConfig `yaml:"playground"` // Playground settings
Whitelist []string `yaml:"whitelist,omitempty"` // Whitelist of IP-addresses
// undocumented fields
PortShift int64 `yaml:"portshift,omitempty"` // shift of the port
CDN string `yaml:"cdn,omitempty"` // url for static files in task

path string // path to cfg file
develop bool
Expand All @@ -51,6 +55,7 @@ type Config struct {
const (
AccessLocalhost = Localhost
AccessPrivate = `private`
AccessHost = `host`
)

var (
Expand Down Expand Up @@ -129,12 +134,19 @@ func LoadConfig() {
cfg.HTTP.Theme = DefTheme
}
switch cfg.HTTP.Access {
case AccessHost:
case AccessPrivate:
default:
cfg.HTTP.Access = AccessLocalhost
}
cfg.develop = cfg.Mode == ModeDevelop
cfg.playground = cfg.Mode == ModePlayground
if cfg.playground {
if cfg.Playground.Tasks == 0 {
cfg.Playground.Tasks = DefTaskLimit
}
}

SetLogging(basename)
if err = InitTaskManager(); err != nil {
golog.Fatal(err)
Expand Down
6 changes: 4 additions & 2 deletions const.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ package main

const (
// Version of the application
Version = "1.1.0+1"
Version = "1.2.0+1"
// DefPort is the default web-server port
DefPort = 3234
// DefTheme is the default web-server theme
Expand All @@ -27,12 +27,14 @@ const (
PortsPool = 1000
TasksLimit = 50
TimeFormat = `2006/01/02 15:04:05`
TimeoutOpen = 3000
TimeoutOpen = 4000
SourceCode = `source-code`
DefLang = 0
// ConsolePrefix is the prefix of eonza console version
ConsolePrefix = `ez`
Localhost = `localhost`
// DefTaskLimit is the maximum running scripts in playground mode
DefTaskLimit = 2
)

// AppInfo contains information about the application
Expand Down
1 change: 1 addition & 0 deletions lib/lib.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ type PlaygroundConfig struct {
Summary int64 `yaml:"summary"` // all files size limit. By default, 10MB
Files int64 `yaml:"files"` // count of files limit. By default, 100
Size int64 `yaml:"size"` // file size limit. By default, 5MB
Tasks int64 `yaml:"tasks"` // running task limit. By default, 1
}

var (
Expand Down
11 changes: 8 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,18 @@ var (

func main() {
var (
e *echo.Echo
psw string
isRun bool
e *echo.Echo
psw string
isRun bool
install bool
)
if isRun = CheckConsole(); isRun && len(consoleData) == 0 {
return
}
golog.SetTimeFormat("2006/01/02 15:04:05")
flag.StringVar(&cfg.path, "cfg", "", "The path of the `config file`")
flag.StringVar(&psw, "psw", "", "The login password")
flag.BoolVar(&install, "install", false, "only install")
flag.Parse()
if err := script.InitEngine(); err != nil {
golog.Fatal(err)
Expand Down Expand Up @@ -91,6 +93,9 @@ func main() {
} else {
LoadConfig()
LoadStorage(psw)
if install {
return
}
LoadUsers()
defer CloseLog()
if err := LoadCustomAsset(cfg.AssetsDir, cfg.HTTP.Theme); err != nil {
Expand Down
4 changes: 4 additions & 0 deletions render.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ type Render struct {
Lang string
Login bool
Localhost bool
PortShift int64
// Port int
/* Params map[string]string
Url string
Expand All @@ -38,6 +39,7 @@ type RenderScript struct {
IsScript bool
Start string
Finish string
CDN string
Source template.HTML
Stdout template.HTML
Logout template.HTML
Expand Down Expand Up @@ -94,6 +96,7 @@ func RenderPage(c echo.Context, url string) (string, error) {
if IsScript {
renderScript.Task = task
renderScript.Title = scriptTask.Header.Title
renderScript.CDN = scriptTask.Header.CDN
} else {
renderScript.Task = *c.Get(`Task`).(*Task)
renderScript.Title = c.Get(`Title`).(string)
Expand Down Expand Up @@ -126,6 +129,7 @@ func RenderPage(c echo.Context, url string) (string, error) {
}
render.Login = len(storage.Settings.PasswordHash) > 0
render.Localhost = cfg.HTTP.Host == Localhost
render.PortShift = cfg.PortShift
data = render
}

Expand Down
23 changes: 18 additions & 5 deletions script/embedded.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"time"

"github.com/gentee/gentee"
"github.com/gentee/gentee/vm"
"gopkg.in/yaml.v2"
)

Expand Down Expand Up @@ -125,12 +126,12 @@ var (
}
)

func IsCond(item *ConditionItem) (err error) {
func IsCond(rt *vm.Runtime, item *ConditionItem) (err error) {
var (
i int64
val, s string
)
if len(item.Var) == 0 {
if len(item.Var) == 0 && len(item.Value) == 0 {
return fmt.Errorf(`empty variable in If Statement`)
}
if val, err = Macro(item.Value); err != nil {
Expand All @@ -149,6 +150,18 @@ func IsCond(item *ConditionItem) (err error) {
}
item.result = s == val
}
case `fileexists`:
if len(item.Var) > 0 {
if s, err = GetVar(item.Var); err != nil {
return
}
} else {
s = val
}
if i, err = vm.ExistFile(rt, s); err != nil {
return
}
item.result = i != 0
default:
return fmt.Errorf(`Unknown comparison type: %s`, item.Cmp)
}
Expand All @@ -158,7 +171,7 @@ func IsCond(item *ConditionItem) (err error) {
return
}

func Condition(casevar, list string) (ret int64, err error) {
func Condition(rt *vm.Runtime, casevar, list string) (ret int64, err error) {
if len(casevar) > 0 {
var used int64
if used, err = GetVarBool(casevar); err != nil || used != 0 {
Expand All @@ -173,7 +186,7 @@ func Condition(casevar, list string) (ret int64, err error) {
if count == 0 {
ret = 1
} else {
if err = IsCond(&cond[0]); err != nil {
if err = IsCond(rt, &cond[0]); err != nil {
return
}
// collect OR
Expand All @@ -190,7 +203,7 @@ func Condition(casevar, list string) (ret int64, err error) {
continue
}
}
if err = IsCond(&cond[i]); err != nil {
if err = IsCond(rt, &cond[i]); err != nil {
return
}
cond[0].result = cond[i].result
Expand Down
2 changes: 2 additions & 0 deletions script/encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ type Header struct {
AssetsDir string
LogDir string
Theme string
CDN string
Console bool
IsPlayground bool
SourceCode []byte
Constants map[string]string
Lang string
UserID uint32
IP string
TaskID uint32
ServerPort int
HTTP *lib.HTTPConfig
Expand Down
11 changes: 7 additions & 4 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,9 @@ func indexHandle(c echo.Context) error {
}*/

func exitHandle(c echo.Context) error {
if cfg.playground {
return jsonError(c, `Access denied`)
}
golog.Info(`Finish`)
stopchan <- os.Interrupt
return c.JSON(http.StatusOK, Response{Success: true})
Expand Down Expand Up @@ -205,10 +208,10 @@ func RunServer(options WebSettings) *echo.Echo {
e.Use(AuthHandle)
e.Use(Logger)
e.Use(md.Recover())
/* e.Use(md.CORSWithConfig(md.CORSConfig{
AllowOrigins: []string{"http://localhost"},
AllowMethods: []string{http.MethodGet, http.MethodPost},
}))*/
/* e.Use(md.CORSWithConfig(md.CORSConfig{
AllowOrigins: []string{"*"},
AllowMethods: []string{http.MethodGet},
}))}*/

//e.HTTPErrorHandler = customHTTPErrorHandler

Expand Down
3 changes: 3 additions & 0 deletions settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ func setPasswordHandle(c echo.Context) error {
err error
hash []byte
)
if cfg.playground {
return jsonError(c, Lang(GetLangId(c.(*Auth).User), `errplaypsw`))
}
if err = c.Bind(&psw); err != nil {
return jsonError(c, err)
}
Expand Down
1 change: 1 addition & 0 deletions task.go
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,7 @@ func initTask() script.Settings {

func wsTaskHandle(c echo.Context) error {
// var cmd WsCmd
upgrader.CheckOrigin = func(r *http.Request) bool { return true }
ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)
if err != nil {
return err
Expand Down
Loading

0 comments on commit 5a64065

Please sign in to comment.