1 /* Copyright 2020-2021 IGEL Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
16 #include "dlmclient.h"
18 #include "socket-path.h"
26 #include <sys/socket.h>
30 void dlm_enable_debug_log(bool enable)
32 dlm_log_enable_debug(enable);
40 static bool lease_connect(struct dlm_lease *lease, const char *name)
42 struct sockaddr_un sa = {
43 .sun_family = AF_UNIX,
46 if (!sockaddr_set_lease_server_path(&sa, name))
49 int dlm_server_sock = socket(AF_UNIX, SOCK_STREAM, 0);
50 if (dlm_server_sock < 0) {
51 DEBUG_LOG("Socket creation failed: %s\n", strerror(errno));
55 while (connect(dlm_server_sock, (struct sockaddr *)&sa,
56 sizeof(struct sockaddr_un)) == -1) {
59 DEBUG_LOG("Cannot connect to %s: %s\n", sa.sun_path,
61 close(dlm_server_sock);
64 lease->dlm_server_sock = dlm_server_sock;
68 static bool lease_recv_fd(struct dlm_lease *lease)
70 char ctrl_buf[CMSG_SPACE(sizeof(int))] = {0};
74 iov[0].iov_base = data;
75 iov[0].iov_len = sizeof(data);
78 .msg_control = ctrl_buf,
79 .msg_controllen = CMSG_SPACE(sizeof(int)),
85 while ((ret = recvmsg(lease->dlm_server_sock, &msg, 0)) <= 0) {
88 DEBUG_LOG("Request rejected by DRM lease manager\n");
89 // TODO: Report why the request was rejected.
93 DEBUG_LOG("Socket data receive error: %s\n",
100 struct cmsghdr *cmsg;
101 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL;
102 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
103 if (cmsg->cmsg_level == SOL_SOCKET &&
104 cmsg->cmsg_type == SCM_RIGHTS) {
105 int nfds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
106 int *fds = (int *)CMSG_DATA(cmsg);
109 lease->lease_fd = fds[0];
114 "Expected 1 fd from lease manager. Received %d\n",
116 /* Close any unexpected fds so we don't leak them. */
117 for (int i = 0; i < nfds; i++)
123 if (lease->lease_fd < 0) {
124 DEBUG_LOG("Expected data not received from lease manager\n");
132 struct dlm_lease *dlm_get_lease(const char *name)
134 struct dlm_lease *lease = calloc(1, sizeof(struct dlm_lease));
136 DEBUG_LOG("can't allocate memory : %s\n", strerror(errno));
140 if (!lease_connect(lease, name)) {
145 if (!lease_recv_fd(lease)) {
146 close(lease->dlm_server_sock);
154 void dlm_release_lease(struct dlm_lease *lease)
159 close(lease->lease_fd);
160 close(lease->dlm_server_sock);
164 int dlm_lease_fd(struct dlm_lease *lease)
169 return lease->lease_fd;