1 /* $OpenBSD: cmd-load-buffer.c,v 1.11 2010/02/22 20:33:12 nicm Exp $ */ 2 3 /* 4 * Copyright (c) 2009 Tiago Cunha <me@tiagocunha.org> 5 * 6 * Permission to use, copy, modify, and distribute this software for any 7 * purpose with or without fee is hereby granted, provided that the above 8 * copyright notice and this permission notice appear in all copies. 9 * 10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER 15 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 16 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17 */ 18 19 #include <errno.h> 20 #include <stdio.h> 21 #include <stdlib.h> 22 #include <string.h> 23 24 #include "tmux.h" 25 26 /* 27 * Loads a session paste buffer from a file. 28 */ 29 30 int cmd_load_buffer_exec(struct cmd *, struct cmd_ctx *); 31 32 const struct cmd_entry cmd_load_buffer_entry = { 33 "load-buffer", "loadb", 34 CMD_BUFFER_SESSION_USAGE " path", 35 CMD_ARG1, "", 36 cmd_buffer_init, 37 cmd_buffer_parse, 38 cmd_load_buffer_exec, 39 cmd_buffer_free, 40 cmd_buffer_print 41 }; 42 43 int 44 cmd_load_buffer_exec(struct cmd *self, struct cmd_ctx *ctx) 45 { 46 struct cmd_buffer_data *data = self->data; 47 struct session *s; 48 FILE *f; 49 char *pdata, *new_pdata; 50 size_t psize; 51 u_int limit; 52 int ch; 53 54 if ((s = cmd_find_session(ctx, data->target)) == NULL) 55 return (-1); 56 57 if ((f = fopen(data->arg, "rb")) == NULL) { 58 ctx->error(ctx, "%s: %s", data->arg, strerror(errno)); 59 return (-1); 60 } 61 62 pdata = NULL; 63 psize = 0; 64 while ((ch = getc(f)) != EOF) { 65 /* Do not let the server die due to memory exhaustion. */ 66 if ((new_pdata = realloc(pdata, psize + 2)) == NULL) { 67 ctx->error(ctx, "realloc error: %s", strerror(errno)); 68 goto error; 69 } 70 pdata = new_pdata; 71 pdata[psize++] = ch; 72 } 73 if (ferror(f)) { 74 ctx->error(ctx, "%s: read error", data->arg); 75 goto error; 76 } 77 if (pdata != NULL) 78 pdata[psize] = '\0'; 79 80 fclose(f); 81 82 limit = options_get_number(&s->options, "buffer-limit"); 83 if (data->buffer == -1) { 84 paste_add(&s->buffers, pdata, psize, limit); 85 return (0); 86 } 87 if (paste_replace(&s->buffers, data->buffer, pdata, psize) != 0) { 88 ctx->error(ctx, "no buffer %d", data->buffer); 89 goto error; 90 } 91 92 return (0); 93 94 error: 95 if (pdata != NULL) 96 xfree(pdata); 97 fclose(f); 98 return (-1); 99 } 100