summaryrefslogtreecommitdiffstats
path: root/src/rpc.c
blob: e63f7fed1bc53cb70a1ff4ae85bfa8409a34383e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
#include "rpc.h"
#include "util.h"
#include "main.h"
#include "userlist.h"

#include <poll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

#define SENDSTRING(fd,x) write( fd, x, strlen(x) )

#define SOCKPATH "/run/idle-daemon"

#pragma pack(1)
static struct {
    int read;
    int write;
} rpcPipe = {
    .read = -1,
    .write = -1,
};
#pragma pack(0)

_Static_assert( sizeof(rpcPipe) == ( sizeof(int) * 2 ), "Structsize mismatch" );

static void handleClient( int fd, struct ucred *user );

int rpc_open( void )
{
    int fd = socket( AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0 );
    if ( fd == -1 ) {
        perror( "Cannot create local RPC socket" );
        return -1;
    }
    struct sockaddr_un address = {
        .sun_family = AF_UNIX,
        .sun_path = SOCKPATH,
    };
    unlink( SOCKPATH );
    if ( bind( fd, (struct sockaddr *)&address, sizeof(address) ) == -1 ) {
        perror( "Could not bind RPC socket" );
        close( fd );
        return -1;
    }
    chmod( SOCKPATH, 0777 );
    if ( listen( fd, 10 ) == -1 ) {
        perror( "Could not listen() on RPC socket" );
        close( fd );
        return -1;
    }
    if ( rpcPipe.write == -1 && rpcPipe.read == -1 ) {
        if ( pipe2( (int*)&rpcPipe, O_DIRECT ) == -1 ) {
            perror( "Cannot create local RPC pipe" );
        } else {
            // Read end nonblocking
            int flags = fcntl( rpcPipe.read, F_GETFL, 0 );
            fcntl( rpcPipe.read, F_SETFL, flags | O_NONBLOCK );
        }
    }
    return fd;
}

void rpc_wait( int listenFd, int seconds )
{
    struct pollfd pd[2] = {
        { .fd = listenFd, .events = POLLIN | POLLHUP | POLLRDHUP },
        { .fd = rpcPipe.read, .events = POLLIN | POLLHUP | POLLRDHUP },
    };
    if ( poll( pd, 2, seconds * 1000 ) == -1 ) {
        perror( "Error polling RPC sockets" );
    }
}

void rpc_handle( int listenFd )
{
    int fd;
    while ( ( fd = accept( listenFd, NULL, NULL ) ) != -1 ) {
        // Determine who connected
        socklen_t len;
        struct ucred ucred;
        len = sizeof(struct ucred);
        if ( getsockopt( fd, SOL_SOCKET, SO_PEERCRED, &ucred, &len ) == -1 ) {
            perror( "Could not get credentials of connection" );
            close( fd ); // TODO: Allow more for root (eg. cancel reboot/poweroff)
            continue;
        }
        if ( ! doublefork() ) {
            close( fd );
            continue; // Parent continues
        }
        handleClient( fd, &ucred );
        exit( 0 );
    }
    if ( errno != EAGAIN && errno != EWOULDBLOCK ) {
        perror( "accept() on RPC socket failed" );
    }
    // Check if any RPC client talks to us
    char buffer[200];
    ssize_t len;
    while ( ( len = read( rpcPipe.read, buffer, sizeof(buffer) - 1 ) ) > 0 ) {
        buffer[len] = '\0';
        const char *ptr = NULL;
        enum Shutdown action = SHUTDOWN_ENUM_END;
        if ( strncmp( buffer, "reboot ", 7 ) == 0 ) {
            ptr = buffer + 7;
            action = REBOOT;
        } else if ( strncmp( buffer, "poweroff ", 9 ) == 0 ) {
            ptr = buffer + 9;
            action = POWEROFF;
        } else if ( strncmp( buffer, "kexec ", 6 ) == 0 ) {
            ptr = buffer + 6;
            action = KEXEC;
        } else {
            fprintf( stderr, "Unknown RPC pipe callback: %s\n", buffer );
        }
        if ( ptr != NULL ) {
            char *end;
            int seconds = strtol( ptr, &end, 10 );
            if ( end != ptr && seconds >= 0 ) {
                main_queueAction( action, seconds );
            } else {
                fprintf( stderr, "RPC: Ignoring reboot/poweroff with invalid timeout\n" );
            }
        }
    }
    if ( len == -1 && errno != EAGAIN && errno != EWOULDBLOCK ) {
        perror( "Error reading vom RPC local pipe" );
    }
}

static void handleClient( int fd, struct ucred *creds )
{
    //printf( "Credentials from SO_PEERCRED: pid=%ld, euid=%ld, egid=%ld\n",
    //    (long) ucred.pid, (long) ucred.uid, (long) ucred.gid );
    // Make socket blocking (should be default on linux after accept() but...)
    int flags = fcntl( fd, F_GETFL, 0 );
    if ( flags != -1 ) {
        fcntl( fd, F_SETFL, flags & ~O_NONBLOCK );
    }
    // But set timeouts
    struct timeval tv = {
        .tv_sec = 2,
    };
    setsockopt( fd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(tv) );
    setsockopt( fd, SOL_SOCKET, SO_SNDTIMEO, (const char*)&tv, sizeof(tv) );
    // Now read request
    char buffer[1000];
    ssize_t len = read( fd, buffer, sizeof(buffer) - 1 );
    if ( len <= 0 )
        return;
    buffer[len] = '\0';
    if ( strncmp( buffer, "get", 3 ) == 0 ) {
        // Get request
        FILE *s = fdopen( fd, "w" );
        if ( s == NULL ) {
            perror( "Cannot wrap socket in stream" );
            return;
        }
        // 1) Global state
        time_t deadline;
        const char *name = "none";
        main_getStatus( &name, &deadline );
        fprintf( s, "[General]\n"
                "nextAction=%s\n"
                "nextActionTime=%lld\n",
                name, (long long)deadline );
        // 2) Requested sessions
        char *tok = strtok( buffer + 4, " \t\n\r" );
        while ( tok != NULL ) {
            struct user *user = main_getUser( tok );
            if ( user != NULL ) {
                fprintf( s, "[%s]\n"
                        "logoutTime=%lld\n"
                        "locked=%d\n"
                        "idleSeconds=%d\n",
                        tok, (long long)user->logoutTime, (int)user->isLocked, (int)( time(NULL) - user->lastActivity ) );
            }
            tok = strtok( NULL, " \t\n\r" );
        }
        fflush( s );
        // Don't fclose since we need to shutdown below. This is a leak, but since we're
        // running in a child that will exit soon, just close your eyes for a second...
    } else if ( strncmp( buffer, "reboot ", 7 ) == 0 || strncmp( buffer, "poweroff ", 9 ) == 0
            || strncmp( buffer, "kexec ", 6 ) == 0 ) {
        if ( creds->uid != 0 ) {
            SENDSTRING( fd, "error only root can do this" );
        } else {
            if ( write( rpcPipe.write, buffer, len ) == -1 ) {
                perror( "RPC Child: Cannot write to parent pipe" );
                SENDSTRING( fd, "error cannot write to parent" );
            } else {
                SENDSTRING( fd, "ok" );
            }
        }
    } else if ( strncmp( buffer, "warn ", 5 ) == 0 ) {
        if ( creds->uid != 0 ) {
            SENDSTRING( fd, "error only root can do this" );
        } else {
            main_warnAll( buffer + 5 );
            SENDSTRING( fd, "ok" );
        }
    } else {
        SENDSTRING( fd, "error unknown command" );
    }
    shutdown( fd, SHUT_WR );
    read( fd, buffer, sizeof(buffer) );
    close( fd );
}

bool rpc_send( const char *data )
{
    struct sockaddr_un addr = {
        .sun_family = AF_UNIX,
        .sun_path = SOCKPATH,
    };
    int fd = socket( AF_UNIX, SOCK_STREAM, 0 );
    if ( fd == -1 ) {
        perror( "RPC Client: socket() failed" );
        return false;
    }
    if ( connect( fd, &addr, sizeof(addr) ) == -1 ) {
        perror( "RPC Client: connect() failed" );
        close( fd );
        return false;
    }
    if ( write( fd, data, strlen( data ) ) <= 0 ) {
        perror( "RPC Client: write() failed" );
        close( fd );
        return false;
    }
    shutdown( fd, SHUT_WR );
    char buffer[200];
    ssize_t len;
    if ( ( len = read( fd, buffer, sizeof(buffer) - 1 ) ) == -1 ) {
        perror( "RPC Client: read()ing reply failed" );
    } else {
        buffer[len] = '\0';
        printf( "%s\n", buffer );
    }
    close( fd );
    return true;
}