Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 49db7f64b1
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 342 lines (287 sloc) 8.806 kb
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 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

#define _GNU_SOURCE
#include <ctype.h>
#include <errno.h>
#include <getopt.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

#ifndef SUSPEND_COMMAND
# define SUSPEND_COMMAND "pm-suspend"
#endif

struct timespec_t {
    long hour;
    long min;
    long sec;
};

struct event_t {
    const char *cmd;
};

static struct event_t event;

static const char *suspend_cmd;
static long epochtime;

/* convert hours and minutes to seconds */
static long
timespec_to_seconds(struct timespec_t *ts)
{
    return (ts->hour * 3600) + (ts->min * 60) + ts->sec;
}

/* printf the help message */
static void
help(FILE *stream, char *name)
{
    fprintf(stream, "Usage: %s [time]\n\n"
            " -a, --at SEC specify an absolute time in seconds from epoch\n"
            " -c, --command \"CMD\" execute CMD instead of default '%s'\n"
            " -e, --event \"CMD\" execute CMD after wakeup\n"
            " -h, --help display this help and exit\n\n"
            "time can be any combination of hours, minutes, and seconds\n"
            "specified by hH, mM, and sS, respecitively.\n\n",
            name,
            SUSPEND_COMMAND);
    fprintf(stream, "Examples:\n"
            " %s 1h 20m 42S # 1 hour, 20 minutes, 42 seconds\n"
            " %s 1h20M 2h # 3 hours, 20 minutes\n"
            " %s -a $(date -d tomorrow +%%s) # 24 hours\n",
            name,
            name,
            name);

    exit(stream == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
}

/* execute the suspend cmd */
static int
do_suspend(const char *command)
{
    pid_t pid;
    int status;

    pid = vfork();
    if(pid == -1) {
        perror("fork");
        return 1;
    }

    if(pid == 0) {
        execlp("/bin/sh", command, "-c", command, NULL);
        fprintf(stderr, "error: failed to execute %s: %s\n", command,
                strerror(errno));
        _exit(127);
    }

    while(wait(&status) != pid);
    if(WIFEXITED(status) && WEXITSTATUS(status) != 0) {
        fprintf(stderr, "error: %s exited with status %d\n", command,
            WEXITSTATUS(status));
        return 1;
    }

    fprintf(stdout, "tick.\n");

    return 0;
}

/* parse command line args */
static int
parse_options(int argc, char **argv)
{
    int opt;
    static struct option opts[] = {
        { "at", no_argument, NULL, 'a' },
        { "command", required_argument, NULL, 'c' },
        { "execute", required_argument, NULL, 'e' },
        { "help", no_argument, NULL, 'h' },
        { 0, 0, 0, 0 }
    };

    while((opt = getopt_long(argc, argv, "ac:e:h", opts, NULL)) != -1) {
        switch(opt) {
            case 'a':
                epochtime = 1;
                break;
            case 'c':
                suspend_cmd = optarg;
                break;
            case 'e':
                event.cmd = optarg;
                break;
            case 'h':
                help(stdout, argv[0]);
                break;
            default:
            case '?':
                return 1;
        }
    }

    /* optind is set globally */
    return 0;
}

/* split up the time argument given e.g. 4h15m30s into individual variables */
static int
parse_timefragment(const char *fragment, struct timespec_t *ts)
{
    const char *f;
    long accum = 0;

    for(f = fragment; *f != '\0'; f++) {
        switch(*f) {
            case 'h':
            case 'H':
                ts->hour += accum;
                accum = 0;
                break;
            case 'm':
            case 'M':
                ts->min += accum;
                accum = 0;
                break;
            case 's':
            case 'S':
                ts->sec += accum;
                accum = 0;
                break;
            default:
                if(isdigit(*f)) {
                    accum *= 10;
                    accum += *f - '0';
                } else {
                    fprintf(stderr, "illegal character in format: %c\n", *f);
                    return 1;
                }
        }
    }

    return 0;
}


static int
parse_timespec(int optind, int argc, char **argv, struct timespec_t *ts)
{
    if(epochtime) {
        char *endptr;
        int64_t now, epoch, diff;

        epoch = strtoll(argv[optind], &endptr, 10);
        if(*endptr != '\0' || errno == ERANGE) {
            fprintf(stderr, "failed to parse absolute time: %s: %s",
                    argv[optind], strerror(errno == ERANGE ? ERANGE : EINVAL));
            return 1;
        }

        /* get the current time */
        if(time((time_t *)&now) == (time_t)-1) {
            fprintf(stderr, "error: failed to get current time\n");
            return 1;
        }

        if(epoch < now) {
            fprintf(stderr, "error: cannot specify a time in the past\n");
            return 1;
        }

        diff = epoch - now;
        ts->hour = diff / 3600;
        diff %= 3600;
        ts->min = diff / 60;
        ts->sec = diff % 60;
    }
    
    else {
        while(optind < argc) {
            if(parse_timefragment(argv[optind], ts) != 0) {
                fprintf(stderr, "error: failed to parse time: %s\n", argv[optind]);
                return 1;
            }
            optind++;
        }

        if(timespec_to_seconds(ts) == 0) {
            fprintf(stderr, "error: duration must be non-zero\n");
            return 1;
        }
    }

    return 0;
}

/* signal callback. gets executed onde the timer triggers */
static void
signal_event(union sigval sival)
{
    struct event_t *event;

    event = sival.sival_ptr;

    fprintf(stdout, "tock.\n");

    execl("/bin/sh", event->cmd, "-c", event->cmd, NULL);
    fprintf(stderr, "error: failed to execute command: %s: %s\n",
            (const char *)event->cmd, strerror(errno));
    exit(1);
}

/* set the timer */
static int
create_alarm(struct timespec_t *ts)
{
    struct itimerspec wakeup;
    struct sigevent sigev;
    union sigval sigv;
    timer_t timerid;

    memset(&wakeup, 0, sizeof(struct itimerspec));

    /* if we have a command that shall be exexuted, hook it up to the signal event */
    if(event.cmd) {
        memset(&sigev, 0, sizeof(struct sigevent));
        sigv.sival_ptr = (void *)&event;
        sigev.sigev_notify = SIGEV_THREAD;
        sigev.sigev_notify_function = signal_event;
        sigev.sigev_value = sigv;
    }

    /* init timer */
    if(timer_create(CLOCK_REALTIME_ALARM, event.cmd ? &sigev : NULL,
                &timerid) != 0) {
        perror("error: failed to create timer");
        return 1;
    }

    /* init itimerspec */
    if(clock_gettime(CLOCK_REALTIME_ALARM, &wakeup.it_value)) {
        perror("error: failed to get time from RTC");
        return 1;
    }

    /* set itimerspec to some future time */
    wakeup.it_value.tv_sec += timespec_to_seconds(ts);

    if(timer_settime(timerid, TIMER_ABSTIME, &wakeup, NULL)) {
        perror("error: failed to set wakeup time");
        return 1;
    }

    /* informational message */
    fprintf(stdout, "timer set for wakeup in: %ld hours %ld min %ld sec\n",
            ts->hour, ts->min, ts->sec);

    /* tick, tock makes the clock */
    fprintf(stdout, "tick.\n");
    if(event.cmd == NULL) {
        fprintf(stdout, "tock.\n");
    }

    return 0;
}


int
main(int argc, char *argv[])
{
    struct timespec_t ts;

    if(argc <= 1) {
        fprintf(stderr, "error: no timespec specified (use -h for help)\n");
        help(stderr, argv[0]);
    }

    memset(&ts, 0, sizeof(struct timespec_t));

    if(parse_options(argc, argv) != 0) {
        return 1;
    }

    if(parse_timespec(optind, argc, argv, &ts) != 0) {
        return 2;
    }

    if(create_alarm(&ts) != 0) {
        return 3;
    }

    if(do_suspend(suspend_cmd ? suspend_cmd : SUSPEND_COMMAND) != 0) {
        return 4;
    }

    pthread_exit(NULL);
    return EXIT_SUCCESS;
}

/* vim: set et ts=4 sw=4: */
Something went wrong with that request. Please try again.