Ejemplo n.º 1
0
static int handle_subwin_resize(char *msg) {
	int new_x, new_y;
	int i, check = 10, ms = 250;	/* 2.5 secs total... */

	if (msg) {}	/* unused vars warning: */
	if (! subwin) {
		return 0;	/* hmmm... */
	}
	if (! valid_window(subwin, NULL, 0)) {
		rfbLogEnable(1);
		rfbLog("subwin 0x%lx went away!\n", subwin);
		X_UNLOCK;
		clean_up_exit(1);
	}
	if (! get_window_size(subwin, &new_x, &new_y)) {
		rfbLogEnable(1);
		rfbLog("could not get size of subwin 0x%lx\n", subwin);
		X_UNLOCK;
		clean_up_exit(1);
	}
	if (wdpy_x == new_x && wdpy_y == new_y) {
		/* no change */
		return 0;
	}

	/* window may still be changing (e.g. drag resize) */
	for (i=0; i < check; i++) {
		int newer_x, newer_y;
		usleep(ms * 1000);

		if (! get_window_size(subwin, &newer_x, &newer_y)) {
			rfbLogEnable(1);
			rfbLog("could not get size of subwin 0x%lx\n", subwin);
			clean_up_exit(1);
		}
		if (new_x == newer_x && new_y == newer_y) {
			/* go for it... */
			break;
		} else {
			rfbLog("subwin 0x%lx still changing size...\n", subwin);
			new_x = newer_x;
			new_y = newer_y;
		}
	}

	rfbLog("subwin 0x%lx new size: x: %d -> %d, y: %d -> %d\n",
	    subwin, wdpy_x, new_x, wdpy_y, new_y);
	rfbLog("calling handle_xrandr_change() for resizing\n");

	X_UNLOCK;
	handle_xrandr_change(new_x, new_y);
	return 1;
}
Ejemplo n.º 2
0
static void
process_next_event(struct piglit_x11_framework *x11_fw)
{
	struct piglit_winsys_framework *winsys_fw = &x11_fw->winsys_fw;
	const struct piglit_gl_test_config *test_config = winsys_fw->wfl_fw.gl_fw.test_config;

	Display *dpy = x11_fw->display;
	XEvent event;

	XNextEvent(dpy, &event);

	switch (event.type) {
	case Expose:
		get_window_size(x11_fw);
		winsys_fw->need_redisplay = true;
		break;
	case ConfigureNotify:
		get_window_size(x11_fw);
		if (winsys_fw->user_reshape_func)
			winsys_fw->user_reshape_func(event.xconfigure.width,
			                             event.xconfigure.height);
		winsys_fw->need_redisplay = true;
		break;
	case KeyPress: {
		char buffer[1];
		KeySym sym;
		int n;

		n = XLookupString(&event.xkey,
				  buffer,
				  sizeof(buffer), &sym, NULL);

		if (n > 0 && winsys_fw->user_keyboard_func)
			winsys_fw->user_keyboard_func(buffer[0],
			                              event.xkey.x,
			                              event.xkey.y);
		winsys_fw->need_redisplay = true;
		break;
	}
	default:
		break;
	}

	if (winsys_fw->need_redisplay) {
		enum piglit_result result = PIGLIT_PASS;
		if (test_config->display)
			result = test_config->display();
		if (piglit_automatic)
			piglit_report_result(result);
		winsys_fw->need_redisplay = false;
	}
}
Ejemplo n.º 3
0
// caller should own dup_lock
static void init(void)
{
    static bool inited;
    if (inited && bucket_width == last_bucket_width) return;
    inited = true;
    last_bucket_width = bucket_width;

    if (bucket_width == 0) {
        unsigned columns;
        get_window_size(&columns, NULL);
        if (0 == columns) {
            columns = 80;  // good old defaults never fail us
        }
        bucket_width = CEIL_DIV(max_dup_delay, columns);
        if (0 == bucket_width) {
            // It's ok to use the console as at this point we are likely
            // in the debugger already
            fprintf(stderr, "Cannot compute bucket width");
            bucket_width = 1;
        }
    }
    nb_buckets = CEIL_DIV(max_dup_delay, bucket_width);
    if (dups) free(dups);
    dups = malloc(nb_buckets * sizeof(*dups));
    assert(dups);
    dup_reset_locked();
}
Ejemplo n.º 4
0
void OS_JavaScript::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver) {

	print_line("Init OS");

	if (gfx_init_func)
		gfx_init_func(gfx_init_ud,use_gl2,p_desired.width,p_desired.height,p_desired.fullscreen);

	// nothing to do here, can't fulfil fullscreen request due to
	// browser security, window size is already set from HTML
	video_mode=p_desired;
	video_mode.fullscreen=false;
	_windowed_size=get_window_size();

	// find locale, emscripten only sets "C"
	char locale_ptr[16];
	/* clang-format off */
	EM_ASM_({
		var locale = "";
		if (Module.locale) {
			// best case: server-side script reads Accept-Language early and
			// defines the locale to be read here
			locale = Module.locale;
		} else {
			// no luck, use what the JS engine can tell us
			// if this turns out not compatible enough, add tests for
			// browserLanguage, systemLanguage and userLanguage
			locale = navigator.languages ? navigator.languages[0] : navigator.language;
		}
		locale = locale.split('.')[0];
		stringToUTF8(locale, $0, 16);
	}, locale_ptr);
Ejemplo n.º 5
0
bool ActiveWindow::MoveResize(const Dimensions& activewin) {
    if (!init()) {
        return false;
    }

    unsigned int margin_width, margin_height;
    if (!get_window_size(disp, *win, NULL, &margin_width, &margin_height)) {
        return false;
    }

    //demaximize the window before attempting to move it
    if (!maximize_window(disp, *win, false)) {
        ERROR("couldn't demaximize");
        //disregard failure
    }

    unsigned long new_interior_width = activewin.width - margin_width,
        new_interior_height = activewin.height - margin_height;

    //moveresize uses exterior for position, but interior for width/height
    DEBUG("%ldx %ldy %luw %luh - margins %dw %dh = %ldx %ldy %luw %luh",
            activewin.x, activewin.y, activewin.width, activewin.height,
            margin_width, margin_height,
            activewin.x, activewin.y, new_interior_width, new_interior_height);

    if (XMoveResizeWindow(disp, *win, activewin.x, activewin.y,
                    new_interior_width, new_interior_height) == 0) {
        ERROR("MoveResize to %ldx %ldy %luw %luh failed.",
                activewin.x, activewin.y, new_interior_width, new_interior_height);
        return false;
    }
    return true;
}
Ejemplo n.º 6
0
int
main( int argc, char *argv[] )
{
   Display *dpy;
   VisualID vid;
   XVisualInfo *visinfo;
   Window win;

   parse_opts(argc, argv);

   key_usage();

   dpy = XOpenDisplay(DisplayName);

   /* find the VisualID for the named window */
   vid = get_window_visualid(dpy, WindowID);
   get_window_size(dpy, WindowID, &Width, &Height);

   visinfo = visualid_to_visualinfo(dpy, vid);

   Context = glXCreateContext( dpy, visinfo, NULL, True );
   if (!Context) {
      printf("Error: glXCreateContext failed\n");
      exit(1);
   }

   win = make_gl_window(dpy, visinfo, Width, Height);
   XMapWindow(dpy, win);
   update_window_title(dpy, win);

   event_loop( dpy, win );

   return 0;
}
Ejemplo n.º 7
0
char	*loop_cmd(t_param *param, t_history **history)
{
  int	start;
  int	ret;
  char	buff[10];

  ret = 1;
  start = 0;
  while (ret > 0)
    {
      if ((ret = read(0, buff, 9)) == -1)
        return (NULL);
      buff[ret] = '\0';
      if (buff[0] == CTRLD && buff[1] == '\0')
        return (NULL);
      if (buff[0] == '\n' && buff[1] == '\0')
        return (return_string(param->cmd, param));
      if (buff[0] != '\n' && start == 0)
	actu_begin_pos(param, &start);
      if (get_window_size(param->cmd, param->begin_pos_x) == 1 &&
          gere_keyboard(buff, param->cmd, param, history) == 1)
        {
          add_character(param->cmd, param, buff[0]);
          view(param->cmd, param);
        }
    }
  return (param->cmd);
}
Ejemplo n.º 8
0
bool window::select_activate(grid::POS dir) {
    Display* disp = XOpenDisplay(NULL);
    if (disp == NULL) {
        ERROR("unable to get display");
        return false;
    }

    std::vector<Window> wins;

    {
        size_t win_count = 0;
        static Atom clientlist_msg = XInternAtom(disp, "_NET_CLIENT_LIST", False);
        Window* all_wins = (Window*)x11_util::get_property(disp, DefaultRootWindow(disp),
                XA_WINDOW, clientlist_msg, &win_count);
        if (all_wins == NULL || win_count == 0) {
            ERROR("unable to get list of windows");
            if (all_wins != NULL) {
                x11_util::free_property(all_wins);
            }
            XCloseDisplay(disp);
            return false;
        }
        // only select normal windows, ignore docks and menus
        for (size_t i = 0; i < win_count; ++i) {
            if (!is_dock_window(disp, all_wins[i]) && !is_menu_window(disp, all_wins[i])) {
                wins.push_back(all_wins[i]);
            }
        }
        x11_util::free_property(all_wins);
    }

    size_t active_window = 0;
    dim_list_t all_windows;
    {
        Window* active = get_active_window(disp);
        if (active == NULL) {
            XCloseDisplay(disp);
            return false;
        }
        for (size_t i = 0; i < wins.size(); ++i) {
            if (wins[i] == *active) {
                active_window = i;
                DEBUG("ACTIVE:");
            }
            all_windows.push_back(Dimensions());
            get_window_size(disp, wins[i], &all_windows.back(), NULL, NULL);
        }
        x11_util::free_property(active);
    }

    size_t next_window;
    neighbor::select(dir, all_windows, active_window, next_window);

    bool ok = activate_window(disp, wins[active_window], wins[next_window]);

    XCloseDisplay(disp);
    return ok;
}
Ejemplo n.º 9
0
static void
swrast_check_and_update_window_size( struct gl_context *ctx, struct gl_framebuffer *fb )
{
    GLsizei width, height;

    get_window_size(fb, &width, &height);
    if (fb->Width != width || fb->Height != height) {
	_mesa_resize_framebuffer(ctx, fb, width, height);
    }
}
Ejemplo n.º 10
0
void			ft_resize(int i)
{
	t_select	*s;

	s = SING;
	tputs(tgoto(tgetstr("cm", NULL), 0, 0), s->fd, tputs_putchar);
	tputs(tgetstr("cd", NULL), s->fd, tputs_putchar);
	get_window_size(s);
	print_list(s);
	(void)i;
}
Ejemplo n.º 11
0
/* ARGSUSED */
static void
sigwinch(int signo __unused)
{
	struct winsize ws;

	if (dosigwinch && get_window_size(0, &ws) == 0 &&
	    bcmp(&ws, &winsize, sizeof(ws))) {
		winsize = ws;
		sendwindow();
	}
}
Ejemplo n.º 12
0
int
TerminalWindowSize(long *rows, long *cols)
{
    int irows, icols;

    if (get_window_size(STDIN_FILENO, &irows, &icols) == 0) {
	*rows = irows;
	*cols = icols;
	return 1;
    } else
	return 0;
}
Ejemplo n.º 13
0
int
TerminalWindowSize(long *rows, long *cols)
{
    struct winsize ws;

    if (get_window_size (STDIN_FILENO, &ws) == 0) {
	*rows = ws.ws_row;
	*cols = ws.ws_col;
	return 1;
    } else
	return 0;
}
Ejemplo n.º 14
0
BaseWidget::BaseWidget(int width, int height) {
    int swidth, sheight;
    get_window_size(&swidth, &sheight);
    
    int xgap = swidth - width;
    int ygap = sheight - height;
    
    this->x = xgap / 2;
    this->y = ygap / 2;
    this->width = width;
    this->height = height;
    printf("Making widget at (%d,%d) by (%d, %d)\n", x, y, width, height);
}
Ejemplo n.º 15
0
static void gl_capture(HDC hdc)
{
	static bool functions_initialized = false;
	static bool critical_failure = false;

	if (critical_failure) {
		return;
	}

	if (!functions_initialized) {
		functions_initialized = init_gl_functions();
		if (!functions_initialized) {
			critical_failure = true;
			return;
		}
	}

	/* reset error flag */
	glGetError();

	if (capture_should_stop()) {
		gl_free();
	}
	if (capture_should_init()) {
		if (gl_init(hdc) == INIT_SHTEX_FAILED) {
			data.shmem_fallback = true;
			gl_init(hdc);
		}
	}
	if (capture_ready() && hdc == data.hdc) {
		uint32_t new_cx;
		uint32_t new_cy;

		/* reset capture if resized */
		get_window_size(hdc, &new_cx, &new_cy);
		if (new_cx != data.base_cx || new_cy != data.base_cy) {
			if (new_cx != 0 && new_cy != 0)
				gl_free();
			return;
		}

		if (data.using_shtex)
			gl_shtex_capture();
		else
			gl_shmem_capture();
	}
}
Ejemplo n.º 16
0
void
__move_preedit(IC* ic)
{
    int root_x, root_y;
    get_window_position(ic->client_window, &root_x, &root_y);
    LOG("root: %d, %d offset: %d,%d", root_x, root_y,
        ic->offset_x, ic->offset_y);
    if (ic->offset_x <= 0 && ic->offset_y <= 0) {
        int height;
        get_window_size(ic->client_window, NULL, &height);
        root_x += 4;
        root_y += height;
    } else {
        root_x += ic->offset_x;
        root_y += ic->offset_y;
    }

    preedit_move(root_x, root_y);
}
Ejemplo n.º 17
0
bool ActiveWindow::Size(Dimensions& activewin) {
    if (!init()) {
        return false;
    }

    if (is_dock_window(disp, *win) || is_menu_window(disp, *win)) {
        LOG("Active window is a desktop or dock. Ignoring move request.");
        return false;
    }

    if (!get_window_size(disp, *win, &activewin, NULL, NULL)) {
        ERROR("couldn't get window size");
        return false;
    }

    DEBUG("activewin %dx %dy %luw %luh",
            activewin.x, activewin.y, activewin.width, activewin.height);

    return true;
}
Ejemplo n.º 18
0
void
get_screen_size(int* width, int* height)
{
    get_window_size(DefaultRootWindow(dpy), width, height);
}
Ejemplo n.º 19
0
int
main(int argc, char *argv[])
{
	struct passwd *pw;
	struct servent *sp;
	struct sgttyb ttyb;
	long omask;
	int argoff, ch, dflag, Dflag, one, uid;
	char *host, *localname, *p, *user, term[1024];
#ifdef KERBEROS
	char *k;
#endif
	struct sockaddr_storage ss;
	int sslen;

	argoff = dflag = Dflag = 0;
	one = 1;
	host = localname = user = NULL;

	if ((p = strrchr(argv[0], '/')))
		++p;
	else
		p = argv[0];

	if (strcmp(p, "rlogin"))
		host = p;

	/* handle "rlogin host flags" */
	if (!host && argc > 2 && argv[1][0] != '-') {
		host = argv[1];
		argoff = 1;
	}

#ifdef KERBEROS
#define	OPTIONS	"468DEKLde:i:k:l:x"
#else
#define	OPTIONS	"468DEKLde:i:l:"
#endif
	while ((ch = getopt(argc - argoff, argv + argoff, OPTIONS)) != -1)
		switch(ch) {
		case '4':
			family = PF_INET;
			break;

		case '6':
			family = PF_INET6;
			break;

		case '8':
			eight = 1;
			break;
		case 'D':
			Dflag = 1;
			break;
		case 'E':
			noescape = 1;
			break;
		case 'K':
#ifdef KERBEROS
			use_kerberos = 0;
#endif
			break;
		case 'L':
			litout = 1;
			break;
		case 'd':
			dflag = 1;
			break;
		case 'e':
			noescape = 0;
			escapechar = getescape(optarg);
			break;
		case 'i':
			if (getuid() != 0)
				errx(1, "-i user: permission denied");
			localname = optarg;
			break;
#ifdef KERBEROS
		case 'k':
			dest_realm = dst_realm_buf;
			(void)strncpy(dest_realm, optarg, REALM_SZ);
			break;
#endif
		case 'l':
			user = optarg;
			break;
#ifdef CRYPT
#ifdef KERBEROS
		case 'x':
			doencrypt = 1;
			break;
#endif
#endif
		case '?':
		default:
			usage();
		}
	optind += argoff;

	/* if haven't gotten a host yet, do so */
	if (!host && !(host = argv[optind++]))
		usage();

	if (argv[optind])
		usage();

	if (!(pw = getpwuid(uid = getuid())))
		errx(1, "unknown user id");
	if (!user)
		user = pw->pw_name;
	if (!localname)
		localname = pw->pw_name;

	sp = NULL;
#ifdef KERBEROS
	k = auth_getval("auth_list");
	if (k && !strstr(k, "kerberos"))
	    use_kerberos = 0;
	if (use_kerberos) {
		sp = getservbyname((doencrypt ? "eklogin" : "klogin"), "tcp");
		if (sp == NULL) {
			use_kerberos = 0;
			warn("can't get entry for %s/tcp service",
			    doencrypt ? "eklogin" : "klogin");
		}
	}
#endif
	if (sp == NULL)
		sp = getservbyname("login", "tcp");
	if (sp == NULL)
		errx(1, "login/tcp: unknown service");

#define	MAX_TERM_LENGTH	(sizeof(term) - 1 - MAX_SPEED_LENGTH - 1)

	(void)strncpy(term, (p = getenv("TERM")) ? p : "network",
		      MAX_TERM_LENGTH);
	term[MAX_TERM_LENGTH] = '\0';
	if (ioctl(0, TIOCGETP, &ttyb) == 0) {
		(void)strcat(term, "/");
		(void)strcat(term, speeds[(int)ttyb.sg_ospeed]);
	}

	(void)get_window_size(0, &winsize);

	(void)signal(SIGPIPE, lostpeer);
	/* will use SIGUSR1 for window size hack, so hold it off */
	omask = sigblock(sigmask(SIGURG) | sigmask(SIGUSR1));
	/*
	 * We set SIGURG and SIGUSR1 below so that an
	 * incoming signal will be held pending rather than being
	 * discarded. Note that these routines will be ready to get
	 * a signal by the time that they are unblocked below.
	 */
	(void)signal(SIGURG, copytochild);
	(void)signal(SIGUSR1, writeroob);

#ifdef KERBEROS
	if (use_kerberos) {
		setuid(getuid());
		rem = KSUCCESS;
		errno = 0;
		if (dest_realm == NULL)
			dest_realm = krb_realmofhost(host);

#ifdef CRYPT
		if (doencrypt) {
			rem = krcmd_mutual(&host, sp->s_port, user, term, 0,
			    dest_realm, &cred, schedule);
			des_set_key(&cred.session, schedule);
		} else
#endif /* CRYPT */
			rem = krcmd(&host, sp->s_port, user, term, 0,
			    dest_realm);
		if (rem < 0) {
			int i;
			char **newargv;

			sp = getservbyname("login", "tcp");
			if (sp == NULL)
				errx(1, "unknown service login/tcp");
			if (errno == ECONNREFUSED)
				warn("remote host doesn't support Kerberos");
			if (errno == ENOENT)
				warn("can't provide Kerberos auth data");
			newargv = malloc((argc + 2) * sizeof(*newargv));
			if (newargv == NULL)
				err(1, "malloc");
			newargv[0] = argv[0];
			newargv[1] = "-K";
			for(i = 1; i < argc; ++i)
				newargv[i + 1] = argv[i];
			newargv[argc + 1] = NULL;
			execv(_PATH_RLOGIN, newargv);
		}
	} else {
#ifdef CRYPT
		if (doencrypt)
			errx(1, "the -x flag requires Kerberos authentication");
#endif /* CRYPT */
		rem = rcmd_af(&host, sp->s_port, localname, user, term, 0,
			      family);
	}
#else
	rem = rcmd_af(&host, sp->s_port, localname, user, term, 0, family);
#endif /* KERBEROS */

	if (rem < 0)
		exit(1);

	if (dflag &&
	    setsockopt(rem, SOL_SOCKET, SO_DEBUG, &one, sizeof(one)) < 0)
		warn("setsockopt");
	if (Dflag &&
	    setsockopt(rem, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)) < 0)
		warn("setsockopt NODELAY (ignored)");

	sslen = sizeof(ss);
	one = IPTOS_LOWDELAY;
	if (getsockname(rem, (struct sockaddr *)&ss, &sslen) == 0 &&
	    ss.ss_family == AF_INET) {
		if (setsockopt(rem, IPPROTO_IP, IP_TOS, (char *)&one,
			       sizeof(int)) < 0)
			warn("setsockopt TOS (ignored)");
	} else
		if (ss.ss_family == AF_INET)
			warn("setsockopt getsockname failed");

	(void)setuid(uid);
	doit(omask);
	/*NOTREACHED*/
}
Ejemplo n.º 20
0
int WINAPI WinMain(HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR lpCmdLine,
	int nCmdShow)
{
	MSG msg;
	bool done = false;


#if PROMPT_FULLSCREEN
	fullscreen = MessageBox(nullptr,
		L"Do you want run application in fullscreen mode?",
		L"Is fullscreen mode", MB_YESNO | MB_ICONQUESTION) == IDNO ? false : true;
#endif

	int width = WND_WIDTH;
	int	height = WND_HEIGHT;

	get_window_size(&width, &height);

	if (!create_gl_window(WND_TITLE, width, height, COLOR_BITS, fullscreen))
		return 0;

	while (!done)
	{
		if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
		{
			if (msg.message == WM_QUIT)
				done = true;
			else
			{
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
		}
		else
		{
			if ((active && !draw_gl_scene()) || keys[VK_ESCAPE])
			{
#ifdef _DEBUG
				OutputDebugString(L"[INFO] ESC typed. Program will be closed\n");
#endif
				done = true;
			}
			else
				SwapBuffers(hDC);

			if (keys['T'] && !t_press)
			{
				t_press = true;
				twinkle = !twinkle;
			}

			if (!keys['T']) t_press = false;

			//if (keys[VK_UP]) tilt -= 0.5f;		// Up
			//if (keys[VK_DOWN]) tilt += 0.5f;	// Down
			if (keys[VK_PRIOR]) zoom -= 0.2f;	// PgUp
			if (keys[VK_NEXT]) zoom += 0.2f;	// PgDown

			glBlendFunc(GL_SRC_ALPHA, GL_ONE);
			glEnable(GL_BLEND);

			if (keys[VK_F1])
			{
				keys[VK_F1] = false;
				kill_gl_window();
				fullscreen = !fullscreen;
				get_window_size(&width, &height);
				if (!create_gl_window(WND_TITLE, width, height, COLOR_BITS, fullscreen))
					return 0;
			}
		}
	}

	kill_gl_window();
	return (msg.wParam);
}
/*
 * ******************************************* 
 *  Function: handle_transport_layer_packet  
 *
 *  Description: 
 *
 *  handle a transport layer 
 *  packet. Core transport layer handling 
 *  function , all the other funcitons 
 *  were written to support this big guy 
 *  
 *  Parameters: 
 *     buffer - packet buffer 
 *     src_id  - Source id 
 *     dest_id - Destination id 
 *
 * ******************************************* 
 */
void handle_transport_layer_packet( void * buffer , int src_id , int dest_id )
{

      
        int packet_type; 
        int requested_mtu; 
        int seq_no; 
        int connect_id; 
        void *realloc_buffer;
        int win_size ;	
	void *packet_data;
        int cid_seq_no; 	
        int current_sender_id; 
	int current_cid_state; 
	int sender_id ;
        char *realloc_buf_ptr; 	
	int max_connections_permitted = get_state(&__max_connections);
	packet_type = get_packet_type(buffer);

	switch(packet_type)
	{
		case CONTROL_CONNECT:
			requested_mtu = get_requested_mtu(buffer);
		        connect_id  =allocate_sender(max_connections_permitted);
			sender_id  = get_sender_id(buffer);
		        if ( connect_id  <  max_connections_permitted)
			{
                             
		              init_state(&__session_tab.cid_info[connect_id].curr_state);
		              set_state(&__session_tab.cid_info[connect_id].curr_state ,STATE_CONNECTED);
		              __session_tab.cid_info[connect_id].sequence_number = 0;  
		              __session_tab.cid_info[connect_id].buf_len = 0;  	
			        
                              send_connect_ack(src_id  , requested_mtu , connect_id,sender_id); 

			}
		        else
		        {
                              fprintf(stderr ,"%s", "\n Connection not possilbe  all slots full \n"); 
                              
		        }	
                        break;
		case CONTROL_ACK:
                        seq_no = get_sequence_number(buffer);
                        current_sender_id = get_sender_id(buffer);
			connect_id  = get_cid(buffer); 
			sender_buffer[current_sender_id].seq_no = seq_no; 
		        sender_buffer[current_sender_id].response_code = CONTROL_ACK; 
			sender_buffer[current_sender_id].connection_id = connect_id; 
                        break;
		case CONTROL_DATA:
		   {	
                       
			fprintf(stderr,"DATA packet received  ... ");    
		        connect_id  = get_cid(buffer);
		        seq_no = get_sequence_number(buffer);
			sender_id = get_sender_id(buffer);
                        cid_seq_no = __session_tab.cid_info[connect_id].sequence_number;
                        current_cid_state = get_state(&__session_tab.cid_info[connect_id].curr_state); 			
			fprintf(stderr,"\n seq no = %d cid seq no = %d window size = %d  CID = %d" , seq_no , cid_seq_no , get_window_size(buffer) , connect_id);
		        /* are we getting the next sequnce number  & we are connected */
			if( (  seq_no == cid_seq_no + 1 ) )
			{
                              win_size = get_window_size(buffer); 
		              realloc_buffer = malloc(win_size + __session_tab.cid_info[connect_id].buf_len);
		              if ( __session_tab.cid_info[connect_id].buf_len >  0  && ( current_cid_state != STATE_CLOSE)) 
			      {
			              memcpy(realloc_buffer,__session_tab.cid_info[connect_id].data_buf,__session_tab.cid_info[connect_id].buf_len);
				      realloc_buf_ptr = (char *) realloc_buffer + __session_tab.cid_info[connect_id].buf_len ;
				      packet_data    = (char *) buffer + TRASPORT_LAYER_SIZE ;  
				      memcpy(realloc_buf_ptr,packet_data , win_size);
				      __session_tab.cid_info[connect_id].buf_len += win_size; 
				      free( __session_tab.cid_info[connect_id].data_buf); 
				      __session_tab.cid_info[connect_id].data_buf = realloc_buffer;
                                      __session_tab.cid_info[connect_id].sequence_number++;
				      send_ack_request(src_id,seq_no,sender_id) ;   
		              }	     
			      else
			      {

				      packet_data    = (char *) buffer + TRASPORT_LAYER_SIZE ;  
				      memcpy(realloc_buffer,packet_data , win_size); 
				      __session_tab.cid_info[connect_id].buf_len += win_size; 
				      __session_tab.cid_info[connect_id].data_buf = realloc_buffer;
                                      __session_tab.cid_info[connect_id].sequence_number++;
				      send_ack_request(src_id,seq_no,sender_id) ;  

			      } 
                             
			}
		        else  if (  seq_no == cid_seq_no   )
			{
			        send_ack_request(src_id,seq_no,sender_id) ;   

			
			}
			else
			{
                            fprintf(stderr , "%s" , "\n Packet out of sequence number / duplicate  discarded \n ");  

			}	
                      }     
		      break; 

		case CONTROL_FIN:
		      fprintf(stderr ,"\n fin received  "); 
                      connect_id  = get_cid(buffer);
		      sender_id   = get_sender_id(buffer);
		      current_cid_state = get_state(&__session_tab.cid_info[connect_id].curr_state); 			
                      if ( current_cid_state  == STATE_CONNECTED )
		      {  
                              nfd_buffer_receved(__session_tab.cid_info[connect_id].data_buf,__session_tab.cid_info[connect_id].buf_len);
		              free(__session_tab.cid_info[connect_id].data_buf);
		              __session_tab.cid_info[connect_id].buf_len = 0 ; 
 		      }
		      else
		      {

                               set_state(&__session_tab.cid_info[connect_id].curr_state,STATE_FIN); 	
		      }
		      send_ack_request(src_id,0,sender_id); 
		      break;

		case  CONTROL_CLOSE:
                      connect_id  = get_cid(buffer);
		      set_state(&__session_tab.cid_info[connect_id].curr_state,STATE_CLOSE);
                      deallocate_connection(connect_id);
		      fprintf(stderr , "\nRecevied close packet "); 
		      break;

		case CONTROL_CONNECT_ACK:
	               seq_no = get_sequence_number(buffer);
                       current_sender_id = get_sender_id(buffer);
		       connect_id  = get_cid(buffer); 
		       sender_buffer[current_sender_id].response_code = CONTROL_CONNECT_ACK;
		       sender_buffer[current_sender_id].mtu_possible = get_window_size(buffer);  
		       sender_buffer[current_sender_id].connection_id = connect_id; 
	               fprintf(stderr , "\n Recieved control connect ack  sender id %d  mtu_possible  %d " ,current_sender_id, sender_buffer[current_sender_id].mtu_possible );  
 	       
 	               break; 

                default:
		       /* None of the known control types */
		       /* dropping packet */
		      fprintf(stderr,"\n Not one of the known packet types, Type = %d " , packet_type ); 
		      break; 

	}

}
Ejemplo n.º 22
0
void		resize(void)
{
	get_window_size();
	clr_screen();
}
Ejemplo n.º 23
0
int tty_ioctl(struct inode * inode, struct file * file,
	unsigned int cmd, unsigned int arg)
{
	struct tty_struct * tty;
	struct tty_struct * other_tty;
	int pgrp;
	int dev;

	if (MAJOR(file->f_rdev) != 4) {
		printk("tty_ioctl: tty pseudo-major != 4\n");
		return -EINVAL;
	}
	dev = MINOR(file->f_rdev);
	tty = TTY_TABLE(dev);
	if (!tty)
		return -EINVAL;

	if (IS_A_PTY(dev))
		other_tty = tty_table[PTY_OTHER(dev)];
	else
		other_tty = NULL;
		
	switch (cmd) {
		case TCGETS:
			return get_termios(tty,(struct termios *) arg);
		case TCSETSF:
			flush_input(tty);
		/* fallthrough */
		case TCSETSW:
			wait_until_sent(tty);
		/* fallthrough */
		case TCSETS:
			return set_termios(tty,(struct termios *) arg, dev);
		case TCGETA:
			return get_termio(tty,(struct termio *) arg);
		case TCSETAF:
			flush_input(tty);
		/* fallthrough */
		case TCSETAW:
			wait_until_sent(tty); /* fallthrough */
		case TCSETA:
			return set_termio(tty,(struct termio *) arg, dev);
		case TCXONC:
			switch (arg) {
			case TCOOFF:
				tty->stopped = 1;
				TTY_WRITE_FLUSH(tty);
				return 0;
			case TCOON:
				tty->stopped = 0;
				TTY_WRITE_FLUSH(tty);
				return 0;
			case TCIOFF:
				if (STOP_CHAR(tty))
					put_tty_queue(STOP_CHAR(tty),
						      &tty->write_q);
				return 0;
			case TCION:
				if (START_CHAR(tty))
					put_tty_queue(START_CHAR(tty),
						      &tty->write_q);
				return 0;
			}
			return -EINVAL; /* not implemented */
		case TCFLSH:
			if (arg==0)
				flush_input(tty);
			else if (arg==1)
				flush_output(tty);
			else if (arg==2) {
				flush_input(tty);
				flush_output(tty);
			} else
				return -EINVAL;
			return 0;
		case TIOCEXCL:
			return -EINVAL; /* not implemented */
		case TIOCNXCL:
			return -EINVAL; /* not implemented */
		case TIOCSCTTY:
			return -EINVAL; /* set controlling term NI */
		case TIOCGPGRP:
			verify_area((void *) arg,4);
			put_fs_long(tty->pgrp,(unsigned long *) arg);
			return 0;
		case TIOCSPGRP:
			if ((current->tty < 0) ||
			    (current->tty != dev) ||
			    (tty->session != current->session))
				return -ENOTTY;
			pgrp=get_fs_long((unsigned long *) arg);
			if (pgrp < 0)
				return -EINVAL;
			if (session_of_pgrp(pgrp) != current->session)
				return -EPERM;
			tty->pgrp = pgrp;			
			return 0;
		case TIOCOUTQ:
			verify_area((void *) arg,4);
			put_fs_long(CHARS(&tty->write_q),
				    (unsigned long *) arg);
			return 0;
		case TIOCINQ:
			verify_area((void *) arg,4);
			if (L_CANON(tty) && !tty->secondary.data)
				put_fs_long(0, (unsigned long *) arg);
			else
				put_fs_long(CHARS(&tty->secondary),
					(unsigned long *) arg);
			return 0;
		case TIOCSTI:
			return -EINVAL; /* not implemented */
		case TIOCGWINSZ:
			return get_window_size(tty,(struct winsize *) arg);
		case TIOCSWINSZ:
			if (IS_A_PTY_MASTER(dev))
				set_window_size(other_tty,(struct winsize *) arg);
			return set_window_size(tty,(struct winsize *) arg);
		case TIOCGSOFTCAR:
			return -EINVAL; /* not implemented */
		case TIOCSSOFTCAR:
			return -EINVAL; /* not implemented */
		case TIOCLINUX:
			switch (get_fs_byte((char *)arg))
			{
				case 0: 
					return do_screendump(arg);
				case 1: 
					return do_get_ps_info(arg);
				default: 
					return -EINVAL;
			}
		case TIOCCONS:
			if (!IS_A_PTY(dev))
				return -EINVAL;
			if (redirect)
				return -EBUSY;
			if (!suser())
				return -EPERM;
			if (IS_A_PTY_MASTER(dev))
				redirect = other_tty;
			else
				redirect = tty;
			return 0;
		case FIONBIO:
			if (arg)
				file->f_flags |= O_NONBLOCK;
			else
				file->f_flags &= ~O_NONBLOCK;
			return 0;
		case TIOCNOTTY:
			if (MINOR(file->f_rdev) != current->tty)
				return -EINVAL;
			current->tty = -1;
			if (current->leader) {
				if (tty->pgrp > 0)
					kill_pg(tty->pgrp, SIGHUP, 0);
				tty->pgrp = -1;
				tty->session = 0;
			}
			return 0;

	       case TIOCPKT:
			{
			   int on;
			   if (!IS_A_PTY_MASTER(dev))
			     return (-EINVAL);
			   verify_area ((unsigned long *)arg, sizeof (int));
			   on=get_fs_long ((unsigned long *)arg);
			   if (on )
			     tty->packet = 1;
			   else
			     tty->packet = 0;
			   return (0);
			}

		default:
			if (tty->ioctl)
				return (tty->ioctl)(tty, file, cmd, arg);
			else
				return -EINVAL;
	}
}
Ejemplo n.º 24
0
int
main(int argc, char *argv[])
{
	struct passwd *pw;
	struct servent *sp;
	struct termios tty;
	long omask;
	int argoff, ch, dflag, Dflag, one;
	uid_t uid;
	char *host, *localname, *p, *user, term[1024];
	speed_t ospeed;
	struct sockaddr_storage ss;
	socklen_t sslen;
	size_t len, len2;
	int i;

	argoff = dflag = Dflag = 0;
	one = 1;
	host = localname = user = NULL;

	if ((p = strrchr(argv[0], '/')))
		++p;
	else
		p = argv[0];

	if (strcmp(p, "rlogin"))
		host = p;

	/* handle "rlogin host flags" */
	if (!host && argc > 2 && argv[1][0] != '-') {
		host = argv[1];
		argoff = 1;
	}

#define	OPTIONS	"468DEde:i:l:"
	while ((ch = getopt(argc - argoff, argv + argoff, OPTIONS)) != -1)
		switch(ch) {
		case '4':
			family = PF_INET;
			break;

		case '6':
			family = PF_INET6;
			break;

		case '8':
			eight = 1;
			break;
		case 'D':
			Dflag = 1;
			break;
		case 'E':
			noescape = 1;
			break;
		case 'd':
			dflag = 1;
			break;
		case 'e':
			noescape = 0;
			escapechar = getescape(optarg);
			break;
		case 'i':
			if (getuid() != 0)
				errx(1, "-i user: permission denied");
			localname = optarg;
			break;
		case 'l':
			user = optarg;
			break;
		case '?':
		default:
			usage();
		}
	optind += argoff;

	/* if haven't gotten a host yet, do so */
	if (!host && !(host = argv[optind++]))
		usage();

	if (argv[optind])
		usage();

	if (!(pw = getpwuid(uid = getuid())))
		errx(1, "unknown user id");
	if (!user)
		user = pw->pw_name;
	if (!localname)
		localname = pw->pw_name;

	sp = NULL;
	sp = getservbyname("login", "tcp");
	if (sp == NULL)
		errx(1, "login/tcp: unknown service");

	if ((p = getenv("TERM")) != NULL)
		(void)strlcpy(term, p, sizeof(term));
	len = strlen(term);
	if (len < (sizeof(term) - 1) && tcgetattr(0, &tty) == 0) {
		/* start at 2 to include the / */
		for (ospeed = i = cfgetospeed(&tty), len2 = 2; i > 9; len2++)
			i /= 10;
		if (len + len2 < sizeof(term))
			(void)snprintf(term + len, len2 + 1, "/%d", ospeed);
	}

	(void)get_window_size(0, &winsize);

	(void)signal(SIGPIPE, lostpeer);
	/* will use SIGUSR1 for window size hack, so hold it off */
	omask = sigblock(sigmask(SIGURG) | sigmask(SIGUSR1));
	/*
	 * We set SIGURG and SIGUSR1 below so that an
	 * incoming signal will be held pending rather than being
	 * discarded. Note that these routines will be ready to get
	 * a signal by the time that they are unblocked below.
	 */
	(void)signal(SIGURG, copytochild);
	(void)signal(SIGUSR1, writeroob);

	rem = rcmd_af(&host, sp->s_port, localname, user, term, 0, family);

	if (rem < 0)
		exit(1);

	if (dflag &&
	    setsockopt(rem, SOL_SOCKET, SO_DEBUG, &one, sizeof(one)) < 0)
		warn("setsockopt");
	if (Dflag &&
	    setsockopt(rem, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)) < 0)
		warn("setsockopt NODELAY (ignored)");

	sslen = sizeof(ss);
	one = IPTOS_LOWDELAY;
	if (getsockname(rem, (struct sockaddr *)&ss, &sslen) == 0 &&
	    ss.ss_family == AF_INET) {
		if (setsockopt(rem, IPPROTO_IP, IP_TOS, (char *)&one,
			       sizeof(int)) < 0)
			warn("setsockopt TOS (ignored)");
	} else
		if (ss.ss_family == AF_INET)
			warn("setsockopt getsockname failed");

	(void)setuid(uid);
	doit(omask);
	/*NOTREACHED*/
}
Ejemplo n.º 25
0
static void do_display(struct timeval const *now)
{
    if (! refresh_rate) return;

    printf(TOPLEFT CLEAR);
    printf("Duplicogram - Every " BRIGHT "%.2fs" NORMAL " - " BRIGHT "%s" NORMAL, refresh_rate / 1000000., ctime(&now->tv_sec));
    printf(BRIGHT "dups" NORMAL ":  %12"PRIu64"/%-12"PRIu64" (%6.2f%%)\n", nb_dups, nb_dups+nb_nodups, 100.*(double)nb_dups/(nb_dups+nb_nodups));
    printf(BRIGHT "bytes" NORMAL ": %12"PRIu64"/%-12"PRIu64" (%6.2f%%)\n", sz_dups, sz_dups+sz_nodups, 100.*(double)sz_dups/(sz_dups+sz_nodups));

    unsigned lines, columns;
    get_window_size(&columns, &lines);

    if (lines <= 5) return;

    mutex_lock(&dup_lock);
    if (! dups) {
        printf("no data yet\n");
        mutex_unlock(&dup_lock);
        return;
    }

    // look for max dups
    static unsigned dups_max = 0;
    unsigned cur_dups_max = 0;
    for (unsigned b = 0; b < nb_buckets; b++) {
        if (dups[b] > cur_dups_max) cur_dups_max = dups[b];
    }
    if (dups_max == 0) {
        dups_max = cur_dups_max;
    } else {
        if (cur_dups_max > dups_max) {
            dups_max = cur_dups_max;
        } else if (cur_dups_max < dups_max/2) {
            dups_max = cur_dups_max;
        }
    }

    unsigned prev_y_label = ~0U;
    unsigned no_y_tick = 0;
    for (unsigned y = lines - 5; y > 0; y--) {
        unsigned const y_label = ROUND_DIV(dups_max*y, lines-3);
        if (no_y_tick++ == 5 && y_label != prev_y_label) {
            printf("%5u|", y_label);
            prev_y_label = y_label;
            no_y_tick = 0;
        } else {
            printf("     |");
        }
        for (unsigned x = 0; x < columns-6; x++) {
            printf(dups[x] >= y_label ? "*":" ");
        }
        puts("");
    }

    // we are done with dups
    mutex_unlock(&dup_lock);

#   define X_TICK 16    // one tick every X_TICK chars (must be power of 2)
    printf("     ");
    unsigned x;
    for (x = 0; x < columns-7; x++) printf(x & (X_TICK-1) ? "-" : "+");
    printf(">\n     ");
    unsigned x_label = 0;
    for (x = 0; x < columns-7-X_TICK; x+=X_TICK, x_label += X_TICK*bucket_width) {
        if (x > 0) printf("           "); // X_TICK-5 spaces long
        printf("%-5u", x_label);
    }
    for (; x < columns-8; x++) printf(" ");
    printf("           us");  // X_TICK-5 spaces long

    fflush(stdout);
}
Ejemplo n.º 26
0
void main_loop(void)
{
   char key;
   int paper_w, paper_h;
   long diff;

   if (!landscape) {
      paper_w = XLENG / shrink;
      paper_h = YLENG / shrink;
   } else {
      paper_w = YLENG / shrink;
      paper_h = XLENG / shrink;
   }
   set_all();
   XUndefineCursor(display, main_window);
   for (;;) {
      XNextEvent(display, &ev);
      switch (ev.type) {
      case Expose:
         if (ev.xexpose.count == 0)
            get_window_size();
         realize_part(ev.xexpose.x, ev.xexpose.y,
                      ev.xexpose.width, ev.xexpose.height,
                      ev.xexpose.x, ev.xexpose.y);
         break;
      case MappingNotify:
         /*      XRefreshKeyboardMapping(&ev);
          */
         XRefreshKeyboardMapping((XMappingEvent *) & ev);
         break;
         /*  case ConfigureNotify:
            get_window_size();
            shr_w = paper_w / window_w;
            shr_h = paper_h / window_h;
            shrink = (shr_w >= shr_h) ? shr_w :shr_h;
            rewind(stdin);
            plot();
            main_loop();

            origin_x += window_x;
            origin_y += window_y;
            realize();
            realize_part(origin_x, origin_y, window_w, window_h,
            origin_x, origin_y);
            origin_x = paper_w - xsh.width;
            origin_y = paper_h - xsh.height;
            origin_x += xsh.x;
            origin_y += xsh.y;
            break;
          */
      case MotionNotify:
         break;
      case ButtonPress:
         break;
      case KeyPress:
         get_window_size();
         XLookupString(&ev.xkey, &key, 1, NULL, NULL);
         switch (key) {
         case 'j':
            diff = paper_h - window_h;
            if (origin_y >= diff) {
               beep();
               break;
            }
            origin_y += window_h / 4;
            if (origin_y > diff)
               origin_y = diff;
            if (origin_y < 0)
               origin_y = 0;
            realize();
            continue;
            break;
         case 'k':
            if (origin_y <= 0) {
               beep();
               break;
            }
            origin_y -= window_h / 4;
            if (origin_y < 0)
               origin_y = 0;
            realize();
            continue;
            break;
         case 'l':
            diff = paper_w - window_w;
            if (origin_x >= diff) {
               beep();
               break;
            }
            origin_x += window_w / 4;
            if (origin_x > diff)
               origin_x = diff;
            if (origin_x < 0)
               origin_x = 0;
            realize();
            continue;
            break;
         case 'h':
            if (origin_x <= 0) {
               beep();
               break;
            }
            origin_x -= window_w / 4;
            if (origin_x < 0)
               origin_x = 0;
            realize();
            continue;
            break;
         case 'q':
         case '\003':          /*  control-C  */
         case '\004':          /*  control-D  */
            close_window();
            break;
         default:
            beep();
            break;
         }
         break;
      default:
         break;
      }
   }
}
Ejemplo n.º 27
0
void ROKEN_LIB_FUNCTION
arg_printusage_i18n (struct getargs *args,
		     size_t num_args,
		     const char *usage,
		     const char *progname,
		     const char *extra_string,
		     char *(i18n)(const char *))
{
    int i;
    size_t max_len = 0;
    char buf[128];
    int col = 0, columns;
    struct winsize ws;

    if (progname == NULL)
	progname = getprogname();

    if (i18n == NULL)
	i18n = builtin_i18n;

    if(getenv("GETARGMANDOC")){
	mandoc_template(args, num_args, progname, extra_string, i18n);
	return;
    }
    if(get_window_size(2, &ws) == 0)
	columns = ws.ws_col;
    else
	columns = 80;
    col = 0;
    col += fprintf (stderr, "%s: %s", usage, progname);
    buf[0] = '\0';
    for (i = 0; i < num_args; ++i) {
	if(args[i].short_name && ISFLAG(args[i])) {
	    char s[2];
	    if(buf[0] == '\0')
		strlcpy(buf, "[-", sizeof(buf));
	    s[0] = args[i].short_name;
	    s[1] = '\0';
	    strlcat(buf, s, sizeof(buf));
	}
    }
    if(buf[0] != '\0') {
	strlcat(buf, "]", sizeof(buf));
	col = check_column(stderr, col, strlen(buf) + 1, columns);
	col += fprintf(stderr, " %s", buf);
    }

    for (i = 0; i < num_args; ++i) {
	size_t len = 0;

	if (args[i].long_name) {
	    buf[0] = '\0';
	    strlcat(buf, "[--", sizeof(buf));
	    len += 2;
	    if(args[i].type == arg_negative_flag) {
		strlcat(buf, "no-", sizeof(buf));
		len += 3;
	    }
	    strlcat(buf, args[i].long_name, sizeof(buf));
	    len += strlen(args[i].long_name);
	    len += print_arg(buf + strlen(buf), sizeof(buf) - strlen(buf),
			     0, 1, &args[i], i18n);
	    strlcat(buf, "]", sizeof(buf));
	    if(args[i].type == arg_strings)
		strlcat(buf, "...", sizeof(buf));
	    col = check_column(stderr, col, strlen(buf) + 1, columns);
	    col += fprintf(stderr, " %s", buf);
	}
	if (args[i].short_name && !ISFLAG(args[i])) {
	    snprintf(buf, sizeof(buf), "[-%c", args[i].short_name);
	    len += 2;
	    len += print_arg(buf + strlen(buf), sizeof(buf) - strlen(buf),
			     0, 0, &args[i], i18n);
	    strlcat(buf, "]", sizeof(buf));
	    if(args[i].type == arg_strings)
		strlcat(buf, "...", sizeof(buf));
	    col = check_column(stderr, col, strlen(buf) + 1, columns);
	    col += fprintf(stderr, " %s", buf);
	}
	if (args[i].long_name && args[i].short_name)
	    len += 2; /* ", " */
	max_len = max(max_len, len);
    }
    if (extra_string) {
	check_column(stderr, col, strlen(extra_string) + 1, columns);
	fprintf (stderr, " %s\n", extra_string);
    } else
	fprintf (stderr, "\n");
    for (i = 0; i < num_args; ++i) {
	if (args[i].help) {
	    size_t count = 0;

	    if (args[i].short_name) {
		count += fprintf (stderr, "-%c", args[i].short_name);
		print_arg (buf, sizeof(buf), 0, 0, &args[i], i18n);
		count += fprintf(stderr, "%s", buf);
	    }
	    if (args[i].short_name && args[i].long_name)
		count += fprintf (stderr, ", ");
	    if (args[i].long_name) {
		count += fprintf (stderr, "--");
		if (args[i].type == arg_negative_flag)
		    count += fprintf (stderr, "no-");
		count += fprintf (stderr, "%s", args[i].long_name);
		print_arg (buf, sizeof(buf), 0, 1, &args[i], i18n);
		count += fprintf(stderr, "%s", buf);
	    }
	    while(count++ <= max_len)
		putc (' ', stderr);
	    fprintf (stderr, "%s\n", (*i18n)(args[i].help));
	}
    }
}
Ejemplo n.º 28
0
int tty_ioctl(int dev, int cmd, int arg)
{
	struct tty_struct * tty;
	struct tty_struct * other_tty;
	int pgrp;

	if (MAJOR(dev) == 5) {
		dev = current->tty;
		if (dev<0)
			return -EINVAL;
	} else
		dev=MINOR(dev);
	tty = tty_table + (dev ? ((dev < 64)? dev-1:dev) : fg_console);

	if (IS_A_PTY(dev))
		other_tty = tty_table + PTY_OTHER(dev);
	else
		other_tty = NULL;
		
	if (!(tty->write_q && tty->read_q && tty->secondary && tty->write))
		return -EINVAL;
	switch (cmd) {
		case TCGETS:
			return get_termios(tty,(struct termios *) arg);
		case TCSETSF:
			flush(tty->read_q);
			flush(tty->secondary);
			if (other_tty)
				flush(other_tty->write_q);
		/* fallthrough */
		case TCSETSW:
			wait_until_sent(tty);
		/* fallthrough */
		case TCSETS:
			return set_termios(tty,(struct termios *) arg, dev);
		case TCGETA:
			return get_termio(tty,(struct termio *) arg);
		case TCSETAF:
			flush(tty->read_q);
			flush(tty->secondary);
			if (other_tty)
				flush(other_tty->write_q);
		/* fallthrough */
		case TCSETAW:
			wait_until_sent(tty); /* fallthrough */
		case TCSETA:
			return set_termio(tty,(struct termio *) arg, dev);
		case TCSBRK:
			if (!arg) {
				wait_until_sent(tty);
				send_break(tty);
			}
			return 0;
		case TCXONC:
			switch (arg) {
			case TCOOFF:
				tty->stopped = 1;
				tty->write(tty);
				return 0;
			case TCOON:
				tty->stopped = 0;
				tty->write(tty);
				return 0;
			case TCIOFF:
				if (STOP_CHAR(tty))
					PUTCH(STOP_CHAR(tty),tty->write_q);
				return 0;
			case TCION:
				if (START_CHAR(tty))
					PUTCH(START_CHAR(tty),tty->write_q);
				return 0;
			}
			return -EINVAL; /* not implemented */
		case TCFLSH:
			if (arg==0) {
				flush(tty->read_q);
				flush(tty->secondary);
				if (other_tty)
					flush(other_tty->write_q);
			} else if (arg==1)
				flush(tty->write_q);
			else if (arg==2) {
				flush(tty->read_q);
				flush(tty->secondary);
				flush(tty->write_q);
				if (other_tty)
					flush(other_tty->write_q);
			} else
				return -EINVAL;
			return 0;
		case TIOCEXCL:
			return -EINVAL; /* not implemented */
		case TIOCNXCL:
			return -EINVAL; /* not implemented */
		case TIOCSCTTY:
			return -EINVAL; /* set controlling term NI */
		case TIOCGPGRP:
			verify_area((void *) arg,4);
			put_fs_long(tty->pgrp,(unsigned long *) arg);
			return 0;
		case TIOCSPGRP:
			if ((current->tty < 0) ||
			    (current->tty != dev) ||
			    (tty->session != current->session))
				return -ENOTTY;
			pgrp=get_fs_long((unsigned long *) arg);
			if (pgrp < 0)
				return -EINVAL;
			if (session_of_pgrp(pgrp) != current->session)
				return -EPERM;
			tty->pgrp = pgrp;			
			return 0;
		case TIOCOUTQ:
			verify_area((void *) arg,4);
			put_fs_long(CHARS(tty->write_q),(unsigned long *) arg);
			return 0;
		case TIOCINQ:
			verify_area((void *) arg,4);
			put_fs_long(CHARS(tty->secondary),
				(unsigned long *) arg);
			return 0;
		case TIOCSTI:
			return -EINVAL; /* not implemented */
		case TIOCGWINSZ:
			return get_window_size(tty,(struct winsize *) arg);
		case TIOCSWINSZ:
			if (other_tty)
				set_window_size(other_tty,(struct winsize *) arg);
			return set_window_size(tty,(struct winsize *) arg);
		case TIOCMGET:
			return -EINVAL; /* not implemented */
		case TIOCMBIS:
			return -EINVAL; /* not implemented */
		case TIOCMBIC:
			return -EINVAL; /* not implemented */
		case TIOCMSET:
			return -EINVAL; /* not implemented */
		case TIOCGSOFTCAR:
			return -EINVAL; /* not implemented */
		case TIOCSSOFTCAR:
			return -EINVAL; /* not implemented */
		case TIOCLINUX:
			switch (get_fs_byte((char *)arg))
			{
				case 0: 
					return do_screendump(arg);
				case 1: 
					return do_get_ps_info(arg);
				default: 
					return -EINVAL;
			}
		default:
			return -EINVAL;
	}
}