source: mainline/uspace/app/bdsh/cmds/modules/cat/cat.c@ b5b5d84

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since b5b5d84 was 58898d1d, checked in by Jakub Jermar <jakub@…>, 9 years ago

Remove VFS_IN_SEEK from VFS

  • Property mode set to 100644
File size: 9.9 KB
Line 
1/*
2 * Copyright (c) 2008 Tim Post
3 * Copyright (c) 2011, Martin Sucha
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * - Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * - Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * - The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30#include <stdio.h>
31#include <stdlib.h>
32#include <unistd.h>
33#include <sys/stat.h>
34#include <getopt.h>
35#include <str.h>
36#include <fcntl.h>
37#include <io/console.h>
38#include <io/color.h>
39#include <io/style.h>
40#include <io/keycode.h>
41#include <errno.h>
42#include <vfs/vfs.h>
43#include <assert.h>
44
45#include "config.h"
46#include "util.h"
47#include "errors.h"
48#include "entry.h"
49#include "cat.h"
50#include "cmds.h"
51
52static const char *cmdname = "cat";
53#define CAT_VERSION "0.0.1"
54#define CAT_DEFAULT_BUFLEN 1024
55#define CAT_FULL_FILE 0
56
57static const char *hexchars = "0123456789abcdef";
58
59static bool paging_enabled = false;
60static size_t chars_remaining = 0;
61static size_t lines_remaining = 0;
62static sysarg_t console_cols = 0;
63static sysarg_t console_rows = 0;
64static bool should_quit = false;
65static bool dash_represents_stdin = false;
66static unsigned int lineno = 0;
67static bool number = false;
68static bool last_char_was_newline = false;
69
70static console_ctrl_t *console = NULL;
71
72static struct option const long_options[] = {
73 { "help", no_argument, 0, 'h' },
74 { "version", no_argument, 0, 'v' },
75 { "head", required_argument, 0, 'H' },
76 { "tail", required_argument, 0, 't' },
77 { "buffer", required_argument, 0, 'b' },
78 { "more", no_argument, 0, 'm' },
79 { "hex", no_argument, 0, 'x' },
80 { "stdin", no_argument, 0, 's' },
81 { "number", no_argument, 0, 'n' },
82 { 0, 0, 0, 0 }
83};
84
85/* Dispays help for cat in various levels */
86void help_cmd_cat(unsigned int level)
87{
88 if (level == HELP_SHORT) {
89 printf("`%s' shows the contents of files\n", cmdname);
90 } else {
91 help_cmd_cat(HELP_SHORT);
92 printf(
93 "Usage: %s [options] <file1> [file2] [...]\n"
94 "Options:\n"
95 " -h, --help A short option summary\n"
96 " -v, --version Print version information and exit\n"
97 " -H, --head ## Print only the first ## bytes\n"
98 " -t, --tail ## Print only the last ## bytes\n"
99 " -b, --buffer ## Set the read buffer size to ##\n"
100 " -m, --more Pause after each screen full\n"
101 " -x, --hex Print bytes as hex values\n"
102 " -s, --stdin Treat `-' in file list as standard input\n"
103 " -n, --number Number all output lines\n"
104 "Currently, %s is under development, some options don't work.\n",
105 cmdname, cmdname);
106 }
107
108 return;
109}
110
111static void waitprompt(void)
112{
113 console_set_pos(console, 0, console_rows-1);
114 console_set_color(console, COLOR_WHITE, COLOR_BLUE, 0);
115
116 printf("ENTER/SPACE/PAGE DOWN - next page, "
117 "ESC/Q - quit, C - continue unpaged");
118 fflush(stdout);
119
120 console_set_style(console, STYLE_NORMAL);
121}
122
123static void waitkey(void)
124{
125 cons_event_t ev;
126 kbd_event_t *kev;
127
128 while (true) {
129 if (!console_get_event(console, &ev)) {
130 return;
131 }
132 if (ev.type == CEV_KEY && ev.ev.key.type == KEY_PRESS) {
133 kev = &ev.ev.key;
134
135 if (kev->key == KC_ESCAPE || kev->key == KC_Q) {
136 should_quit = true;
137 return;
138 }
139 if (kev->key == KC_C) {
140 paging_enabled = false;
141 return;
142 }
143 if (kev->key == KC_ENTER || kev->key == KC_SPACE ||
144 kev->key == KC_PAGE_DOWN) {
145 return;
146 }
147 }
148 }
149 assert(false);
150}
151
152static void newpage(void)
153{
154 console_clear(console);
155 chars_remaining = console_cols;
156 lines_remaining = console_rows - 1;
157}
158
159static void paged_char(wchar_t c)
160{
161 if (last_char_was_newline && number) {
162 lineno++;
163 printf("%6u ", lineno);
164 }
165 putchar(c);
166 last_char_was_newline = c == '\n';
167 if (paging_enabled) {
168 chars_remaining--;
169 if (c == '\n' || chars_remaining == 0) {
170 chars_remaining = console_cols;
171 lines_remaining--;
172 }
173 if (lines_remaining == 0) {
174 fflush(stdout);
175 waitprompt();
176 waitkey();
177 newpage();
178 }
179 }
180}
181
182static unsigned int cat_file(const char *fname, size_t blen, bool hex,
183 off64_t head, off64_t tail, bool tail_first)
184{
185 int fd, bytes = 0, count = 0, reads = 0;
186 char *buff = NULL;
187 int i;
188 size_t offset = 0, copied_bytes = 0;
189 off64_t file_size = 0, length = 0;
190 aoff64_t pos = 0;
191
192 bool reading_stdin = dash_represents_stdin && (str_cmp(fname, "-") == 0);
193
194 if (reading_stdin) {
195 fd = fileno(stdin);
196 /* Allow storing the whole UTF-8 character. */
197 blen = STR_BOUNDS(1);
198 } else
199 fd = open(fname, O_RDONLY);
200
201 if (fd < 0) {
202 printf("Unable to open %s\n", fname);
203 return 1;
204 }
205
206 if (NULL == (buff = (char *) malloc(blen + 1))) {
207 close(fd);
208 printf("Unable to allocate enough memory to read %s\n",
209 fname);
210 return 1;
211 }
212
213 if (tail != CAT_FULL_FILE) {
214 struct stat st;
215
216 if (fstat(fd, &st) != EOK) {
217 close(fd);
218 free(buff);
219 printf("Unable to fstat %d\n", fd);
220 return 1;
221 }
222 file_size = st.size;
223 if (head == CAT_FULL_FILE) {
224 head = file_size;
225 length = tail;
226 } else if (tail_first) {
227 length = head;
228 } else {
229 if (tail > head)
230 tail = head;
231 length = tail;
232 }
233
234 if (tail_first) {
235 pos = (tail >= file_size) ? 0 : (file_size - tail);
236 } else {
237 pos = ((head - tail) >= file_size) ? 0 : (head - tail);
238 }
239 } else
240 length = head;
241
242 do {
243 size_t bytes_to_read;
244 if (reading_stdin) {
245 bytes_to_read = 1;
246 } else {
247 if ((length != CAT_FULL_FILE) &&
248 (length - (off64_t)count <= (off64_t)(blen - copied_bytes))) {
249 bytes_to_read = (size_t) (length - count);
250 } else {
251 bytes_to_read = blen - copied_bytes;
252 }
253 }
254
255 bytes = read(fd, &pos, buff + copied_bytes, bytes_to_read);
256 copied_bytes = 0;
257
258 if (bytes > 0) {
259 buff[bytes] = '\0';
260 offset = 0;
261 for (i = 0; i < bytes && !should_quit; i++) {
262 if (hex) {
263 paged_char(hexchars[((uint8_t)buff[i])/16]);
264 paged_char(hexchars[((uint8_t)buff[i])%16]);
265 paged_char(((count+i+1) & 0xf) == 0 ? '\n' : ' ');
266 }
267 else {
268 wchar_t c = str_decode(buff, &offset, bytes);
269 if (c == 0) {
270 /* Reached end of string */
271 break;
272 } else if (c == U_SPECIAL && offset + 2 >= (size_t)bytes) {
273 /* If an extended character is cut off due to the size of the buffer,
274 we will copy it over to the next buffer so it can be read correctly. */
275 copied_bytes = bytes - offset + 1;
276 memcpy(buff, buff + offset - 1, copied_bytes);
277 break;
278 }
279 paged_char(c);
280 }
281
282 }
283 count += bytes;
284 reads++;
285 }
286
287 if (reading_stdin)
288 fflush(stdout);
289 } while (bytes > 0 && !should_quit && (count < length || length == CAT_FULL_FILE));
290
291 close(fd);
292 if (bytes == -1) {
293 printf("Error reading %s\n", fname);
294 free(buff);
295 return 1;
296 }
297
298 free(buff);
299
300 return 0;
301}
302
303/* Main entry point for cat, accepts an array of arguments */
304int cmd_cat(char **argv)
305{
306 unsigned int argc, i, ret = 0;
307 size_t buffer = 0;
308 int c, opt_ind;
309 aoff64_t head = CAT_FULL_FILE, tail = CAT_FULL_FILE;
310 bool hex = false;
311 bool more = false;
312 bool tailFirst = false;
313 sysarg_t rows, cols;
314 int rc;
315
316 /*
317 * reset global state
318 * TODO: move to structure?
319 */
320 paging_enabled = false;
321 chars_remaining = 0;
322 lines_remaining = 0;
323 console_cols = 0;
324 console_rows = 0;
325 should_quit = false;
326 console = console_init(stdin, stdout);
327 number = false;
328 lineno = 0;
329 /* This enables printing of the first number. */
330 last_char_was_newline = true;
331
332
333 argc = cli_count_args(argv);
334
335 for (c = 0, optreset = 1, optind = 0, opt_ind = 0; c != -1;) {
336 c = getopt_long(argc, argv, "xhvmH:t:b:s:n", long_options, &opt_ind);
337 switch (c) {
338 case 'h':
339 help_cmd_cat(HELP_LONG);
340 return CMD_SUCCESS;
341 case 'v':
342 printf("%s\n", CAT_VERSION);
343 return CMD_SUCCESS;
344 case 'H':
345 if (!optarg || str_uint64_t(optarg, NULL, 10, false, &head) != EOK ) {
346 puts("Invalid head size\n");
347 return CMD_FAILURE;
348 }
349 break;
350 case 't':
351 if (!optarg || str_uint64_t(optarg, NULL, 10, false, &tail) != EOK ) {
352 puts("Invalid tail size\n");
353 return CMD_FAILURE;
354 }
355 if (head == CAT_FULL_FILE)
356 tailFirst = true;
357 break;
358 case 'b':
359 if (!optarg || str_size_t(optarg, NULL, 10, false, &buffer) != EOK ) {
360 puts("Invalid buffer size\n");
361 return CMD_FAILURE;
362 }
363 break;
364 case 'm':
365 more = true;
366 break;
367 case 'x':
368 hex = true;
369 break;
370 case 's':
371 dash_represents_stdin = true;
372 break;
373 case 'n':
374 number = true;
375 break;
376 }
377 }
378
379 argc -= optind;
380
381 if (argc < 1) {
382 printf("%s - incorrect number of arguments. Try `%s --help'\n",
383 cmdname, cmdname);
384 return CMD_FAILURE;
385 }
386
387 if (buffer < 4)
388 buffer = CAT_DEFAULT_BUFLEN;
389
390 if (more) {
391 rc = console_get_size(console, &cols, &rows);
392 if (rc != EOK) {
393 printf("%s - cannot get console size\n", cmdname);
394 return CMD_FAILURE;
395 }
396 console_cols = cols;
397 console_rows = rows;
398 paging_enabled = true;
399 newpage();
400 }
401
402 for (i = optind; argv[i] != NULL && !should_quit; i++)
403 ret += cat_file(argv[i], buffer, hex, head, tail, tailFirst);
404
405 if (ret)
406 return CMD_FAILURE;
407 else
408 return CMD_SUCCESS;
409}
410
Note: See TracBrowser for help on using the repository browser.