Browse code

Merge pull request #6485 from crosbymichael/update-libcontainer

Update libcontainer dependency to 77ffd49dfedbc78a

Tibor Vass authored on 2014/06/18 05:57:35
Showing 16 changed files
... ...
@@ -61,4 +61,4 @@ mv tmp-tar src/code.google.com/p/go/src/pkg/archive/tar
61 61
 
62 62
 clone git github.com/godbus/dbus v1
63 63
 clone git github.com/coreos/go-systemd v2
64
-clone git github.com/docker/libcontainer v1.0.0
64
+clone git github.com/docker/libcontainer 77ffd49dfedbc78a7cd4cb7a50c7446cf118725f
65 65
new file mode 100644
... ...
@@ -0,0 +1,11 @@
0
+language: go
1
+
2
+install:
3
+    - go get -d ./...
4
+    - go get -d github.com/dotcloud/docker # just to be sure
5
+    - DOCKER_PATH="${GOPATH%%:*}/src/github.com/dotcloud/docker"
6
+    - sed -i 's!dotcloud/docker!docker/libcontainer!' "$DOCKER_PATH/hack/make/.validate"
7
+
8
+script:
9
+    - bash "$DOCKER_PATH/hack/make/validate-dco"
10
+    - bash "$DOCKER_PATH/hack/make/validate-gofmt"
0 11
new file mode 100644
... ...
@@ -0,0 +1,204 @@
0
+# The libcontainer Contributors' Guide
1
+
2
+Want to hack on libcontainer? Awesome! Here are instructions to get you
3
+started. They are probably not perfect, please let us know if anything
4
+feels wrong or incomplete.
5
+
6
+## Reporting Issues
7
+
8
+When reporting [issues](https://github.com/docker/libcontainer/issues) 
9
+on GitHub please include your host OS (Ubuntu 12.04, Fedora 19, etc),
10
+the output of `uname -a`. Please include the steps required to reproduce
11
+the problem if possible and applicable.
12
+This information will help us review and fix your issue faster.
13
+
14
+## Development Environment
15
+
16
+*Add instructions on setting up the development environment.*
17
+
18
+## Contribution Guidelines
19
+
20
+### Pull requests are always welcome
21
+
22
+We are always thrilled to receive pull requests, and do our best to
23
+process them as fast as possible. Not sure if that typo is worth a pull
24
+request? Do it! We will appreciate it.
25
+
26
+If your pull request is not accepted on the first try, don't be
27
+discouraged! If there's a problem with the implementation, hopefully you
28
+received feedback on what to improve.
29
+
30
+We're trying very hard to keep libcontainer lean and focused. We don't want it
31
+to do everything for everybody. This means that we might decide against
32
+incorporating a new feature. However, there might be a way to implement
33
+that feature *on top of* libcontainer.
34
+
35
+### Discuss your design on the mailing list
36
+
37
+We recommend discussing your plans [on the mailing
38
+list](https://groups.google.com/forum/?fromgroups#!forum/docker-dev)
39
+before starting to code - especially for more ambitious contributions.
40
+This gives other contributors a chance to point you in the right
41
+direction, give feedback on your design, and maybe point out if someone
42
+else is working on the same thing.
43
+
44
+### Create issues...
45
+
46
+Any significant improvement should be documented as [a GitHub
47
+issue](https://github.com/docker/libcontainer/issues) before anybody
48
+starts working on it.
49
+
50
+### ...but check for existing issues first!
51
+
52
+Please take a moment to check that an issue doesn't already exist
53
+documenting your bug report or improvement proposal. If it does, it
54
+never hurts to add a quick "+1" or "I have this problem too". This will
55
+help prioritize the most common problems and requests.
56
+
57
+### Conventions
58
+
59
+Fork the repo and make changes on your fork in a feature branch:
60
+
61
+- If it's a bugfix branch, name it XXX-something where XXX is the number of the
62
+  issue
63
+- If it's a feature branch, create an enhancement issue to announce your
64
+  intentions, and name it XXX-something where XXX is the number of the issue.
65
+
66
+Submit unit tests for your changes.  Go has a great test framework built in; use
67
+it! Take a look at existing tests for inspiration. Run the full test suite on
68
+your branch before submitting a pull request.
69
+
70
+Update the documentation when creating or modifying features. Test
71
+your documentation changes for clarity, concision, and correctness, as
72
+well as a clean documentation build. See ``docs/README.md`` for more
73
+information on building the docs and how docs get released.
74
+
75
+Write clean code. Universally formatted code promotes ease of writing, reading,
76
+and maintenance. Always run `gofmt -s -w file.go` on each changed file before
77
+committing your changes. Most editors have plugins that do this automatically.
78
+
79
+Pull requests descriptions should be as clear as possible and include a
80
+reference to all the issues that they address.
81
+
82
+Pull requests must not contain commits from other users or branches.
83
+
84
+Commit messages must start with a capitalized and short summary (max. 50
85
+chars) written in the imperative, followed by an optional, more detailed
86
+explanatory text which is separated from the summary by an empty line.
87
+
88
+Code review comments may be added to your pull request. Discuss, then make the
89
+suggested modifications and push additional commits to your feature branch. Be
90
+sure to post a comment after pushing. The new commits will show up in the pull
91
+request automatically, but the reviewers will not be notified unless you
92
+comment.
93
+
94
+Before the pull request is merged, make sure that you squash your commits into
95
+logical units of work using `git rebase -i` and `git push -f`. After every
96
+commit the test suite should be passing. Include documentation changes in the
97
+same commit so that a revert would remove all traces of the feature or fix.
98
+
99
+Commits that fix or close an issue should include a reference like `Closes #XXX`
100
+or `Fixes #XXX`, which will automatically close the issue when merged.
101
+
102
+### Testing
103
+
104
+Make sure you include suitable tests, preferably unit tests, in your pull request
105
+and that all the tests pass.
106
+
107
+*Instructions for running tests to be added.*
108
+
109
+### Merge approval
110
+
111
+libcontainer maintainers use LGTM (looks good to me) in comments on the code review
112
+to indicate acceptance.
113
+
114
+A change requires LGTMs from at lease one maintainer of each
115
+component affected. For example, if a change affects `netlink/` and `security/`, it
116
+needs at least one LGTM from the maintainers of `netlink/` AND, separately, at
117
+least one LGTM from the maintainers of `security/`.
118
+
119
+For more details see [MAINTAINERS.md](hack/MAINTAINERS.md)
120
+
121
+### Sign your work
122
+
123
+The sign-off is a simple line at the end of the explanation for the
124
+patch, which certifies that you wrote it or otherwise have the right to
125
+pass it on as an open-source patch.  The rules are pretty simple: if you
126
+can certify the below (from
127
+[developercertificate.org](http://developercertificate.org/)):
128
+
129
+```
130
+Developer Certificate of Origin
131
+Version 1.1
132
+
133
+Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
134
+660 York Street, Suite 102,
135
+San Francisco, CA 94110 USA
136
+
137
+Everyone is permitted to copy and distribute verbatim copies of this
138
+license document, but changing it is not allowed.
139
+
140
+
141
+Developer's Certificate of Origin 1.1
142
+
143
+By making a contribution to this project, I certify that:
144
+
145
+(a) The contribution was created in whole or in part by me and I
146
+    have the right to submit it under the open source license
147
+    indicated in the file; or
148
+
149
+(b) The contribution is based upon previous work that, to the best
150
+    of my knowledge, is covered under an appropriate open source
151
+    license and I have the right under that license to submit that
152
+    work with modifications, whether created in whole or in part
153
+    by me, under the same open source license (unless I am
154
+    permitted to submit under a different license), as indicated
155
+    in the file; or
156
+
157
+(c) The contribution was provided directly to me by some other
158
+    person who certified (a), (b) or (c) and I have not modified
159
+    it.
160
+
161
+(d) I understand and agree that this project and the contribution
162
+    are public and that a record of the contribution (including all
163
+    personal information I submit with it, including my sign-off) is
164
+    maintained indefinitely and may be redistributed consistent with
165
+    this project or the open source license(s) involved.
166
+```
167
+
168
+then you just add a line to every git commit message:
169
+
170
+    Docker-DCO-1.1-Signed-off-by: Joe Smith <joe.smith@email.com> (github: github_handle)
171
+
172
+using your real name (sorry, no pseudonyms or anonymous contributions.)
173
+
174
+One way to automate this, is customise your get ``commit.template`` by adding
175
+a ``prepare-commit-msg`` hook to your libcontainer checkout:
176
+
177
+```
178
+curl -o .git/hooks/prepare-commit-msg https://raw.githubusercontent.com/dotcloud/docker/master/contrib/prepare-commit-msg.hook && chmod +x .git/hooks/prepare-commit-msg
179
+```
180
+
181
+* Note: the above script expects to find your GitHub user name in ``git config --get github.user``
182
+
183
+#### Small patch exception
184
+
185
+There are several exceptions to the signing requirement. Currently these are:
186
+
187
+* Your patch fixes spelling or grammar errors.
188
+* Your patch is a single line change to documentation contained in the
189
+  `docs` directory.
190
+* Your patch fixes Markdown formatting or syntax errors in the
191
+  documentation contained in the `docs` directory.
192
+
193
+If you have any questions, please refer to the FAQ in the [docs](to be written)
194
+
195
+### How can I become a maintainer?
196
+
197
+* Step 1: learn the component inside out
198
+* Step 2: make yourself useful by contributing code, bugfixes, support etc.
199
+* Step 3: volunteer on the irc channel (#libcontainer@freenode)
200
+
201
+Don't forget: being a maintainer is a time investment. Make sure you will have time to make yourself available.
202
+You don't have to be a maintainer to make a difference on the project!
203
+
... ...
@@ -1,3 +1,4 @@
1
-Michael Crosby <michael@crosbymichael.com> (@crosbymichael)
1
+Michael Crosby <michael@docker.com> (@crosbymichael)
2 2
 Rohit Jnagal <jnagal@google.com> (@rjnagal)
3 3
 Victor Marmol <vmarmol@google.com> (@vmarmol)
4
+.travis.yml: Tianon Gravi <admwiggin@gmail.com> (@tianon)
4 5
new file mode 100644
... ...
@@ -0,0 +1,99 @@
0
+# The libcontainer Maintainers' Guide
1
+
2
+## Introduction
3
+
4
+Dear maintainer. Thank you for investing the time and energy to help
5
+make libcontainer as useful as possible. Maintaining a project is difficult,
6
+sometimes unrewarding work.  Sure, you will get to contribute cool
7
+features to the project. But most of your time will be spent reviewing,
8
+cleaning up, documenting, answering questions, justifying design
9
+decisions - while everyone has all the fun! But remember - the quality
10
+of the maintainers work is what distinguishes the good projects from the
11
+great.  So please be proud of your work, even the unglamourous parts,
12
+and encourage a culture of appreciation and respect for *every* aspect
13
+of improving the project - not just the hot new features.
14
+
15
+This document is a manual for maintainers old and new. It explains what
16
+is expected of maintainers, how they should work, and what tools are
17
+available to them.
18
+
19
+This is a living document - if you see something out of date or missing,
20
+speak up!
21
+
22
+## What are a maintainer's responsibility?
23
+
24
+It is every maintainer's responsibility to:
25
+
26
+* 1) Expose a clear roadmap for improving their component.
27
+* 2) Deliver prompt feedback and decisions on pull requests.
28
+* 3) Be available to anyone with questions, bug reports, criticism etc.
29
+  on their component. This includes IRC, GitHub requests and the mailing
30
+  list.
31
+* 4) Make sure their component respects the philosophy, design and
32
+  roadmap of the project.
33
+
34
+## How are decisions made?
35
+
36
+Short answer: with pull requests to the libcontainer repository.
37
+
38
+libcontainer is an open-source project with an open design philosophy. This
39
+means that the repository is the source of truth for EVERY aspect of the
40
+project, including its philosophy, design, roadmap and APIs. *If it's
41
+part of the project, it's in the repo. It's in the repo, it's part of
42
+the project.*
43
+
44
+As a result, all decisions can be expressed as changes to the
45
+repository. An implementation change is a change to the source code. An
46
+API change is a change to the API specification. A philosophy change is
47
+a change to the philosophy manifesto. And so on.
48
+
49
+All decisions affecting libcontainer, big and small, follow the same 3 steps:
50
+
51
+* Step 1: Open a pull request. Anyone can do this.
52
+
53
+* Step 2: Discuss the pull request. Anyone can do this.
54
+
55
+* Step 3: Accept (`LGTM`) or refuse a pull request. The relevant maintainers do 
56
+this (see below "Who decides what?")
57
+
58
+
59
+## Who decides what?
60
+
61
+All decisions are pull requests, and the relevant maintainers make
62
+decisions by accepting or refusing the pull request. Review and acceptance
63
+by anyone is denoted by adding a comment in the pull request: `LGTM`. 
64
+However, only currently listed `MAINTAINERS` are counted towards the required
65
+majority.
66
+
67
+libcontainer follows the timeless, highly efficient and totally unfair system
68
+known as [Benevolent dictator for life](http://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), with Michael Crosby in the role of BDFL.
69
+This means that all decisions are made by default by Michael. Since making
70
+every decision himself would be highly un-scalable, in practice decisions
71
+are spread across multiple maintainers.
72
+
73
+The relevant maintainers for a pull request can be worked out in two steps:
74
+
75
+* Step 1: Determine the subdirectories affected by the pull request. This
76
+  might be `netlink/` and `security/`, or any other part of the repo.
77
+
78
+* Step 2: Find the `MAINTAINERS` file which affects this directory. If the
79
+  directory itself does not have a `MAINTAINERS` file, work your way up
80
+  the repo hierarchy until you find one.
81
+
82
+### I'm a maintainer, and I'm going on holiday
83
+
84
+Please let your co-maintainers and other contributors know by raising a pull
85
+request that comments out your `MAINTAINERS` file entry using a `#`.
86
+
87
+### I'm a maintainer, should I make pull requests too?
88
+
89
+Yes. Nobody should ever push to master directly. All changes should be
90
+made through a pull request.
91
+
92
+### Who assigns maintainers?
93
+
94
+Michael has final `LGTM` approval for all pull requests to `MAINTAINERS` files.
95
+
96
+### How is this process changed?
97
+
98
+Just like everything else: by making a pull request :)
0 99
new file mode 100644
... ...
@@ -0,0 +1,19 @@
0
+# libcontainer Principles
1
+
2
+In the design and development of libcontainer we try to follow these principles:
3
+
4
+(Work in progress)
5
+
6
+* Don't try to replace every tool. Instead, be an ingredient to improve them.
7
+* Less code is better.
8
+* Fewer components are better. Do you really need to add one more class?
9
+* 50 lines of straightforward, readable code is better than 10 lines of magic that nobody can understand.
10
+* Don't do later what you can do now. "//FIXME: refactor" is not acceptable in new code.
11
+* When hesitating between two options, choose the one that is easier to reverse.
12
+* "No" is temporary; "Yes" is forever. If you're not sure about a new feature, say no. You can change your mind later.
13
+* Containers must be portable to the greatest possible number of machines. Be suspicious of any change which makes machines less interchangeable.
14
+* The fewer moving parts in a container, the better.
15
+* Don't merge it unless you document it.
16
+* Don't document it unless you can keep it up-to-date.
17
+* Don't merge it unless you test it!
18
+* Everyone's problem is slightly different. Focus on the part that is the same for everyone, and solve that.
... ...
@@ -1,16 +1,16 @@
1 1
 ## libcontainer - reference implementation for containers
2 2
 
3
-#### background
3
+#### Background
4 4
 
5 5
 libcontainer specifies configuration options for what a container is.  It provides a native Go implementation 
6 6
 for using Linux namespaces with no external dependencies.  libcontainer provides many convenience functions for working with namespaces, networking, and management.  
7 7
 
8 8
 
9
-#### container
9
+#### Container
10 10
 A container is a self contained directory that is able to run one or more processes without 
11 11
 affecting the host system.  The directory is usually a full system tree.  Inside the directory
12 12
 a `container.json` file is placed with the runtime configuration for how the processes 
13
-should be contained and ran.  Environment, networking, and different capabilities for the 
13
+should be contained and run.  Environment, networking, and different capabilities for the 
14 14
 process are specified in this file.  The configuration is used for each process executed inside the container.
15 15
 
16 16
 See the `container.json` file for what the configuration should look like.
... ...
@@ -35,8 +35,19 @@ If you wish to spawn another process inside the container while your current bas
35 35
 running just run the exact same command again to get another bash shell or change the command.  If the original process dies, PID 1, all other processes spawned inside the container will also be killed and the namespace will be removed. 
36 36
 
37 37
 You can identify if a process is running in a container by looking to see if `pid` is in the root of the directory.   
38
+#### Future
39
+See the [roadmap](ROADMAP.md).
38 40
 
39 41
 ## Copyright and license
40 42
 
41 43
 Code and documentation copyright 2014 Docker, inc. Code released under the Apache 2.0 license.
42 44
 Docs released under Creative commons.
45
+
46
+## Hacking on libcontainer
47
+
48
+First of all, please familiarise yourself with the [libcontainer Principles](PRINCIPLES.md).
49
+
50
+If you're a *contributor* or aspiring contributor, you should read the [Contributors' Guide](CONTRIBUTORS_GUIDE.md).
51
+
52
+If you're a *maintainer* or aspiring maintainer, you should read the [Maintainers' Guide](MAINTAINERS_GUIDE.md) and
53
+"How can I become a maintainer?" in the Contributors' Guide.
43 54
new file mode 100644
... ...
@@ -0,0 +1,16 @@
0
+# libcontainer: what's next?
1
+
2
+This document is a high-level overview of where we want to take libcontainer next.
3
+It is a curated selection of planned improvements which are either important, difficult, or both.
4
+
5
+For a more complete view of planned and requested improvements, see [the Github issues](https://github.com/docker/libcontainer/issues).
6
+
7
+To suggest changes to the roadmap, including additions, please write the change as if it were already in effect, and make a pull request.
8
+
9
+## Broader kernel support
10
+
11
+Our goal is to make libcontainer run everywhere, but currently libcontainer requires Linux version 3.8 or higher. If you’re deploying new machines for the purpose of running libcontainer, this is a fairly easy requirement to meet. However, if you’re adding libcontainer to an existing deployment, you may not have the flexibility to update and patch the kernel.
12
+
13
+## Cross-architecture support
14
+
15
+Our goal is to make libcontainer run everywhere. However currently libcontainer only runs on x86_64 systems. We plan on expanding architecture support, so that libcontainer containers can be created and used on more architectures.
... ...
@@ -31,7 +31,7 @@ func TestGetCgroupParamsInt(t *testing.T) {
31 31
 	if err != nil {
32 32
 		t.Fatal(err)
33 33
 	} else if value != floatValue {
34
-		t.Fatalf("Expected %f to equal %f", value, floatValue)
34
+		t.Fatalf("Expected %d to equal %f", value, floatValue)
35 35
 	}
36 36
 
37 37
 	// Success with new line.
... ...
@@ -43,7 +43,7 @@ func TestGetCgroupParamsInt(t *testing.T) {
43 43
 	if err != nil {
44 44
 		t.Fatal(err)
45 45
 	} else if value != floatValue {
46
-		t.Fatalf("Expected %f to equal %f", value, floatValue)
46
+		t.Fatalf("Expected %d to equal %f", value, floatValue)
47 47
 	}
48 48
 
49 49
 	// Not a float.
... ...
@@ -2,6 +2,7 @@ package cgroups
2 2
 
3 3
 import (
4 4
 	"bufio"
5
+	"fmt"
5 6
 	"io"
6 7
 	"os"
7 8
 	"path/filepath"
... ...
@@ -30,6 +31,80 @@ func FindCgroupMountpoint(subsystem string) (string, error) {
30 30
 	return "", ErrNotFound
31 31
 }
32 32
 
33
+type Mount struct {
34
+	Mountpoint string
35
+	Subsystems []string
36
+}
37
+
38
+func (m Mount) GetThisCgroupDir() (string, error) {
39
+	if len(m.Subsystems) == 0 {
40
+		return "", fmt.Errorf("no subsystem for mount")
41
+	}
42
+
43
+	return GetThisCgroupDir(m.Subsystems[0])
44
+}
45
+
46
+func GetCgroupMounts() ([]Mount, error) {
47
+	mounts, err := mount.GetMounts()
48
+	if err != nil {
49
+		return nil, err
50
+	}
51
+
52
+	all, err := GetAllSubsystems()
53
+	if err != nil {
54
+		return nil, err
55
+	}
56
+
57
+	allMap := make(map[string]bool)
58
+	for _, s := range all {
59
+		allMap[s] = true
60
+	}
61
+
62
+	res := []Mount{}
63
+	for _, mount := range mounts {
64
+		if mount.Fstype == "cgroup" {
65
+			m := Mount{Mountpoint: mount.Mountpoint}
66
+
67
+			for _, opt := range strings.Split(mount.VfsOpts, ",") {
68
+				if strings.HasPrefix(opt, "name=") {
69
+					m.Subsystems = append(m.Subsystems, opt)
70
+				}
71
+				if allMap[opt] {
72
+					m.Subsystems = append(m.Subsystems, opt)
73
+				}
74
+			}
75
+			res = append(res, m)
76
+		}
77
+	}
78
+	return res, nil
79
+}
80
+
81
+// Returns all the cgroup subsystems supported by the kernel
82
+func GetAllSubsystems() ([]string, error) {
83
+	f, err := os.Open("/proc/cgroups")
84
+	if err != nil {
85
+		return nil, err
86
+	}
87
+	defer f.Close()
88
+
89
+	subsystems := []string{}
90
+
91
+	s := bufio.NewScanner(f)
92
+	for s.Scan() {
93
+		if err := s.Err(); err != nil {
94
+			return nil, err
95
+		}
96
+		text := s.Text()
97
+		if text[0] != '#' {
98
+			parts := strings.Fields(text)
99
+			if len(parts) > 4 && parts[3] != "0" {
100
+				subsystems = append(subsystems, parts[0])
101
+			}
102
+		}
103
+	}
104
+	return subsystems, nil
105
+}
106
+
33 107
 // Returns the relative path to the cgroup docker is running in.
34 108
 func GetThisCgroupDir(subsystem string) (string, error) {
35 109
 	f, err := os.Open("/proc/self/cgroup")
... ...
@@ -39,8 +39,8 @@ func (device *Device) GetCgroupAllowString() string {
39 39
 }
40 40
 
41 41
 // Given the path to a device and it's cgroup_permissions(which cannot be easilly queried) look up the information about a linux device and return that information as a Device struct.
42
-func GetDevice(path string, cgroupPermissions string) (*Device, error) {
43
-	fileInfo, err := os.Stat(path)
42
+func GetDevice(path, cgroupPermissions string) (*Device, error) {
43
+	fileInfo, err := os.Lstat(path)
44 44
 	if err != nil {
45 45
 		return nil, err
46 46
 	}
... ...
@@ -4,17 +4,18 @@ package mount
4 4
 
5 5
 import (
6 6
 	"fmt"
7
-	"github.com/dotcloud/docker/pkg/system"
8 7
 	"io/ioutil"
9 8
 	"os"
10 9
 	"path/filepath"
11 10
 	"syscall"
11
+
12
+	"github.com/dotcloud/docker/pkg/system"
12 13
 )
13 14
 
14 15
 func PivotRoot(rootfs string) error {
15 16
 	pivotDir, err := ioutil.TempDir(rootfs, ".pivot_root")
16 17
 	if err != nil {
17
-		return fmt.Errorf("can't create pivot_root dir %s", pivotDir, err)
18
+		return fmt.Errorf("can't create pivot_root dir %s, error %v", pivotDir, err)
18 19
 	}
19 20
 	if err := system.Pivotroot(rootfs, pivotDir); err != nil {
20 21
 		return fmt.Errorf("pivot_root %s", err)
... ...
@@ -185,7 +185,10 @@ func setupRoute(container *libcontainer.Container) error {
185 185
 // and working dir, and closes any leaky file descriptors
186 186
 // before execing the command inside the namespace
187 187
 func FinalizeNamespace(container *libcontainer.Container) error {
188
-	if err := system.CloseFdsFrom(3); err != nil {
188
+	// Ensure that all non-standard fds we may have accidentally
189
+	// inherited are marked close-on-exec so they stay out of the
190
+	// container
191
+	if err := utils.CloseExecFrom(3); err != nil {
189 192
 		return fmt.Errorf("close open file descriptors %s", err)
190 193
 	}
191 194
 
... ...
@@ -217,6 +220,7 @@ func FinalizeNamespace(container *libcontainer.Container) error {
217 217
 			return fmt.Errorf("chdir to %s %s", container.WorkingDir, err)
218 218
 		}
219 219
 	}
220
+
220 221
 	return nil
221 222
 }
222 223
 
... ...
@@ -1,9 +1,12 @@
1
+// +build linux
2
+
1 3
 package namespaces
2 4
 
3 5
 /*
4 6
 #include <dirent.h>
5 7
 #include <errno.h>
6 8
 #include <fcntl.h>
9
+#include <linux/limits.h>
7 10
 #include <linux/sched.h>
8 11
 #include <signal.h>
9 12
 #include <stdio.h>
... ...
@@ -49,6 +52,18 @@ void get_args(int *argc, char ***argv) {
49 49
 	(*argv)[*argc] = NULL;
50 50
 }
51 51
 
52
+// Use raw setns syscall for versions of glibc that don't include it (namely glibc-2.12)
53
+#if __GLIBC__ == 2 && __GLIBC_MINOR__ < 14
54
+#define _GNU_SOURCE
55
+#include <sched.h>
56
+#include "syscall.h"
57
+#ifdef SYS_setns
58
+int setns(int fd, int nstype) {
59
+  return syscall(SYS_setns, fd, nstype);
60
+}
61
+#endif
62
+#endif
63
+
52 64
 void nsenter() {
53 65
 	int argc;
54 66
 	char **argv;
... ...
@@ -73,12 +88,9 @@ void nsenter() {
73 73
 	argv += 3;
74 74
 
75 75
 	// Setns on all supported namespaces.
76
-	char ns_dir[kBufSize];
77
-	memset(ns_dir, 0, kBufSize);
78
-	if (snprintf(ns_dir, kBufSize - 1, "/proc/%d/ns/", init_pid) < 0) {
79
-		fprintf(stderr, "nsenter: Error getting ns dir path with error: \"%s\"\n", strerror(errno));
80
-		exit(1);
81
-	}
76
+	char ns_dir[PATH_MAX];
77
+	memset(ns_dir, 0, PATH_MAX);
78
+	snprintf(ns_dir, PATH_MAX - 1, "/proc/%d/ns/", init_pid);
82 79
 	struct dirent *dent;
83 80
 	DIR *dir = opendir(ns_dir);
84 81
 	if (dir == NULL) {
... ...
@@ -92,10 +104,9 @@ void nsenter() {
92 92
 		}
93 93
 
94 94
 		// Get and open the namespace for the init we are joining..
95
-		char buf[kBufSize];
96
-		memset(buf, 0, kBufSize);
97
-		strncat(buf, ns_dir, kBufSize - 1);
98
-		strncat(buf, dent->d_name, kBufSize - 1);
95
+		char buf[PATH_MAX];
96
+		memset(buf, 0, PATH_MAX);
97
+		snprintf(buf, PATH_MAX - 1, "%s%s", ns_dir, dent->d_name);
99 98
 		int fd = open(buf, O_RDONLY);
100 99
 		if (fd == -1) {
101 100
 			fprintf(stderr, "nsenter: Failed to open ns file \"%s\" for ns \"%s\" with error: \"%s\"\n", buf, dent->d_name, strerror(errno));
... ...
@@ -15,13 +15,14 @@ const defaultMountFlags = syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NOD
15 15
 
16 16
 func mountReadonly(path string) error {
17 17
 	for i := 0; i < 5; i++ {
18
-		if err := system.Mount("", path, "", syscall.MS_REMOUNT|syscall.MS_RDONLY, ""); err != nil {
18
+		if err := system.Mount("", path, "", syscall.MS_REMOUNT|syscall.MS_RDONLY, ""); err != nil && !os.IsNotExist(err) {
19 19
 			switch err {
20 20
 			case syscall.EINVAL:
21 21
 				// Probably not a mountpoint, use bind-mount
22 22
 				if err := system.Mount(path, path, "", syscall.MS_BIND, ""); err != nil {
23 23
 					return err
24 24
 				}
25
+
25 26
 				return system.Mount(path, path, "", syscall.MS_BIND|syscall.MS_REMOUNT|syscall.MS_RDONLY|syscall.MS_REC|defaultMountFlags, "")
26 27
 			case syscall.EBUSY:
27 28
 				time.Sleep(100 * time.Millisecond)
... ...
@@ -30,15 +31,16 @@ func mountReadonly(path string) error {
30 30
 				return err
31 31
 			}
32 32
 		}
33
+
33 34
 		return nil
34 35
 	}
36
+
35 37
 	return fmt.Errorf("unable to mount %s as readonly max retries reached", path)
36 38
 }
37 39
 
38 40
 // This has to be called while the container still has CAP_SYS_ADMIN (to be able to perform mounts).
39 41
 // However, afterwards, CAP_SYS_ADMIN should be dropped (otherwise the user will be able to revert those changes).
40 42
 func Restrict(mounts ...string) error {
41
-	// remount proc and sys as readonly
42 43
 	for _, dest := range mounts {
43 44
 		if err := mountReadonly(dest); err != nil {
44 45
 			return fmt.Errorf("unable to remount %s readonly: %s", dest, err)
... ...
@@ -48,5 +50,6 @@ func Restrict(mounts ...string) error {
48 48
 	if err := system.Mount("/dev/null", "/proc/kcore", "", syscall.MS_BIND, ""); err != nil && !os.IsNotExist(err) {
49 49
 		return fmt.Errorf("unable to bind-mount /dev/null over /proc/kcore: %s", err)
50 50
 	}
51
+
51 52
 	return nil
52 53
 }
... ...
@@ -4,7 +4,10 @@ import (
4 4
 	"crypto/rand"
5 5
 	"encoding/hex"
6 6
 	"io"
7
+	"io/ioutil"
7 8
 	"path/filepath"
9
+	"strconv"
10
+	"syscall"
8 11
 )
9 12
 
10 13
 // GenerateRandomName returns a new name joined with a prefix.  This size
... ...
@@ -26,3 +29,27 @@ func ResolveRootfs(uncleanRootfs string) (string, error) {
26 26
 	}
27 27
 	return filepath.EvalSymlinks(rootfs)
28 28
 }
29
+
30
+func CloseExecFrom(minFd int) error {
31
+	fdList, err := ioutil.ReadDir("/proc/self/fd")
32
+	if err != nil {
33
+		return err
34
+	}
35
+	for _, fi := range fdList {
36
+		fd, err := strconv.Atoi(fi.Name())
37
+		if err != nil {
38
+			// ignore non-numeric file names
39
+			continue
40
+		}
41
+
42
+		if fd < minFd {
43
+			// ignore descriptors lower than our specified minimum
44
+			continue
45
+		}
46
+
47
+		// intentionally ignore errors from syscall.CloseOnExec
48
+		syscall.CloseOnExec(fd)
49
+		// the cases where this might fail are basically file descriptors that have already been closed (including and especially the one that was created when ioutil.ReadDir did the "opendir" syscall)
50
+	}
51
+	return nil
52
+}