41ce5743b174402b52d84f1bd79e15051e0d4663
[platform/core/security/key-manager.git] / src / manager / service / file-lock.cpp
1 /*
2  *  Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *  Licensed under the Apache License, Version 2.0 (the "License");
5  *  you may not use this file except in compliance with the License.
6  *  You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License
15  */
16 /*
17  * @file       file-lock.cpp
18  * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
19  * @version    1.0
20  */
21
22 #include "file-lock.h"
23
24 #include <fcntl.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <unistd.h>
28 #include <string.h>
29
30 #include <stdexcept>
31 #include <string>
32 #include <sstream>
33
34 #include <stringify.h>
35
36 namespace CKM {
37
38 namespace {
39
40 // TODO replace it with custom exception when they are implemented
41 template <typename... Args>
42 std::runtime_error io_exception(const Args&... args)
43 {
44     return std::runtime_error(Stringify()(args...));
45 };
46
47 } // namespace anonymous
48
49 FileLock::FileLock(const char* const file)
50 {
51     // Open lock file
52     m_lockFd = TEMP_FAILURE_RETRY(creat(file, 0644));
53     if (m_lockFd == -1) {
54         throw io_exception("Cannot open lock file. Errno: ", strerror(errno));
55     }
56
57     if (-1 == lockf(m_lockFd, F_TLOCK, 0)) {
58         if (errno == EACCES || errno == EAGAIN)
59             throw io_exception("Can't acquire lock. Another instance must be running.");
60         else
61             throw io_exception("Can't acquire lock. Errno: ", strerror(errno));
62     }
63
64     std::string pid = std::to_string(getpid());
65
66     ssize_t written = TEMP_FAILURE_RETRY(write(m_lockFd, pid.c_str(), pid.size()));
67     if (-1 == written || static_cast<ssize_t>(pid.size()) > written)
68         throw io_exception("Can't write file lock. Errno: ", strerror(errno));
69
70     int ret = fsync(m_lockFd);
71     if (-1 == ret)
72         throw io_exception("Fsync failed. Errno: ",strerror(errno));
73 }
74
75 FileLock::~FileLock()
76 {
77     // this will also release the lock
78     close(m_lockFd);
79 }
80
81 } /* namespace CKM */