summaryrefslogtreecommitdiff
path: root/nslcd_systemd/misc_test.go
blob: a75083de5d7c898f49f90718a09c043c0fb7cf92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// Copyright (C) 2017 Luke Shumaker <lukeshu@sbcglobal.net>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
// 02110-1301 USA

package nslcd_systemd_test

import (
	"fmt"
	"io/ioutil"
	"net"
	"os"
	"runtime"
	"strings"
	"sync"
	"syscall"
	"testing"
	"time"

	"git.lukeshu.com/go/libnslcd/nslcd_proto"
	"git.lukeshu.com/go/libnslcd/nslcd_server"
	"git.lukeshu.com/go/libnslcd/nslcd_systemd"
	"golang.org/x/sys/unix"
)

func init() {
	if fdIsDevNull(3) == nil {
		return
	}

	devnull, err := os.OpenFile("/dev/null", os.O_RDWR, 0666)
	if err != nil {
		panic(err)
	}
	if devnull.Fd() == 3 {
		return
	}

	fmt.Fprintln(os.Stderr, "Could not open /dev/null on FD 3; calling dup2 and re-exec()ing")
	// shell out to do the FD manipulation--If we made it here,
	// there's a good chance that FD3 was managed by the go
	// runtime, and would be changed before we execve(2).
	panic(syscall.Exec("/bin/sh", append([]string{"sh", "-c", "exec -- \"$@\" 3<>/dev/null"}, os.Args...), os.Environ()))
}

type testContext struct {
	*testing.T
	tmpdir string
	status chan<- string
}

func testDriver(
	t *testContext,
	backend nslcd_systemd.Backend,
	limits nslcd_server.Limits,
	notifyHandler func(dat []byte, oob []byte) error,
	client func(sockname string)) {

	t.status <- "setting up"

	errfatal := func(err error) {
		if err != nil {
			t.Fatal(err)
		}
	}

	evExitSupervisor := make(chan error)
	evExitServer := make(chan uint8)

	// supervisor //////////////////////////////////////////////////////////
	notify_sock, err := sdNotifyListen(t.tmpdir + "/notify.sock")
	errfatal(err)
	go func() {
		evExitSupervisor <- sdNotifyHandle(notify_sock, notifyHandler)
	}()

	// server //////////////////////////////////////////////////////////////
	errfatal(sdActivatedStream(t.tmpdir + "/nslcd.sock"))
	go func() {
		evExitServer <- nslcd_systemd.Main(backend, limits)
	}()

	// client/driver ///////////////////////////////////////////////////////
	t.status <- "running client"
	client(t.tmpdir + "/nslcd.sock")

	// exit ////////////////////////////////////////////////////////////////

	// A limitation of Unix sockets is that some may get dropped
	// if they arrive close together.  So give it some (a half
	// second is probably generous by a couple orders of
	// magnitude) time between the client sending any signals and
	// us sending SIGTERM, so that we are sure it gets both.
	time.Sleep(time.Second / 2)

	t.status <- "waiting for server exit"
	errfatal(unix.Kill(unix.Getpid(), unix.SIGTERM))
	status := <-evExitServer
	if status != 0 {
		t.Fatalf("Main() exited with %d", status)
	}

	t.status <- "waiting for supervisor exit"
	errfatal(notify_sock.SetReadDeadline(time.Now()))
	err = <-evExitSupervisor
	if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
		err = nil
	}
	errfatal(err)
	errfatal(notify_sock.Close())
}

func testClientHang(t *testContext, backend nslcd_systemd.Backend, toclose bool) {
}

type NonLockingBackend struct {
	nslcd_server.NilBackend
}

func (o *NonLockingBackend) Init() error   { return nil }
func (o *NonLockingBackend) Reload() error { return nil }
func (o *NonLockingBackend) Close()        {}

func (o *NonLockingBackend) Passwd_All(cred unix.Ucred, req nslcd_proto.Request_Passwd_All) <-chan nslcd_proto.Passwd {
	ret := make(chan nslcd_proto.Passwd)
	go func() {
		defer close(ret)

		for i := 0; i < 500; i++ {
			ret <- nslcd_proto.Passwd{
				Name:    fmt.Sprintf("user%d", i),
				PwHash:  "x",
				UID:     int32(1000 + i),
				GID:     1000,
				GECOS:   fmt.Sprintf("User %d", i),
				HomeDir: fmt.Sprintf("/home/user%d", i),
				Shell:   "/bin/sh",
			}
		}
	}()
	return ret
}

type LockingBackend struct {
	NonLockingBackend
	lock sync.RWMutex
}

func (o *LockingBackend) Reload() error {
	o.lock.Lock()
	defer o.lock.Unlock()
	return o.NonLockingBackend.Reload()
}

func (o *LockingBackend) Close() {
	o.lock.Lock()
	defer o.lock.Unlock()
	o.NonLockingBackend.Close()
}

func (o *LockingBackend) Passwd_All(cred unix.Ucred, req nslcd_proto.Request_Passwd_All) <-chan nslcd_proto.Passwd {
	o.lock.RLock()
	ret := make(chan nslcd_proto.Passwd)
	go func() {
		defer o.lock.RUnlock()
		defer close(ret)

		for i := 0; i < 500; i++ {
			ret <- nslcd_proto.Passwd{
				Name:    fmt.Sprintf("user%d", i),
				PwHash:  "x",
				UID:     int32(1000 + i),
				GID:     1000,
				GECOS:   fmt.Sprintf("User %d", i),
				HomeDir: fmt.Sprintf("/home/user%d", i),
				Shell:   "/bin/sh",
			}
		}
	}()
	return ret
}

func TestClientHang(t *testing.T) {
	testcases := []struct {
		name    string
		backend nslcd_systemd.Backend
		toclose bool
	}{
		{"NoLocks-ClientOpen", &NonLockingBackend{}, false},
		{"NoLocks-ClientClose", &NonLockingBackend{}, true},
		{"Locking-ClientOpen", &LockingBackend{}, false},
		{"Locking-ClientClose", &LockingBackend{}, true},
	}
	for _, testcase := range testcases {
		func() {
			tmpdir, err := ioutil.TempDir("", "go-test-libnslcd-client-hang.")
			if err != nil {
				t.Fatal(err)
			}
			defer os.RemoveAll(tmpdir)
			defer sdActivatedReset()
			t.Run(testcase.name, func(t *testing.T) {
				testWithTimeout(t, 2*time.Second, func(t *testing.T, s chan<- string) {
					ctx := &testContext{T: t, tmpdir: tmpdir, status: s}

					backend := testcase.backend

					limits := nslcd_server.Limits{
						Timeout: 1 * time.Second,
					}

					evReload := make(chan bool)

					notifyHandler := func() func(dat []byte, oob []byte) error {
						reloading := false
						return func(dat []byte, oob []byte) error {
							for _, line := range strings.Split(string(dat), "\n") {
								switch line {
								case "RELOADING=1":
									reloading = true
								case "READY=1":
									if reloading {
										evReload <- true
									}
									reloading = false
								}
							}
							return nil
						}
					}()

					client := func(sockname string) {
						errfatal := func(err error) {
							if err != nil {
								t.Fatal(err)
							}
						}

						ctx.status <- "talking with server"
						conn, err := net.Dial("unix", sockname)
						errfatal(err)
						errfatal(nslcd_proto.Write(conn, nslcd_proto.NSLCD_VERSION))
						errfatal(nslcd_proto.Write(conn, nslcd_proto.NSLCD_ACTION_PASSWD_ALL))
						// Wait for NSLCD_RESULT_*, to make sure the server has made
						// it in to backend code.
						var n int32
						errfatal(nslcd_proto.Read(conn, &n))
						if n != nslcd_proto.NSLCD_VERSION {
							ctx.Fatal("server version wrong")
						}
						errfatal(nslcd_proto.Read(conn, &n))
						if n != nslcd_proto.NSLCD_ACTION_PASSWD_ALL {
							ctx.Fatal("server action wrong")
						}
						errfatal(nslcd_proto.Read(conn, &n))
						if n != nslcd_proto.NSLCD_RESULT_BEGIN && n != nslcd_proto.NSLCD_RESULT_END {
							ctx.Fatal("server result malformed")
						}
						if testcase.toclose {
							errfatal(conn.Close())
						}

						ctx.status <- "waiting for server reload"
						errfatal(unix.Kill(unix.Getpid(), unix.SIGHUP))
						<-evReload
					}

					testDriver(ctx, backend, limits, notifyHandler, client)
				})
			})
		}()
	}
}

func TestLargeRequest(t *testing.T) {
	tmpdir, err := ioutil.TempDir("", "go-test-libnslcd-large-request.")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tmpdir)
	defer sdActivatedReset()
	t.Run("large-request", func(t *testing.T) {
		testWithTimeout(t, 2*time.Second, func(t *testing.T, s chan<- string) {
			KiB := 1024
			GiB := 1024 * 1024 * 1024

			ctx := &testContext{T: t, tmpdir: tmpdir, status: s}

			backend := &LockingBackend{}

			limits := nslcd_server.Limits{
				Timeout:        1 * time.Second,
				RequestMaxSize: int64(1 * KiB),
			}

			notifyHandler := func(dat []byte, oob []byte) error { return nil }

			client := func(sockname string) {
				errfatal := func(err error) {
					if err != nil {
						t.Fatal(err)
					}
				}

				conn, err := net.Dial("unix", sockname)
				errfatal(err)
				errfatal(nslcd_proto.Write(conn, nslcd_proto.NSLCD_VERSION))
				errfatal(nslcd_proto.Write(conn, nslcd_proto.NSLCD_ACTION_PASSWD_BYNAME))
				errfatal(nslcd_proto.Write(conn, int32(1*GiB)))
			}

			testDriver(ctx, backend, limits, notifyHandler, client)

			var memstats runtime.MemStats
			runtime.ReadMemStats(&memstats)
			if memstats.HeapSys > uint64(1*GiB) {
				t.Fatalf("Used more than 1 GiB heap: %s B", humanizeU64(memstats.HeapSys))
			}
		})
	})
}