github.com/annchain/OG@v0.0.9/tests/configServer/config_server.go (about)

     1  // Copyright © 2019 Annchain Authors <EMAIL ADDRESS>
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  package main
    15  
    16  import (
    17  	"fmt"
    18  	"github.com/gin-gonic/gin"
    19  	"net/http"
    20  	"path/filepath"
    21  	"strconv"
    22  	"strings"
    23  )
    24  
    25  var DOWNLOADS_PATH = ""
    26  
    27  type Server struct {
    28  	router *gin.Engine
    29  	server *http.Server
    30  	port   string
    31  }
    32  
    33  func main() {
    34  	port := "18012"
    35  	router := gin.New()
    36  	router.GET("og_config", DownloadFile)
    37  	router.GET("", HelpFunc)
    38  	srv := &Server{
    39  		server: &http.Server{
    40  			Addr:    ":" + port,
    41  			Handler: router,
    42  		},
    43  	}
    44  	if err := srv.server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
    45  		panic(fmt.Errorf("error in Http server %v", err))
    46  	}
    47  }
    48  
    49  func DownloadFile(ctx *gin.Context) {
    50  	node_id := ctx.Query("node_id")
    51  	_, err := strconv.Atoi(node_id)
    52  	if err != nil {
    53  		ctx.JSON(http.StatusBadRequest, gin.H{
    54  			"error": "node_id error"})
    55  		return
    56  	}
    57  	fileName := "config_" + node_id + ".toml"
    58  	targetPath := filepath.Join(DOWNLOADS_PATH, fileName)
    59  	//This ckeck is for example, I not sure is it can prevent all possible filename attacks - will be much better if real filename will not come from user side. I not even tryed this code
    60  	if !strings.HasPrefix(filepath.Clean(targetPath), DOWNLOADS_PATH) {
    61  		ctx.String(403, "Look like you attacking me")
    62  		return
    63  	}
    64  	//Seems this headers needed for some browsers (for example without this headers Chrome will download files as txt)
    65  	//ctx.Header("Content-Description", "File Transfer")
    66  	//ctx.Header("Content-Transfer-Encoding", "binary")
    67  	//ctx.Header("Content-Disposition", "attachment; filename="+fileName )
    68  	//ctx.Header("Content-Type", "application/octet-stream")
    69  	fmt.Println("will serve file", targetPath)
    70  	ctx.File(targetPath)
    71  }
    72  
    73  func HelpFunc(ctx *gin.Context) {
    74  	ctx.JSON(403, gin.H{
    75  		"error": "not allowed"})
    76  }