(Pseudo) Fix history (non gabbiness) by stripping PS_ARGLIST_MASK
[s-mailx.git] / dotlock.c
blob38464f6c8b4af4e78476d37d5a2f054b324ba726
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ n_dotlock(): creation of an exclusive "dotlock" file.
4 * Copyright (c) 2016 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
5 */
6 #undef n_FILE
7 #define n_FILE dotlock
9 #ifndef HAVE_AMALGAMATION
10 # include "nail.h"
11 #endif
13 #include <sys/wait.h>
15 #ifdef HAVE_DOTLOCK
16 # include "dotlock.h"
17 #endif
19 /* XXX Our Popen() main() takes void, temporary global data store */
20 #ifdef HAVE_DOTLOCK
21 static enum n_file_lock_type a_dotlock_flt;
22 static int a_dotlock_fd;
23 struct n_dotlock_info *a_dotlock_dip;
24 #endif
26 /* main() of fork(2)ed dot file locker */
27 #ifdef HAVE_DOTLOCK
28 static int a_dotlock_main(void);
29 #endif
31 #ifdef HAVE_DOTLOCK
32 static int
33 a_dotlock_main(void){
34 /* Use PATH_MAX not NAME_MAX to catch those "we proclaim the minimum value"
35 * problems (SunOS), since the pathconf(3) value comes too late! */
36 char name[PATH_MAX +1];
37 struct n_dotlock_info di;
38 struct stat stb, fdstb;
39 enum n_dotlock_state dls;
40 char const *cp;
41 int fd;
42 enum n_file_lock_type flt;
43 NYD_ENTER;
45 /* Ignore SIGPIPE, we'll see EPIPE and "fall through" */
46 safe_signal(SIGPIPE, SIG_IGN);
48 /* Get the arguments "passed to us" */
49 flt = a_dotlock_flt;
50 fd = a_dotlock_fd;
51 UNUSED(fd);
52 di = *a_dotlock_dip;
54 /* chdir(2)? */
55 jislink:
56 dls = n_DLS_CANT_CHDIR | n_DLS_ABANDON;
58 if((cp = strrchr(di.di_file_name, '/')) != NULL){
59 char const *fname = cp + 1;
61 while(PTRCMP(cp - 1, >, di.di_file_name) && cp[-1] == '/')
62 --cp;
63 cp = savestrbuf(di.di_file_name, PTR2SIZE(cp - di.di_file_name));
64 if(chdir(cp))
65 goto jmsg;
67 di.di_file_name = fname;
70 /* So we're here, but then again the file can be a symbolic link!
71 * This is however only true if we do not have realpath(3) available since
72 * that'll have resolved the path already otherwise; nonetheless, let
73 * readlink(2) be a precondition for dotlocking and keep this code */
74 if(lstat(cp = di.di_file_name, &stb) == -1)
75 goto jmsg;
76 if(S_ISLNK(stb.st_mode)){
77 /* Use salloc() and hope we stay in builtin buffer.. */
78 char *x;
79 size_t i;
80 ssize_t sr;
82 for(x = NULL, i = PATH_MAX;; i += PATH_MAX){
83 x = salloc(i +1);
84 sr = readlink(cp, x, i);
85 if(sr <= 0){
86 dls = n_DLS_FISHY | n_DLS_ABANDON;
87 goto jmsg;
89 if(UICMP(z, sr, <, i)){
90 x[sr] = '\0';
91 i = (size_t)sr;
92 break;
95 di.di_file_name = x;
96 goto jislink;
99 dls = n_DLS_FISHY | n_DLS_ABANDON;
101 /* Bail out if the file has changed its identity in the meanwhile */
102 if(fstat(fd, &fdstb) == -1 ||
103 fdstb.st_dev != stb.st_dev || fdstb.st_ino != stb.st_ino ||
104 fdstb.st_uid != stb.st_uid || fdstb.st_gid != stb.st_gid ||
105 fdstb.st_mode != stb.st_mode)
106 goto jmsg;
108 /* Be aware, even if the error is false! Note the shared code in dotlock.h
109 * *requires* that it is possible to create a filename at least one byte
110 * longer than di_lock_name! */
111 do/* while(0) breaker */{
112 # ifdef HAVE_PATHCONF
113 long pc;
114 # endif
115 int i = snprintf(name, sizeof name, "%s.lock", di.di_file_name);
117 /* fd is a file, not portable to use for _PC_NAME_MAX */
118 if(i < 0){
119 jenametool:
120 dls = n_DLS_NAMETOOLONG | n_DLS_ABANDON;
121 goto jmsg;
123 # ifdef HAVE_PATHCONF
124 errno = 0;
125 if((pc = pathconf(".", _PC_NAME_MAX)) == -1){
126 /* errno unchanged: no limit */
127 if(errno == 0)
128 break;
129 }else if(pc - 1 >= (long)i)
130 break;
131 else
132 goto jenametool;
133 # endif
134 if(UICMP(z, NAME_MAX - 1, <, (uiz_t)i))
135 goto jenametool;
136 }while(0);
138 di.di_lock_name = name;
140 /* We are in the directory of the mailbox for which we have to create
141 * a dotlock file for. We don't know whether we have realpath(3) available,
142 * and manually resolving the path is due especially given that S-nail
143 * supports the special "%:" syntax to warp any file into a "system
144 * mailbox"; there may also be multiple system mailbox directories...
145 * So what we do is that we fstat(2) the mailbox and check its UID and
146 * GID against that of our own process: if any of those mismatch we must
147 * either assume a directory we are not allowed to write in, or that we run
148 * via -u/$USER/%USER as someone else, in which case we favour our
149 * privilege-separated dotlock process */
150 assert(cp != NULL); /* Ugly: avoid a useless var and reuse that one */
151 if(access(".", W_OK)){
152 /* This may however also indicate a read-only filesystem, which is not
153 * really an error from our point of view since the mailbox will degrade
154 * to a readonly one for which no dotlock is needed, then, and errors
155 * may arise only due to actions which require box modifications */
156 if(errno == EROFS){
157 dls = n_DLS_ROFS | n_DLS_ABANDON;
158 goto jmsg;
160 cp = NULL;
162 if(cp == NULL || stb.st_uid != user_id || stb.st_gid != group_id){
163 char itoabuf[64];
164 char const *args[13];
166 snprintf(itoabuf, sizeof itoabuf, "%" PRIuZ, di.di_pollmsecs);
167 args[ 0] = VAL_PRIVSEP;
168 args[ 1] = (flt == FLT_READ ? "rdotlock" : "wdotlock");
169 args[ 2] = "mailbox"; args[ 3] = di.di_file_name;
170 args[ 4] = "name"; args[ 5] = di.di_lock_name;
171 args[ 6] = "hostname"; args[ 7] = di.di_hostname;
172 args[ 8] = "randstr"; args[ 9] = di.di_randstr;
173 args[10] = "pollmsecs"; args[11] = itoabuf;
174 args[12] = NULL;
175 execv(VAL_LIBEXECDIR "/" VAL_UAGENT "-privsep", UNCONST(args));
177 dls = n_DLS_NOEXEC;
178 write(STDOUT_FILENO, &dls, sizeof dls);
179 /* But fall through and try it with normal privileges! */
182 /* So let's try and call it ourselfs! Note that we don't block signals just
183 * like our privsep child does, the user will anyway be able to remove his
184 * file again, and if we're in -u/$USER mode then we are allowed to access
185 * the user's box: shall we leave behind a stale dotlock then at least we
186 * start a friendly human conversation. Since we cannot handle SIGKILL and
187 * SIGSTOP malicious things could happen whatever we do */
188 safe_signal(SIGHUP, SIG_IGN);
189 safe_signal(SIGINT, SIG_IGN);
190 safe_signal(SIGQUIT, SIG_IGN);
191 safe_signal(SIGTERM, SIG_IGN);
193 NYD;
194 dls = a_dotlock_create(&di);
195 NYD;
197 /* Finally: notify our parent about the actual lock state.. */
198 jmsg:
199 write(STDOUT_FILENO, &dls, sizeof dls);
200 close(STDOUT_FILENO);
202 /* ..then eventually wait until we shall remove the lock again, which will
203 * be notified via the read returning */
204 if(dls == n_DLS_NONE){
205 read(STDIN_FILENO, &dls, sizeof dls);
207 unlink(name);
209 NYD_LEAVE;
210 return EXIT_OK;
212 #endif /* HAVE_DOTLOCK */
214 FL FILE *
215 n_dotlock(char const *fname, int fd, enum n_file_lock_type flt,
216 off_t off, off_t len, size_t pollmsecs){
217 #undef _DOMSG
218 #ifdef HAVE_DOTLOCK
219 # define _DOMSG() \
220 n_err(_("Creating dotlock for %s "), n_shexp_quote_cp(fname, FAL0))
221 #else
222 # define _DOMSG() \
223 n_err(_("Trying to lock file %s "), n_shexp_quote_cp(fname, FAL0))
224 #endif
226 #ifdef HAVE_DOTLOCK
227 int cpipe[2];
228 struct n_dotlock_info di;
229 enum n_dotlock_state dls;
230 char const *emsg;
231 #endif
232 int serrno;
233 union {size_t tries; int (*ptf)(void); char const *sh; ssize_t r;} u;
234 bool_t flocked, didmsg;
235 FILE *rv;
236 NYD_ENTER;
238 if(pollmsecs == UIZ_MAX)
239 pollmsecs = FILE_LOCK_MILLIS;
241 rv = NULL;
242 didmsg = FAL0;
243 UNINIT(serrno, 0);
244 #ifdef HAVE_DOTLOCK
245 emsg = NULL;
246 #endif
248 if(options & OPT_D_VV){
249 _DOMSG();
250 didmsg = TRUM1;
253 flocked = FAL0;
254 for(u.tries = 0; !n_file_lock(fd, flt, off, len, 0);)
255 switch((serrno = errno)){
256 case EACCES:
257 case EAGAIN:
258 case ENOLCK:
259 if(pollmsecs > 0 && ++u.tries < FILE_LOCK_TRIES){
260 if(!didmsg)
261 _DOMSG();
262 n_err(".");
263 didmsg = TRUM1;
264 n_msleep(pollmsecs, FAL0);
265 continue;
267 /* FALLTHRU */
268 default:
269 goto jleave;
271 flocked = TRU1;
273 #ifndef HAVE_DOTLOCK
274 jleave:
275 if(didmsg == TRUM1)
276 n_err("\n");
277 if(flocked)
278 rv = (FILE*)-1;
279 else
280 errno = serrno;
281 NYD_LEAVE;
282 return rv;
284 #else
285 /* Create control-pipe for our dot file locker process, which will remove
286 * the lock and terminate once the pipe is closed, for whatever reason */
287 if(pipe_cloexec(cpipe) == -1){
288 serrno = errno;
289 emsg = N_(" Can't create dotlock file control pipe\n");
290 goto jemsg;
293 /* And the locker process itself; it'll be a (rather cheap) thread only
294 * unless the lock has to be placed in the system spool and we have our
295 * privilege-separated dotlock program available, in which case that will be
296 * executed and do "it" with changed group-id */
297 di.di_file_name = fname;
298 di.di_pollmsecs = pollmsecs;
299 /* Initialize some more stuff; query the two strings in the parent in order
300 * to cache the result of the former and anyway minimalize child page-ins.
301 * Especially uname(3) may hang for multiple seconds when it is called the
302 * first time! */
303 di.di_hostname = nodename(FAL0);
304 di.di_randstr = getrandstring(16);
305 a_dotlock_flt = flt;
306 a_dotlock_fd = fd;
307 a_dotlock_dip = &di;
309 u.ptf = &a_dotlock_main;
310 rv = Popen((char*)-1, "W", u.sh, NULL, cpipe[1]);
311 serrno = errno;
313 close(cpipe[1]);
314 if(rv == NULL){
315 close(cpipe[0]);
316 emsg = N_(" Can't create file lock process\n");
317 goto jemsg;
320 /* Let's check whether we were able to create the dotlock file */
321 for(;;){
322 u.r = read(cpipe[0], &dls, sizeof dls);
323 if(UICMP(z, u.r, !=, sizeof dls)){
324 serrno = (u.r != -1) ? EAGAIN : errno;
325 dls = n_DLS_DUNNO | n_DLS_ABANDON;
326 }else
327 serrno = 0;
329 if(dls == n_DLS_NONE || (dls & n_DLS_ABANDON))
330 close(cpipe[0]);
332 switch(dls & ~n_DLS_ABANDON){
333 case n_DLS_NONE:
334 goto jleave;
335 case n_DLS_CANT_CHDIR:
336 if(options & OPT_D_V)
337 emsg = N_(" Can't change directory! Please check permissions\n");
338 serrno = EACCES;
339 break;
340 case n_DLS_NAMETOOLONG:
341 emsg = N_("Resulting dotlock filename would be too long\n");
342 serrno = EACCES;
343 break;
344 case n_DLS_ROFS:
345 assert(dls & n_DLS_ABANDON);
346 if(options & OPT_D_V)
347 emsg = N_(" Read-only filesystem, not creating lock file\n");
348 serrno = EROFS;
349 break;
350 case n_DLS_NOPERM:
351 if(options & OPT_D_V)
352 emsg = N_(" Can't create a dotlock file, "
353 "please check permissions\n"
354 " (Or ignore by setting *dotlock-ignore-error* variable)\n");
355 serrno = EACCES;
356 break;
357 case n_DLS_NOEXEC:
358 if(options & OPT_D_V)
359 emsg = N_(" Can't find privilege-separated dotlock program\n");
360 serrno = ENOENT;
361 break;
362 case n_DLS_PRIVFAILED:
363 emsg = N_(" Privilege-separated dotlock program can't change "
364 "privileges\n");
365 serrno = EPERM;
366 break;
367 case n_DLS_EXIST:
368 emsg = N_(" It seems there is a stale dotlock file?\n"
369 " Please remove the lock file manually, then retry\n");
370 serrno = EEXIST;
371 break;
372 case n_DLS_FISHY:
373 emsg = N_(" Fishy! Is someone trying to \"steal\" foreign files?\n"
374 " Please check the mailbox file etc. manually, then retry\n");
375 serrno = EAGAIN; /* ? Hack to ignore *dotlock-ignore-error* xxx */
376 break;
377 default:
378 case n_DLS_DUNNO:
379 emsg = N_(" Unspecified dotlock file control process error.\n"
380 " Like broken I/O pipe; this one is unlikely to happen\n");
381 if(serrno != EAGAIN)
382 serrno = EINVAL;
383 break;
384 case n_DLS_PING:
385 if(!didmsg)
386 _DOMSG();
387 n_err(".");
388 didmsg = TRUM1;
389 continue;
392 if(emsg != NULL){
393 if(!didmsg){
394 _DOMSG();
395 didmsg = TRUM1;
397 if(didmsg == TRUM1)
398 n_err(_(". failed\n"));
399 didmsg = TRU1;
400 n_err(V_(emsg));
401 emsg = NULL;
404 if(dls & n_DLS_ABANDON){
405 Pclose(rv, FAL0);
406 rv = NULL;
407 break;
411 jleave:
412 if(didmsg == TRUM1)
413 n_err(". %s\n", (rv != NULL ? _("ok") : _("failed")));
414 if(rv == NULL) {
415 if(flocked){
416 if(serrno == EROFS)
417 rv = (FILE*)-1;
418 else if(serrno != EAGAIN && serrno != EEXIST &&
419 ok_blook(dotlock_ignore_error)){
420 if(options & OPT_D_V)
421 n_err(_(" *dotlock-ignore-error* set: continuing\n"));
422 rv = (FILE*)-1;
423 }else
424 goto jserrno;
425 }else
426 jserrno:
427 errno = serrno;
429 NYD_LEAVE;
430 return rv;
431 jemsg:
432 if(!didmsg)
433 _DOMSG();
434 n_err("\n");
435 didmsg = TRU1;
436 n_err(V_(emsg));
437 goto jleave;
438 #endif /* HAVE_DOTLOCK */
439 #undef _DOMSG
442 /* s-it-mode */