blob: 6312a1a3060c3146f869c87dd4c524ba2a1b9893 [file] [log] [blame]
Shad Ansari2f7f9be2017-06-07 13:34:53 -07001/* linenoise.c -- guerrilla line editing library against the idea that a
2 * line editing lib needs to be 20,000 lines of C code.
3 *
4 * You can find the latest source code at:
5 *
6 * http://github.com/antirez/linenoise
7 *
8 * Does a number of crazy assumptions that happen to be true in 99.9999% of
9 * the 2010 UNIX computers around.
10 *
11 * ------------------------------------------------------------------------
12 *
13 * Copyright (c) 2010-2013, Salvatore Sanfilippo <antirez at gmail dot com>
14 * Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
15 *
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met:
21 *
22 * * Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
24 *
25 * * Redistributions in binary form must reproduce the above copyright
26 * notice, this list of conditions and the following disclaimer in the
27 * documentation and/or other materials provided with the distribution.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 *
41 * ------------------------------------------------------------------------
42 *
43 * References:
44 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
45 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
46 *
47 * Todo list:
48 * - Filter bogus Ctrl+<char> combinations.
49 * - Win32 support
50 *
51 * Bloat:
52 * - History search like Ctrl+r in readline?
53 *
54 * List of escape sequences used by this program, we do everything just
55 * with three sequences. In order to be so cheap we may have some
56 * flickering effect with some slow terminal, but the lesser sequences
57 * the more compatible.
58 *
59 * CHA (Cursor Horizontal Absolute)
60 * Sequence: ESC [ n G
61 * Effect: moves cursor to column n
62 *
63 * EL (Erase Line)
64 * Sequence: ESC [ n K
65 * Effect: if n is 0 or missing, clear from cursor to end of line
66 * Effect: if n is 1, clear from beginning of line to cursor
67 * Effect: if n is 2, clear entire line
68 *
69 * CUF (CUrsor Forward)
70 * Sequence: ESC [ n C
71 * Effect: moves cursor forward of n chars
72 *
73 * When multi line mode is enabled, we also use an additional escape
74 * sequence. However multi line editing is disabled by default.
75 *
76 * CUU (Cursor Up)
77 * Sequence: ESC [ n A
78 * Effect: moves cursor up of n chars.
79 *
80 * CUD (Cursor Down)
81 * Sequence: ESC [ n B
82 * Effect: moves cursor down of n chars.
83 *
84 * The following are used to clear the screen: ESC [ H ESC [ 2 J
85 * This is actually composed of two sequences:
86 *
87 * cursorhome
88 * Sequence: ESC [ H
89 * Effect: moves the cursor to upper left corner
90 *
91 * ED2 (Clear entire screen)
92 * Sequence: ESC [ 2 J
93 * Effect: clear the whole screen
94 *
95 */
96#include <bcmos_system.h>
97#ifndef LINENOISE_DISABLE_TERMIOS
98#include <termios.h>
99#endif
100#ifndef LINENOISE_DISABLE_IOCTL
101#include <sys/ioctl.h>
102#endif
103#include "linenoise.h"
104
105#ifndef STDIN_FILENO
106#define STDIN_FILENO 0
107#endif
108
109#ifndef STDOUT_FILENO
110#define STDOUT_FILENO 1
111#endif
112
113#define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
114#define LINENOISE_MAX_LINE 4096
115
116/* The linenoiseState structure represents the state during line editing.
117 * We pass this state to functions implementing specific editing
118 * functionalities. */
119struct linenoiseState {
120 long ifd; /* Terminal stdin file descriptor. */
121 char *buf; /* Edited line buffer. */
122 int buflen; /* Edited line buffer size. */
123 const char *prompt; /* Prompt to display. */
124 int plen; /* Prompt length. */
125 int pos; /* Current cursor position. */
126 int oldpos; /* Previous refresh cursor position. */
127 int len; /* Current edited line length. */
128 int cols; /* Number of columns in terminal. */
129 int maxrows; /* Maximum num of rows used so far (multiline mode) */
130 int history_index; /* The history index we are currently editing. */
131};
132
133/* Session */
134struct linenoiseSession {
135 struct linenoiseSession *next;
136 struct linenoiseState state;
137 linenoiseSessionIO io;
138 linenoiseCompletionCallback *completionCallback;
139 char *read_ahead_buf;
140 int read_ahead_pos;
141 int history_max_len;
142 int history_len;
143 char **history;
144 int mlmode; /* Multi line mode. Default is single line. */
145 int rawmode; /* For atexit() function to check if restore is needed*/
146#ifndef LINENOISE_DISABLE_TERMIOS
147 struct termios orig_termios; /* In order to restore at exit.*/
148#endif
149 int dumb_terminal;
150 int forced_dumb;
151 int ncolreqs; /* Outstandige get columns requests */
152 void *session_data;
153};
154
155enum KEY_ACTION{
156 KEY_NULL = 0, /* NULL */
157 CTRL_A = 1, /* Ctrl+a */
158 CTRL_B = 2, /* Ctrl-b */
159 CTRL_C = 3, /* Ctrl-c */
160 CTRL_D = 4, /* Ctrl-d */
161 CTRL_E = 5, /* Ctrl-e */
162 CTRL_F = 6, /* Ctrl-f */
163 CTRL_H = 8, /* Ctrl-h */
164 KEY_TAB = 9, /* Tab */
165 CTRL_K = 11, /* Ctrl+k */
166 CTRL_L = 12, /* Ctrl+l */
167 KEY_LF = 10, /* Enter: \n */
168 KEY_CR = 13, /* Enter: \r */
169 CTRL_N = 14, /* Ctrl-n */
170 CTRL_P = 16, /* Ctrl-p */
171 CTRL_T = 20, /* Ctrl-t */
172 CTRL_U = 21, /* Ctrl+u */
173 CTRL_W = 23, /* Ctrl+w */
174 ESC = 27, /* Escape */
175 BACKSPACE = 127 /* Backspace */
176};
177
178static void refreshLine(linenoiseSession *session);
179static void freeHistory(linenoiseSession *session);
180static int linenoiseRaw(linenoiseSession *session, char *buf, size_t buflen, const char *prompt);
181
182/* Debugging macro. */
183/* #define LINENOISE_DEBUG_MODE */
184
185#ifdef LINENOISE_DEBUG_MODE
186#define lndebug(fmt, args...) \
187 do {\
188 bcmos_printf("%s:%d " fmt, __FUNCTION__, __LINE__, ##args);\
189 } while(0)
190#else
191#define lndebug(fmt, ...)
192#endif
193
194
195/* Session list. ToDo: protect update */
196static linenoiseSession *sessions;
197
198/* ======================= Low level terminal handling ====================== */
199
200/* Set if to use or not the multi line mode. */
201void linenoiseSetMultiLine(linenoiseSession *session, int ml) {
202 session->mlmode = ml;
203}
204
205int linenoiseGetMultiLine(linenoiseSession *session) {
206 return session->mlmode;
207}
208
209int linenoiseGetDumbTerminal(linenoiseSession *session) {
210 return session->dumb_terminal;
211}
212
213/* Raw mode: 1960 magic shit. */
214static int enableRawMode(linenoiseSession *session) {
215#ifndef LINENOISE_DISABLE_TERMIOS
216 struct termios raw;
217
218 if (tcgetattr(session->state.ifd, &session->orig_termios) == -1) goto fatal;
219
220 raw = session->orig_termios; /* modify the original mode */
221 /* input modes: no break, no CR to NL, no parity check, no strip char,
222 * no start/stop output control. */
223 raw.c_iflag &= ~(BRKINT | IGNBRK | ICRNL | INPCK | ISTRIP | IXON | IXOFF);
224
225 /* output modes - disable post processing */
226 /* raw.c_oflag &= ~(OPOST); */
227
228 /* control modes - set 8 bit chars */
229 raw.c_cflag |= (CS8 /* | ISIG */);
230
231 /* local modes - echoing off, canonical off, no extended functions,
232 * no signal chars (^Z,^C) */
233 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN);
234 /* control chars - set return condition: min number of bytes and timer.
235 * We want read to return every single byte, without timeout. */
236 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
237
238 /* put terminal in raw mode after flushing */
239 if (tcsetattr(session->state.ifd, TCSAFLUSH, &raw) < 0) goto fatal;
240 session->rawmode = 1;
241 return 0;
242
243fatal:
244 errno = ENOTTY;
245 return -1;
246#else
247 session->rawmode = 1;
248 return 0; /* assume raw mode */
249#endif
250}
251
252static void disableRawMode(linenoiseSession *session) {
253 /* Don't even check the return value as it's too late. */
254#ifndef LINENOISE_DISABLE_TERMIOS
255 if (session->rawmode && tcsetattr(session->state.ifd,TCSAFLUSH,&session->orig_termios) != -1)
256 session->rawmode = 0;
257#endif
258}
259
260
261/* write ESC sequence */
262static int writeEscSequence(linenoiseSession *session, const char *seq, int seq_len)
263{
264 int n;
265 if (!seq_len)
266 seq_len = strlen(seq);
267 n = session->io.write(session->io.fd_out, seq, seq_len);
268 return n;
269}
270
271
272/* Try to get the number of columns in the current terminal, or assume 80
273 * if it fails. */
274static int getColumnsRequest(linenoiseSession *session) {
275 struct linenoiseState *l = &session->state;
276#ifndef LINENOISE_DISABLE_IOCTL
277 struct winsize ws;
278 if (ioctl(1, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0)
279 {
280 l->cols = ws.ws_col;
281 }
282#endif
283 {
284 /* 4 sequences: store position, go to right margin, request position, restore position. */
285 if (writeEscSequence(session, "\x1b" "7" "\x1b" "[999C" "\x1b" "[6n" "\x1b" "8", 14) != 14)
286 goto failed;
287 ++session->ncolreqs;
288 }
289 return l->cols;
290
291failed:
292 lndebug("getColumnsRequest failed: cols=80\n");
293 return 80;
294}
295
296/* Clear the screen. Used to handle ctrl+l */
297void linenoiseClearScreen(linenoiseSession *session) {
298#ifndef LINENOISE_DEBUG_MODE
299 if (writeEscSequence(session, "\x1b[H\x1b[2J", 7) <= 0) {
300 /* nothing to do, just to avoid warning. */
301 }
302#endif
303}
304
305/* Beep, used for completion when there is nothing to complete or when all
306 * the choices were already shown. */
307static void linenoiseBeep(void) {
308 fprintf(stderr, "\x7");
309 fflush(stderr);
310}
311
312static int linenoiseDefaultReadChar(long fd_in, char *c)
313{
314 int n;
315 do {
316 n = read(fd_in, c, 1);
317 } while(!n || (n==1 && ! *c));
318 return n;
319}
320
321static int linenoiseDefaultWrite(long fd_out, const char *buf, size_t len)
322{
323 return write(fd_out, buf, len);
324}
325
326int linenoiseSessionOpen(const linenoiseSessionIO *io, void *session_data, linenoiseSession **session)
327{
328 linenoiseSession *s;
329 if (!io || !session)
330 return -1;
331 s = bcmos_calloc(sizeof(*s));
332 if (!s)
333 return -1;
334 s->history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
335 s->io = *io;
336 s->dumb_terminal = io->dumb_terminal;
337 s->session_data = session_data;
338 *session = s;
339 s->next = sessions;
340 sessions = s;
341
342 if (!s->io.read_char)
343 {
344 s->io.read_char = linenoiseDefaultReadChar;
345 if (!s->io.fd_in)
346 s->io.fd_in = STDIN_FILENO;
347 }
348 if (!s->io.write)
349 {
350 s->io.write = linenoiseDefaultWrite;
351 if (!s->io.fd_out)
352 s->io.fd_out = STDOUT_FILENO;
353 }
354
355 /* IT: temp */
356 s->mlmode = 1;
357 s->state.ifd = STDIN_FILENO;
358
359 return 0;
360}
361
362
363void linenoiseSessionClose(linenoiseSession *session)
364{
365 linenoiseSession *s = sessions, *prev=NULL;
366 while (s && s != session)
367 {
368 prev = s;
369 s = s->next;
370 }
371 if (s)
372 {
373 if (prev)
374 prev->next = s->next;
375 else
376 sessions = s->next;
377 disableRawMode(s);
378 freeHistory(s);
379 if (s->read_ahead_buf)
380 bcmos_free(s->read_ahead_buf);
381 bcmos_free(s);
382 }
383}
384
385void *linenoiseSessionData(linenoiseSession *session) {
386 return session->session_data;
387}
388
389
390void linenoiseSetDumbTerminal(linenoiseSession *session, int dumb) {
391 if (!session->io.dumb_terminal)
392 {
393 session->dumb_terminal = dumb;
394 session->forced_dumb = dumb;
395 }
396}
397
398/* ============================== Completion ================================ */
399
400/* This is an helper function for linenoiseEdit() and is called when the
401 * user types the <tab> key in order to complete the string currently in the
402 * input. It can call linenoiseSetBuffer in order to replace the current edit buffer
403 */
404static void completeLine(linenoiseSession *session) {
405 struct linenoiseState *ls = &session->state;
406
407 if (!session->completionCallback(session, ls->buf, ls->pos))
408 {
409 linenoiseBeep();
410 }
411 refreshLine(session);
412}
413
414/* Register a callback function to be called for tab-completion. */
415void linenoiseSetCompletionCallback(linenoiseSession *session, linenoiseCompletionCallback *fn) {
416 session->completionCallback = fn;
417}
418
419/* This function is used by the callback function registered by the user
420 * in order to add completion options given the input string when the
421 * user typed <tab>. See the example.c source code for a very easy to
422 * understand example. */
423void linenoiseSetBuffer(linenoiseSession *session, const char *buf, int pos)
424{
425 if (!session->state.buf)
426 return;
427 strncpy(session->state.buf, buf, session->state.buflen - 1);
428 session->state.buf[session->state.buflen - 1] = 0;
429 session->state.len = strlen(session->state.buf);
430 session->state.pos = (pos >= 0 && pos < session->state.len) ? pos : session->state.len;
431 refreshLine(session);
432}
433
434/* =========================== Line editing ================================= */
435
436/* We define a very simple "append buffer" structure, that is an heap
437 * allocated string where we can append to. This is useful in order to
438 * write all the escape sequences in a buffer and flush them to the standard
439 * output in a single call, to avoid flickering effects. */
440struct abuf {
441 char *b;
442 int len;
443};
444
445static void abInit(struct abuf *ab) {
446 ab->b = NULL;
447 ab->len = 0;
448}
449
450static void abAppend(struct abuf *ab, const char *s, int len) {
451 char *new = bcmos_alloc(ab->len+len);
452 if (new == NULL) return;
453 memcpy(new,ab->b,ab->len);
454 memcpy(new+ab->len,s,len);
455 bcmos_free(ab->b);
456 ab->b = new;
457 ab->len += len;
458}
459
460static void abFree(struct abuf *ab) {
461 bcmos_free(ab->b);
462}
463
464/* Single line low level cursor refresh.
465 */
466static void refreshCursorSingleLine(linenoiseSession *session) {
467 struct linenoiseState *l = &session->state;
468 char seq[64];
469 size_t plen = strlen(l->prompt);
470 char *buf = l->buf;
471 size_t len = l->len;
472 size_t pos = l->pos;
473 struct abuf ab;
474
475 while((plen+pos) >= l->cols) {
476 buf++;
477 len--;
478 pos--;
479 }
480 while (plen+len > l->cols) {
481 len--;
482 }
483
484 abInit(&ab);
485 /* Cursor to left edge */
486 snprintf(seq,64,"\x1b[999D");
487 abAppend(&ab,seq,strlen(seq));
488 if (pos+plen)
489 {
490 snprintf(seq,64,"\x1b[%dC", (int)(pos+plen));
491 abAppend(&ab,seq,strlen(seq));
492 }
493 if (writeEscSequence(session, ab.b, ab.len) == -1) {} /* Can't recover from write error. */
494 abFree(&ab);
495}
496
497/* Single line low level line refresh.
498 *
499 * Rewrite the currently edited line accordingly to the buffer content,
500 * cursor position, and number of columns of the terminal. */
501static void refreshSingleLine(linenoiseSession *session) {
502 struct linenoiseState *l = &session->state;
503 char seq[64];
504 size_t plen = strlen(l->prompt);
505 char *buf = l->buf;
506 size_t len = l->len;
507 size_t pos = l->pos;
508 struct abuf ab;
509
510 while((plen+pos) >= l->cols) {
511 buf++;
512 len--;
513 pos--;
514 }
515 while (plen+len > l->cols) {
516 len--;
517 }
518
519 abInit(&ab);
520 /* Cursor to left edge */
521 snprintf(seq,64,"\x1b[999D");
522 abAppend(&ab,seq,strlen(seq));
523 /* Write the prompt and the current buffer content */
524 abAppend(&ab,l->prompt,strlen(l->prompt));
525 abAppend(&ab,buf,len);
526 /* Erase to right */
527 snprintf(seq,64,"\x1b[0K");
528 abAppend(&ab,seq,strlen(seq));
529 /* Move cursor to original position. */
530 snprintf(seq,64,"\x1b[999D");
531 abAppend(&ab,seq,strlen(seq));
532 if (pos+plen)
533 {
534 snprintf(seq,64,"\x1b[%dC", (int)(pos+plen));
535 abAppend(&ab,seq,strlen(seq));
536 }
537 if (writeEscSequence(session, ab.b, ab.len) == -1) {} /* Can't recover from write error. */
538 abFree(&ab);
539}
540
541/* Multi line low level cursor position refresh.
542 *
543 * Rewrite the currently edited line accordingly to the buffer content,
544 * cursor position, and number of columns of the terminal. */
545static void refreshCursorMultiLine(linenoiseSession *session) {
546 struct linenoiseState *l = &session->state;
547 char seq[64];
548 int plen = strlen(l->prompt);
549 int old_rpos = (plen+l->oldpos+l->cols)/l->cols; /* cursor relative row. */
550 int new_rpos = (plen+l->pos+l->cols)/l->cols; /* cursor relative row. */
551 int old_cpos = (plen+l->oldpos)%l->cols; /* cursor relative row. */
552 int new_cpos = (plen+l->pos)%l->cols; /* cursor relative row. */
553 struct abuf ab;
554
555 /* Update maxrows if needed. */
556 if (new_rpos > (int)l->maxrows) new_rpos = l->maxrows;
557
558 lndebug("oldp=%d newp=%d or=%d nr=%d oc=%d nc=%d\n\n", l->oldpos, l->pos, old_rpos, new_rpos, old_cpos, new_cpos);
559
560 abInit(&ab);
561
562 /* Handle row */
563 if (new_rpos > old_rpos)
564 {
565 snprintf(seq,64,"\x1b[%dB", new_rpos - old_rpos);
566 abAppend(&ab,seq,strlen(seq));
567 }
568 else if (new_rpos < old_rpos)
569 {
570 snprintf(seq,64,"\x1b[%dA", old_rpos - new_rpos);
571 abAppend(&ab,seq,strlen(seq));
572 }
573
574 /* Handle column */
575 if (new_cpos > old_cpos)
576 {
577 snprintf(seq,64,"\x1b[%dC", new_cpos - old_cpos);
578 abAppend(&ab,seq,strlen(seq));
579 }
580 else if (new_cpos < old_cpos)
581 {
582 snprintf(seq,64,"\x1b[%dD", old_cpos - new_cpos);
583 abAppend(&ab,seq,strlen(seq));
584 }
585
586 l->oldpos = l->pos;
587
588 if (writeEscSequence(session, ab.b, ab.len) == -1) {} /* Can't recover from write error. */
589 abFree(&ab);
590}
591
592/* Multi line low level line refresh.
593 *
594 * Rewrite the currently edited line accordingly to the buffer content,
595 * cursor position, and number of columns of the terminal. */
596static void refreshMultiLine(linenoiseSession *session) {
597 struct linenoiseState *l = &session->state;
598 char seq[64];
599 int plen = strlen(l->prompt);
600 int rows = (plen+l->len+l->cols-1)/l->cols; /* rows used by current buf. */
601 int rpos = (plen+l->oldpos+l->cols)/l->cols; /* cursor relative row. */
602 int rpos2; /* rpos after refresh. */
603 int old_rows = l->maxrows;
604 int pos;
605 int j;
606 struct abuf ab;
607
608 /* Update maxrows if needed. */
609 if (rows > (int)l->maxrows) l->maxrows = rows;
610
611 /* First step: clear all the lines used before. To do so start by
612 * going to the last row. */
613 abInit(&ab);
614 if (old_rows-rpos > 0) {
615 lndebug("go down %d", old_rows-rpos);
616 snprintf(seq,64,"\x1b[%dB", old_rows-rpos);
617 abAppend(&ab,seq,strlen(seq));
618 }
619
620 /* Now for every row clear it, go up. */
621 for (j = 0; j < old_rows-1; j++) {
622 lndebug("clear+up");
623 snprintf(seq,64,"\x1b[999D\x1b[0K\x1b[1A");
624 abAppend(&ab,seq,strlen(seq));
625 }
626
627 /* Clean the top line. */
628 lndebug("clear");
629 snprintf(seq,64,"\x1b[999D\x1b[0K");
630 abAppend(&ab,seq,strlen(seq));
631
632 /* Write the prompt and the current buffer content */
633 abAppend(&ab,l->prompt,strlen(l->prompt));
634 abAppend(&ab,l->buf,l->len);
635
636 /* If we are at the very end of the screen with our prompt, we need to
637 * emit a newline and move the prompt to the first column. */
638 if (l->pos &&
639 l->pos == l->len &&
640 (l->pos+plen) % l->cols == 0)
641 {
642 lndebug("<newline>");
643 abAppend(&ab,"\n",1);
644 snprintf(seq,64,"\x1b[999D");
645 abAppend(&ab,seq,strlen(seq));
646 rows++;
647 if (rows > (int)l->maxrows) l->maxrows = rows;
648 }
649
650 /* Move cursor to right position. */
651 rpos2 = (plen+l->pos+l->cols)/l->cols; /* current cursor relative row. */
652 lndebug("rpos2 %d", rpos2);
653
654 /* Go up till we reach the expected positon. */
655 if (rows-rpos2 > 0) {
656 lndebug("go-up %d", rows-rpos2);
657 snprintf(seq,64,"\x1b[%dA", rows-rpos2);
658 abAppend(&ab,seq,strlen(seq));
659 }
660
661 /* Set column. */
662 lndebug("set col %d", 1+((plen+(int)l->pos) % (int)l->cols));
663 snprintf(seq,64,"\x1b[999D");
664 abAppend(&ab,seq,strlen(seq));
665 pos = ((plen+(int)l->pos) % (int)l->cols);
666 if (pos)
667 {
668 snprintf(seq,64,"\x1b[%dC", pos);
669 abAppend(&ab,seq,strlen(seq));
670 }
671 lndebug("\n");
672 l->oldpos = l->pos;
673
674 if (writeEscSequence(session, ab.b, ab.len) == -1) {} /* Can't recover from write error. */
675 abFree(&ab);
676
677 lndebug(" - out\n");
678}
679
680/* Calls the two low level functions refreshCursorSingleLine() or
681 * refreshCursorMultiLine() according to the selected mode. */
682static void refreshCursor(linenoiseSession *session) {
683 if (session->mlmode)
684 refreshCursorMultiLine(session);
685 else
686 refreshCursorSingleLine(session);
687}
688
689/* Calls the two low level functions refreshSingleLine() or
690 * refreshMultiLine() according to the selected mode. */
691static void refreshLine(linenoiseSession *session) {
692 if (session->mlmode)
693 refreshMultiLine(session);
694 else
695 refreshSingleLine(session);
696}
697
698/* Insert the character 'c' at cursor current position.
699 *
700 * On error writing to the terminal -1 is returned, otherwise 0. */
701static int linenoiseEditInsert(linenoiseSession *session, char c) {
702 struct linenoiseState *l = &session->state;
703 if (l->len < l->buflen) {
704 if (l->len == l->pos) {
705 int plen = strlen(l->prompt);
706 int rows = (plen+l->len+l->cols)/l->cols;
707
708 l->buf[l->pos] = c;
709 l->pos++;
710 l->len++;
711 l->buf[l->len] = '\0';
712 lndebug(" plen=%d len=%d pos=%d cols=%d buf=<%s>\n",
713 (int)l->plen, (int)l->len, (int)l->pos, (int)l->cols, l->buf);
714 if (session->io.write(session->io.fd_out, &c, 1) == -1) return -1;
715 l->oldpos = l->pos;
716 l->maxrows = rows;
717 } else {
718 memmove(l->buf+l->pos+1,l->buf+l->pos,l->len-l->pos);
719 l->buf[l->pos] = c;
720 l->len++;
721 l->pos++;
722 l->buf[l->len] = '\0';
723 lndebug(" plen=%d len=%d pos=%d cols=%d buf=<%s>\n",
724 l->plen, l->len, l->pos, l->cols, l->buf);
725 refreshLine(session);
726 }
727 }
728 return 0;
729}
730
731/* Move cursor on the left. */
732static void linenoiseEditMoveLeft(linenoiseSession *session) {
733 struct linenoiseState *l = &session->state;
734 if (l->pos > 0) {
735 l->pos--;
736 refreshCursor(session);
737 }
738}
739
740/* Move cursor on the right. */
741static void linenoiseEditMoveRight(linenoiseSession *session) {
742 struct linenoiseState *l = &session->state;
743 if (l->pos != l->len) {
744 l->pos++;
745 refreshCursor(session);
746 }
747}
748
749/* Move cursor to the start of the line. */
750static void linenoiseEditMoveHome(linenoiseSession *session) {
751 struct linenoiseState *l = &session->state;
752 if (l->pos != 0) {
753 l->pos = 0;
754 refreshCursor(session);
755 }
756}
757
758/* Move cursor to the end of the line. */
759static void linenoiseEditMoveEnd(linenoiseSession *session) {
760 struct linenoiseState *l = &session->state;
761 if (l->pos != l->len) {
762 l->pos = l->len;
763 refreshCursor(session);
764 }
765}
766
767/* strdup implementation */
768static inline char *linenoise_strdup(const char *s)
769{
770 size_t size = strlen(s) + 1;
771 char *new = bcmos_alloc(size);
772 if (new)
773 memcpy(new, s, size);
774 return new;
775}
776
777/* Substitute the currently edited line with the next or previous history
778 * entry as specified by 'dir'. */
779#define LINENOISE_HISTORY_NEXT 0
780#define LINENOISE_HISTORY_PREV 1
781static void linenoiseEditHistoryNext(linenoiseSession *session, int dir) {
782 struct linenoiseState *l = &session->state;
783 if (session->history_len > 1) {
784 /* Update the current history entry before to
785 * overwrite it with the next one. */
786 bcmos_free(session->history[session->history_len - 1 - l->history_index]);
787 session->history[session->history_len - 1 - l->history_index] = linenoise_strdup(l->buf);
788 /* Show the new entry */
789 l->history_index += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1;
790 if (l->history_index < 0) {
791 l->history_index = 0;
792 return;
793 } else if (l->history_index >= session->history_len) {
794 l->history_index = session->history_len-1;
795 return;
796 }
797 strncpy(l->buf,session->history[session->history_len - 1 - l->history_index],l->buflen);
798 l->buf[l->buflen-1] = '\0';
799 l->len = l->pos = strlen(l->buf);
800 refreshLine(session);
801 }
802}
803
804/* Delete the character at the right of the cursor without altering the cursor
805 * position. Basically this is what happens with the "Delete" keyboard key. */
806static void linenoiseEditDelete(linenoiseSession *session) {
807 struct linenoiseState *l = &session->state;
808 if (l->len > 0 && l->pos < l->len) {
809 memmove(l->buf+l->pos,l->buf+l->pos+1,l->len-l->pos-1);
810 l->len--;
811 l->buf[l->len] = '\0';
812 refreshLine(session);
813 }
814}
815
816/* Backspace implementation. */
817static void linenoiseEditBackspace(linenoiseSession *session) {
818 struct linenoiseState *l = &session->state;
819 if (l->pos > 0 && l->len > 0) {
820 memmove(l->buf+l->pos-1,l->buf+l->pos,l->len-l->pos);
821 l->pos--;
822 l->len--;
823 l->buf[l->len] = '\0';
824 refreshLine(session);
825 }
826}
827
828/* Delete the previosu word, maintaining the cursor at the start of the
829 * current word. */
830static void linenoiseEditDeletePrevWord(linenoiseSession *session) {
831 struct linenoiseState *l = &session->state;
832 size_t old_pos = l->pos;
833 size_t diff;
834
835 while (l->pos > 0 && l->buf[l->pos-1] == ' ')
836 l->pos--;
837 while (l->pos > 0 && l->buf[l->pos-1] != ' ')
838 l->pos--;
839 diff = old_pos - l->pos;
840 memmove(l->buf+l->pos,l->buf+old_pos,l->len-old_pos+1);
841 l->len -= diff;
842 refreshLine(session);
843}
844
845static int linenoiseReadChar(linenoiseSession *session, char *c)
846{
847 int n;
848
849 do {
850 if (session->read_ahead_buf)
851 {
852 *c = session->read_ahead_buf[session->read_ahead_pos++];
853 lndebug("read char from buf %d(%c)\n", *c, *c);
854 if (*c)
855 return 1;
856 bcmos_free(session->read_ahead_buf);
857 session->read_ahead_buf = NULL;
858 /* Fall through */
859 }
860 n = session->io.read_char(session->io.fd_in, c);
861 } while (!n || (n == 1 && ! *c));
862 lndebug("read char from io %d(%c) n=%d\n", *c, *c, n);
863 return n;
864}
865
866static int linenoiseHandleEscSequence(linenoiseSession *session)
867{
868 struct linenoiseState *l = &session->state;
869 char seq[32];
870
871 /* Read the next two bytes representing the escape sequence.
872 * Use two calls to handle slow terminals returning the two
873 * chars at different times. */
874 if (linenoiseReadChar(session, seq) == -1) return -1;
875 if (linenoiseReadChar(session, seq+1) == -1) return -1;
876 lndebug("seq=%02x(%c) seq1=%02x(%c)\n", seq[0], seq[0], seq[1], seq[1]);
877
878 /* ESC [ sequences. */
879 if (seq[0] == '[') {
880 if (seq[1] >= '0' && seq[1] <= '9') {
881 int n = 2;
882 char terminator = 0;
883
884 /* Extended escape, read additional byte(s) */
885 while (linenoiseReadChar(session, seq+n) != -1 && n < sizeof(seq) - 1)
886 {
887 terminator = seq[n++];
888 if ( !(terminator >= '0' && terminator <= '9') && terminator != ';')
889 break;
890 }
891 seq[n] = 0;
892 switch (terminator ) {
893 case '~':
894 linenoiseEditDelete(session);
895 break;
896 case 'R':
897 {
898 int row, col;
899 /* Position report */
900 seq[n-1] = 0; /* Cut R */
901 sscanf(seq+1, "%d;%d", &row, &col);
902 l->cols = col;
903 session->ncolreqs = 0;
904 lndebug("position report row=%d col=%d\n", row, col);
905 }
906 default:
907 break;
908 }
909 } else {
910 switch(seq[1]) {
911 case 'A': /* Up */
912 linenoiseEditHistoryNext(session, LINENOISE_HISTORY_PREV);
913 break;
914 case 'B': /* Down */
915 linenoiseEditHistoryNext(session, LINENOISE_HISTORY_NEXT);
916 break;
917 case 'C': /* Right */
918 linenoiseEditMoveRight(session);
919 break;
920 case 'D': /* Left */
921 linenoiseEditMoveLeft(session);
922 break;
923 case 'H': /* Home */
924 linenoiseEditMoveHome(session);
925 break;
926 case 'F': /* End*/
927 linenoiseEditMoveEnd(session);
928 break;
929 default:
930 break;
931 }
932 }
933 }
934
935 /* ESC O sequences. */
936 else if (seq[0] == 'O') {
937 switch(seq[1]) {
938 case 'H': /* Home */
939 linenoiseEditMoveHome(session);
940 break;
941 case 'F': /* End*/
942 linenoiseEditMoveEnd(session);
943 break;
944 default:
945 break;
946 }
947 }
948 return 0;
949}
950
951/* This function is the core of the line editing capability of linenoise.
952 * It expects 'fd' to be already in "raw mode" so that every key pressed
953 * will be returned ASAP to read().
954 *
955 * The resulting string is put into 'buf' when the user type enter, or
956 * when ctrl+d is typed.
957 *
958 * The function returns the length of the current buffer. */
959static int linenoiseEdit(linenoiseSession *session, char *buf, size_t buflen, const char *prompt)
960{
961 struct linenoiseState *l = &session->state;
962 int nread = 0;
963
964 /* Populate the linenoise state that we pass to functions implementing
965 * specific editing functionalities. */
966 l->buf = buf;
967 l->buflen = buflen;
968 l->prompt = prompt;
969 l->plen = strlen(prompt);
970 l->oldpos = l->pos = 0;
971 l->len = 0;
972 if (!l->cols)
973 l->cols = 80;
974 getColumnsRequest(session);
975 l->maxrows = 0;
976 l->history_index = 0;
977
978 /* Buffer starts empty. */
979 l->buf[0] = '\0';
980 l->buflen--; /* Make sure there is always space for the nulterm */
981
982 /* The latest history entry is always our current buffer, that
983 * initially is just an empty string. */
984 linenoiseHistoryAdd(session, "");
985 if (l->plen && session->io.write(session->io.fd_out, prompt, l->plen) == -1) return -1;
986 while(1) {
987 char c;
988
989 nread = linenoiseReadChar(session, &c);
990 if (nread <= 0) goto edit_out;
991
992 lndebug("c=%02x(%c)\n", c, c);
993 /* Only autocomplete when the callback is set. It returns < 0 when
994 * there was an error reading from fd. Otherwise it will return the
995 * character that should be handled next. */
996 if (c == KEY_TAB && session->completionCallback != NULL) {
997 completeLine(session);
998 continue;
999 }
1000
1001 switch(c) {
1002 case KEY_CR: /* enter */
1003 case KEY_LF: /* enter */
1004 session->history_len--;
1005 bcmos_free(session->history[session->history_len]);
1006 goto edit_out;
1007 case CTRL_C: /* ctrl-c */
1008 return -1;
1009 case BACKSPACE: /* backspace */
1010 case 8: /* ctrl-h */
1011 linenoiseEditBackspace(session);
1012 break;
1013 case CTRL_D: /* ctrl-d, remove char at right of cursor, or of the
1014 line is empty, act as end-of-file. */
1015 if (l->len > 0) {
1016 linenoiseEditDelete(session);
1017 } else {
1018 session->history_len--;
1019 bcmos_free(session->history[session->history_len]);
1020 return -1;
1021 }
1022 break;
1023 case CTRL_T: /* ctrl-t, swaps current character with previous. */
1024 if (l->pos > 0 && l->pos < l->len) {
1025 int aux = buf[l->pos-1];
1026 buf[l->pos-1] = buf[l->pos];
1027 buf[l->pos] = aux;
1028 if (l->pos != l->len-1) l->pos++;
1029 refreshLine(session);
1030 }
1031 break;
1032 case CTRL_B: /* ctrl-b */
1033 linenoiseEditMoveLeft(session);
1034 break;
1035 case CTRL_F: /* ctrl-f */
1036 linenoiseEditMoveRight(session);
1037 break;
1038 case CTRL_P: /* ctrl-p */
1039 linenoiseEditHistoryNext(session, LINENOISE_HISTORY_PREV);
1040 break;
1041 case CTRL_N: /* ctrl-n */
1042 linenoiseEditHistoryNext(session, LINENOISE_HISTORY_NEXT);
1043 break;
1044 case ESC: /* escape sequence */
1045 linenoiseHandleEscSequence(session);
1046 break;
1047 default:
1048 if (linenoiseEditInsert(session,c))
1049 {
1050 lndebug("editInsert failed\n");
1051 return -1;
1052 };
1053 break;
1054 case CTRL_U: /* Ctrl+u, delete the whole line. */
1055 buf[0] = '\0';
1056 l->pos = l->len = 0;
1057 refreshLine(session);
1058 break;
1059 case CTRL_K: /* Ctrl+k, delete from current to end of line. */
1060 buf[l->pos] = '\0';
1061 l->len = l->pos;
1062 refreshLine(session);
1063 break;
1064 case CTRL_A: /* Ctrl+a, go to the start of the line */
1065 linenoiseEditMoveHome(session);
1066 break;
1067 case CTRL_E: /* ctrl+e, go to the end of the line */
1068 linenoiseEditMoveEnd(session);
1069 break;
1070 case CTRL_L: /* ctrl+l, clear screen */
1071 linenoiseClearScreen(session);
1072 refreshLine(session);
1073 break;
1074 case CTRL_W: /* ctrl+w, delete previous word */
1075 linenoiseEditDeletePrevWord(session);
1076 break;
1077 }
1078 }
1079edit_out:
1080 lndebug(" - out. len=%d buf=<%s>\n", l->len, buf);
1081 return (nread >= 0) ? l->len : -1;
1082}
1083
1084/* Get without editing */
1085static int linenoiseNoedit(linenoiseSession *session, char *buf, size_t buflen) {
1086 char c;
1087 int len = 0;
1088 int switch_to_smart_mode = 0;
1089 int nread = 0;
1090#ifndef LINENOISE_DISABLE_TERMIOS
1091 int atty_term = isatty(STDIN_FILENO);
1092#else
1093 int atty_term = 1;
1094#endif
1095
1096 while ((nread = linenoiseReadChar(session, &c)) != -1 && len < buflen - 1)
1097 {
1098 if (c == '\n' || c == '\r')
1099 break;
1100 buf[len++] = c;
1101 /* If buffer contains ESC sequence - perhaps the terminal is not dumb after all */
1102 if (c == ESC && !session->io.dumb_terminal && !session->forced_dumb && atty_term)
1103 {
1104 switch_to_smart_mode = 1;
1105 break;
1106 }
1107 /* Echo here is terminal is in raw mode */
1108 if (session->rawmode)
1109 {
1110 session->io.write(session->io.fd_out, &c, 1);
1111 }
1112 }
1113 buf[len] = 0;
1114 if (switch_to_smart_mode)
1115 {
1116 /* Copy buffer into read-ahead buffer and re-parse */
1117 lndebug("switching to smart mode\n");
1118 /* If there already is read_ahead buf - realloc it */
1119 if (session->read_ahead_buf)
1120 {
1121 char *new_buf;
1122 new_buf = bcmos_alloc(strlen(session->read_ahead_buf) - session->read_ahead_pos + len + 1);
1123 if (!new_buf)
1124 return -1;
1125 memcpy(new_buf, buf, len);
1126 strcpy(&new_buf[len], &session->read_ahead_buf[session->read_ahead_pos]);
1127 bcmos_free(session->read_ahead_buf);
1128 session->read_ahead_buf = new_buf;
1129 }
1130 else
1131 {
1132 session->read_ahead_buf = bcmos_alloc(len + 1);
1133 if (!session->read_ahead_buf)
1134 return -1;
1135 strcpy(session->read_ahead_buf, buf);
1136 }
1137 session->read_ahead_pos = 0;
1138 session->dumb_terminal = 0;
1139 session->ncolreqs = 0;
1140 *buf = 0;
1141 nread = linenoiseEdit(session, buf, buflen, "");
1142 }
1143 lndebug(" - out. len=%d buf=<%s> nread=%d\n", (int)strlen(buf), buf, nread);
1144 return (nread >=0) ? strlen(buf) : -1;
1145}
1146
1147
1148/* This function calls the line editing function linenoiseEdit() using
1149 * the STDIN file descriptor set in raw mode. */
1150static int linenoiseRaw(linenoiseSession *session, char *buf, size_t buflen, const char *prompt) {
1151 int rc = 0;
1152
1153 lndebug("\n");
1154#ifndef LINENOISE_DISABLE_TERMIOS
1155 if (!isatty(STDIN_FILENO)) {
1156 /* Not a tty: read from file / pipe. */
1157 rc = linenoiseNoedit(session, buf, buflen);
1158 if (rc >= 0)
1159 session->io.write(session->io.fd_out, "\n", 1);
1160 }
1161 else
1162#endif
1163 {
1164 /* Interactive editing. */
1165 if (enableRawMode(session) == -1) return -1;
1166
1167 if (!session->dumb_terminal && session->ncolreqs > 1)
1168 {
1169 session->dumb_terminal = 1;
1170 lndebug("dumb_terminal=%d\n", session->dumb_terminal);
1171 }
1172 if (session->dumb_terminal) {
1173 session->io.write(session->io.fd_out, prompt, strlen(prompt));
1174 rc = linenoiseNoedit(session, buf, buflen);
1175 } else {
1176 rc = linenoiseEdit(session, buf, buflen, prompt);
1177 }
1178
1179 disableRawMode(session);
1180 if (rc >= 0)
1181 session->io.write(session->io.fd_out, "\n", 1);
1182 }
1183 lndebug(" - out. len=%d buf=<%s> rc=%d\n", (int)strlen(buf), buf, rc);
1184 return rc;
1185}
1186
1187/* The high level function that is the main API of the linenoise library.
1188 * This function checks if the terminal has basic capabilities, just checking
1189 * for a blacklist of stupid terminals, and later either calls the line
1190 * editing function or uses dummy fgets() so that you will be able to type
1191 * something even in the most desperate of the conditions. */
1192char *linenoise(linenoiseSession *session, const char *prompt, char *buf, size_t size) {
1193
1194 if (size == 0) {
1195 errno = EINVAL;
1196 return NULL;
1197 }
1198
1199 /* Configure terminal as dumb if it doesn't support basic ESC sequences */
1200 if (session->io.dumb_terminal || session->forced_dumb) {
1201 int rc;
1202
1203 session->io.write(session->io.fd_out, prompt, strlen(prompt));
1204 rc = linenoiseNoedit(session, buf, size);
1205 session->io.write(session->io.fd_out, "\n", 1);
1206 lndebug(" - out. len=%d buf=<%s>\n", (int)strlen(buf), buf);
1207 return (rc == -1) ? NULL : buf;
1208 } else {
1209 if (linenoiseRaw(session, buf, size, prompt) == -1) return NULL;
1210 lndebug(" - out. len=%d buf=<%s>\n", (int)strlen(buf), buf);
1211 return buf;
1212 }
1213}
1214
1215/* ================================ History ================================= */
1216
1217/* Free the history, but does not reset it. Only used when we have to
1218 * exit() to avoid memory leaks are reported by valgrind & co. */
1219static void freeHistory(linenoiseSession *session) {
1220 if (session->history) {
1221 int j;
1222
1223 for (j = 0; j < session->history_len; j++)
1224 bcmos_free(session->history[j]);
1225 bcmos_free(session->history);
1226 session->history = NULL;
1227 }
1228}
1229
1230/* This is the API call to add a new entry in the linenoise history.
1231 * It uses a fixed array of char pointers that are shifted (memmoved)
1232 * when the history max length is reached in order to remove the older
1233 * entry and make room for the new one, so it is not exactly suitable for huge
1234 * histories, but will work well for a few hundred of entries.
1235 *
1236 * Using a circular buffer is smarter, but a bit more complex to handle. */
1237int linenoiseHistoryAdd(linenoiseSession *session, const char *line) {
1238 char *linecopy;
1239
1240 if (session->history_max_len == 0) return 0;
1241
1242 /* Initialization on first call. */
1243 if (session->history == NULL) {
1244 session->history = bcmos_alloc(sizeof(char*)*session->history_max_len);
1245 if (session->history == NULL) return 0;
1246 memset(session->history,0,(sizeof(char*)*session->history_max_len));
1247 }
1248
1249 /* Don't add duplicated lines. */
1250 if (session->history_len && !strcmp(session->history[session->history_len-1], line)) return 0;
1251
1252 /* Add an heap allocated copy of the line in the history.
1253 * If we reached the max length, remove the older line. */
1254 linecopy = linenoise_strdup(line);
1255 if (!linecopy) return 0;
1256 if (session->history_len == session->history_max_len) {
1257 bcmos_free(session->history[0]);
1258 memmove(session->history,session->history+1,sizeof(char*)*(session->history_max_len-1));
1259 session->history_len--;
1260 }
1261 session->history[session->history_len] = linecopy;
1262 session->history_len++;
1263 return 1;
1264}
1265
1266/* Set the maximum length for the history. This function can be called even
1267 * if there is already some history, the function will make sure to retain
1268 * just the latest 'len' elements if the new history length value is smaller
1269 * than the amount of items already inside the history. */
1270int linenoiseHistorySetMaxLen(linenoiseSession *session, int len) {
1271 char **new;
1272
1273 if (len < 1) return 0;
1274 if (session->history) {
1275 int tocopy = session->history_len;
1276
1277 new = bcmos_alloc(sizeof(char*)*len);
1278 if (new == NULL) return 0;
1279
1280 /* If we can't copy everything, free the elements we'll not use. */
1281 if (len < tocopy) {
1282 int j;
1283
1284 for (j = 0; j < tocopy-len; j++) bcmos_free(session->history[j]);
1285 tocopy = len;
1286 }
1287 memset(new,0,sizeof(char*)*len);
1288 memcpy(new,session->history+(session->history_len-tocopy), sizeof(char*)*tocopy);
1289 bcmos_free(session->history);
1290 session->history = new;
1291 }
1292 session->history_max_len = len;
1293 if (session->history_len > session->history_max_len)
1294 session->history_len = session->history_max_len;
1295 return 1;
1296}
1297
1298int linenoiseSetRaw(linenoiseSession *session, int raw)
1299{
1300 int rc = 0;
1301 if (raw)
1302 rc = enableRawMode(session);
1303 else
1304 disableRawMode(session);
1305 return rc;
1306}
1307
1308int linenoiseGetRaw(linenoiseSession *session)
1309{
1310 return session->rawmode;
1311}
1312
1313#ifndef LINENOISE_DISABLE_HIST_SAVE
1314
1315/* Save the history in the specified file. On success 0 is returned
1316 * otherwise -1 is returned. */
1317int linenoiseHistorySave(linenoiseSession *session, const char *filename) {
1318 FILE *fp = fopen(filename,"w");
1319 int j;
1320
1321 if (fp == NULL) return -1;
1322 for (j = 0; j < session->history_len; j++)
1323 fprintf(fp,"%s\n",session->history[j]);
1324 fclose(fp);
1325 return 0;
1326}
1327
1328/* Load the history from the specified file. If the file does not exist
1329 * zero is returned and no operation is performed.
1330 *
1331 * If the file exists and the operation succeeded 0 is returned, otherwise
1332 * on error -1 is returned. */
1333int linenoiseHistoryLoad(linenoiseSession *session, const char *filename) {
1334 FILE *fp = fopen(filename,"r");
1335 char *buf;
1336
1337 if (fp == NULL) return -1;
1338 buf = bcmos_alloc(LINENOISE_MAX_LINE);
1339 if (!buf)
1340 {
1341 fclose(fp);
1342 return -1;
1343 }
1344
1345 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1346 char *p;
1347
1348 p = strchr(buf,'\r');
1349 if (!p) p = strchr(buf,'\n');
1350 if (p) *p = '\0';
1351 linenoiseHistoryAdd(session, buf);
1352 }
1353 fclose(fp);
1354 bcmos_free(buf);
1355 return 0;
1356}
1357
1358#endif