cmd-save-buffer.c revision 1.9
1/* $OpenBSD: cmd-save-buffer.c,v 1.9 2010/12/30 23:16:18 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 <sys/types.h> 20#include <sys/stat.h> 21 22#include <errno.h> 23#include <string.h> 24 25#include "tmux.h" 26 27/* 28 * Saves a session paste buffer to a file. 29 */ 30 31int cmd_save_buffer_exec(struct cmd *, struct cmd_ctx *); 32 33const struct cmd_entry cmd_save_buffer_entry = { 34 "save-buffer", "saveb", 35 "[-a] " CMD_BUFFER_USAGE " path", 36 CMD_ARG1, "a", 37 cmd_buffer_init, 38 cmd_buffer_parse, 39 cmd_save_buffer_exec, 40 cmd_buffer_free, 41 cmd_buffer_print 42}; 43 44int 45cmd_save_buffer_exec(struct cmd *self, struct cmd_ctx *ctx) 46{ 47 struct cmd_buffer_data *data = self->data; 48 struct paste_buffer *pb; 49 mode_t mask; 50 FILE *f; 51 52 if (data->buffer == -1) { 53 if ((pb = paste_get_top(&global_buffers)) == NULL) { 54 ctx->error(ctx, "no buffers"); 55 return (-1); 56 } 57 } else { 58 pb = paste_get_index(&global_buffers, data->buffer); 59 if (pb == NULL) { 60 ctx->error(ctx, "no buffer %d", data->buffer); 61 return (-1); 62 } 63 } 64 65 if (strcmp(data->arg, "-") == 0) { 66 if (ctx->cmdclient == NULL) { 67 ctx->error(ctx, "%s: can't write to stdout", data->arg); 68 return (-1); 69 } 70 bufferevent_write( 71 ctx->cmdclient->stdout_event, pb->data, pb->size); 72 } else { 73 mask = umask(S_IRWXG | S_IRWXO); 74 if (cmd_check_flag(data->chflags, 'a')) 75 f = fopen(data->arg, "ab"); 76 else 77 f = fopen(data->arg, "wb"); 78 umask(mask); 79 if (f == NULL) { 80 ctx->error(ctx, "%s: %s", data->arg, strerror(errno)); 81 return (-1); 82 } 83 if (fwrite(pb->data, 1, pb->size, f) != pb->size) { 84 ctx->error(ctx, "%s: fwrite error", data->arg); 85 fclose(f); 86 return (-1); 87 } 88 fclose(f); 89 } 90 91 return (0); 92} 93