Ejemplo n.º 1
0
/*
 * Callback function for when a channel receives data from the ipc socket.
 * Emits the corresponding signal with the reply.
 */
static gboolean ipc_on_data(GIOChannel *channel, GIOCondition condition, i3ipcConnection *conn) {
  if (condition != G_IO_IN)
    return TRUE;

  GIOStatus status;
  uint32_t reply_length;
  uint32_t reply_type;
  gchar *reply;
  GError *err = NULL;
  JsonParser *parser;
  JsonObject *json_reply;

  status = ipc_recv_message(channel, &reply_type, &reply_length, &reply, &err);

  if (status == G_IO_STATUS_EOF) {
    g_signal_emit(conn, connection_signals[IPC_SHUTDOWN], 0);

    if (conn->priv->main_loop != NULL)
      i3ipc_connection_main_quit(conn);

    return FALSE;
  }

  if (err) {
    g_warning("could not get event reply\n");
    g_error_free(err);
    g_free(reply);
    return TRUE;
  }

  reply[reply_length] = '\0';

  parser = json_parser_new();
  json_parser_load_from_data(parser, reply, -1, &err);

  if (err) {
    g_warning("could not parse event reply json (%s)\n", err->message);
    g_error_free(err);
    g_free(reply);
    g_object_unref(parser);
    return TRUE;
  }

  json_reply = json_node_get_object(json_parser_get_root(parser));

  switch (1 << (reply_type & 0x7F))
  {
    case I3IPC_EVENT_WORKSPACE:
      {
        i3ipcWorkspaceEvent *e = g_slice_new0(i3ipcWorkspaceEvent);

        e->change = g_strdup(json_object_get_string_member(json_reply, "change"));

        if (json_object_has_member(json_reply, "current") && !json_object_get_null_member(json_reply, "current"))
          e->current = i3ipc_con_new(NULL, json_object_get_object_member(json_reply, "current"), conn);

        if (json_object_has_member(json_reply, "old") && !json_object_get_null_member(json_reply, "old"))
          e->old = i3ipc_con_new(NULL, json_object_get_object_member(json_reply, "old"), conn);

        g_signal_emit(conn, connection_signals[WORKSPACE], g_quark_from_string(e->change), e);
        break;
      }

    case I3IPC_EVENT_OUTPUT:
      {
        i3ipcGenericEvent *e = g_slice_new0(i3ipcGenericEvent);

        e->change = g_strdup(json_object_get_string_member(json_reply, "change"));

        g_signal_emit(conn, connection_signals[OUTPUT], g_quark_from_string(e->change), e);
        break;
      }

    case I3IPC_EVENT_MODE:
      {
        i3ipcGenericEvent *e = g_slice_new0(i3ipcGenericEvent);

        e->change = g_strdup(json_object_get_string_member(json_reply, "change"));

        g_signal_emit(conn, connection_signals[MODE], g_quark_from_string(e->change), e);
        break;
      }

    case I3IPC_EVENT_WINDOW:
      {
        i3ipcWindowEvent *e = g_slice_new0(i3ipcWindowEvent);

        e->change = g_strdup(json_object_get_string_member(json_reply, "change"));

        if (json_object_has_member(json_reply, "container") && !json_object_get_null_member(json_reply, "container"))
          e->container = i3ipc_con_new(NULL, json_object_get_object_member(json_reply, "container"), conn);

        g_signal_emit(conn, connection_signals[WINDOW], g_quark_from_string(e->change), e);
        break;
      }

    case I3IPC_EVENT_BARCONFIG_UPDATE:
      {
        i3ipcBarconfigUpdateEvent *e = g_slice_new0(i3ipcBarconfigUpdateEvent);

        e->id = g_strdup(json_object_get_string_member(json_reply, "id"));
        e->hidden_state = g_strdup(json_object_get_string_member(json_reply, "hidden_state"));
        e->mode = g_strdup(json_object_get_string_member(json_reply, "mode"));

        g_signal_emit(conn, connection_signals[BARCONFIG_UPDATE], 0, e);
        break;
      }
    case I3IPC_EVENT_BINDING:
      {
        i3ipcBindingEvent *e = g_slice_new0(i3ipcBindingEvent);

        e->change = g_strdup(json_object_get_string_member(json_reply, "change"));

        JsonObject *json_binding_info = json_object_get_object_member(json_reply, "binding");
        e->binding = g_slice_new0(i3ipcBindingInfo);
        e->binding->command = g_strdup(json_object_get_string_member(json_binding_info, "command"));
        e->binding->input_code = json_object_get_int_member(json_binding_info, "input_code");
        e->binding->input_type = g_strdup(json_object_get_string_member(json_binding_info, "input_type"));
        e->binding->symbol = g_strdup(json_object_get_string_member(json_binding_info, "symbol"));

        JsonArray *mods = json_object_get_array_member(json_binding_info, "mods");
        gint mods_len = json_array_get_length(mods);

        for (int i = 0; i < mods_len; i += 1) {
          e->binding->mods = g_slist_append(e->binding->mods, g_strdup(json_array_get_string_element(mods, i)));
        }

        g_signal_emit(conn, connection_signals[BINDING], g_quark_from_string(e->change), e);
        break;
      }

    default:
      g_warning("got unknown event\n");
      break;
  }

  g_object_unref(parser);
  g_free(reply);

  return TRUE;
}
Ejemplo n.º 2
0
int main(int argc, char *argv[]) {
    char *env_socket_path = getenv("I3SOCK");
    if (env_socket_path)
        socket_path = sstrdup(env_socket_path);
    else
        socket_path = NULL;
    int o, option_index = 0;
    uint32_t message_type = I3_IPC_MESSAGE_TYPE_COMMAND;
    char *payload = NULL;
    bool quiet = false;

    static struct option long_options[] = {
        {"socket", required_argument, 0, 's'},
        {"type", required_argument, 0, 't'},
        {"version", no_argument, 0, 'v'},
        {"quiet", no_argument, 0, 'q'},
        {"help", no_argument, 0, 'h'},
        {0, 0, 0, 0}};

    char *options_string = "s:t:vhq";

    while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
        if (o == 's') {
            if (socket_path != NULL)
                free(socket_path);
            socket_path = sstrdup(optarg);
        } else if (o == 't') {
            if (strcasecmp(optarg, "command") == 0)
                message_type = I3_IPC_MESSAGE_TYPE_COMMAND;
            else if (strcasecmp(optarg, "get_workspaces") == 0)
                message_type = I3_IPC_MESSAGE_TYPE_GET_WORKSPACES;
            else if (strcasecmp(optarg, "get_outputs") == 0)
                message_type = I3_IPC_MESSAGE_TYPE_GET_OUTPUTS;
            else if (strcasecmp(optarg, "get_tree") == 0)
                message_type = I3_IPC_MESSAGE_TYPE_GET_TREE;
            else if (strcasecmp(optarg, "get_marks") == 0)
                message_type = I3_IPC_MESSAGE_TYPE_GET_MARKS;
            else if (strcasecmp(optarg, "get_bar_config") == 0)
                message_type = I3_IPC_MESSAGE_TYPE_GET_BAR_CONFIG;
            else if (strcasecmp(optarg, "get_version") == 0)
                message_type = I3_IPC_MESSAGE_TYPE_GET_VERSION;
            else {
                printf("Unknown message type\n");
                printf("Known types: command, get_workspaces, get_outputs, get_tree, get_marks, get_bar_config, get_version\n");
                exit(EXIT_FAILURE);
            }
        } else if (o == 'q') {
            quiet = true;
        } else if (o == 'v') {
            printf("i3-msg " I3_VERSION "\n");
            return 0;
        } else if (o == 'h') {
            printf("i3-msg " I3_VERSION "\n");
            printf("i3-msg [-s <socket>] [-t <type>] <message>\n");
            return 0;
        }
    }

    if (socket_path == NULL)
        socket_path = root_atom_contents("I3_SOCKET_PATH", NULL, 0);

    /* Fall back to the default socket path */
    if (socket_path == NULL)
        socket_path = sstrdup("/tmp/i3-ipc.sock");

    /* Use all arguments, separated by whitespace, as payload.
     * This way, you don’t have to do i3-msg 'mark foo', you can use
     * i3-msg mark foo */
    while (optind < argc) {
        if (!payload) {
            payload = sstrdup(argv[optind]);
        } else {
            char *both;
            sasprintf(&both, "%s %s", payload, argv[optind]);
            free(payload);
            payload = both;
        }
        optind++;
    }

    if (!payload)
        payload = "";

    int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
    if (sockfd == -1)
        err(EXIT_FAILURE, "Could not create socket");

    struct sockaddr_un addr;
    memset(&addr, 0, sizeof(struct sockaddr_un));
    addr.sun_family = AF_LOCAL;
    strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
    if (connect(sockfd, (const struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0)
        err(EXIT_FAILURE, "Could not connect to i3 on socket \"%s\"", socket_path);

    if (ipc_send_message(sockfd, strlen(payload), message_type, (uint8_t *)payload) == -1)
        err(EXIT_FAILURE, "IPC: write()");

    if (quiet)
        return 0;

    uint32_t reply_length;
    uint32_t reply_type;
    uint8_t *reply;
    int ret;
    if ((ret = ipc_recv_message(sockfd, &reply_type, &reply_length, &reply)) != 0) {
        if (ret == -1)
            err(EXIT_FAILURE, "IPC: read()");
        exit(1);
    }
    if (reply_type != message_type)
        errx(EXIT_FAILURE, "IPC: Received reply of type %d but expected %d", reply_type, message_type);
    /* For the reply of commands, have a look if that command was successful.
     * If not, nicely format the error message. */
    if (reply_type == I3_IPC_MESSAGE_TYPE_COMMAND) {
        yajl_handle handle;
        handle = yajl_alloc(&reply_callbacks, NULL, NULL);
        yajl_status state = yajl_parse(handle, (const unsigned char *)reply, reply_length);
        switch (state) {
            case yajl_status_ok:
                break;
            case yajl_status_client_canceled:
            case yajl_status_error:
                errx(EXIT_FAILURE, "IPC: Could not parse JSON reply.");
        }

        /* NB: We still fall-through and print the reply, because even if one
         * command failed, that doesn’t mean that all commands failed. */
    }
    printf("%.*s\n", reply_length, reply);
    free(reply);

    close(sockfd);

    return 0;
}
Ejemplo n.º 3
0
/*
 * Connects to i3 to find out the currently running version. Useful since it
 * might be different from the version compiled into this binary (maybe the
 * user didn’t correctly install i3 or forgot te restart it).
 *
 * The output looks like this:
 * Running i3 version: 4.2-202-gb8e782c (2012-08-12, branch "next") (pid 14804)
 *
 * The i3 binary you just called: /home/michael/i3/i3
 * The i3 binary you are running: /home/michael/i3/i3
 *
 */
void display_running_version(void) {
    char *socket_path = root_atom_contents("I3_SOCKET_PATH", conn, conn_screen);
    if (socket_path == NULL)
        exit(EXIT_SUCCESS);

    char *pid_from_atom = root_atom_contents("I3_PID", conn, conn_screen);
    if (pid_from_atom == NULL) {
        /* If I3_PID is not set, the running version is older than 4.2-200. */
        printf("\nRunning version: < 4.2-200\n");
        exit(EXIT_SUCCESS);
    }

    /* Inform the user of what we are doing. While a single IPC request is
     * really fast normally, in case i3 hangs, this will not terminate. */
    printf("(Getting version from running i3, press ctrl-c to abort…)");
    fflush(stdout);

    /* TODO: refactor this with the code for sending commands */
    int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
    if (sockfd == -1)
        err(EXIT_FAILURE, "Could not create socket");

    struct sockaddr_un addr;
    memset(&addr, 0, sizeof(struct sockaddr_un));
    addr.sun_family = AF_LOCAL;
    strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
    if (connect(sockfd, (const struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0)
        err(EXIT_FAILURE, "Could not connect to i3");

    if (ipc_send_message(sockfd, 0, I3_IPC_MESSAGE_TYPE_GET_VERSION,
                         (uint8_t *)"") == -1)
        err(EXIT_FAILURE, "IPC: write()");

    uint32_t reply_length;
    uint32_t reply_type;
    uint8_t *reply;
    int ret;
    if ((ret = ipc_recv_message(sockfd, &reply_type, &reply_length, &reply)) != 0) {
        if (ret == -1)
            err(EXIT_FAILURE, "IPC: read()");
        exit(EXIT_FAILURE);
    }

    if (reply_type != I3_IPC_MESSAGE_TYPE_GET_VERSION)
        errx(EXIT_FAILURE, "Got reply type %d, but expected %d (GET_VERSION)", reply_type, I3_IPC_MESSAGE_TYPE_GET_VERSION);

    yajl_handle handle = yajl_alloc(&version_callbacks, NULL, NULL);

    yajl_status state = yajl_parse(handle, (const unsigned char *)reply, (int)reply_length);
    if (state != yajl_status_ok)
        errx(EXIT_FAILURE, "Could not parse my own reply. That's weird. reply is %.*s", (int)reply_length, reply);

    printf("\rRunning i3 version: %s (pid %s)\n", human_readable_version, pid_from_atom);

    if (loaded_config_file_name) {
        struct stat sb;
        time_t now;
        char mtime[64];
        printf("Loaded i3 config: %s", loaded_config_file_name);
        if (stat(loaded_config_file_name, &sb) == -1) {
            printf("\n");
            ELOG("Cannot stat config file \"%s\"\n", loaded_config_file_name);
        } else {
            strftime(mtime, sizeof(mtime), "%c", localtime(&(sb.st_mtime)));
            time(&now);
            printf(" (Last modified: %s, %.f seconds ago)\n", mtime, difftime(now, sb.st_mtime));
        }
    }

#ifdef __linux__
    size_t destpath_size = 1024;
    ssize_t linksize;
    char *exepath;
    char *destpath = smalloc(destpath_size);

    sasprintf(&exepath, "/proc/%d/exe", getpid());

    while ((linksize = readlink(exepath, destpath, destpath_size)) == (ssize_t)destpath_size) {
        destpath_size = destpath_size * 2;
        destpath = srealloc(destpath, destpath_size);
    }
    if (linksize == -1)
        err(EXIT_FAILURE, "readlink(%s)", exepath);

    /* readlink() does not NULL-terminate strings, so we have to. */
    destpath[linksize] = '\0';

    printf("\n");
    printf("The i3 binary you just called: %s\n", destpath);

    free(exepath);
    sasprintf(&exepath, "/proc/%s/exe", pid_from_atom);

    while ((linksize = readlink(exepath, destpath, destpath_size)) == (ssize_t)destpath_size) {
        destpath_size = destpath_size * 2;
        destpath = srealloc(destpath, destpath_size);
    }
    if (linksize == -1)
        err(EXIT_FAILURE, "readlink(%s)", exepath);

    /* readlink() does not NULL-terminate strings, so we have to. */
    destpath[linksize] = '\0';

    /* Check if "(deleted)" is the readlink result. If so, the running version
     * does not match the file on disk. */
    if (strstr(destpath, "(deleted)") != NULL)
        printf("RUNNING BINARY DIFFERENT FROM BINARY ON DISK!\n");

    /* Since readlink() might put a "(deleted)" somewhere in the buffer and
     * stripping that out seems hackish and ugly, we read the process’s argv[0]
     * instead. */
    free(exepath);
    sasprintf(&exepath, "/proc/%s/cmdline", pid_from_atom);

    int fd;
    if ((fd = open(exepath, O_RDONLY)) == -1)
        err(EXIT_FAILURE, "open(%s)", exepath);
    if (read(fd, destpath, sizeof(destpath)) == -1)
        err(EXIT_FAILURE, "read(%s)", exepath);
    close(fd);

    printf("The i3 binary you are running: %s\n", destpath);

    free(exepath);
    free(destpath);
#endif

    yajl_free(handle);
}