1 /*
2  * Copyright (c) 2006-2023, RT-Thread Development Team
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  *
6  * Change Logs:
7  * Date             Author          Notes
8  * 2023-07-20       zmq810150896    first version
9  * 2024-04-30       TroyMitchell    Add comments for all functions
10  */
11 
12 #include <dfs_file.h>
13 #include <unistd.h>
14 #include "mqueue.h"
15 
16 /**
17  * @brief   Sets the attributes of a message queue.
18  * @param   id Identifier of the message queue.
19  * @param   mqstat Pointer to a struct mq_attr containing the new attributes (ignored).
20  * @param   omqstat Pointer to a struct mq_attr where the old attributes will be stored.
21  * @return  Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
22  *
23  * @note    This function sets the attributes of the message queue specified by id.
24  *          The new attributes are provided in the mqstat parameter, but this implementation ignores it.
25  *          Instead, the function calls mq_getattr() to retrieve the current attributes of the message queue
26  *          and stores them in the struct mq_attr pointed to by omqstat.
27  *          If mqstat is RT_NULL, the function behaves as a query and retrieves the attributes without setting new values.
28  *          If an error occurs during the operation, errno is set to indicate the error, and the function returns -1.
29  */
mq_setattr(mqd_t id,const struct mq_attr * mqstat,struct mq_attr * omqstat)30 int mq_setattr(mqd_t                 id,
31                const struct mq_attr *mqstat,
32                struct mq_attr       *omqstat)
33 {
34     if (mqstat == RT_NULL)
35         return mq_getattr(id, omqstat);
36     else
37         rt_set_errno(-RT_ERROR);
38 
39     return -1;
40 }
41 RTM_EXPORT(mq_setattr);
42 
43 /**
44  * @brief   Gets the attributes of a message queue.
45  * @param   id Identifier of the message queue.
46  * @param   mqstat Pointer to a struct mq_attr where the attributes will be stored.
47  * @return  Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
48  *
49  * @note    This function retrieves the attributes of the message queue specified by id.
50  *          The attributes include the maximum number of messages that can be queued (mq_maxmsg),
51  *          the maximum size of each message (mq_msgsize), the number of messages currently in the queue (mq_curmsgs),
52  *          and the flags associated with the queue (mq_flags).
53  *          The attributes are stored in the struct mq_attr pointed to by mqstat.
54  *          If the message queue identified by id does not exist or if mqstat is a null pointer, errno is set to EBADF,
55  *          indicating a bad file descriptor, and the function returns -1.
56  *          Otherwise, the function retrieves the attributes from the message queue and stores them in mqstat, returning 0 to indicate success.
57  */
mq_getattr(mqd_t id,struct mq_attr * mqstat)58 int mq_getattr(mqd_t id, struct mq_attr *mqstat)
59 {
60     rt_mq_t mq;
61     struct mqueue_file *mq_file;
62     mq_file = fd_get(id)->vnode->data;
63     mq = (rt_mq_t)mq_file->data;
64     if ((mq == RT_NULL) || mqstat == RT_NULL)
65     {
66         rt_set_errno(EBADF);
67         return -1;
68     }
69 
70     mqstat->mq_maxmsg = mq->max_msgs;
71     mqstat->mq_msgsize = mq->msg_size;
72     mqstat->mq_curmsgs = 0;
73     mqstat->mq_flags = 0;
74 
75     return 0;
76 }
77 RTM_EXPORT(mq_getattr);
78 
79 /**
80  * @brief   Opens or creates a message queue.
81  * @param   name Name of the message queue.
82  * @param   oflag Flags indicating the access mode and creation options (O_CREAT, O_EXCL, etc.).
83  * @param   ... Additional arguments for creation options (mode, attr) (ignored).
84  * @return  Upon successful completion, returns a message queue descriptor (mqd_t);
85  *          otherwise, returns (mqd_t)(-1) and sets errno to indicate the error.
86  *
87  * @note    This function opens or creates a message queue specified by name with the specified flags.
88  *          If the name starts with '/', the leading '/' is ignored.
89  *          The function then checks the length of the name and verifies if it exceeds the maximum allowed length.
90  *          If the name is too long, errno is set to ENAMETOOLONG, indicating a name too long error.
91  *          Next, the function attempts to find the message queue file corresponding to the name.
92  *          If the file exists and O_CREAT and O_EXCL flags are both set, indicating exclusive creation,
93  *          errno is set to EEXIST, indicating that the file already exists.
94  *          If the file does not exist and O_CREAT flag is set, the function checks the message queue attributes.
95  *          If the maximum number of messages (mq_maxmsg) in the attributes is less than or equal to 0,
96  *          errno is set to EINVAL, indicating an invalid argument for the maximum number of messages.
97  *          If the file does not exist and O_CREAT flag is not set, errno is set to ENOENT, indicating no such file or directory.
98  *          If the message queue needs to be created (O_CREAT flag set), a new mqueue_file structure is allocated and initialized
99  *          with the specified message queue attributes, and it is inserted into the message queue filesystem.
100  *          Finally, the function constructs the path to the message queue device file, opens it with the specified flags,
101  *          and returns the file descriptor as a message queue descriptor (mqd_t).
102  */
mq_open(const char * name,int oflag,...)103 mqd_t mq_open(const char *name, int oflag, ...)
104 {
105     int mq_fd;
106     va_list arg;
107     mode_t mode;
108     struct mq_attr *attr = RT_NULL;
109     va_start(arg, oflag);
110     mode = (mode_t)va_arg(arg, unsigned int);
111     mode = (mode_t)mode; /* self-assignment avoids compiler optimization */
112     attr = (struct mq_attr *)va_arg(arg, struct mq_attr *);
113     attr = (struct mq_attr *)attr; /* self-assignment avoids compiler optimization */
114     va_end(arg);
115     if(*name == '/')
116     {
117         name++;
118     }
119 
120     int len = rt_strlen(name);
121     if (len > RT_NAME_MAX)
122     {
123         rt_set_errno(ENAMETOOLONG);
124         return (mqd_t)(-1);
125     }
126     rt_size_t size;
127     struct mqueue_file *mq_file;
128     mq_file = dfs_mqueue_lookup(name, &size);
129     if(mq_file != RT_NULL)
130     {
131         if (oflag & O_CREAT && oflag & O_EXCL)
132         {
133             rt_set_errno(EEXIST);
134             return (mqd_t)(-1);
135         }
136     }
137     else if (oflag & O_CREAT)
138     {
139         if (attr->mq_maxmsg <= 0)
140         {
141             rt_set_errno(EINVAL);
142             return (mqd_t)(-1);
143         }
144         struct mqueue_file *mq_file;
145         mq_file = (struct mqueue_file *) rt_malloc (sizeof(struct mqueue_file));
146 
147         if (mq_file == RT_NULL)
148         {
149             rt_set_errno(ENFILE);
150             return (mqd_t)(-1);
151         }
152         mq_file->msg_size = attr->mq_msgsize;
153         mq_file->max_msgs = attr->mq_maxmsg;
154         mq_file->data = RT_NULL;
155         strncpy(mq_file->name, name, RT_NAME_MAX);
156         dfs_mqueue_insert_after(&(mq_file->list));
157     }
158     else
159     {
160         rt_set_errno(ENOENT);
161         return (mqd_t)(-1);
162     }
163 
164     const char* mq_path = "/dev/mqueue/";
165     char mq_name[RT_NAME_MAX + 12] = {0};
166     rt_sprintf(mq_name, "%s%s", mq_path, name);
167     mq_fd = open(mq_name, oflag);
168 
169     return (mqd_t)(mq_fd);
170 }
171 RTM_EXPORT(mq_open);
172 
173 /**
174  * @brief   Receives a message from a message queue.
175  * @param   id Message queue descriptor.
176  * @param   msg_ptr Pointer to the buffer where the received message will be stored.
177  * @param   msg_len Maximum size of the message buffer.
178  * @param   msg_prio Pointer to an unsigned integer where the priority of the received message will be stored (ignored).
179  * @return  Upon successful completion, returns the number of bytes received;
180  *          otherwise, returns -1 and sets errno to indicate the error.
181  *
182  * @note    This function receives a message from the message queue identified by id.
183  *          The received message is stored in the buffer pointed to by msg_ptr, with a maximum size of msg_len bytes.
184  *          The priority of the received message is stored in the unsigned integer pointed to by msg_prio (ignored in this implementation).
185  *          If either the message queue identified by id or the msg_ptr buffer is a null pointer, errno is set to EINVAL,
186  *          indicating an invalid argument, and the function returns -1.
187  *          The function then attempts to receive a message from the message queue using the rt_mq_recv_prio() function
188  *          with an infinite timeout and uninterruptible mode.
189  *          If a message is successfully received, the function returns the number of bytes received.
190  *          If an error occurs during the receive operation, errno is set to EBADF, indicating a bad file descriptor,
191  *          and the function returns -1.
192  */
mq_receive(mqd_t id,char * msg_ptr,size_t msg_len,unsigned * msg_prio)193 ssize_t mq_receive(mqd_t id, char *msg_ptr, size_t msg_len, unsigned *msg_prio)
194 {
195     rt_mq_t mq;
196     rt_err_t result;
197     struct mqueue_file *mq_file;
198     mq_file = fd_get(id)->vnode->data;
199     mq = (rt_mq_t)mq_file->data;
200     if ((mq == RT_NULL) || (msg_ptr == RT_NULL))
201     {
202         rt_set_errno(EINVAL);
203         return -1;
204     }
205 
206     result = rt_mq_recv_prio(mq, msg_ptr, msg_len, (rt_int32_t *)msg_prio, RT_WAITING_FOREVER, RT_UNINTERRUPTIBLE);
207     if (result >= 0)
208         return result;
209 
210     rt_set_errno(EBADF);
211     return -1;
212 }
213 RTM_EXPORT(mq_receive);
214 
215 /**
216  * @brief   Sends a message to a message queue.
217  * @param   id Message queue descriptor.
218  * @param   msg_ptr Pointer to the buffer containing the message to be sent.
219  * @param   msg_len Size of the message to be sent.
220  * @param   msg_prio Priority of the message to be sent.
221  * @return  Upon successful completion, returns 0;
222  *          otherwise, returns -1 and sets errno to indicate the error.
223  *
224  * @note    This function sends a message to the message queue identified by id.
225  *          The message to be sent is contained in the buffer pointed to by msg_ptr, with a size of msg_len bytes.
226  *          The priority of the message is specified by the msg_prio parameter.
227  *          If either the message queue identified by id or the msg_ptr buffer is a null pointer, errno is set to EINVAL,
228  *          indicating an invalid argument, and the function returns -1.
229  *          The function then attempts to send the message to the message queue using the rt_mq_send_wait_prio() function
230  *          with zero timeout and uninterruptible mode.
231  *          If the message is successfully sent, the function returns 0.
232  *          If an error occurs during the send operation, errno is set to EBADF, indicating a bad file descriptor,
233  *          and the function returns -1.
234  */
mq_send(mqd_t id,const char * msg_ptr,size_t msg_len,unsigned msg_prio)235 int mq_send(mqd_t id, const char *msg_ptr, size_t msg_len, unsigned msg_prio)
236 {
237     rt_mq_t mq;
238     rt_err_t result;
239     struct mqueue_file *mq_file;
240     mq_file = fd_get(id)->vnode->data;
241     mq = (rt_mq_t)mq_file->data;
242 
243     if ((mq == RT_NULL) || (msg_ptr == RT_NULL))
244     {
245         rt_set_errno(EINVAL);
246         return -1;
247     }
248     result = rt_mq_send_wait_prio(mq, (void *)msg_ptr, msg_len, msg_prio, 0, RT_UNINTERRUPTIBLE);
249     if (result == RT_EOK)
250         return 0;
251 
252     rt_set_errno(EBADF);
253 
254     return -1;
255 }
256 RTM_EXPORT(mq_send);
257 
258 /**
259  * @brief   Receives a message from a message queue with a timeout.
260  * @param   id Message queue descriptor.
261  * @param   msg_ptr Pointer to the buffer where the received message will be stored.
262  * @param   msg_len Maximum size of the message buffer.
263  * @param   msg_prio Pointer to an unsigned integer where the priority of the received message will be stored.
264  * @param   abs_timeout Pointer to a struct timespec specifying the absolute timeout value (ignored if null).
265  * @return  Upon successful completion, returns the number of bytes received;
266  *          otherwise, returns -1 and sets errno to indicate the error.
267  *
268  * @note    This function receives a message from the message queue identified by id with a specified timeout.
269  *          The received message is stored in the buffer pointed to by msg_ptr, with a maximum size of msg_len bytes.
270  *          The priority of the received message is stored in the unsigned integer pointed to by msg_prio.
271  *          If either the message queue identified by id or the msg_ptr buffer is a null pointer, errno is set to EINVAL,
272  *          indicating an invalid argument, and the function returns -1.
273  *          The function then converts the absolute timeout value specified by abs_timeout to system ticks,
274  *          or sets the timeout to RT_WAITING_FOREVER if abs_timeout is null.
275  *          It attempts to receive a message from the message queue using the rt_mq_recv_prio() function
276  *          with the specified timeout and uninterruptible mode.
277  *          If a message is successfully received, the function returns the number of bytes received.
278  *          If the receive operation times out, errno is set to ETIMEDOUT, indicating a timeout error.
279  *          If the received message is too large for the specified buffer, errno is set to EMSGSIZE, indicating a message too large error.
280  *          If an unknown error occurs during the receive operation, errno is set to EBADMSG, indicating a bad message error,
281  *          and the function returns -1.
282  */
mq_timedreceive(mqd_t id,char * msg_ptr,size_t msg_len,unsigned * msg_prio,const struct timespec * abs_timeout)283 ssize_t mq_timedreceive(mqd_t                  id,
284                         char                  *msg_ptr,
285                         size_t                 msg_len,
286                         unsigned              *msg_prio,
287                         const struct timespec *abs_timeout)
288 {
289     rt_mq_t mq;
290     rt_err_t result;
291     int tick = 0;
292     struct mqueue_file *mq_file;
293     mq_file = fd_get(id)->vnode->data;
294     mq = (rt_mq_t)mq_file->data;
295     /* parameters check */
296     if ((mq == RT_NULL) || (msg_ptr == RT_NULL))
297     {
298         rt_set_errno(EINVAL);
299         return -1;
300     }
301     if (abs_timeout != RT_NULL)
302         tick = rt_timespec_to_tick(abs_timeout);
303     else
304         tick = RT_WAITING_FOREVER;
305 
306     result = rt_mq_recv_prio(mq, msg_ptr, msg_len, (rt_int32_t *)msg_prio, tick, RT_UNINTERRUPTIBLE);
307 
308     if (result >= 0)
309         return result;
310 
311     if (result == -RT_ETIMEOUT)
312         rt_set_errno(ETIMEDOUT);
313     else if (result == -RT_ERROR)
314         rt_set_errno(EMSGSIZE);
315     else
316         rt_set_errno(EBADMSG);
317 
318     return -1;
319 }
320 RTM_EXPORT(mq_timedreceive);
321 
322 /**
323  * @brief   Sends a message to a message queue with a timeout (not supported).
324  * @param   id Message queue descriptor.
325  * @param   msg_ptr Pointer to the buffer containing the message to be sent.
326  * @param   msg_len Size of the message to be sent.
327  * @param   msg_prio Priority of the message to be sent.
328  * @param   abs_timeout Pointer to a struct timespec specifying the absolute timeout value (ignored).
329  * @return  Upon successful completion, returns 0;
330  *          otherwise, returns -1 and sets errno to indicate the error.
331  *
332  * @note    This function attempts to send a message to the message queue identified by id with a specified timeout,
333  *          but timed send is not supported in the RT-Thread environment.
334  *          Therefore, the function simply delegates the message sending operation to the mq_send() function,
335  *          which does not involve a timeout.
336  *          The abs_timeout parameter is ignored, and the message is sent without waiting for a timeout to occur.
337  *          The function returns the result of the mq_send() function, which indicates whether the message was successfully sent.
338  */
mq_timedsend(mqd_t id,const char * msg_ptr,size_t msg_len,unsigned msg_prio,const struct timespec * abs_timeout)339 int mq_timedsend(mqd_t                  id,
340                  const char            *msg_ptr,
341                  size_t                 msg_len,
342                  unsigned               msg_prio,
343                  const struct timespec *abs_timeout)
344 {
345     /* RT-Thread does not support timed send */
346     return mq_send(id, msg_ptr, msg_len, msg_prio);
347 }
348 RTM_EXPORT(mq_timedsend);
349 
350 /**
351  * @brief   Registers for notification when a message is available in a message queue (not supported).
352  * @param   id Message queue descriptor.
353  * @param   notification Pointer to a struct sigevent specifying the notification settings (ignored).
354  * @return  Upon successful completion, returns 0;
355  *          otherwise, returns -1 and sets errno to indicate the error.
356  *
357  * @note    This function attempts to register for notification when a message is available in the message queue identified by id.
358  *          However, message queue notification is not supported in the RT-Thread environment.
359  *          Therefore, this function simply sets errno to EBADF, indicating a bad file descriptor,
360  *          and returns -1 to indicate that the operation is not supported.
361  */
mq_notify(mqd_t id,const struct sigevent * notification)362 int mq_notify(mqd_t id, const struct sigevent *notification)
363 {
364     rt_mq_t mq;
365     struct mqueue_file *mq_file;
366     mq_file = fd_get(id)->vnode->data;
367     mq = (rt_mq_t)mq_file->data;
368     if (mq == RT_NULL)
369     {
370         rt_set_errno(EBADF);
371         return -1;
372     }
373     rt_set_errno(-RT_ERROR);
374 
375     return -1;
376 }
377 RTM_EXPORT(mq_notify);
378 
379 /**
380  * @brief   Closes a message queue descriptor.
381  * @param   id Message queue descriptor to be closed.
382  * @return  Upon successful completion, returns 0;
383  *          otherwise, returns -1 and sets errno to indicate the error.
384  *
385  * @note    This function closes the message queue descriptor specified by id.
386  *          It delegates the closing operation to the close() function, which closes the file descriptor associated with the message queue.
387  *          If the close operation is successful, the function returns 0.
388  *          If an error occurs during the close operation, errno is set to indicate the error, and the function returns -1.
389  */
mq_close(mqd_t id)390 int mq_close(mqd_t id)
391 {
392     return close(id);
393 }
394 RTM_EXPORT(mq_close);
395 
396 /**
397  * @brief    This function will remove a message queue (REALTIME).
398  *
399  * @note    The mq_unlink() function shall remove the message queue named by the string name.
400  *          If one or more processes have the message queue open when mq_unlink() is called,
401  *          destruction of the message queue shall be postponed until all references to the message queue have been closed.
402  *          However, the mq_unlink() call need not block until all references have been closed; it may return immediately.
403  *
404  *          After a successful call to mq_unlink(), reuse of the name shall subsequently cause mq_open() to behave as if
405  *          no message queue of this name exists (that is, mq_open() will fail if O_CREAT is not set,
406  *          or will create a new message queue if O_CREAT is set).
407  *
408  * @param    name  is the name of the message queue.
409  *
410  * @return   Upon successful completion, the function shall return a value of zero.
411  *           Otherwise, the named message queue shall be unchanged by this function call,
412  *           and the function shall return a value of -1 and set errno to indicate the error.
413  *
414  * @warning  This function can ONLY be called in the thread context, you can use RT_DEBUG_IN_THREAD_CONTEXT to
415  *           check the context.
416  *           The mq_unlink() function shall fail if:
417  *              [EACCES]
418  *              Permission is denied to unlink the named message queue.
419  *              [EINTR]
420  *              The call to mq_unlink() blocked waiting for all references to the named message queue to be closed and a signal interrupted the call.
421  *              [ENOENT]
422  *              The named message queue does not exist.
423  *           The mq_unlink() function may fail if:
424  *              [ENAMETOOLONG]
425  *              The length of the name argument exceeds {_POSIX_PATH_MAX} on systems that do not support the XSI option
426  *              or exceeds {_XOPEN_PATH_MAX} on XSI systems,or has a pathname component that is longer than {_POSIX_NAME_MAX} on systems that do
427  *              not support the XSI option or longer than {_XOPEN_NAME_MAX} on XSI systems.A call to mq_unlink() with a name argument that contains
428  *              the same message queue name as was previously used in a successful mq_open() call shall not give an [ENAMETOOLONG] error.
429  */
mq_unlink(const char * name)430 int mq_unlink(const char *name)
431 {
432     if(*name == '/')
433     {
434         name++;
435     }
436     const char *mq_path = "/dev/mqueue/";
437     char mq_name[RT_NAME_MAX + 12] = {0};
438     rt_sprintf(mq_name, "%s%s", mq_path, name);
439     return unlink(mq_name);
440 }
441 RTM_EXPORT(mq_unlink);
442