newgen
兔子 4 years ago
parent 7835d1fae7
commit 4a8458fab6

@ -0,0 +1,45 @@
package main
import (
"fmt"
"b612.me/starainrt"
"b612.me/starlog"
"github.com/spf13/cobra"
)
var attachcmd = &cobra.Command{
Use: "attach",
Short: "合并两个文件",
Long: "合并两个文件",
Run: func(this *cobra.Command, args []string) {
var src, dst, out string
if len(args) == 3 {
src = args[0]
dst = args[1]
out = args[2]
} else {
src, _ = this.Flags().GetString("src")
dst, _ = this.Flags().GetString("dst")
out, _ = this.Flags().GetString("out")
}
if src == "" || dst == "" {
starlog.Criticalln("ERROR PATH")
this.Help()
return
}
cryp := new(starainrt.StarCrypto)
err := cryp.Attach(src, dst, out)
if err != nil {
starlog.Criticalln(err.Error)
} else {
fmt.Println("完成")
}
},
}
func init() {
attachcmd.Flags().StringP("src", "s", "", "源文件路径")
attachcmd.Flags().StringP("dst", "d", "", "目标文件路径")
attachcmd.Flags().StringP("out", "o", "", "输出文件路径")
}

@ -0,0 +1,47 @@
package main
import (
"fmt"
"b612.me/starainrt"
"b612.me/starlog"
"github.com/spf13/cobra"
)
var detachcmd = &cobra.Command{
Use: "detach",
Short: "分离两个文件",
Long: "分离两个文件",
Run: func(this *cobra.Command, args []string) {
var src, dst, out string
if len(args) == 3 {
src = args[0]
dst = args[1]
out = args[2]
} else {
src, _ = this.Flags().GetString("src")
dst, _ = this.Flags().GetString("dst")
out, _ = this.Flags().GetString("out")
}
num, _ := this.Flags().GetInt("num")
if src == "" || dst == "" {
starlog.Criticalln("ERROR PATH")
this.Help()
return
}
cryp := new(starainrt.StarCrypto)
err := cryp.Detach(src, num, dst, out)
if err != nil {
starlog.Criticalln(err.Error)
} else {
fmt.Println("完成")
}
},
}
func init() {
detachcmd.Flags().StringP("src", "s", "", "源文件路径")
detachcmd.Flags().StringP("dst", "d", "", "目标文件路径1")
detachcmd.Flags().StringP("out", "o", "", "目标文件路径2")
detachcmd.Flags().IntP("num", "n", 0, "分割开始字节")
}

@ -1,23 +1,34 @@
package main
import (
"Victorique/vtqe/httpserver"
"os"
"os/signal"
"syscall"
"b612.me/starlog"
"b612.me/staros"
"github.com/spf13/cobra"
)
var httpPort, httpIP, httpPath, httpBasicAuth, httpCertKey, logPath string
var doUpload, daemon bool
var httpPort, httpIP, httpPath, httpBasicAuth, httpCertKey, logPath, httpIndexFile string
var doUpload, daemon, httpStopMime bool
func init() {
httpcmd.Flags().StringVarP(&httpPort, "port", "p", "80", "监听端口")
httpcmd.Flags().StringVarP(&httpIP, "ip", "i", "0.0.0.0", "监听ip")
httpcmd.Flags().StringVarP(&httpPath, "folder", "f", "./", "本地文件地址")
httpcmd.Flags().BoolVarP(&doUpload, "upload", "u", false, "是否开启文件上传")
httpcmd.Flags().BoolVarP(&doUpload, "daemon", "d", false, "以后台进程运行")
httpcmd.Flags().BoolVarP(&daemon, "daemon", "d", false, "以后台进程运行")
httpcmd.Flags().StringVarP(&httpBasicAuth, "auth", "a", "", "HTTP BASIC AUTH认证(用户名:密码)")
httpcmd.Flags().StringVarP(&httpBasicAuth, "log", "l", "", "log地址")
httpcmd.Flags().StringVarP(&httpIndexFile, "index", "n", "", "Index文件名如index.html")
httpcmd.Flags().StringVarP(&logPath, "log", "l", "", "log地址")
httpcmd.Flags().StringVarP(&httpCertKey, "cert", "c", "", "TLS证书路径用:分割证书与密钥")
httpcmd.Flags().MarkHidden("front")
httpcmd.Flags().BoolVarP(&httpStopMime, "disablemime", "m", false, "停止解析MIME全部按下载文件处理")
httpcmd.Flags().Bool("daeapplied", false, "")
httpcmd.Flags().MarkHidden("daeapplied")
}
// httpCmd represents the http command
@ -26,8 +37,57 @@ var httpcmd = &cobra.Command{
Short: "HTTP文件服务器",
Long: `HTTP文件服务器`,
Run: func(cmd *cobra.Command, args []string) {
if daemon {
apply, _ := cmd.Flags().GetBool("daeapplied")
if daemon && !apply {
nArgs := append(os.Args[1:], "--daeapplied")
pid, err := staros.Daemon(os.Args[0], nArgs...)
if err != nil {
starlog.Criticalln("Daemon Error:", err)
os.Exit(1)
}
starlog.StdPrintf([]starlog.Attr{starlog.BgGreen}, "Success,PID=%v\n", pid)
return
}
err := run()
if err != nil {
starlog.Errorln("Http Server Closed by Errors")
os.Exit(4)
}
starlog.Infoln("Http Server Closed Normally")
return
},
}
func run() error {
if logPath != "" {
if !staros.Exists(logPath) {
err := starlog.SetLogFile(logPath)
if err != nil {
starlog.Errorln("Create LogFile Failed:", err)
os.Exit(2)
}
defer starlog.Close()
} else {
logFp, err := os.OpenFile(logPath, os.O_APPEND, 0755)
if err != nil {
starlog.Errorln("Create LogFile Failed:", err)
os.Exit(2)
}
defer logFp.Close()
starlog.Std.SwitchOut(logFp)
}
}
stopChan := make(chan os.Signal, 1)
overChan := make(chan error)
signal.Notify(stopChan, syscall.SIGINT, syscall.SIGKILL)
go func(stop chan<- error) {
err := httpserver.RunHttpServer(httpIP, httpPort, httpBasicAuth, httpPath, httpCertKey, vtqe_version, httpIndexFile, doUpload, httpStopMime)
stop <- err
}(overChan)
select {
case <-stopChan:
return nil
case err := <-overChan:
return err
}
}

@ -2,6 +2,7 @@ package httpserver
import (
"encoding/base64"
"errors"
"fmt"
"io"
"io/ioutil"
@ -11,38 +12,51 @@ import (
"strconv"
"strings"
"b612.me/starainrt"
"b612.me/starcrypto"
"b612.me/starlog"
"b612.me/staros"
)
func RunHttpServer(listenIp, port, basicAuth, path, cert string, doUpload bool) {
type VtqeHttpServer struct {
basicAuth string
path string
upload bool
version string
indexFile string
stopMime bool
}
func RunHttpServer(listenIp, port, auth, folderPath, certKey, version, indexFile string, doUpload, stopMime bool) error {
var err error
http.HandleFunc("/", httplisten)
path, _ = filepath.Abs(path)
starlog.Infoln("Listening On Port:" + port)
if up {
starlog.Infoln("upload is openned,path is /vtqeupload1127")
http.HandleFunc("/vtqeupload1127", uploadfile)
var vtqe VtqeHttpServer = VtqeHttpServer{auth, folderPath, doUpload, version, indexFile, stopMime}
http.HandleFunc("/", vtqe.httpListen)
starlog.Noticeln("Listening On " + listenIp + ":" + port)
if doUpload {
starlog.Noticeln("upload is openned,path is /vtqeupload1127")
http.HandleFunc("/vtqeupload1127", vtqe.uploadFile)
}
if certKey == "" {
err = http.ListenAndServe(ip+":"+port, nil)
err = http.ListenAndServe(listenIp+":"+port, nil)
} else {
certs := strings.Split(certKey, ":")
if len(certs) != 2 {
starlog.Criticalln("证书不正确!")
return
return errors.New("ZSBZQ")
}
err = http.ListenAndServeTLS(ip+":"+port, certs[0], certs[1], nil)
err = http.ListenAndServeTLS(listenIp+":"+port, certs[0], certs[1], nil)
}
if err != nil {
starlog.Criticalln("Error:" + err.Error())
return err
}
return nil
}
func httplisten(w http.ResponseWriter, r *http.Request) {
func (v VtqeHttpServer) httpListen(w http.ResponseWriter, r *http.Request) {
log := starlog.Std.NewFlag()
w.Header().Set("Server", "Vicorique")
w.Header().Set("Powered", "B612.ME")
w.Header().Set("Powered By", "B612.ME")
write401 := func() {
w.Header().Set("WWW-Authenticate", ` Basic realm="Please Enter Passwd"`)
w.WriteHeader(401)
@ -55,14 +69,14 @@ func httplisten(w http.ResponseWriter, r *http.Request) {
</body>
</html>`))
}
if basicAuth != "" {
if v.basicAuth != "" {
authHeader := strings.TrimSpace(r.Header.Get("Authorization"))
if len(authHeader) == 0 {
log.Noticeln("No Authed! Get Path is", r.URL.Path, r.RemoteAddr)
write401()
return
} else {
userAuth := base64.StdEncoding.EncodeToString([]byte(basicAuth))
userAuth := base64.StdEncoding.EncodeToString([]byte(v.basicAuth))
authStr := strings.Split(authHeader, " ")
if strings.TrimSpace(authStr[1]) != userAuth {
log.Noticeln("Auth Failed! Get Path is", r.URL.Path, r.RemoteAddr, "pwd enter is", authHeader)
@ -73,14 +87,20 @@ func httplisten(w http.ResponseWriter, r *http.Request) {
}
p := r.URL.Path
cmd := r.URL.Query()["cmd"]
fullpath, _ := filepath.Abs(v.path + p)
if p == "/" && v.indexFile != "" {
tmppath, _ := filepath.Abs(v.path + "/" + v.indexFile)
if staros.Exists(tmppath) {
fullpath = tmppath
p = "/" + v.indexFile
}
}
log.Noticeln("Get " + p + " " + r.RemoteAddr)
fullpath, _ := filepath.Abs(path + p)
if p == "/" {
ReadFolder(w, r, fullpath, true)
v.readFolder(w, r, fullpath, true)
return
}
if up {
if v.upload {
if p == "/vtqeupload1127/web" {
w.Write([]byte(`<html><body><form id= "uploadForm" action= "../vtqeupload1127" method= "post" enctype ="multipart/form-data">
<h1 >B612 File Upload Page </h1>
@ -91,7 +111,7 @@ func httplisten(w http.ResponseWriter, r *http.Request) {
return
}
}
if !starainrt.Exists(fullpath) {
if !staros.Exists(fullpath) {
w.WriteHeader(404)
if len(cmd) != 0 {
if cmd[0] == "header" {
@ -105,8 +125,8 @@ func httplisten(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("<h1>404 NOT FOUND</h1>"))
return
}
if starainrt.IsFolder(fullpath) {
ReadFolder(w, r, fullpath, false)
if staros.IsFolder(fullpath) {
v.readFolder(w, r, fullpath, false)
return
}
fpdst, err := os.Open(fullpath)
@ -118,26 +138,16 @@ func httplisten(w http.ResponseWriter, r *http.Request) {
}
fpinfo, _ := os.Stat(fullpath)
name := filepath.Base(fullpath)
tmp := strings.Split(name, ".")
ext := ""
if len(tmp) >= 2 {
ext = strings.ToLower(tmp[len(tmp)-1])
}
switch ext {
case "jpeg", "jpg", "jpe":
w.Header().Set("Content-Type", "image/jpeg")
case "mpeg", "mpg", "mkv":
w.Header().Set("Content-Type", "video/mpeg")
case "mp4":
w.Header().Set("Content-Type", "video/mp4")
case "pdf":
w.Header().Set("Content-Type", "application/pdf")
default:
ext := filepath.Ext(name)[1:]
mime := GetMIME(ext)
if mime == "" || v.stopMime {
w.Header().Set("Content-Type", "application/download")
w.Header().Set("Content-Disposition", "attachment;filename="+name)
w.Header().Set("Content-Transfer-Encoding", "binary")
} else {
w.Header().Set("Content-Type", mime)
}
etag := new(starainrt.StarCrypto).MD5([]byte(fpinfo.ModTime().String()))
w.Header().Set("Content-Transfer-Encoding", "binary")
etag := starcrypto.Md5Str([]byte(fpinfo.ModTime().String()))
w.Header().Set("Accept-Ranges", "bytes")
w.Header().Set("ETag", etag)
w.Header().Set("Last-Modified", strings.ReplaceAll(fpinfo.ModTime().UTC().Format("Mon, 2 Jan 2006 15:04:05 MST"), "UTC", "GMT"))
@ -244,15 +254,15 @@ func httplisten(w http.ResponseWriter, r *http.Request) {
log.Infoln(fpinfo.Name(), "客户端下载已结束,共传输大小:"+tani)
}
func ReadFolder(w http.ResponseWriter, r *http.Request, fullpath string, isroot bool) {
func (v VtqeHttpServer) readFolder(w http.ResponseWriter, r *http.Request, fullpath string, isroot bool) {
dir, err := ioutil.ReadDir(fullpath)
if err != nil {
starlog.Errorln(err)
w.WriteHeader(403)
w.Write([]byte("<h1>May Cannot Access!</h1>"))
}
w.Write([]byte("<html>\n<style>\np{margin: 2px auto}\n</style>\n<h1>B612 Http Server - " + Version + "</h1>"))
if up {
w.Write([]byte("<html>\n<style>\np{margin: 2px auto}\n</style>\n<h1>B612 Http Server - " + v.version + "</h1>"))
if v.upload {
w.Write([]byte("<a href=/vtqeupload1127/web>Upload Web Page Is Openned!</a><br /><br />"))
}
w.Write([]byte("<hr /><pre>\n"))
@ -277,7 +287,7 @@ func ReadFolder(w http.ResponseWriter, r *http.Request, fullpath string, isroot
return
}
func uploadfile(w http.ResponseWriter, r *http.Request) {
func (v VtqeHttpServer) uploadFile(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.Write([]byte("USE POST METHOD!"))
return

File diff suppressed because it is too large Load Diff

@ -7,13 +7,15 @@ import (
// Vtqe is my own toolbox
func init() {
cmdMain.AddCommand(tcpingcmd, httpcmd)
cmdMain.AddCommand(tcpingcmd, httpcmd, attachcmd, detachcmd)
}
const vtqe_version string = "v1.0.0NG RC1"
var cmdMain = &cobra.Command{
Short: "Victorique Wisdom ToolBox",
Long: "中二的工具箱:未来を照らし出せ!",
Version: "v1.0.0 NG",
Version: vtqe_version,
}
func main() {

@ -30,8 +30,8 @@ var (
var tcpingcmd = &cobra.Command{
Use: "tcping",
Short: "tcp ping",
Long: "进行Tcping",
Short: "tcp/http ping",
Long: "使用进行Tcp或Http协议进行ping探测",
Example: `
1. ping over tcp
> tcping google.com

Loading…
Cancel
Save