예제 #1
0
파일: utils.go 프로젝트: GloriaH/docker
// ValidateContextDirectory checks if all the contents of the directory
// can be read and returns an error if some files can't be read
// symlinks which point to non-existing files don't trigger an error
func ValidateContextDirectory(srcPath string) error {
	var finalError error

	filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error {
		// skip this directory/file if it's not in the path, it won't get added to the context
		_, err = filepath.Rel(srcPath, filePath)
		if err != nil && os.IsPermission(err) {
			return nil
		}

		if _, err := os.Stat(filePath); err != nil && os.IsPermission(err) {
			finalError = fmt.Errorf("can't stat '%s'", filePath)
			return err
		}
		// skip checking if symlinks point to non-existing files, such symlinks can be useful
		lstat, _ := os.Lstat(filePath)
		if lstat.Mode()&os.ModeSymlink == os.ModeSymlink {
			return err
		}

		if !f.IsDir() {
			currentFile, err := os.Open(filePath)
			if err != nil && os.IsPermission(err) {
				finalError = fmt.Errorf("no permission to read from '%s'", filePath)
				return err
			} else {
				currentFile.Close()
			}
		}
		return nil
	})
	return finalError
}
예제 #2
0
파일: init.go 프로젝트: Kubuxu/go-ipfs
func checkWriteable(dir string) error {
	_, err := os.Stat(dir)
	if err == nil {
		// dir exists, make sure we can write to it
		testfile := path.Join(dir, "test")
		fi, err := os.Create(testfile)
		if err != nil {
			if os.IsPermission(err) {
				return fmt.Errorf("%s is not writeable by the current user", dir)
			}
			return fmt.Errorf("unexpected error while checking writeablility of repo root: %s", err)
		}
		fi.Close()
		return os.Remove(testfile)
	}

	if os.IsNotExist(err) {
		// dir doesnt exist, check that we can create it
		return os.Mkdir(dir, 0775)
	}

	if os.IsPermission(err) {
		return fmt.Errorf("cannot write to %s, incorrect permissions", err)
	}

	return err
}
예제 #3
0
파일: browse.go 프로젝트: FiloSottile/caddy
// ServeHTTP determines if the request is for this plugin, and if all prerequisites are met.
// If so, control is handed over to ServeListing.
func (b Browse) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	var bc *Config
	// See if there's a browse configuration to match the path
	for i := range b.Configs {
		if httpserver.Path(r.URL.Path).Matches(b.Configs[i].PathScope) {
			bc = &b.Configs[i]
			goto inScope
		}
	}
	return b.Next.ServeHTTP(w, r)
inScope:

	// Browse works on existing directories; delegate everything else
	requestedFilepath, err := bc.Root.Open(r.URL.Path)
	if err != nil {
		switch {
		case os.IsPermission(err):
			return http.StatusForbidden, err
		case os.IsExist(err):
			return http.StatusNotFound, err
		default:
			return b.Next.ServeHTTP(w, r)
		}
	}
	defer requestedFilepath.Close()

	info, err := requestedFilepath.Stat()
	if err != nil {
		switch {
		case os.IsPermission(err):
			return http.StatusForbidden, err
		case os.IsExist(err):
			return http.StatusGone, err
		default:
			return b.Next.ServeHTTP(w, r)
		}
	}
	if !info.IsDir() {
		return b.Next.ServeHTTP(w, r)
	}

	// Do not reply to anything else because it might be nonsensical
	switch r.Method {
	case http.MethodGet, http.MethodHead:
		// proceed, noop
	case "PROPFIND", http.MethodOptions:
		return http.StatusNotImplemented, nil
	default:
		return b.Next.ServeHTTP(w, r)
	}

	// Browsing navigation gets messed up if browsing a directory
	// that doesn't end in "/" (which it should, anyway)
	if !strings.HasSuffix(r.URL.Path, "/") {
		staticfiles.Redirect(w, r, r.URL.Path+"/", http.StatusTemporaryRedirect)
		return 0, nil
	}

	return b.ServeListing(w, r, requestedFilepath, bc)
}
예제 #4
0
파일: posix.go 프로젝트: balamurugana/minio
// deleteFile - delete file path if its empty.
func deleteFile(basePath, deletePath string) error {
	if basePath == deletePath {
		return nil
	}
	// Verify if the path exists.
	pathSt, err := os.Stat(preparePath(deletePath))
	if err != nil {
		if os.IsNotExist(err) {
			return errFileNotFound
		} else if os.IsPermission(err) {
			return errFileAccessDenied
		}
		return err
	}
	if pathSt.IsDir() && !isDirEmpty(deletePath) {
		// Verify if directory is empty.
		return nil
	}
	// Attempt to remove path.
	if err := os.Remove(preparePath(deletePath)); err != nil {
		if os.IsNotExist(err) {
			return errFileNotFound
		} else if os.IsPermission(err) {
			return errFileAccessDenied
		}
		return err
	}
	// Recursively go down the next path and delete again.
	if err := deleteFile(basePath, slashpath.Dir(deletePath)); err != nil {
		return err
	}
	return nil
}
예제 #5
0
파일: fs-common.go 프로젝트: fwessels/mc
// fsStat - wrapper function to get file stat.
func (f *fsClient) fsStat() (os.FileInfo, *probe.Error) {
	fpath := f.PathURL.Path
	// Golang strips trailing / if you clean(..) or
	// EvalSymlinks(..). Adding '.' prevents it from doing so.
	if strings.HasSuffix(fpath, string(f.PathURL.Separator)) {
		fpath = fpath + "."
	}
	fpath, e := filepath.EvalSymlinks(fpath)
	if e != nil {
		if os.IsPermission(e) {
			if runtime.GOOS == "windows" {
				return f.handleWindowsSymlinks(f.PathURL.Path)
			}
			return nil, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
		}
		err := f.toClientError(e, f.PathURL.Path)
		return nil, err.Trace(fpath)
	}
	st, e := os.Stat(fpath)
	if e != nil {
		if os.IsPermission(e) {
			if runtime.GOOS == "windows" {
				return f.handleWindowsSymlinks(fpath)
			}
			return nil, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
		}
		if os.IsNotExist(e) {
			return nil, probe.NewError(client.PathNotFound{Path: f.PathURL.Path})
		}
		return nil, probe.NewError(e)
	}
	return st, nil
}
예제 #6
0
파일: archdiff.go 프로젝트: daaku/archdiff
func (ad *ArchDiff) DiffRepoFile() FileList {
	if ad.diffRepoFile == nil {
		ad.diffRepoFile = make(FileList)
		for _, file := range ad.RepoFile() {
			realpath := filepath.Join(ad.Root, file.Name)
			repopath := filepath.Join(ad.Repo, file.Name)
			realhash, err := filehash(realpath)
			if err != nil && !os.IsNotExist(err) {
				if os.IsPermission(err) {
					if !ad.Silent {
						log.Printf("Skipping file: %s", err)
					}
					continue
				}
				log.Fatalf("Error looking for modified repo files (real): %s", err)
			}
			repohash, err := filehash(repopath)
			if err != nil && !os.IsNotExist(err) {
				if os.IsPermission(err) {
					if !ad.Silent {
						log.Printf("Skipping file: %s", err)
					}
					continue
				}
				log.Fatalf("Error looking for modified repo files (repo): %s", err)
			}
			if realhash != repohash {
				ad.diffRepoFile.Add(file)
			}
		}
	}
	return ad.diffRepoFile
}
예제 #7
0
파일: fs.go 프로젝트: axcoto-lab/mc
func (f *fsClient) listRecursiveInRoutine(contentCh chan client.ContentOnChannel) {
	defer close(contentCh)
	visitFS := func(fp string, fi os.FileInfo, err error) error {
		// fp also sends back itself with visitFS, ignore it we don't need it
		if fp == f.path {
			return nil
		}
		if err != nil {
			if strings.Contains(err.Error(), "operation not permitted") {
				contentCh <- client.ContentOnChannel{
					Content: nil,
					Err:     probe.NewError(err),
				}
				return nil
			}
			if os.IsPermission(err) {
				contentCh <- client.ContentOnChannel{
					Content: nil,
					Err:     probe.NewError(err),
				}
				return nil
			}
			return err
		}
		if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
			fi, err = os.Stat(fp)
			if err != nil {
				if os.IsNotExist(err) || os.IsPermission(err) { // ignore broken symlinks and permission denied
					contentCh <- client.ContentOnChannel{
						Content: nil,
						Err:     probe.NewError(err),
					}
					return nil
				}
				return err
			}
		}
		if fi.Mode().IsRegular() || fi.Mode().IsDir() {
			content := &client.Content{
				Name: f.delimited(fp),
				Time: fi.ModTime(),
				Size: fi.Size(),
				Type: fi.Mode(),
			}
			contentCh <- client.ContentOnChannel{
				Content: content,
				Err:     nil,
			}
		}
		return nil
	}
	err := filepath.Walk(f.path, visitFS)
	if err != nil {
		contentCh <- client.ContentOnChannel{
			Content: nil,
			Err:     probe.NewError(err),
		}
	}
}
예제 #8
0
파일: lsenvs.go 프로젝트: jmartiuk5/VenGO
// return a list of available virtual go environments for the user
func (e *EnvironmentsList) getEnvironments() ([]string, []string, error) {
	envs_path := filepath.Join("~", ".VenGO", "*")
	files, err := filepath.Glob(cache.ExpandUser(envs_path))
	if err != nil {
		fmt.Println("while getting list of environments:", err)
		return nil, nil, err
	}
	available, invalid := []string{}, []string{}
	for _, file := range files {
		var vengoenv string
		filename := path.Base(file)
		stat, err := os.Stat(file)
		if err != nil {
			fmt.Println("while getting list of environments:", err)
			return nil, nil, err
		}
		if stat.IsDir() && filename != "bin" && filename != "scripts" {
			_, err := os.Open(filepath.Join(file, "bin", "activate"))
			if err != nil {
				if os.IsNotExist(err) || os.IsPermission(err) {
					invalid = append(invalid, filename)
				}
				continue
			}
			if r, err := os.Readlink(filepath.Join(file, "lib")); err != nil {
				if os.IsNotExist(err) || os.IsPermission(err) {
					invalid = append(invalid, filename)
				}
				continue
			} else {
				if e.DisplayAs == Text {
					vengoenv = fmt.Sprintf("%-22s%-8s", filename, path.Base(r))
				} else {
					vengoenv = filename
				}
				if _, err := os.Stat(r); err != nil {
					if os.IsNotExist(err) || os.IsPermission(err) {
						invalid = append(invalid, vengoenv)
					}
					continue
				}
			}

			available = append(available, vengoenv)
		}
	}

	return available, invalid, nil
}
예제 #9
0
func checkUserNS(t *testing.T) {
	if _, err := os.Stat("/proc/self/ns/user"); err != nil {
		if os.IsNotExist(err) {
			t.Skip("kernel doesn't support user namespaces")
		}
		if os.IsPermission(err) {
			t.Skip("unable to test user namespaces due to permissions")
		}
		t.Fatalf("Failed to stat /proc/self/ns/user: %v", err)
	}
	if isChrooted(t) {
		// create_user_ns in the kernel (see
		// https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/kernel/user_namespace.c)
		// forbids the creation of user namespaces when chrooted.
		t.Skip("cannot create user namespaces when chrooted")
	}
	// On some systems, there is a sysctl setting.
	if os.Getuid() != 0 {
		data, errRead := ioutil.ReadFile("/proc/sys/kernel/unprivileged_userns_clone")
		if errRead == nil && data[0] == '0' {
			t.Skip("kernel prohibits user namespace in unprivileged process")
		}
	}
	// When running under the Go continuous build, skip tests for
	// now when under Kubernetes. (where things are root but not quite)
	// Both of these are our own environment variables.
	// See Issue 12815.
	if os.Getenv("GO_BUILDER_NAME") != "" && os.Getenv("IN_KUBERNETES") == "1" {
		t.Skip("skipping test on Kubernetes-based builders; see Issue 12815")
	}
}
예제 #10
0
파일: lock.go 프로젝트: Kubuxu/go-ipfs
func Locked(confdir string) (bool, error) {
	log.Debugf("Checking lock")
	if !util.FileExists(path.Join(confdir, LockFile)) {
		log.Debugf("File doesn't exist: %s", path.Join(confdir, LockFile))
		return false, nil
	}
	if lk, err := Lock(confdir); err != nil {
		// EAGAIN == someone else has the lock
		if err == syscall.EAGAIN {
			log.Debugf("Someone else has the lock: %s", path.Join(confdir, LockFile))
			return true, nil
		}
		if strings.Contains(err.Error(), "can't Lock file") {
			log.Debugf("Can't lock file: %s.\n reason: %s", path.Join(confdir, LockFile), err.Error())
			return true, nil
		}

		// lock fails on permissions error
		if os.IsPermission(err) {
			log.Debugf("Lock fails on permissions error")
			return false, errPerm(confdir)
		}
		if isLockCreatePermFail(err) {
			log.Debugf("Lock fails on permissions error")
			return false, errPerm(confdir)
		}

		// otherwise, we cant guarantee anything, error out
		return false, err
	} else {
		log.Debugf("No one has a lock")
		lk.Close()
		return false, nil
	}
}
예제 #11
0
파일: status.go 프로젝트: peer23peer/TMSU
func statusCheckFile(absPath string, file *entities.File, report *StatusReport) error {
	log.Infof(2, "%v: checking file status.", absPath)

	stat, err := os.Stat(file.Path())
	if err != nil {
		switch {
		case os.IsNotExist(err):
			log.Infof(2, "%v: file is missing.", absPath)

			report.AddRow(Row{absPath, MISSING})
			return nil
		case os.IsPermission(err):
			log.Warnf("%v: permission denied.", absPath)
		case strings.Contains(err.Error(), "not a directory"): //TODO improve
			report.AddRow(Row{file.Path(), MISSING})
			return nil
		default:
			return fmt.Errorf("%v: could not stat: %v", file.Path(), err)
		}
	} else {
		if stat.Size() != file.Size || !stat.ModTime().UTC().Equal(file.ModTime) {
			log.Infof(2, "%v: file is modified.", absPath)

			report.AddRow(Row{absPath, MODIFIED})
		} else {
			log.Infof(2, "%v: file is unchanged.", absPath)

			report.AddRow(Row{absPath, TAGGED})
		}
	}

	return nil
}
예제 #12
0
파일: volume.go 프로젝트: yonglehou/weedfs
func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool) error {
	var e error
	fileName := v.FileName()

	if exists, canRead, canWrite, _ := checkFile(fileName + ".dat"); exists {
		if !canRead {
			return fmt.Errorf("cannot read Volume Data file %s.dat", fileName)
		}
		if canWrite {
			v.dataFile, e = os.OpenFile(fileName+".dat", os.O_RDWR|os.O_CREATE, 0644)
		} else {
			glog.V(0).Infoln("opening " + fileName + ".dat in READONLY mode")
			v.dataFile, e = os.Open(fileName + ".dat")
			v.readOnly = true
		}
	} else {
		if createDatIfMissing {
			v.dataFile, e = os.OpenFile(fileName+".dat", os.O_RDWR|os.O_CREATE, 0644)
		} else {
			return fmt.Errorf("Volume Data file %s.dat does not exist.", fileName)
		}
	}

	if e != nil {
		if !os.IsPermission(e) {
			return fmt.Errorf("cannot load Volume Data %s.dat: %s", fileName, e.Error())
		}
	}

	if v.ReplicaPlacement == nil {
		e = v.readSuperBlock()
	} else {
		e = v.maybeWriteSuperBlock()
	}
	if e == nil && alsoLoadIndex {
		if v.readOnly {
			if v.ensureConvertIdxToCdb(fileName) {
				v.nm, e = OpenCdbMap(fileName + ".cdb")
				return e
			}
		}
		var indexFile *os.File
		if v.readOnly {
			glog.V(1).Infoln("open to read file", fileName+".idx")
			if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDONLY, 0644); e != nil {
				return fmt.Errorf("cannot read Volume Index %s.idx: %s", fileName, e.Error())
			}
		} else {
			glog.V(1).Infoln("open to write file", fileName+".idx")
			if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDWR|os.O_CREATE, 0644); e != nil {
				return fmt.Errorf("cannot write Volume Index %s.idx: %s", fileName, e.Error())
			}
		}
		glog.V(0).Infoln("loading file", fileName+".idx", "readonly", v.readOnly)
		if v.nm, e = LoadNeedleMap(indexFile); e != nil {
			glog.V(0).Infoln("loading error:", e)
		}
	}
	return e
}
예제 #13
0
파일: json.go 프로젝트: polluks/client
func (f *JSONFile) Load(warnOnNotFound bool) error {
	f.G().Log.Debug("+ loading %s file: %s", f.which, f.filename)
	file, err := os.Open(f.filename)
	if err != nil {
		if os.IsNotExist(err) {
			msg := fmt.Sprintf("No %s file found; tried %s", f.which, f.filename)
			if warnOnNotFound {
				f.G().Log.Warning(msg)
			} else {
				f.G().Log.Debug(msg)
			}
			return nil
		} else if os.IsPermission(err) {
			f.G().Log.Warning("Permission denied opening %s file %s", f.which, f.filename)
			return nil
		} else {
			return err
		}
	}
	f.exists = true
	defer file.Close()
	decoder := json.NewDecoder(file)
	obj := make(map[string]interface{})
	// Treat empty files like an empty dictionary
	if err = decoder.Decode(&obj); err != nil && err != io.EOF {
		f.G().Log.Errorf("Error decoding %s file %s", f.which, f.filename)
		return err
	}
	f.jw = jsonw.NewWrapper(obj)
	f.G().Log.Debug("- successfully loaded %s file", f.which)
	return nil
}
예제 #14
0
파일: volume.go 프로젝트: tgulacsi/weed-fs
func (v *Volume) load(alsoLoadIndex bool) error {
	var e error
	fileName := path.Join(v.dir, v.Id.String())
	if exists, canRead, canWrite, _ := checkFile(fileName + ".dat"); exists && !canRead {
		return fmt.Errorf("cannot read Volume Data file %s.dat", fileName)
	} else if !exists || canWrite {
		v.dataFile, e = os.OpenFile(fileName+".dat", os.O_RDWR|os.O_CREATE, 0644)
	} else if exists && canRead {
		glog.V(0).Infoln("opening " + fileName + ".dat in READONLY mode")
		v.dataFile, e = os.Open(fileName + ".dat")
		v.readOnly = true
	} else {
		return fmt.Errorf("Unknown state about Volume Data file %s.dat", fileName)
	}
	if e != nil {
		if !os.IsPermission(e) {
			return fmt.Errorf("cannot load Volume Data %s.dat: %s", fileName, e.Error())
		}
	}

	if v.ReplicaType == CopyNil {
		e = v.readSuperBlock()
	} else {
		e = v.maybeWriteSuperBlock()
	}
	if e == nil && alsoLoadIndex {
		var indexFile *os.File
		if v.readOnly {
			glog.V(1).Infoln("open to read file", fileName+".idx")
			if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDONLY, 0644); e != nil {
				return fmt.Errorf("cannot read Volume Data %s.dat: %s", fileName, e.Error())
			}

			if v.ensureConvertIdxToCdb(fileName) {
				v.nm, e = OpenCdbMap(fileName + ".cdb")
				return e
			}
			if indexFile != nil {
				glog.V(0).Infoln("converting %s.idx to %s.cdb", fileName, fileName)
				if e = ConvertIndexToCdb(fileName+".cdb", indexFile); e != nil {
					glog.Errorln("error converting %s.idx to %s.cdb: %s", fileName, fileName, e)
				} else {
					indexFile.Close()
					os.Remove(indexFile.Name())
					indexFile = nil
				}
			}
		} else {
			glog.V(1).Infoln("open to write file", fileName+".idx")
			if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDWR|os.O_CREATE, 0644); e != nil {
				return fmt.Errorf("cannot write Volume Data %s.dat: %s", fileName, e.Error())
			}
		}
		glog.V(0).Infoln("loading file", fileName+".idx", "readonly", v.readOnly)
		if v.nm, e = LoadNeedleMap(indexFile); e != nil {
			glog.V(0).Infoln("loading error:", e)
		}
	}
	return e
}
예제 #15
0
// setupLogging attempts to log to a file, otherwise stderr
func setupLogging() (*os.File, error) {
	// use date, time and filename for log output
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	log.SetPrefix(*pluginName + "-volume-plugin: ")

	// setup logfile - path is set from logfileDir and pluginName
	logfileName := logfilePath()
	if !isDebugEnabled() && logfileName != "" {
		logFile, err := os.OpenFile(logfileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			// check if we can write to directory - otherwise just log to stderr?
			if os.IsPermission(err) {
				log.Printf("WARN: logging fallback to STDERR: %v", err)
			} else {
				// some other, more extreme system error
				return nil, err
			}
		} else {
			log.Printf("INFO: setting log file: %s", logfileName)
			log.SetOutput(logFile)
			return logFile, nil
		}
	}
	return nil, nil
}
예제 #16
0
// TestHostKeyFile tests that reading and writing the wrong host key file fails
func TestWrongHostKeyFile(t *testing.T) {
	// Non-existent host key file should fail
	f := NewHostKeyFile(wrongHostFile)
	_, err := f.GetHostKeys()
	if err == nil {
		t.Fatal("should fail to read wrong host file")
	}
	if _, ok := err.(*os.PathError); !ok {
		t.Fatalf("should fail to read wrong host file due to file miss, but got %v", err)
	}

	// Create a host key file we do not have permission to read
	os.OpenFile(wrongHostFile, os.O_CREATE, 0000)
	defer os.Remove(wrongHostFile)
	// If run as root, drop privileges temporarily
	if id := syscall.Geteuid(); id == 0 {
		if err := syscall.Setuid(12345); err != nil {
			t.Fatalf("error setting uid: %v", err)
		}
		defer syscall.Setuid(id)
	}
	err = f.PutHostKey("", nil)
	if err == nil {
		t.Fatal("should fail to write wrong host file")
	}
	if !os.IsPermission(err) {
		t.Fatalf("should fail to write wrong host file due to permission denied, but got %v", err)
	}
}
예제 #17
0
파일: cfg.go 프로젝트: jmoiron/cm
// initialize config path if not present, return an error if either the dir
// exists and is not writable or the dir does not exist and cannot be created
func configPathInit() error {
	fi, err := os.Stat(CONFIG_PATH)
	// if it doesn't exist
	if err != nil && os.IsNotExist(err) {
		err = os.MkdirAll(CONFIG_PATH, CONFIG_PATH_MODE)
		return err
		// if it isn't a dir or symlink
	} else if !fi.IsDir() && (fi.Mode()&os.ModeSymlink) == 0 {
		return fmt.Errorf("Path %s must be directory or symlink.", CONFIG_PATH)
	}
	// if it exists, check for writability
	for i := 0; ; i++ {
		path := C(fmt.Sprintf("__testfile%d", i))
		if isFile(path) {
			continue
		}
		_, err := os.Create(path)
		if err == nil {
			os.Remove(path)
			return nil
		}
		if os.IsPermission(err) {
			return fmt.Errorf("Path %s must be writable.", CONFIG_PATH)
		}
		return err
	}
	return errors.New("Unknown error setting up config path.")
}
예제 #18
0
func Locked(confdir string) (bool, error) {
	if !util.FileExists(path.Join(confdir, LockFile)) {
		return false, nil
	}
	if lk, err := Lock(confdir); err != nil {
		// EAGAIN == someone else has the lock
		if err == syscall.EAGAIN {
			return true, nil
		}
		if strings.Contains(err.Error(), "can't Lock file") {
			return true, nil
		}

		// lock fails on permissions error
		if os.IsPermission(err) {
			return false, errPerm(confdir)
		}
		if isLockCreatePermFail(err) {
			return false, errPerm(confdir)
		}

		// otherwise, we cant guarantee anything, error out
		return false, err
	} else {
		lk.Close()
		return false, nil
	}
}
예제 #19
0
파일: error.go 프로젝트: devtoby/gofs
func reportError(w http.ResponseWriter, e error, p string) {
	w.Header().Set("Content-Type", "text/html;charset=utf-8")
	data := make(map[string]string)
	data["title"] = "访问出错!"
	data["head"] = "<strong>当前位置:</strong> " + getPathLink(p)

	var text string
	switch {
	case os.IsNotExist(e):
		text = "您访问的文件不存在!"
		w.WriteHeader(404)
	case os.IsPermission(e):
		text = "当前目录或文件不允许访问!"
		w.WriteHeader(403)
	case PathAuthError == e:
		text = "您没有当前路径的访问权限!"
		w.WriteHeader(403)
	case AuthError == e:
		text = "认证失败!"
		w.Header().Set("WWW-Authenticate", "Basic realm=\"Please login\"")
		w.WriteHeader(401)
	default:
		text = "未知错误!"
	}
	data["content"] = fmt.Sprintf("<i><%s></i>", text)

	render(w, data)
}
예제 #20
0
파일: main.go 프로젝트: robinmonjo/procfs
func printSockets(p *procfs.Proc, sockets []*procfs.Socket) error {
	fds, err := p.Fds()
	if err != nil {
		if !os.IsPermission(err) {
			return err
		}
	}

	inodes := []string{}

	for _, fd := range fds {
		inode := fd.SocketInode()
		if inode != "" {
			inodes = append(inodes, inode)
		}
	}

	str := []string{}
	for _, inode := range inodes {
		if s := procfs.Sockets(sockets).Find(inode); s != nil {
			str = append(str, fmt.Sprintf("%s %v %s", s.Protocol, s.LocalIP, s.LocalPort))
		}
	}
	fmt.Printf(" %s", strings.Join(str, ", "))
	return nil
}
예제 #21
0
파일: article.go 프로젝트: rdnelson/avala
func handleArticles(site *Website, out string) error {

	dirs := []string{"articles"}

	for _, dir := range dirs {
		err := handleArticlePath(site, dir, "", out)

		if err != nil {

			switch {
			case os.IsNotExist(err):
				progress("%s", err.Error())
				progress("The file was likely deleted during processing")
			case os.IsPermission(err):
				progress("%s", err.Error())
				progress("Please check the file permissions on the repo")
			default:
				switch err.(type) {
				case TemplateError:
					progress("Required template missing: %s", err.Error())
					return err
				case ParseError:
					if err.(ParseError).IsFatal() {
						return err.(ParseError).Err()
					} else {
						progress(err.Error())
						return nil
					}
				}
			}
		}
	}

	return nil
}
예제 #22
0
// convertCode converts a standard Go error into its canonical code. Note that
// this is only used to translate the error returned by the server applications.
func convertCode(err error) codes.Code {
	switch err {
	case nil:
		return codes.OK
	case io.EOF:
		return codes.OutOfRange
	case io.ErrClosedPipe, io.ErrNoProgress, io.ErrShortBuffer, io.ErrShortWrite, io.ErrUnexpectedEOF:
		return codes.FailedPrecondition
	case os.ErrInvalid:
		return codes.InvalidArgument
	case context.Canceled:
		return codes.Canceled
	case context.DeadlineExceeded:
		return codes.DeadlineExceeded
	}
	switch {
	case os.IsExist(err):
		return codes.AlreadyExists
	case os.IsNotExist(err):
		return codes.NotFound
	case os.IsPermission(err):
		return codes.PermissionDenied
	}
	return codes.Unknown
}
예제 #23
0
func (self *supervisorBase) killByCmd(pid int) (bool, string) {
	pr, e := os.FindProcess(pid)
	if nil != e {
		if os.IsPermission(e) {
			e = execWithTimeout(self.killTimeout, self.stop_cmd.command(self.mode))
			if nil != e {
				return false, e.Error()
			}
			return true, ""
		}
		return false, e.Error()
	}
	defer pr.Release()

	started := time.Now()
	e = execWithTimeout(self.killTimeout, self.stop_cmd.command(self.mode))
	if nil != e {
		return false, e.Error()
	}

	used := time.Now().Sub(started)
	if used >= self.killTimeout {
		return false, fmt.Sprintf("timed out after %v", self.killTimeout)
	}

	e = waitWithTimeout(self.killTimeout-used, pr)
	if nil != e {
		return false, e.Error()
	}
	return true, ""
}
예제 #24
0
// ConvertSystemError converts system error to appropriate trace error
// if it is possible, otherwise, returns original error
func ConvertSystemError(err error) error {
	innerError := Unwrap(err)

	if os.IsNotExist(innerError) {
		return WrapWithMessage(&NotFoundError{Message: innerError.Error()}, innerError.Error())
	}
	if os.IsPermission(innerError) {
		return WrapWithMessage(&AccessDeniedError{Message: innerError.Error()}, innerError.Error())
	}
	switch realErr := innerError.(type) {
	case *net.OpError:
		message := fmt.Sprintf("failed to connect to server %v", realErr.Addr)
		return WrapWithMessage(&ConnectionProblemError{
			Message: message,
			Err:     realErr}, message)
	case *os.PathError:
		message := fmt.Sprintf("failed to execute command %v error:  %v", realErr.Path, realErr.Err)
		return WrapWithMessage(&AccessDeniedError{
			Message: message,
		}, message)
	case x509.SystemRootsError, x509.UnknownAuthorityError:
		return wrapWithDepth(&TrustError{Err: innerError}, 2)
	default:
		return err
	}
}
예제 #25
0
func TestMountOptionDefaultPermissions(t *testing.T) {
	if runtime.GOOS == "freebsd" {
		t.Skip("FreeBSD does not support DefaultPermissions")
	}
	t.Parallel()
	mnt, err := fstestutil.MountedT(t,
		fstestutil.SimpleFS{
			fstestutil.ChildMap{"child": unwritableFile{}},
		},
		fuse.DefaultPermissions(),
	)

	if err != nil {
		t.Fatal(err)
	}
	defer mnt.Close()

	// This will be prevented by kernel-level access checking when
	// DefaultPermissions is used.
	f, err := os.OpenFile(mnt.Dir+"/child", os.O_WRONLY, 0000)
	if err == nil {
		f.Close()
		t.Fatal("expected an error")
	}
	if !os.IsPermission(err) {
		t.Fatalf("expected a permission error, got %T: %v", err, err)
	}
}
예제 #26
0
파일: tun_test.go 프로젝트: keysonZZZ/kmg
func TestTap(ot *testing.T) {
	tap, err := NewTap("")
	if os.IsPermission(err) {
		ot.Skip("you need root permission to run this test.")
		return
	}
	kmgTest.Equal(err, nil)
	defer tap.Close()
	kmgTest.Equal(tap.GetDeviceType(), DeviceTypeTap)

	err = kmgCmd.CmdString("ifconfig " + tap.Name() + " 10.209.34.1 up").GetExecCmd().Run()
	kmgTest.Equal(err, nil)
	/*
		cmd := kmgCmd.NewOsStdioCmdString("ping 10.0.0.2")
		err = cmd.Start()
		t.Equal(err, nil)
		defer cmd.Process.Kill()

		buf := make([]byte, 4096)
		n, err := tun.Read(buf)
		t.Equal(err, nil)
		t.Ok(n > 0)

		tun2, err := NewTap("")
		t.Equal(err, nil)
		defer tun2.Close()
	*/
}
예제 #27
0
파일: error_test.go 프로젝트: 2thetop/go
func TestIsPermission(t *testing.T) {
	for _, tt := range isPermissionTests {
		if got := os.IsPermission(tt.err); got != tt.want {
			t.Errorf("os.IsPermission(%#v) = %v; want %v", tt.err, got, tt.want)
		}
	}
}
예제 #28
0
파일: posix.go 프로젝트: balamurugana/minio
// Make a volume entry.
func (s *posix) MakeVol(volume string) (err error) {
	defer func() {
		if err == syscall.EIO {
			atomic.AddInt32(&s.ioErrCount, 1)
		}
	}()

	if s.ioErrCount > maxAllowedIOError {
		return errFaultyDisk
	}

	if err = s.checkDiskFound(); err != nil {
		return err
	}

	volumeDir, err := s.getVolDir(volume)
	if err != nil {
		return err
	}
	// Make a volume entry, with mode 0777 mkdir honors system umask.
	err = os.Mkdir(preparePath(volumeDir), 0777)
	if err != nil {
		if os.IsExist(err) {
			return errVolumeExists
		} else if os.IsPermission(err) {
			return errDiskAccessDenied
		}
		return err
	}
	// Success
	return nil
}
예제 #29
0
파일: node_linux.go 프로젝트: rawtaz/restic
func (node *Node) OpenForReading() (*os.File, error) {
	file, err := os.OpenFile(node.path, os.O_RDONLY|syscall.O_NOATIME, 0)
	if os.IsPermission(err) {
		return os.OpenFile(node.path, os.O_RDONLY, 0)
	}
	return file, err
}
예제 #30
0
파일: tun_test.go 프로젝트: keysonZZZ/kmg
func TestTun(ot *testing.T) {
	fmt.Println(1)
	tun, err := NewTun("")
	fmt.Println(2)
	if os.IsPermission(err) {
		ot.Skip("you need root permission to run this test.")
		return
	}
	kmgTest.Equal(err, nil)
	defer tun.Close()
	kmgTest.Equal(tun.GetDeviceType(), DeviceTypeTun)
	fmt.Println(3)

	err = SetP2PIpAndUp(tun, "10.209.34.1", "10.209.34.2")
	kmgTest.Equal(err, nil)

	err = SetMtu(tun, 1420)
	kmgTest.Equal(err, nil)
	fmt.Println(4)
	cmd := kmgCmd.CmdString("ping 10.209.34.2").GetExecCmd()
	err = cmd.Start()
	kmgTest.Equal(err, nil)
	defer cmd.Process.Kill()

	buf := make([]byte, 4096)
	n, err := tun.Read(buf)
	kmgTest.Equal(err, nil)
	kmgTest.Ok(n > 0)
	/*
		tun2, err := NewTun("")
		t.Equal(err, nil)
		defer tun2.Close()
	*/
}