1 /*
2 SMS Server Tools 3
3 Copyright (C) 2006- Keijo Kasvi
4 http://smstools3.kekekasvi.com/
5 
6 Based on SMS Server Tools 2, http://stefanfrings.de/smstools/
7 SMS Server Tools version 2 and below are Copyright (C) Stefan Frings.
8 
9 This program is free software unless you got it under another license directly
10 from the author. You can redistribute it and/or modify it under the terms of
11 the GNU General Public License as published by the Free Software Foundation.
12 Either version 2 of the License, or (at your option) any later version.
13 */
14 
15 #include "locking.h"
16 #include "smsd_cfg.h"
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include <fcntl.h>
22 #include <limits.h>
23 #include <unistd.h>
24 
lockfile(char * filename)25 int lockfile( char*  filename)
26 {
27   char lockfilename[PATH_MAX +5];
28   int lockfile;
29   struct stat statbuf;
30   char pid[64];
31 
32   if (!filename)
33     return 0;
34   if (strlen(filename) + 5 >= sizeof(lockfilename))
35     return 0;
36 
37   strcpy(lockfilename,filename);
38   strcat(lockfilename,".LOCK");
39   if (stat(lockfilename,&statbuf))
40   {
41     lockfile=open(lockfilename,O_CREAT|O_EXCL|O_WRONLY,0644);
42     if (lockfile>=0)
43     {
44       // 3.1.15:
45       //snprintf(pid, sizeof(pid), "%i %s\n", (int)getpid(), DEVICE.name);
46       snprintf(pid, sizeof(pid), "%i %s\n", (int)getpid(),
47                // 3.1.18: Use process_title now when there are other process_id's below 0,
48                // even when CHILD or NOTIFIER do not use lockfiles (at least currently):
49                //(process_id == -1) ? "MAINPROCESS" : DEVICE.name);
50                process_title);
51 
52       write(lockfile, pid, strlen(pid));
53       // 3.1.16beta: Fix: Use fsync instead of sync after close:
54       fsync(lockfile);
55       close(lockfile);
56       return 1;
57     }
58   }
59 
60   return 0;
61 }
62 
islocked(char * filename)63 int islocked( char*  filename)
64 {
65   char lockfilename[PATH_MAX +5];
66   struct stat statbuf;
67 
68   if (!filename)
69     return 0;
70   if (strlen(filename) + 5 >= sizeof(lockfilename))
71     return 0;
72 
73   strcpy(lockfilename,filename);
74   strcat(lockfilename,".LOCK");
75   if (stat(lockfilename,&statbuf))
76     return 0;
77   return 1;
78 }
79 
unlockfile(char * filename)80 int unlockfile( char*  filename)
81 {
82   char lockfilename[PATH_MAX +5];
83   struct stat statbuf;
84 
85   if (!filename)
86     return 0;
87   if (strlen(filename) + 5 >= sizeof(lockfilename))
88     return 0;
89 
90   strcpy(lockfilename,filename);
91   strcat(lockfilename,".LOCK");
92   if (!stat(lockfilename, &statbuf)) // 3.1.16beta: Check if file exists
93     if (unlink(lockfilename))
94       return 0;
95   return 1;
96 }
97