Esempio n. 1
0
int main(int argc, char **argv) {
    int forkres;
    int master, slave;

    /* Get subtest number */
    if(argc != 2) {
        printf("Usage: %s subtest_no\n", argv[0]);
        exit(-1);
    } else if(sscanf(argv[1], "%d", &subtest) != 1) {
        printf("Usage: %s subtest_no\n", argv[0]);
        exit(-1);
    }

    open_terminal(&master, &slave);

    forkres = fork();
    if(forkres == 0) do_child(master);
    else if(forkres > 0)  do_parent(forkres, slave);
    else { /* Fork failed */
        perror("Unable to fork");
        exit(-1);
    }

    exit(-2); /* We're not supposed to get here. Both do_* routines should exit*/

}
Esempio n. 2
0
int main(int argc, char* argv[])
{
	if(argc<2)
	{
                printf("Argument is not correct\n");
		return 0;
	}
	int fd = open_port(argv[1]);
	int fd_tty = open_terminal();
	configure_port(fd);
	configure_terminal(fd_tty);
	char rec=' ',rec_tty=' ';
	while(fd!=-1 && fd_tty!=-1)
	{
		int data=read(fd,&rec,1);
		int data_tty=read(fd_tty,&rec_tty,1);
		if(data>0)
			printf("%c",rec);
		if(data_tty>0)
                        printf("%c",rec_tty);
		if(rec_tty=='q')
			break;
		rec=' ';rec_tty=' ';
	}
	close(fd);
	close(fd_tty);	
	return(0);
}
Esempio n. 3
0
/*
 * A newly allocated VT uses the font from the active VT. Here
 * we update all possibly already allocated VTs with the configured
 * font. It also allows to restart systemd-vconsole-setup.service,
 * to apply a new font to all VTs.
 */
static void font_copy_to_all_vcs(int fd) {
        struct vt_stat vcs = {};
        unsigned char map8[E_TABSZ];
        unsigned short map16[E_TABSZ];
        struct unimapdesc unimapd;
        struct unipair unipairs[USHRT_MAX];
        int i, r;

        /* get active, and 16 bit mask of used VT numbers */
        r = ioctl(fd, VT_GETSTATE, &vcs);
        if (r < 0)
                return;

        for (i = 1; i <= 15; i++) {
                char vcname[16];
                _cleanup_close_ int vcfd = -1;
                struct console_font_op cfo = {};

                if (i == vcs.v_active)
                        continue;

                /* skip non-allocated ttys */
                snprintf(vcname, sizeof(vcname), "/dev/vcs%i", i);
                if (access(vcname, F_OK) < 0)
                        continue;

                snprintf(vcname, sizeof(vcname), "/dev/tty%i", i);
                vcfd = open_terminal(vcname, O_RDWR|O_CLOEXEC);
                if (vcfd < 0)
                        continue;

                /* copy font from active VT, where the font was uploaded to */
                cfo.op = KD_FONT_OP_COPY;
                cfo.height = vcs.v_active-1; /* tty1 == index 0 */
                ioctl(vcfd, KDFONTOP, &cfo);

                /* copy map of 8bit chars */
                if (ioctl(fd, GIO_SCRNMAP, map8) >= 0)
                    ioctl(vcfd, PIO_SCRNMAP, map8);

                /* copy map of 8bit chars -> 16bit Unicode values */
                if (ioctl(fd, GIO_UNISCRNMAP, map16) >= 0)
                    ioctl(vcfd, PIO_UNISCRNMAP, map16);

                /* copy unicode translation table */
                /* unimapd is a ushort count and a pointer to an
                   array of struct unipair { ushort, ushort } */
                unimapd.entries  = unipairs;
                unimapd.entry_ct = USHRT_MAX;
                if (ioctl(fd, GIO_UNIMAP, &unimapd) >= 0) {
                        struct unimapinit adv = { 0, 0, 0 };

                        ioctl(vcfd, PIO_UNIMAPCLR, &adv);
                        ioctl(vcfd, PIO_UNIMAP, &unimapd);
                }
        }
}
Esempio n. 4
0
int reset_terminal(const char *name) {
        _cleanup_close_ int fd = -1;

        fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
        if (fd < 0)
                return fd;

        return reset_terminal_fd(fd, true);
}
Esempio n. 5
0
int terminal_vhangup(const char *name) {
        _cleanup_close_ int fd;

        fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
        if (fd < 0)
                return fd;

        return terminal_vhangup_fd(fd);
}
Esempio n. 6
0
int reset_terminal(const char *name) {
        _cleanup_close_ int fd = -1;

        /* We open the terminal with O_NONBLOCK here, to ensure we
         * don't block on carrier if this is a terminal with carrier
         * configured. */

        fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
        if (fd < 0)
                return fd;

        return reset_terminal_fd(fd, true);
}
Esempio n. 7
0
static int log_open_console(void) {

        if (console_fd >= 0)
                return 0;

        if (getpid() == 1) {
                console_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
                if (console_fd < 0)
                        return console_fd;
        } else
                console_fd = STDERR_FILENO;

        return 0;
}
Esempio n. 8
0
static int log_open_console(void) {

        if (console_fd >= 0)
                return 0;

        if (getpid() == 1) {

                console_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
                if (console_fd < 0) {
                        log_error("Failed to open /dev/console for logging: %s", strerror(-console_fd));
                        return console_fd;
                }

                log_debug("Successfully opened /dev/console for logging.");
        } else
                console_fd = STDERR_FILENO;

        return 0;
}
Esempio n. 9
0
/*
 * A newly allocated VT uses the font from the active VT. Here
 * we update all possibly already allocated VTs with the configured
 * font. It also allows to restart systemd-vconsole-setup.service,
 * to apply a new font to all VTs.
 */
static void font_copy_to_all_vcs(int fd) {
        struct vt_stat vcs;
        int i;
        int r;

        /* get active, and 16 bit mask of used VT numbers */
        zero(vcs);
        r = ioctl(fd, VT_GETSTATE, &vcs);
        if (r < 0)
                return;

        for (i = 1; i <= 15; i++) {
                char vcname[16];
                int vcfd;
                struct console_font_op cfo;

                if (i == vcs.v_active)
                        continue;

                /* skip non-allocated ttys */
                snprintf(vcname, sizeof(vcname), "/dev/vcs%i", i);
                if (access(vcname, F_OK) < 0)
                        continue;

                snprintf(vcname, sizeof(vcname), "/dev/tty%i", i);
                vcfd = open_terminal(vcname, O_RDWR|O_CLOEXEC);
                if (vcfd < 0)
                        continue;

                /* copy font from active VT, where the font was uploaded to */
                zero(cfo);
                cfo.op = KD_FONT_OP_COPY;
                cfo.height = vcs.v_active-1; /* tty1 == index 0 */
                ioctl(vcfd, KDFONTOP, &cfo);

                close_nointr_nofail(vcfd);
        }
}
Esempio n. 10
0
int chvt(int vt) {
        _cleanup_close_ int fd;

        fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
        if (fd < 0)
                return -errno;

        if (vt <= 0) {
                int tiocl[2] = {
                        TIOCL_GETKMSGREDIRECT,
                        0
                };

                if (ioctl(fd, TIOCLINUX, tiocl) < 0)
                        return -errno;

                vt = tiocl[0] <= 0 ? 1 : tiocl[0];
        }

        if (ioctl(fd, VT_ACTIVATE, vt) < 0)
                return -errno;

        return 0;
}
Esempio n. 11
0
int main(int argc, char **argv) {
        const char *vc;
        char *vc_keymap = NULL;
        char *vc_keymap_toggle = NULL;
        char *vc_font = NULL;
        char *vc_font_map = NULL;
        char *vc_font_unimap = NULL;
        int fd = -1;
        bool utf8;
        pid_t font_pid = 0, keymap_pid = 0;
        bool font_copy = false;
        int r = EXIT_FAILURE;

        log_set_target(LOG_TARGET_AUTO);
        log_parse_environment();
        log_open();

        umask(0022);

        if (argv[1])
                vc = argv[1];
        else {
                vc = "/dev/tty0";
                font_copy = true;
        }

        fd = open_terminal(vc, O_RDWR|O_CLOEXEC);
        if (fd < 0) {
                log_error("Failed to open %s: %m", vc);
                goto finish;
        }

        if (!is_vconsole(fd)) {
                log_error("Device %s is not a virtual console.", vc);
                goto finish;
        }

        utf8 = is_locale_utf8();

        r = parse_env_file("/etc/vconsole.conf", NEWLINE,
                           "KEYMAP", &vc_keymap,
                           "KEYMAP_TOGGLE", &vc_keymap_toggle,
                           "FONT", &vc_font,
                           "FONT_MAP", &vc_font_map,
                           "FONT_UNIMAP", &vc_font_unimap,
                           NULL);

        if (r < 0 && r != -ENOENT)
                log_warning("Failed to read /etc/vconsole.conf: %s", strerror(-r));

        /* Let the kernel command line override /etc/vconsole.conf */
        if (detect_container(NULL) <= 0) {
                r = parse_env_file("/proc/cmdline", WHITESPACE,
                                   "vconsole.keymap", &vc_keymap,
                                   "vconsole.keymap.toggle", &vc_keymap_toggle,
                                   "vconsole.font", &vc_font,
                                   "vconsole.font.map", &vc_font_map,
                                   "vconsole.font.unimap", &vc_font_unimap,
                                   NULL);

                if (r < 0 && r != -ENOENT)
                        log_warning("Failed to read /proc/cmdline: %s", strerror(-r));
        }

        if (utf8)
                enable_utf8(fd);
        else
                disable_utf8(fd);

        r = EXIT_FAILURE;
        if (keymap_load(vc, vc_keymap, vc_keymap_toggle, utf8, &keymap_pid) >= 0 &&
            font_load(vc, vc_font, vc_font_map, vc_font_unimap, &font_pid) >= 0)
                r = EXIT_SUCCESS;

finish:
        if (keymap_pid > 0)
                wait_for_terminate_and_warn(KBD_LOADKEYS, keymap_pid);

        if (font_pid > 0) {
                wait_for_terminate_and_warn(KBD_SETFONT, font_pid);
                if (font_copy)
                        font_copy_to_all_vcs(fd);
        }

        free(vc_keymap);
        free(vc_font);
        free(vc_font_map);
        free(vc_font_unimap);

        safe_close(fd);

        return r;
}
Esempio n. 12
0
int status_vprintf(const char *status, ShowStatusFlags flags, const char *format, va_list ap) {
        static const char status_indent[] = "         "; /* "[" STATUS "] " */
        _cleanup_free_ char *s = NULL;
        _cleanup_close_ int fd = -1;
        struct iovec iovec[7] = {};
        int n = 0;
        static bool prev_ephemeral;

        assert(format);

        /* This is independent of logging, as status messages are
         * optional and go exclusively to the console. */

        if (vasprintf(&s, format, ap) < 0)
                return log_oom();

        /* Before you ask: yes, on purpose we open/close the console for each status line we write individually. This
         * is a good strategy to avoid PID 1 getting killed by the kernel's SAK concept (it doesn't fix this entirely,
         * but minimizes the time window the kernel might end up killing PID 1 due to SAK). It also makes things easier
         * for us so that we don't have to recover from hangups and suchlike triggered on the console. */

        fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
        if (fd < 0)
                return fd;

        if (FLAGS_SET(flags, SHOW_STATUS_ELLIPSIZE)) {
                char *e;
                size_t emax, sl;
                int c;

                c = fd_columns(fd);
                if (c <= 0)
                        c = 80;

                sl = status ? sizeof(status_indent)-1 : 0;

                emax = c - sl - 1;
                if (emax < 3)
                        emax = 3;

                e = ellipsize(s, emax, 50);
                if (e)
                        free_and_replace(s, e);
        }

        if (prev_ephemeral)
                iovec[n++] = IOVEC_MAKE_STRING(ANSI_REVERSE_LINEFEED "\r" ANSI_ERASE_TO_END_OF_LINE);

        if (status) {
                if (!isempty(status)) {
                        iovec[n++] = IOVEC_MAKE_STRING("[");
                        iovec[n++] = IOVEC_MAKE_STRING(status);
                        iovec[n++] = IOVEC_MAKE_STRING("] ");
                } else
                        iovec[n++] = IOVEC_MAKE_STRING(status_indent);
        }

        iovec[n++] = IOVEC_MAKE_STRING(s);
        iovec[n++] = IOVEC_MAKE_STRING("\n");

        if (prev_ephemeral && !FLAGS_SET(flags, SHOW_STATUS_EPHEMERAL))
                iovec[n++] = IOVEC_MAKE_STRING(ANSI_ERASE_TO_END_OF_LINE);
        prev_ephemeral = FLAGS_SET(flags, SHOW_STATUS_EPHEMERAL) ;

        if (writev(fd, iovec, n) < 0)
                return -errno;

        return 0;
}
Esempio n. 13
0
int acquire_terminal(
                const char *name,
                bool fail,
                bool force,
                bool ignore_tiocstty_eperm,
                usec_t timeout) {

        int fd = -1, notify = -1, r = 0, wd = -1;
        usec_t ts = 0;

        assert(name);

        /* We use inotify to be notified when the tty is closed. We
         * create the watch before checking if we can actually acquire
         * it, so that we don't lose any event.
         *
         * Note: strictly speaking this actually watches for the
         * device being closed, it does *not* really watch whether a
         * tty loses its controlling process. However, unless some
         * rogue process uses TIOCNOTTY on /dev/tty *after* closing
         * its tty otherwise this will not become a problem. As long
         * as the administrator makes sure not configure any service
         * on the same tty as an untrusted user this should not be a
         * problem. (Which he probably should not do anyway.) */

        if (timeout != USEC_INFINITY)
                ts = now(CLOCK_MONOTONIC);

        if (!fail && !force) {
                notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
                if (notify < 0) {
                        r = -errno;
                        goto fail;
                }

                wd = inotify_add_watch(notify, name, IN_CLOSE);
                if (wd < 0) {
                        r = -errno;
                        goto fail;
                }
        }

        for (;;) {
                struct sigaction sa_old, sa_new = {
                        .sa_handler = SIG_IGN,
                        .sa_flags = SA_RESTART,
                };

                if (notify >= 0) {
                        r = flush_fd(notify);
                        if (r < 0)
                                goto fail;
                }

                /* We pass here O_NOCTTY only so that we can check the return
                 * value TIOCSCTTY and have a reliable way to figure out if we
                 * successfully became the controlling process of the tty */
                fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
                if (fd < 0)
                        return fd;

                /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
                 * if we already own the tty. */
                assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);

                /* First, try to get the tty */
                if (ioctl(fd, TIOCSCTTY, force) < 0)
                        r = -errno;

                assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);

                /* Sometimes it makes sense to ignore TIOCSCTTY
                 * returning EPERM, i.e. when very likely we already
                 * are have this controlling terminal. */
                if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
                        r = 0;

                if (r < 0 && (force || fail || r != -EPERM))
                        goto fail;

                if (r >= 0)
                        break;

                assert(!fail);
                assert(!force);
                assert(notify >= 0);

                for (;;) {
                        union inotify_event_buffer buffer;
                        struct inotify_event *e;
                        ssize_t l;

                        if (timeout != USEC_INFINITY) {
                                usec_t n;

                                n = now(CLOCK_MONOTONIC);
                                if (ts + timeout < n) {
                                        r = -ETIMEDOUT;
                                        goto fail;
                                }

                                r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
                                if (r < 0)
                                        goto fail;

                                if (r == 0) {
                                        r = -ETIMEDOUT;
                                        goto fail;
                                }
                        }

                        l = read(notify, &buffer, sizeof(buffer));
                        if (l < 0) {
                                if (errno == EINTR || errno == EAGAIN)
                                        continue;

                                r = -errno;
                                goto fail;
                        }

                        FOREACH_INOTIFY_EVENT(e, buffer, l) {
                                if (e->wd != wd || !(e->mask & IN_CLOSE)) {
                                        r = -EIO;
                                        goto fail;
                                }
                        }

                        break;
                }

                /* We close the tty fd here since if the old session
                 * ended our handle will be dead. It's important that
                 * we do this after sleeping, so that we don't enter
                 * an endless loop. */
                fd = safe_close(fd);
        }

        safe_close(notify);

        r = reset_terminal_fd(fd, true);
        if (r < 0)
                log_warning_errno(r, "Failed to reset terminal: %m");

        return fd;

fail:
        safe_close(fd);
        safe_close(notify);

        return r;
}
Esempio n. 14
0
ErrorCode ProcessSpawner::run(std::function<bool()> preExecAction) {
  if (_pid != 0 || _executablePath.empty())
    return kErrorInvalidArgument;

  //
  // If we have redirection, prepare pipes and handles.
  //
  int fds[3][2] = {{-1, -1}, {-1, -1}, {-1, -1}};
  int term[2] = {-1, -1};
  bool startRedirectThread = false;

  for (size_t n = 0; n < 3; n++) {
    switch (_descriptors[n].mode) {
    case kRedirectConsole:
      // do nothing
      break;

    case kRedirectNull:
      if (n == 0) {
        fds[n][RD] = ::open("/dev/null", O_RDONLY);
      } else {
        fds[n][WR] = ::open("/dev/null", O_WRONLY);
      }
      break;

    case kRedirectFile:
      if (n == 0) {
        fds[n][RD] = ::open(_descriptors[n].path.c_str(), O_RDONLY);
      } else {
        fds[n][WR] = ::open(_descriptors[n].path.c_str(), O_RDWR);
        if (fds[n][WR] < 0) {
          fds[n][WR] =
              ::open(_descriptors[n].path.c_str(), O_CREAT | O_RDWR, 0600);
        }
      }
      break;

    case kRedirectBuffer:
      _outputBuffer.clear();
    // fall-through
    case kRedirectDelegate:
      startRedirectThread = true;
      if (term[0] == -1) {
        if (!open_terminal(term)) {
          return Platform::TranslateError();
        }
      }
      fds[n][RD] = term[RD];
      fds[n][WR] = term[WR];
      break;
    }
  }

  _pid = ::fork();
  if (_pid < 0) {
    close_terminal(term);
    return kErrorNoMemory;
  }

  if (_pid == 0) {
    if (::setgid(::getgid()) == 0) {
      ::setsid();

      for (size_t n = 0; n < 3; n++) {
        switch (_descriptors[n].mode) {
        case kRedirectConsole:
          // do nothing
          break;

        case kRedirectDelegate:
          //
          // We are using the same virtual terminal for all delegate
          // redirections, so dup2() only, do not close. We will close when all
          // FDs have been dup2()'d.
          //
          ::dup2(fds[n][WR], n);
          break;

        default:
          if (n == 0) {
            if (fds[n][WR] != -1) {
              ::close(fds[n][WR]);
            }
            ::dup2(fds[n][RD], n);
            ::close(fds[n][RD]);
          } else {
            if (fds[n][RD] != -1) {
              ::close(fds[n][RD]);
            }
            ::dup2(fds[n][WR], n);
            ::close(fds[n][WR]);
          }
          break;
        }
      }

      close_terminal(term);

      if (!_workingDirectory.empty()) {
        ::chdir(_workingDirectory.c_str());
      }

      std::vector<char *> args;
      args.push_back(const_cast<char *>(_executablePath.c_str()));
      for (auto const &e : _arguments)
        args.push_back(const_cast<char *>(e.c_str()));
      args.push_back(nullptr);

      std::vector<char *> environment;
      for (auto const &env : _environment)
        environment.push_back(const_cast<char *>(
            (new std::string(env.first + '=' + env.second))->c_str()));
      environment.push_back(nullptr);

      if (!preExecAction())
        return kErrorUnknown;

      if (::execve(_executablePath.c_str(), &args[0], &environment[0]) < 0) {
        DS2LOG(Error, "cannot spawn executable %s, error=%s",
               _executablePath.c_str(), strerror(errno));
      }
    }
    ::_exit(127);
  }

  ::close(term[WR]);

  for (size_t n = 0; n < 3; n++) {
    switch (_descriptors[n].mode) {
    case kRedirectConsole:
      // do nothing
      break;

    case kRedirectDelegate:
      _descriptors[n].fd = term[RD];
      break;

    default:
      if (n == 0) {
        if (fds[n][RD] != -1) {
          ::close(fds[n][RD]);
          _descriptors[n].fd = fds[n][WR];
        }
      } else {
        if (fds[n][WR] != -1) {
          ::close(fds[n][WR]);
          _descriptors[n].fd = fds[n][RD];
        }
      }
      break;
    }
  }

  if (startRedirectThread) {
    _delegateThread = std::thread(&ProcessSpawner::redirectionThread, this);
  }

  return kSuccess;
}
Esempio n. 15
0
/* Check if MAGIC is valid and print the Multiboot information structure
   pointed by ADDR. */
void
entry (unsigned long magic, unsigned long addr)
{
	multiboot_info_t *mbi;

	/* Clear the screen. */
	clear();
	
	uint32_t filestart;
	/* Am I booted by a Multiboot-compliant boot loader? */
	if (magic != MULTIBOOT_BOOTLOADER_MAGIC)
	{
		printf ("Invalid magic number: 0x%#x\n", (unsigned) magic);
		return;
	}

	/* Set MBI to the address of the Multiboot information structure. */
	mbi = (multiboot_info_t *) addr;

	/* Print out the flags. */
	printf ("flags = 0x%#x\n", (unsigned) mbi->flags);

	/* Are mem_* valid? */
	if (CHECK_FLAG (mbi->flags, 0))
		printf ("mem_lower = %uKB, mem_upper = %uKB\n",
				(unsigned) mbi->mem_lower, (unsigned) mbi->mem_upper);

	/* Is boot_device valid? */
	if (CHECK_FLAG (mbi->flags, 1))
		printf ("boot_device = 0x%#x\n", (unsigned) mbi->boot_device);

	/* Is the command line passed? */
	if (CHECK_FLAG (mbi->flags, 2))
		printf ("cmdline = %s\n", (char *) mbi->cmdline);

	if (CHECK_FLAG (mbi->flags, 3)) {
		int mod_count = 0;
		int i;
		module_t* mod = (module_t*)mbi->mods_addr;
		while(mod_count < mbi->mods_count) {
			printf("Module %d loaded at address: 0x%#x\n", mod_count, (unsigned int)mod->mod_start);
			filestart = mod->mod_start;
			printf("Module %d ends at address: 0x%#x\n", mod_count, (unsigned int)mod->mod_end);
			printf("First few bytes of module:\n");
			for(i = 0; i<16; i++) {
				printf("0x%x ", *((char*)(mod->mod_start+i)));
			}
			printf("\n");
			mod_count++;
		}
	}
	/* Bits 4 and 5 are mutually exclusive! */
	if (CHECK_FLAG (mbi->flags, 4) && CHECK_FLAG (mbi->flags, 5))
	{
		printf ("Both bits 4 and 5 are set.\n");
		return;
	}

	/* Is the section header table of ELF valid? */
	if (CHECK_FLAG (mbi->flags, 5))
	{
		elf_section_header_table_t *elf_sec = &(mbi->elf_sec);

		printf ("elf_sec: num = %u, size = 0x%#x,"
				" addr = 0x%#x, shndx = 0x%#x\n",
				(unsigned) elf_sec->num, (unsigned) elf_sec->size,
				(unsigned) elf_sec->addr, (unsigned) elf_sec->shndx);
	}

	/* Are mmap_* valid? */
	if (CHECK_FLAG (mbi->flags, 6))
	{
		memory_map_t *mmap;

		printf ("mmap_addr = 0x%#x, mmap_length = 0x%x\n",
				(unsigned) mbi->mmap_addr, (unsigned) mbi->mmap_length);
		for (mmap = (memory_map_t *) mbi->mmap_addr;
				(unsigned long) mmap < mbi->mmap_addr + mbi->mmap_length;
				mmap = (memory_map_t *) ((unsigned long) mmap
					+ mmap->size + sizeof (mmap->size)))
			printf (" size = 0x%x,     base_addr = 0x%#x%#x\n"
					"     type = 0x%x,  length    = 0x%#x%#x\n",
					(unsigned) mmap->size,
					(unsigned) mmap->base_addr_high,
					(unsigned) mmap->base_addr_low,
					(unsigned) mmap->type,
					(unsigned) mmap->length_high,
					(unsigned) mmap->length_low);
	}

	/* Construct an LDT entry in the GDT */
	{
		seg_desc_t the_ldt_desc;
		the_ldt_desc.granularity    = 0;
		the_ldt_desc.opsize         = 1;
		the_ldt_desc.reserved       = 0;
		the_ldt_desc.avail          = 0;
		the_ldt_desc.present        = 1;
		the_ldt_desc.dpl            = 0x0;
		the_ldt_desc.sys            = 0;
		the_ldt_desc.type           = 0x2;

		SET_LDT_PARAMS(the_ldt_desc, &ldt, ldt_size);
		ldt_desc_ptr = the_ldt_desc;
		lldt(KERNEL_LDT);
	}

	/* Construct a TSS entry in the GDT */
	{
		seg_desc_t the_tss_desc;
		the_tss_desc.granularity    = 0;
		the_tss_desc.opsize         = 0;
		the_tss_desc.reserved       = 0;
		the_tss_desc.avail          = 0;
		the_tss_desc.seg_lim_19_16  = TSS_SIZE & 0x000F0000;
		the_tss_desc.present        = 1;
		the_tss_desc.dpl            = 0x0;
		the_tss_desc.sys            = 0;
		the_tss_desc.type           = 0x9;
		the_tss_desc.seg_lim_15_00  = TSS_SIZE & 0x0000FFFF;

		SET_TSS_PARAMS(the_tss_desc, &tss, tss_size);

		tss_desc_ptr = the_tss_desc;

		tss.ldt_segment_selector = KERNEL_LDT;
		tss.ss0 = KERNEL_DS;
		tss.esp0 = 0x800000;
		ltr(KERNEL_TSS);
	}
		//Initialization of IDE
	{
		printf("Initilization of Idt table...");
		set_trap_gate(0,divide_error);
		set_trap_gate(1,debug);
		set_intr_gate(2,nmi);
		set_system_intr_gate(3,int3);	
		set_system_gate(4,overflow);
		set_system_gate(5,bounds);
		set_trap_gate(6,invalid_op);
		set_trap_gate(7,device_not_available);
		set_task_gate(8,31);	
		set_trap_gate(9,coprocessor_segment_overrun);
		set_trap_gate(10,invalid_TSS);
		set_trap_gate(11,segment_not_present);
		set_trap_gate(12,stack_segment);
		set_trap_gate(13,general_protection);
		set_trap_gate(14,page_fault);//intr
		set_trap_gate(16,coprocessor_error);
		set_trap_gate(17,alignment_check);
		set_trap_gate(18,machine_check);
		set_trap_gate(19,simd_coprocessor_error);
		set_system_gate(128,system_call);
		set_intr_gate(32,irq0);  //intr 
		set_intr_gate(33,irq1); //intr
		set_intr_gate(34,0); //intr
		set_intr_gate(40,irq8);  //intr   
		//set_intr_gate(44,irq12); //intr
		lidt(idt_desc_ptr);
		printf("ok!\n");
	}
	
	// Init the PIC 
	i8259_init();
	
	//Enable interrupts

 
	enable_irq(1);
	enable_irq(2);
	open_rtc();
    enable_irq(8);
	enable_irq(12);

    uint8_t file =0x00;
	
	//Enable paging
    printf("Enabling paging...\n");
	paging();
    printf("ok!\n");
	
	//Restore interrupts
	sti();

	//Mounting file system
	printf("Mounting filesystem...\n");
	open_terminal(&file);
	setstart(filestart);
	printf("ok!\n");
	
	//clear();
    //Executing first program shell
    uint8_t cmd[10]={"shell "};
#if debug_by_showing_dentries
test_dentries();
while(1);
#endif

    test_system_call((int32_t)cmd, NULL, 0, 2);

	asm volatile(".1: hlt; jmp .1;");
}
Esempio n. 16
0
void server_forward_console(
                Server *s,
                int priority,
                const char *identifier,
                const char *message,
                const struct ucred *ucred) {

        struct iovec iovec[5];
        struct timespec ts;
        char tbuf[sizeof("[] ")-1 + DECIMAL_STR_MAX(ts.tv_sec) + DECIMAL_STR_MAX(ts.tv_nsec)-3 + 1];
        char header_pid[sizeof("[]: ")-1 + DECIMAL_STR_MAX(pid_t)];
        int n = 0, fd;
        _cleanup_free_ char *ident_buf = NULL;
        const char *tty;

        assert(s);
        assert(message);

        if (LOG_PRI(priority) > s->max_level_console)
                return;

        /* First: timestamp */
        if (prefix_timestamp()) {
                assert_se(clock_gettime(CLOCK_MONOTONIC, &ts) == 0);
                xsprintf(tbuf, "[%5"PRI_TIME".%06ld] ",
                         ts.tv_sec,
                         ts.tv_nsec / 1000);
                IOVEC_SET_STRING(iovec[n++], tbuf);
        }

        /* Second: identifier and PID */
        if (ucred) {
                if (!identifier) {
                        get_process_comm(ucred->pid, &ident_buf);
                        identifier = ident_buf;
                }

                xsprintf(header_pid, "["PID_FMT"]: ", ucred->pid);

                if (identifier)
                        IOVEC_SET_STRING(iovec[n++], identifier);

                IOVEC_SET_STRING(iovec[n++], header_pid);
        } else if (identifier) {
                IOVEC_SET_STRING(iovec[n++], identifier);
                IOVEC_SET_STRING(iovec[n++], ": ");
        }

        /* Fourth: message */
        IOVEC_SET_STRING(iovec[n++], message);
        IOVEC_SET_STRING(iovec[n++], "\n");

        tty = s->tty_path ? s->tty_path : "/dev/console";

        fd = open_terminal(tty, O_WRONLY|O_NOCTTY|O_CLOEXEC);
        if (fd < 0) {
                log_debug_errno(errno, "Failed to open %s for logging: %m", tty);
                return;
        }

        if (writev(fd, iovec, n) < 0)
                log_debug_errno(errno, "Failed to write to %s for logging: %m", tty);

        safe_close(fd);
}
Esempio n. 17
0
void server_forward_console(
                Server *s,
                int priority,
                const char *identifier,
                const char *message,
                const struct ucred *ucred) {

        struct iovec iovec[5];
        struct timespec ts;
        char tbuf[sizeof("[] ")-1 + DECIMAL_STR_MAX(ts.tv_sec) + DECIMAL_STR_MAX(ts.tv_nsec)-3 + 1];
        char header_pid[sizeof("[]: ")-1 + DECIMAL_STR_MAX(pid_t)];
        int n = 0, fd;
        _cleanup_free_ char *ident_buf = NULL;
        const char *tty;

        assert(s);
        assert(message);

        if (LOG_PRI(priority) > s->max_level_console)
                return;

        /* First: timestamp */
        if (prefix_timestamp()) {
                assert_se(clock_gettime(CLOCK_MONOTONIC, &ts) == 0);
                xsprintf(tbuf, "[%5"PRI_TIME".%06ld] ",
                         ts.tv_sec,
                         ts.tv_nsec / 1000);
                IOVEC_SET_STRING(iovec[n++], tbuf);
        }

        /* Second: identifier and PID */
        if (ucred) {
                if (!identifier) {
                        get_process_comm(ucred->pid, &ident_buf);
                        identifier = ident_buf;
                }

                xsprintf(header_pid, "["PID_FMT"]: ", ucred->pid);

                if (identifier)
                        IOVEC_SET_STRING(iovec[n++], identifier);

                IOVEC_SET_STRING(iovec[n++], header_pid);
        } else if (identifier) {
                IOVEC_SET_STRING(iovec[n++], identifier);
                IOVEC_SET_STRING(iovec[n++], ": ");
        }

        /* Fourth: message */
        IOVEC_SET_STRING(iovec[n++], message);
        IOVEC_SET_STRING(iovec[n++], "\n");

        tty = s->tty_path ? s->tty_path : "/dev/console";

        /* Before you ask: yes, on purpose we open/close the console for each log line we write individually. This is a
         * good strategy to avoid journald getting killed by the kernel's SAK concept (it doesn't fix this entirely,
         * but minimizes the time window the kernel might end up killing journald due to SAK). It also makes things
         * easier for us so that we don't have to recover from hangups and suchlike triggered on the console. */

        fd = open_terminal(tty, O_WRONLY|O_NOCTTY|O_CLOEXEC);
        if (fd < 0) {
                log_debug_errno(fd, "Failed to open %s for logging: %m", tty);
                return;
        }

        if (writev(fd, iovec, n) < 0)
                log_debug_errno(errno, "Failed to write to %s for logging: %m", tty);

        safe_close(fd);
}
Esempio n. 18
0
void server_forward_console(
                Server *s,
                int priority,
                const char *identifier,
                const char *message,
                struct ucred *ucred) {

        struct iovec iovec[5];
        char header_pid[16];
        struct timespec ts;
        char tbuf[4 + DECIMAL_STR_MAX(ts.tv_sec) + DECIMAL_STR_MAX(ts.tv_nsec)-3 + 1];
        int n = 0, fd;
        char *ident_buf = NULL;
        const char *tty;

        assert(s);
        assert(message);

        if (LOG_PRI(priority) > s->max_level_console)
                return;

        /* First: timestamp */
        if (prefix_timestamp()) {
                assert_se(clock_gettime(CLOCK_MONOTONIC, &ts) == 0);
                snprintf(tbuf, sizeof(tbuf), "[%5llu.%06llu] ",
                         (unsigned long long) ts.tv_sec,
                         (unsigned long long) ts.tv_nsec / 1000);
                IOVEC_SET_STRING(iovec[n++], tbuf);
        }

        /* Second: identifier and PID */
        if (ucred) {
                if (!identifier) {
                        get_process_comm(ucred->pid, &ident_buf);
                        identifier = ident_buf;
                }

                snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
                char_array_0(header_pid);

                if (identifier)
                        IOVEC_SET_STRING(iovec[n++], identifier);

                IOVEC_SET_STRING(iovec[n++], header_pid);
        } else if (identifier) {
                IOVEC_SET_STRING(iovec[n++], identifier);
                IOVEC_SET_STRING(iovec[n++], ": ");
        }

        /* Fourth: message */
        IOVEC_SET_STRING(iovec[n++], message);
        IOVEC_SET_STRING(iovec[n++], "\n");

        tty = s->tty_path ? s->tty_path : "/dev/console";

        fd = open_terminal(tty, O_WRONLY|O_NOCTTY|O_CLOEXEC);
        if (fd < 0) {
                log_debug("Failed to open %s for logging: %s", tty, strerror(errno));
                goto finish;
        }

        if (writev(fd, iovec, n) < 0)
                log_debug("Failed to write to %s for logging: %s", tty, strerror(errno));

        safe_close(fd);

finish:
        free(ident_buf);
}
Esempio n. 19
0
int vt_disallocate(const char *name) {
        int fd, r;
        unsigned u;

        /* Deallocate the VT if possible. If not possible
         * (i.e. because it is the active one), at least clear it
         * entirely (including the scrollback buffer) */

        if (!startswith(name, "/dev/"))
                return -EINVAL;

        if (!tty_is_vc(name)) {
                /* So this is not a VT. I guess we cannot deallocate
                 * it then. But let's at least clear the screen */

                fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
                if (fd < 0)
                        return fd;

                loop_write(fd,
                           "\033[r"    /* clear scrolling region */
                           "\033[H"    /* move home */
                           "\033[2J",  /* clear screen */
                           10, false);
                safe_close(fd);

                return 0;
        }

        if (!startswith(name, "/dev/tty"))
                return -EINVAL;

        r = safe_atou(name+8, &u);
        if (r < 0)
                return r;

        if (u <= 0)
                return -EINVAL;

        /* Try to deallocate */
        fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
        if (fd < 0)
                return fd;

        r = ioctl(fd, VT_DISALLOCATE, u);
        safe_close(fd);

        if (r >= 0)
                return 0;

        if (errno != EBUSY)
                return -errno;

        /* Couldn't deallocate, so let's clear it fully with
         * scrollback */
        fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
        if (fd < 0)
                return fd;

        loop_write(fd,
                   "\033[r"   /* clear scrolling region */
                   "\033[H"   /* move home */
                   "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
                   10, false);
        safe_close(fd);

        return 0;
}
Esempio n. 20
0
//*******************************************************************
// customEvent                                     PRIVATE inherited
//*******************************************************************
void QBtWorkspace::customEvent( QEvent* const in_event )
{
    const QBtEvent* const event = dynamic_cast< QBtEvent* >( in_event );
    const int type = static_cast<int>( event->type() );

    switch( type ) {
    case QBtEvent::SWITCH_TAB_REQUEST:
        switch_panels();
        break;
    case QBtEvent::F5_KEY:
        copy();
        break;
    case QBtEvent::F9_KEY:
        pack();
        break;
    case QBtEvent::COMPARE_FILES:
        compare_files();
        break;
    case QBtEvent::COMPARE_DIRS:
        compare_dirs();
        break;
    case QBtEvent::SYNC_DIRS:
        sync_dirs();
        break;
    case QBtEvent::JOIN_FILES:
        join_files();
        break;
    case QBtEvent::DIR_TREE:
        dir_tree();
        break;
    case QBtEvent::MD5_CREATE:
        md5_create();
        break;
    case QBtEvent::MD5_CHECK:
        md5_check();
        break;
    case QBtEvent::DATE_TIME:
        date_time();
        break;
    case QBtEvent::DROP_FILES:
        drop_files( event->data(0).toMap() );
        break;
    case QBtEvent::OPEN_OPOSITE:
        open_oposite();
        break;
    case QBtEvent::OPEN_DIR:
        open_dir( event->data(0).toString() );
        break;
    case QBtEvent::OPEN_SHELL:
        open_shell();
        break;
    case QBtEvent::OPEN_TERMINAL:
        open_terminal();
        break;
    case QBtEvent::OPEN_EDITOR:
        open_editor();
        break;
    case QBtEvent::EXECUTE:
        open( event->data(0).toString(), QStringList(), QString() );
        break;
    }
}
Esempio n. 21
0
int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
        static const char status_indent[] = "         "; /* "[" STATUS "] " */
        _cleanup_free_ char *s = NULL;
        _cleanup_close_ int fd = -1;
        struct iovec iovec[6] = {};
        int n = 0;
        static bool prev_ephemeral;

        assert(format);

        /* This is independent of logging, as status messages are
         * optional and go exclusively to the console. */

        if (vasprintf(&s, format, ap) < 0)
                return log_oom();

        fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
        if (fd < 0)
                return fd;

        if (ellipse) {
                char *e;
                size_t emax, sl;
                int c;

                c = fd_columns(fd);
                if (c <= 0)
                        c = 80;

                sl = status ? sizeof(status_indent)-1 : 0;

                emax = c - sl - 1;
                if (emax < 3)
                        emax = 3;

                e = ellipsize(s, emax, 50);
                if (e) {
                        free(s);
                        s = e;
                }
        }

        if (prev_ephemeral)
                IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
        prev_ephemeral = ephemeral;

        if (status) {
                if (!isempty(status)) {
                        IOVEC_SET_STRING(iovec[n++], "[");
                        IOVEC_SET_STRING(iovec[n++], status);
                        IOVEC_SET_STRING(iovec[n++], "] ");
                } else
                        IOVEC_SET_STRING(iovec[n++], status_indent);
        }

        IOVEC_SET_STRING(iovec[n++], s);
        if (!ephemeral)
                IOVEC_SET_STRING(iovec[n++], "\n");

        if (writev(fd, iovec, n) < 0)
                return -errno;

        return 0;
}
int main(int argc, char **argv)
{
   int status;
   int nrx_fd;
   int host_rfd;
   int host_wfd;
   int use_stdin = 0;
   char * ser_dev = NULL;
   int port = 12345;
   char * filename = default_filename;
   void * handle = NULL;
   int host_flash = 0;
   int input_baudrate = 115200;
   speed_t baudrate = B115200;
   int opt;

   struct ifreq ifr;
   struct nanoioctl nr;
   
   while((opt = getopt(argc, argv, "d:s:p:f:b:i")) != -1) {
      switch(opt) {
         case 'b':
            input_baudrate = atoi(optarg);
            switch(input_baudrate) {
               case 9600: baudrate = B9600; break;
               case 19200: baudrate = B19200; break;
               case 38400: baudrate = B38400; break;
               case 57600: baudrate = B57600; break;
               case 115200: baudrate = B115200; break;
               default: usage();
            }
            break;
         case 'd':
            debug = atoi(optarg);
            break;
         case 'f':
            filename = optarg;
            break;
         case 'i':
            use_stdin = 1;
            break;
         case 'p':
            port = atoi(optarg);
            break;
         case 's':
            ser_dev = optarg;
            break;
         default:
            break;
      }
   }
   if(optind == argc)
      usage();

   strcpy(ifr.ifr_name, argv[optind]);
   ifr.ifr_data = (char *)&nr;
   memset(&nr,0,sizeof(nr));
   nr.magic = NR_MAGIC;

   APP_INFO("Nanoradio network interface: %s\n", ifr.ifr_name);
   APP_INFO("Saving persistent MIB data of type HOST to: %s\n", filename);

   if(use_stdin) {
      APP_INFO("Using stdin/stdout as client interface\n");
      host_wfd = host_rfd = open_terminal();
      redirect_stdout("/tmp/hic_proxy.log");
   } else if(ser_dev) 
      {
	APP_INFO("Using %s (baudrate = %d) as serial client interface\n", ser_dev,input_baudrate);
	host_wfd = host_rfd = open_serial(ser_dev, baudrate);
      }
   else 
      {
         APP_INFO("Using ethernet as client interface\n");
         host_wfd = host_rfd = open_socket(port);
      }
    
   nrx_fd = socket(AF_INET, SOCK_DGRAM, 0);
   if(nrx_fd < 0) err(1, "socket");

   for(;;) {      
      status = poll_host(host_rfd, &ifr);
      if(status) {
	
         
         if((nr.data[TYPE_INDEX] ==  HIC_MESSAGE_TYPE_FLASH_PRG))
            {
               APP_DEBUG("flash cmd recieved\n");

               //examine flash cmd
               handle = flash_cmd(&ifr,handle,filename);
 
               if(handle)
                  {
                     //send local host flash cmd reply
                     host_write(host_wfd, nr.data, nr.length);
                  }
               else
                  {
                     //forward to target
                     nrx_write(nrx_fd, &ifr);
                  }
            }
         else
            {
               //forward to target
               nrx_write(nrx_fd, &ifr);
            }
      }
	
      status = poll_target(nrx_fd, &ifr);
  
      if(status)
         host_write(host_wfd, nr.data, nr.length);

      usleep(5000);
   }

   if(!use_stdin) {
      close(host_rfd);
   }
   close(nrx_fd);
}