clean target: +missing hello.o
[gnokii.git] / utils / mgnokiidev.c
1 /*
2
3   $Id$
4   
5   G N O K I I
6
7   A Linux/Unix toolset and driver for Nokia mobile phones.
8
9   Released under the terms of the GNU GPL, see file COPYING for more details.
10
11   Mgnokiidev gets passed a slave pty name by gnokiid and uses this
12   information to create a symlink from the pty to /dev/gnokii.
13
14 */
15
16 #include <stdio.h>
17 #include <errno.h>
18 #include <signal.h>
19 #include <termios.h>
20 #include <grp.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/time.h>
26 #include <unistd.h>
27 #include <ctype.h>
28
29 #define DEVLEN  30
30 #define MAXLEN  12
31
32 int main(int argc, char *argv[])
33 {
34   int count, err;
35   char dev_name[DEVLEN];
36
37   /* Check we have one and only one command line argument. */
38   if (argc != 2) {
39     fprintf(stderr, "mgnokiidev takes one and only one argument!\n");
40     exit(-2);
41   }
42
43   /* Check if argument has a reasonable length (less than MAXLEN characters) */
44   if (strlen(argv[1]) >= MAXLEN) {
45     fprintf(stderr, "Argument must be less than %d characters.\n", MAXLEN);
46     exit (-2);
47   }
48
49   strncpy(dev_name, argv[1], DEVLEN);
50
51   /* Check for suspicious characters. */
52   for (count = 0; count < strlen(dev_name); count ++)
53     if (!(isalnum(dev_name[count]) || dev_name[count]=='/')) {
54       fprintf(stderr, "Suspicious character at index %d in argument.\n", count);
55       exit (-2);
56     }
57
58   /* Now become root */
59   setuid(0);
60
61   /* Change group of slave pty to group of mgnokiidev */
62   err = chown(dev_name, -1, getgid());
63
64   if (err < 0) {
65     perror("mgnokiidev - chown: ");
66     exit (-2);
67   }
68
69   /* Change permissions to rw by group */
70   err = chmod(dev_name, S_IRGRP | S_IWGRP | S_IRUSR | S_IWUSR);
71         
72   if (err < 0) {
73     perror("mgnokiidev - chmod: ");
74     exit (-2);
75   }
76
77   /* FIXME: Possible bug - should check that /dev/gnokii doesn't already exist
78      in case multiple users are trying to run gnokii. Well, but will be
79      mgnokiidev called then? I do not think so - you will probably got the
80      message serialport in use or similar. Don't you. I haven't tested it
81      though. */
82
83   /* Remove symlink in case it already exists. Don't care if it fails.  */
84   unlink ("/dev/gnokii");
85
86   /* Create symlink */
87   err = symlink(dev_name, "/dev/gnokii");
88
89   if (err < 0) {
90     perror("mgnokiidev - symlink: ");
91     exit (-2);
92   }
93
94   /* Done */
95   exit (0);
96 }