Welcome to mirror list, hosted at ThFree Co, Russian Federation.

fhandler_mqueue.cc « cygwin « winsup - cygwin.com/git/newlib-cygwin.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c450c033785e6bb2aded8ec687df60500d20a1ae (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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/* fhandler_mqueue.cc: fhandler for POSIX message queue

This file is part of Cygwin.

This software is a copyrighted work licensed under the terms of the
Cygwin license.  Please consult the file "CYGWIN_LICENSE" for
details. */

#include "winsup.h"
#include "shared_info.h"
#include "path.h"
#include "fhandler.h"
#include "dtable.h"
#include <mqueue.h>
#include <sys/param.h>

#define MSGSIZE(i)      roundup((i), sizeof(long))

struct mq_attr defattr = { 0, 10, 8192, 0 };	/* Linux defaults. */

fhandler_mqueue::fhandler_mqueue () :
  fhandler_disk_file ()
{
  close_on_exec (true);
}

int
fhandler_mqueue::open (int flags, mode_t mode)
{
  /* FIXME: reopen by handle semantics missing yet */
  flags &= ~(O_NOCTTY | O_PATH | O_BINARY | O_TEXT);
  return mq_open (flags, mode, NULL);
}

int
fhandler_mqueue::mq_open (int oflags, mode_t mode, struct mq_attr *attr)
{
  NTSTATUS status;
  IO_STATUS_BLOCK io;
  PUNICODE_STRING mqstream;
  OBJECT_ATTRIBUTES oa;
  struct mq_info *mqinfo = NULL;
  bool created = false;

  if ((oflags & ~(O_ACCMODE | O_CLOEXEC | O_CREAT | O_EXCL | O_NONBLOCK))
      || (oflags & O_ACCMODE) == O_ACCMODE)
    {
      set_errno (EINVAL);
      return 0;
    }

  /* attach a stream suffix to the NT filename, thus creating a stream. */
  mqstream = pc.get_nt_native_path (&ro_u_mq_suffix);
  pc.get_object_attr (oa, sec_none_nih);

again:
  if (oflags & O_CREAT)
    {
      /* Create and disallow sharing */
      status = NtCreateFile (&get_handle (),
			     GENERIC_READ | GENERIC_WRITE | DELETE
			     | SYNCHRONIZE, &oa, &io, NULL,
			     FILE_ATTRIBUTE_NORMAL, FILE_SHARE_DELETE,
			     FILE_CREATE,
			     FILE_OPEN_FOR_BACKUP_INTENT
			     | FILE_SYNCHRONOUS_IO_NONALERT,
			     NULL, 0);
      if (!NT_SUCCESS (status))
	{
	  if (status == STATUS_OBJECT_NAME_COLLISION && (oflags & O_EXCL) == 0)
	    goto exists;
	  __seterrno_from_nt_status (status);
	  return 0;
	}
      if (pc.has_acls ())
	set_created_file_access (get_handle (), pc, mode);
      created = true;
      goto out;
    }
exists:
  /* Open the file, and loop while detecting a sharing violation. */
  while (true)
    {
      status = NtOpenFile (&get_handle (),
			   GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE,
			   &oa, &io, FILE_SHARE_VALID_FLAGS,
			   FILE_OPEN_FOR_BACKUP_INTENT
			   | FILE_SYNCHRONOUS_IO_NONALERT);
      if (NT_SUCCESS (status))
	break;
      if (status == STATUS_OBJECT_NAME_NOT_FOUND && (oflags & O_CREAT))
	goto again;
      if (status != STATUS_SHARING_VIOLATION)
	{
	  __seterrno_from_nt_status (status);
	  return -1;
	}
      Sleep (100L);
    }
out:
  /* We need the filename without STREAM_SUFFIX later on */
  mqstream->Length -= ro_u_mq_suffix.Length;
  mqstream->Buffer[mqstream->Length / sizeof (WCHAR)] = L'\0';

  if (created)
    {
      if (attr == NULL)
	attr = &defattr;
      /* Check minimum and maximum values.  The max values are pretty much
	 arbitrary, taken from the linux mq_overview man page, up to Linux
	 3.4.  These max values make sure that the internal mq_fattr
	 structure can use 32 bit types. */
      if (attr->mq_maxmsg <= 0 || attr->mq_maxmsg > 32768
	       || attr->mq_msgsize <= 0 || attr->mq_msgsize > 1048576)
	set_errno (EINVAL);
      else
	mqinfo = mqinfo_create (attr, mode, oflags & O_NONBLOCK);
    }
  else
    mqinfo = mqinfo_open (oflags & O_NONBLOCK);
  mq_open_finish (mqinfo != NULL, created);
  return mqinfo ? 1 : 0;
}

struct mq_info *
fhandler_mqueue::_mqinfo (SIZE_T filesize, mode_t mode, int flags,
			  bool just_open)
{
  WCHAR buf[NAME_MAX + sizeof ("mqueue/XXX")];
  UNICODE_STRING uname;
  OBJECT_ATTRIBUTES oa;
  NTSTATUS status;
  LARGE_INTEGER fsiz = { QuadPart: (LONGLONG) filesize };
  PVOID mptr = NULL;

  /* Set sectsize prior to using filesize in NtMapViewOfSection.  It will
     get pagesize aligned, which breaks the next NtMapViewOfSection in fork. */
  mqinfo ()->mqi_sectsize = filesize;
  mqinfo ()->mqi_mode = mode;
  mqinfo ()->mqi_flags = flags;

  __small_swprintf (buf, L"mqueue/mtx%s", get_name ());
  RtlInitUnicodeString (&uname, buf);
  InitializeObjectAttributes (&oa, &uname, OBJ_OPENIF | OBJ_CASE_INSENSITIVE,
                              get_shared_parent_dir (),
                              everyone_sd (CYG_MUTANT_ACCESS));
  status = NtCreateMutant (&mqinfo ()->mqi_lock, CYG_MUTANT_ACCESS, &oa,
			   FALSE);
  if (!NT_SUCCESS (status))
    goto err;

  wcsncpy (buf + 7, L"snd", 3);
  /* same length, no RtlInitUnicodeString required */
  InitializeObjectAttributes (&oa, &uname, OBJ_OPENIF | OBJ_CASE_INSENSITIVE,
                              get_shared_parent_dir (),
                              everyone_sd (CYG_EVENT_ACCESS));
  status = NtCreateEvent (&mqinfo ()->mqi_waitsend, CYG_EVENT_ACCESS, &oa,
			  NotificationEvent, FALSE);
  if (!NT_SUCCESS (status))
    goto err;
  wcsncpy (buf + 7, L"rcv", 3);
  /* same length, same attributes, no more init required */
  status = NtCreateEvent (&mqinfo ()->mqi_waitrecv, CYG_EVENT_ACCESS, &oa,
			  NotificationEvent, FALSE);
  if (!NT_SUCCESS (status))
    goto err;

  InitializeObjectAttributes (&oa, NULL, 0, NULL, NULL);
  status = NtCreateSection (&mqinfo ()->mqi_sect, SECTION_ALL_ACCESS, &oa,
			    &fsiz, PAGE_READWRITE, SEC_COMMIT, get_handle ());
  if (!NT_SUCCESS (status))
    goto err;

  status = NtMapViewOfSection (mqinfo ()->mqi_sect, NtCurrentProcess (),
			       &mptr, 0, filesize, NULL, &filesize,
			       ViewShare, MEM_TOP_DOWN, PAGE_READWRITE);
  if (!NT_SUCCESS (status))
    goto err;

  mqinfo ()->mqi_hdr = (struct mq_hdr *) mptr;

  /* Special problem on Cygwin.  /dev/mqueue is just a simple dir,
     so there's a chance normal files are created in there. */
  if (just_open && mqinfo ()->mqi_hdr->mqh_magic != MQI_MAGIC)
    {
      status = STATUS_ACCESS_DENIED;
      goto err;
    }

  mqinfo ()->mqi_magic = MQI_MAGIC;
  return mqinfo ();

err:
  if (mqinfo ()->mqi_sect)
    NtClose (mqinfo ()->mqi_sect);
  if (mqinfo ()->mqi_waitrecv)
    NtClose (mqinfo ()->mqi_waitrecv);
  if (mqinfo ()->mqi_waitsend)
    NtClose (mqinfo ()->mqi_waitsend);
  if (mqinfo ()->mqi_lock)
    NtClose (mqinfo ()->mqi_lock);
  __seterrno_from_nt_status (status);
  return NULL;
}

struct mq_info *
fhandler_mqueue::mqinfo_open (int flags)
{
  FILE_STANDARD_INFORMATION fsi;
  IO_STATUS_BLOCK io;
  NTSTATUS status;
  mode_t mode;

  fsi.EndOfFile.QuadPart = 0;
  status = NtQueryInformationFile (get_handle (), &io, &fsi, sizeof fsi,
				   FileStandardInformation);
  if (!NT_SUCCESS (status))
    {
      __seterrno_from_nt_status (status);
      return NULL;
    }
  if (get_file_attribute (get_handle (), pc, &mode, NULL, NULL))
    mode = STD_RBITS | STD_WBITS;

  return _mqinfo (fsi.EndOfFile.QuadPart, mode, flags, true);
}

struct mq_info *
fhandler_mqueue::mqinfo_create (struct mq_attr *attr, mode_t mode, int flags)
{
  long msgsize;
  off_t filesize = 0;
  FILE_END_OF_FILE_INFORMATION feofi;
  IO_STATUS_BLOCK io;
  NTSTATUS status;
  struct mq_info *mqinfo = NULL;

  msgsize = MSGSIZE (attr->mq_msgsize);
  filesize = sizeof (struct mq_hdr)
	     + (attr->mq_maxmsg * (sizeof (struct msg_hdr) + msgsize));
  feofi.EndOfFile.QuadPart = filesize;
  status = NtSetInformationFile (get_handle (), &io, &feofi, sizeof feofi,
				 FileEndOfFileInformation);
  if (!NT_SUCCESS (status))
    {
      __seterrno_from_nt_status (status);
      return NULL;
    }

  mqinfo = _mqinfo (filesize, mode, flags, false);

  if (mqinfo)
    {
      /* Initialize header at beginning of file */
      /* Create free list with all messages on it */
      int8_t *mptr;
      struct mq_hdr *mqhdr;
      struct msg_hdr *msghdr;

      mptr = (int8_t *) mqinfo->mqi_hdr;
      mqhdr = mqinfo->mqi_hdr;
      mqhdr->mqh_attr.mq_flags = 0;
      mqhdr->mqh_attr.mq_maxmsg = attr->mq_maxmsg;
      mqhdr->mqh_attr.mq_msgsize = attr->mq_msgsize;
      mqhdr->mqh_attr.mq_curmsgs = 0;
      mqhdr->mqh_nwait = 0;
      mqhdr->mqh_pid = 0;
      mqhdr->mqh_head = 0;
      mqhdr->mqh_magic = MQI_MAGIC;
      long index = sizeof (struct mq_hdr);
      mqhdr->mqh_free = index;
      for (int i = 0; i < attr->mq_maxmsg - 1; i++)
	{
	  msghdr = (struct msg_hdr *) &mptr[index];
	  index += sizeof (struct msg_hdr) + msgsize;
	  msghdr->msg_next = index;
	}
      msghdr = (struct msg_hdr *) &mptr[index];
      msghdr->msg_next = 0;         /* end of free list */
    }

  return mqinfo;
}

void
fhandler_mqueue::mq_open_finish (bool success, bool created)
{
  NTSTATUS status;
  HANDLE def_stream;
  OBJECT_ATTRIBUTES oa;
  IO_STATUS_BLOCK io;

  if (get_handle ())
    {
      /* If we have an open queue stream handle, close it and set it to NULL */
      HANDLE queue_stream = get_handle ();
      set_handle (NULL);
      if (success)
	{
	  /* In case of success, open the default stream for reading.  This
	     can be used to implement various IO functions without exposing
	     the actual message queue. */
	  pc.get_object_attr (oa, sec_none_nih);
	  status = NtOpenFile (&def_stream, GENERIC_READ | SYNCHRONIZE,
			       &oa, &io, FILE_SHARE_VALID_FLAGS,
			       FILE_OPEN_FOR_BACKUP_INTENT
			       | FILE_SYNCHRONOUS_IO_NONALERT);
	  if (NT_SUCCESS (status))
	    set_handle (def_stream);
	  else /* Note that we don't treat this as an error! */
	    {
	      debug_printf ("Opening default stream failed: status %y", status);
	      nohandle (true);
	    }
	}
      else if (created)
	{
	  /* In case of error at creation time, delete the file */
	  FILE_DISPOSITION_INFORMATION disp = { TRUE };

	  NtSetInformationFile (queue_stream, &io, &disp, sizeof disp,
				FileDispositionInformation);
	  /* We also have to set the delete disposition on the default stream,
	     otherwise only the queue stream will get deleted */
	  pc.get_object_attr (oa, sec_none_nih);
	  status = NtOpenFile (&def_stream, DELETE, &oa, &io,
			       FILE_SHARE_VALID_FLAGS,
			       FILE_OPEN_FOR_BACKUP_INTENT);
	  if (NT_SUCCESS (status))
	    {
	      NtSetInformationFile (def_stream, &io, &disp, sizeof disp,
				    FileDispositionInformation);
	      NtClose (def_stream);
	    }
	}
      NtClose (queue_stream);
    }
}

char *
fhandler_mqueue::get_proc_fd_name (char *buf)
{
  return strcpy (buf, strrchr (get_name (), '/'));
}

int __reg2
fhandler_mqueue::fstat (struct stat *buf)
{
  int ret = fhandler_disk_file::fstat (buf);
  if (!ret)
    buf->st_dev = FH_MQUEUE;
  return ret;
}

int
fhandler_mqueue::_dup (HANDLE parent, fhandler_mqueue *fhc)
{
  __try
    {
      PVOID mptr = NULL;
      SIZE_T filesize = mqinfo ()->mqi_sectsize;
      NTSTATUS status;

      if (!DuplicateHandle (parent, mqinfo ()->mqi_sect,
			    GetCurrentProcess (), &fhc->mqinfo ()->mqi_sect,
			    0, FALSE, DUPLICATE_SAME_ACCESS))
	__leave;
      status = NtMapViewOfSection (mqinfo ()->mqi_sect, NtCurrentProcess (),
				   &mptr, 0, filesize, NULL, &filesize,
				   ViewShare, MEM_TOP_DOWN, PAGE_READWRITE);
      if (!NT_SUCCESS (status))
	api_fatal ("Mapping message queue failed in fork, status 0x%x\n",
		   status);

      fhc->mqinfo ()->mqi_hdr = (struct mq_hdr *) mptr;
      if (!DuplicateHandle (parent, mqinfo ()->mqi_waitsend,
			    GetCurrentProcess (), &fhc->mqinfo ()->mqi_waitsend,
			    0, FALSE, DUPLICATE_SAME_ACCESS))
	__leave;
      if (!DuplicateHandle (parent, mqinfo ()->mqi_waitrecv,
			    GetCurrentProcess (), &fhc->mqinfo ()->mqi_waitrecv,
			    0, FALSE, DUPLICATE_SAME_ACCESS))
	__leave;
      if (!DuplicateHandle (parent, mqinfo ()->mqi_lock,
			    GetCurrentProcess (), &fhc->mqinfo ()->mqi_lock,
			    0, FALSE, DUPLICATE_SAME_ACCESS))
	__leave;
      return 0;
    }
  __except (EFAULT) {}
  __endtry
  return -1;
}

int
fhandler_mqueue::dup (fhandler_base *child, int flags)
{
  fhandler_mqueue *fhc = (fhandler_mqueue *) child;

  int ret = fhandler_disk_file::dup (child, flags);
  if (!ret)
    ret = _dup (GetCurrentProcess (), fhc);
  return ret;
}

void
fhandler_mqueue::fixup_after_fork (HANDLE parent)
{
  if (_dup (parent, this))
    api_fatal ("Creating IPC object failed in fork, %E");
}

int
fhandler_mqueue::close ()
{
  __try
    {
      mqinfo ()->mqi_magic = 0;          /* just in case */
      NtUnmapViewOfSection (NtCurrentProcess (), mqinfo ()->mqi_hdr);
      NtClose (mqinfo ()->mqi_sect);
      NtClose (mqinfo ()->mqi_waitsend);
      NtClose (mqinfo ()->mqi_waitrecv);
      NtClose (mqinfo ()->mqi_lock);
    }
  __except (0) {}
  __endtry
  return 0;
}