3 * - By John Hodge (thePowersGang)
16 #include <posix_signals.h>
19 #define OUTPUT_RINGBUFFER_LEN 1024 // Number of bytes in output queue before client blocks
20 #define INPUT_RINGBUFFER_LEN 256 // Number of bytes in input queue before being dropped
21 #define INPUT_LINE_LEN 256
32 tPTY_OutputFcn OutputFcn;
33 tPTY_ReqResize ReqResize;
43 char InputData[INPUT_RINGBUFFER_LEN];
46 char LineData[INPUT_LINE_LEN];
51 char OutputData[OUTPUT_RINGBUFFER_LEN];
53 tVFS_Node *ServerNode;
57 tPGID ControllingProcGroup;
61 int PTY_Install(char **Arguments);
62 int PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX]);
63 tVFS_Node *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags);
65 size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len);
66 size_t _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len);
67 size_t PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length);
68 size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length);
70 size_t PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
71 size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
72 void PTY_ReferenceClient(tVFS_Node *Node);
73 void PTY_CloseClient(tVFS_Node *Node);
74 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
75 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
76 void PTY_CloseServer(tVFS_Node *Node);
77 int PTY_IOCtl(tVFS_Node *Node, int ID, void *Arg);
80 MODULE_DEFINE(0, 0x100, PTY, PTY_Install, NULL, NULL);
81 tVFS_NodeType gPTY_NodeType_Root = {
82 .TypeName = "PTY-Root",
83 .ReadDir = PTY_ReadDir,
84 .FindDir = PTY_FindDir,
86 tVFS_NodeType gPTY_NodeType_Client = {
87 .TypeName = "PTY-Client",
88 .Flags = VFS_NODETYPEFLAG_STREAM,
89 .Read = PTY_ReadClient,
90 .Write = PTY_WriteClient,
92 .Reference = PTY_ReferenceClient,
93 .Close = PTY_CloseClient
95 tVFS_NodeType gPTY_NodeType_Server = {
96 .TypeName = "PTY-Server",
97 .Flags = VFS_NODETYPEFLAG_STREAM,
98 .Read = PTY_ReadServer,
99 .Write = PTY_WriteServer,
101 .Close = PTY_CloseServer
103 tDevFS_Driver gPTY_Driver = {
106 .Flags = VFS_FFLAG_DIRECTORY,
107 .Type = &gPTY_NodeType_Root,
112 tRWLock glPTY_NumPTYs;
113 tPTY *gpPTY_FirstNumPTY;
114 int giPTY_NamedCount;
115 tRWLock glPTY_NamedPTYs;
116 tPTY *gpPTY_FirstNamedPTY;
119 int PTY_Install(char **Arguments)
121 DevFS_AddDevice(&gPTY_Driver);
122 return MODULE_ERR_OK;
125 // --- Management ---
126 tPTY *PTY_Create(const char *Name, void *Handle, tPTY_OutputFcn Output, tPTY_ReqResize ReqResize, tPTY_ModeSet ModeSet, const struct ptydims *InitialDims, const struct ptymode *InitialMode)
128 tPTY **prev_np = NULL;
135 if( Name[0] == '\0' )
137 RWLock_AcquireWrite(&glPTY_NumPTYs);
138 // Get a pty ID if Name==NULL
139 prev_np = &gpPTY_FirstNumPTY;
140 for( tPTY *pty = gpPTY_FirstNumPTY; pty; prev_np = &pty->Next, pty = pty->Next )
142 if( pty->NumericName > idx )
146 namelen = snprintf(NULL,0, "%u", idx);
148 else if( Name[strlen(Name)-1] == '#' )
151 // - "gui#" would translate to "gui0", "gui1", "gui2", ...
153 prev_np = &gpPTY_FirstNamedPTY;
155 RWLock_AcquireWrite(&glPTY_NamedPTYs);
157 namelen = strlen(Name)-1;
158 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
160 int cmp = strncmp(pty->Name, Name, namelen);
167 if( pty->Name[namelen] == '\0' )
170 // Find an unused index
172 int this_idx = strtol(pty->Name+namelen, &name_end, 10);
173 if( *name_end != '\0' )
180 namelen += snprintf(NULL, 0, "%u", idx);
184 prev_np = &gpPTY_FirstNamedPTY;
186 // Check the name isn't decimal
188 if( strtol(Name, &end, 10) != 0 && *end == '\0' ) {
193 RWLock_AcquireWrite(&glPTY_NamedPTYs);
195 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
197 int cmp = strcmp(pty->Name, Name);
201 RWLock_Release(&glPTY_NamedPTYs);
207 namelen = strlen(Name);
211 tPTY *ret = calloc(sizeof(tPTY) + namelen + 1, 1);
217 // - List maintainance
218 ret->Next = *prev_np;
220 // - PTY Name (Used by VT)
221 ret->Name = (char*)(ret + 1);
223 strcpy(ret->Name, Name);
225 sprintf(ret->Name, "%.*s%u", strlen(Name)-1, Name, idx);
227 sprintf(ret->Name, "%u", idx);
228 ret->NumericName = idx;
229 // - Output function and handle (same again)
230 ret->OutputHandle = Handle;
231 ret->OutputFcn = Output;
232 ret->ReqResize = ReqResize;
233 ret->ModeSet = ModeSet;
234 // - Initialise modes
236 ret->Dims = *InitialDims;
238 ret->Mode = *InitialMode;
240 ret->ClientNode.Size = -1;
241 ret->ClientNode.ImplPtr = ret;
242 ret->ClientNode.Type = &gPTY_NodeType_Client;
243 ret->ClientNode.UID = Threads_GetUID();
244 ret->ClientNode.GID = Threads_GetGID();
245 ret->ClientNode.NumACLs = 1;
246 ret->ClientNode.ACLs = &ret->OwnerRW;
247 // - Owner Read-Write ACL
248 ret->OwnerRW.Ent.ID = Threads_GetUID();
249 ret->OwnerRW.Perm.Perms = -1;
253 RWLock_Release(&glPTY_NamedPTYs);
257 RWLock_Release(&glPTY_NumPTYs);
263 int PTY_SetAttrib(tPTY *PTY, const struct ptydims *Dims, const struct ptymode *Mode, int WasClient)
267 // (for now) userland terminals can't be put into framebuffer mode
268 // - Userland PTYs are streams, framebuffer is a block
269 if( !PTY->OutputFcn && (Mode->OutputMode & PTYOMODE_BUFFMT) == PTYBUFFMT_FB ) {
275 if( PTY->ModeSet && PTY->ModeSet(PTY->OutputHandle, Mode) )
280 else if( !PTY->OutputFcn )
282 Log_Warning("PTY", "TODO: Inform server of client SETMODE, halt output");
283 // Block slave write until master ACKs
284 // 0-length read on master indicates need to GETMODE
289 // Should the client be informed that the server just twiddled the modes?
290 Log_Warning("PTY", "Server changed mode, TODO: inform client?");
292 LOG("PTY %p mode set to {0%o, 0%o}", PTY, Mode->InputMode, Mode->OutputMode);
300 if( PTY->ReqResize && PTY->ReqResize(PTY->OutputHandle, Dims) )
305 else if( !PTY->OutputFcn )
307 // Inform server process... somehow
308 Log_Warning("PTY", "TODO: Inform server of client resize request");
313 // SIGWINSZ to client
314 if( PTY->ControllingProcGroup > 0 )
315 Threads_SignalGroup(PTY->ControllingProcGroup, SIGWINCH);
317 LOG("PTY %p dims set to %ix%i", PTY, Dims->W, Dims->H);
323 void PTY_Close(tPTY *PTY)
328 size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len)
330 size_t space = (*rd - *wr + buflen - 1) % buflen;
331 len = MIN(space, len);
332 if(*wr + len >= buflen) {
333 size_t prelen = buflen - *wr;
334 memcpy((char*)buf + *wr, data, prelen);
335 memcpy(buf, (char*)data + prelen, len - prelen);
339 memcpy((char*)buf + *wr, data, len);
344 size_t _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len)
346 size_t space = (*wr - *rd + buflen) % buflen;
347 len = MIN(space, len);
348 if(*rd + len >= buflen) {
349 size_t prelen = buflen - *rd;
350 memcpy(data, (char*)buf + *rd, prelen);
351 memcpy((char*)data + prelen, buf, len - prelen);
355 memcpy(data, (char*)buf + *rd, len);
361 size_t PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length)
365 Mutex_Acquire(&PTY->InputMutex);
367 ret = _rb_write(PTY->InputData, INPUT_RINGBUFFER_LEN, &PTY->InputReadPos, &PTY->InputWritePos,
370 Mutex_Release(&PTY->InputMutex);
372 VFS_MarkAvaliable(&PTY->ClientNode, 1);
373 if(ret < Length && PTY->ServerNode)
374 VFS_MarkFull(PTY->ServerNode, 1);
379 size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length)
381 size_t ret = 1, print = 1;
383 // Input mode stuff only counts for text output mode
384 // - Any other mode sends Uint32 keypresses
385 if( (PTY->Mode.OutputMode & PTYOMODE_BUFFMT) != PTYBUFFMT_TEXT )
386 return PTY_int_WriteInput(PTY, Input, Length);
387 // If in raw mode, flush directly
388 if( (PTY->Mode.InputMode & PTYIMODE_RAW) )
389 return PTY_int_WriteInput(PTY, Input, Length);
391 if( PTY->Mode.InputMode & PTYIMODE_CANON )
398 if( PTY->ControllingProcGroup > 0 )
399 Threads_SignalGroup(PTY->ControllingProcGroup, SIGINT);
403 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
404 PTY->HasHitEOF = (PTY->LineLength == 0);
409 if(PTY->LineLength != 0) {
411 PTY_WriteClient(&PTY->ClientNode, 0, 3, "\b \b", 0);
415 case 'w'-'a': // Word erase
416 while(PTY->LineLength != 0 && isalnum(PTY->LineData[--PTY->LineLength]))
417 PTY_WriteClient(&PTY->ClientNode, 0, 1, "\b", 0);
418 PTY_WriteClient(&PTY->ClientNode, 0, 3, "\x1b[K", 0);
421 case 'u'-'a': // Kill
422 PTY_WriteClient(&PTY->ClientNode, 0, 8, "\x1b[2K\x1b[0G", 0);
433 if(PTY->LineLength == INPUT_LINE_LEN) {
434 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
437 PTY->LineData[PTY->LineLength++] = '\n';
438 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
441 // TODO: Handle ^[[D and ^[[C for in-line editing, also ^[[1~/^[[4~ (home/end)
446 if(PTY->LineLength == INPUT_LINE_LEN) {
447 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
450 PTY->LineData[PTY->LineLength++] = Input[0];
457 if( PTY->Mode.InputMode & PTYIMODE_NLCR )
459 if( Input[0] == '\n' ) {
461 ret = PTY_int_WriteInput(PTY, &ch, 1);
465 for( i = 0; i < Length && Input[i] != '\n'; i ++ )
467 ret = PTY_int_WriteInput(PTY, Input, i);
473 ret = PTY_int_WriteInput(PTY, Input, Length);
477 if( PTY->Mode.InputMode & PTYIMODE_ECHO )
479 PTY_WriteClient(&PTY->ClientNode, 0, print, Input, 0);
485 size_t PTY_SendInput(tPTY *PTY, const char *Input, size_t Length)
488 while( ret < Length && !PTY->ClientNode.BufferFull )
490 // TODO: Detect blocking?
491 ret += PTY_int_SendInput(PTY, Input + ret, Length - ret);
497 int PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX])
501 if( idx < giPTY_NumCount )
503 RWLock_AcquireRead(&glPTY_NumPTYs);
504 for( pty = gpPTY_FirstNumPTY; pty && idx; pty = pty->Next )
506 RWLock_Release(&glPTY_NumPTYs);
508 else if( idx < (giPTY_NumCount + giPTY_NamedCount) )
510 idx -= giPTY_NumCount;
511 RWLock_AcquireRead(&glPTY_NamedPTYs);
512 for( pty = gpPTY_FirstNamedPTY; pty && idx; pty = pty->Next )
514 RWLock_Release(&glPTY_NamedPTYs);
521 strncpy(Name, pty->Name, FILENAME_MAX);
525 tVFS_Node *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
528 int num = strtol(Name, &end, 10);
530 if( strcmp(Name, "ptmx") == 0 ) {
531 tVFS_Node *ret = calloc(sizeof(tVFS_Node), 1);
533 ret->Type = &gPTY_NodeType_Server;
537 if( Name[0] == '\0' )
541 if( num && end[0] == '\0' )
544 RWLock_AcquireRead(&glPTY_NumPTYs);
545 for( tPTY *pty = gpPTY_FirstNumPTY; pty; pty = pty->Next )
547 if( pty->NumericName > num )
549 if( pty->NumericName == num ) {
554 RWLock_Release(&glPTY_NumPTYs);
559 RWLock_AcquireRead(&glPTY_NamedPTYs);
560 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; pty = pty->Next )
562 int cmp = strcmp(pty->Name, Name);
570 RWLock_Release(&glPTY_NamedPTYs);
572 // Debug("PTY_FindDir('%s') returned %p", Name, &ret->ClientNode);
574 tVFS_Node *retnode = &ret->ClientNode;
575 retnode->ReferenceCount ++;
582 //\! Read from the client's input
583 size_t PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
585 tPTY *pty = Node->ImplPtr;
587 // Read from flushed queue
588 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
591 // If server has disconnected, return EIO
592 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 ) {
593 //Threads_PostSignal(SIGPIPE);
597 // Wait for data to be ready
598 rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadClient");
600 errno = (timeout ? EWOULDBLOCK : EINTR);
604 Mutex_Acquire(&pty->InputMutex);
605 Length = _rb_read(pty->InputData, INPUT_RINGBUFFER_LEN, &pty->InputReadPos, &pty->InputWritePos,
607 if( Length && pty->ServerNode )
608 VFS_MarkFull(pty->ServerNode, 0);
609 Mutex_Release(&pty->InputMutex);
611 if(pty->InputReadPos == pty->InputWritePos)
612 VFS_MarkAvaliable(Node, 0);
614 if(Length == 0 && !pty->HasHitEOF) {
622 //\! Write to the client's output
623 size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
625 tPTY *pty = Node->ImplPtr;
627 // If the server has terminated, send SIGPIPE
628 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
630 LOG("SIGPIPE, server has terminated");
631 Threads_PostSignal(SIGPIPE);
636 // Write to either FIFO or directly to output function
637 LOG("pty->OutputFcn = %p", pty->OutputFcn);
638 if( pty->OutputFcn ) {
639 pty->OutputFcn(pty->OutputHandle, Length, Buffer);
644 size_t remaining = Length;
647 tTime timeout_z, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
650 rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteClient");
652 errno = (timeout ? EWOULDBLOCK : EINTR);
656 // Write to output ringbuffer
657 size_t written = _rb_write(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
658 &pty->OutputReadPos, &pty->OutputWritePos,
660 LOG("Wrote %i of %i : '%.*s'", written, remaining, written, Buffer);
661 VFS_MarkAvaliable(pty->ServerNode, 1);
662 if( (pty->OutputWritePos + 1) % OUTPUT_RINGBUFFER_LEN == pty->OutputReadPos )
663 VFS_MarkFull(Node, 1);
665 remaining -= written;
666 Buffer = (const char*)Buffer + written;
667 } while( remaining > 0 || (Flags & VFS_IOFLAG_NOBLOCK) );
669 return Length - remaining;
672 void PTY_ReferenceClient(tVFS_Node *Node)
674 Node->ReferenceCount ++;
677 void PTY_CloseClient(tVFS_Node *Node)
679 tPTY *pty = Node->ImplPtr;
680 Node->ReferenceCount --;
682 // Remove PID from list
683 // TODO: Maintain list of client processes
685 // Free structure if this was the last open handle
686 if( Node->ReferenceCount > 0 )
688 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
690 // Free the structure! (Should be off the PTY list now)
691 free(pty->ServerNode);
696 //\! Read from the client's output
697 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
699 tPTY *pty = Node->ImplPtr;
705 // TODO: Prevent two servers fighting over client's output
708 // Kernel-land PTYs can't be read from userland
712 // Read back from fifo
713 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
714 int rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadServer");
716 errno = (timeout ? EWOULDBLOCK : EINTR);
720 Length = _rb_read(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
721 &pty->OutputReadPos, &pty->OutputWritePos,
723 LOG("Read %i '%.*s'", Length, Length, Buffer);
724 if( pty->OutputReadPos == pty->OutputWritePos )
725 VFS_MarkAvaliable(Node, 0);
726 VFS_MarkFull(&pty->ClientNode, 0);
731 //\! Write to the client's input
732 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
734 tPTY *pty = Node->ImplPtr;
740 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
741 int rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteServer");
743 errno = (timeout ? EWOULDBLOCK : EINTR);
748 used += PTY_SendInput(Node->ImplPtr, Buffer, Length);
749 } while( used < Length && !(Flags & VFS_IOFLAG_NOBLOCK) );
751 if( (pty->InputWritePos+1)%INPUT_RINGBUFFER_LEN == pty->InputReadPos )
752 VFS_MarkFull(Node, 1);
756 void PTY_CloseServer(tVFS_Node *Node)
758 tPTY *pty = Node->ImplPtr;
760 Node->ReferenceCount --;
761 // If reference count == 0, remove from main list
762 if( Node->ReferenceCount > 0 )
765 // Locate on list and remove
767 if( pty->NumericName == -1 ) {
768 RWLock_AcquireWrite(&glPTY_NamedPTYs);
769 prev_np = &gpPTY_FirstNamedPTY;
772 RWLock_AcquireWrite(&glPTY_NumPTYs);
773 prev_np = &gpPTY_FirstNumPTY;
776 // Search list until *prev_np is equal to pty
777 for( tPTY *tmp = *prev_np; *prev_np != pty && tmp; prev_np = &tmp->Next, tmp = tmp->Next )
781 if( *prev_np != pty ) {
782 Log_Error("PTY", "PTY %p(%i/%s) not on list at deletion time", pty, pty->NumericName, pty->Name);
785 *prev_np = pty->Next;
789 if( pty->NumericName == -1 ) {
790 RWLock_Release(&glPTY_NamedPTYs);
794 RWLock_Release(&glPTY_NumPTYs);
798 // Send SIGHUP to controling PGID
799 if( pty->ControllingProcGroup > 0 ) {
800 Threads_SignalGroup(pty->ControllingProcGroup, SIGHUP);
803 // If there are no open children, we can safely free this PTY
804 if( pty->ClientNode.ReferenceCount == 0 ) {
810 int PTY_IOCtl(tVFS_Node *Node, int ID, void *Data)
812 tPTY *pty = Node->ImplPtr;
813 struct ptymode *mode = Data;
814 struct ptydims *dims = Data;
816 int is_server = !pty || Node == pty->ServerNode;
818 LOG("(%i,%p) %s", ID, Data, (is_server?"Server":"Client"));
822 case DRV_IOCTL_TYPE: return DRV_TYPE_TERMINAL;
823 case DRV_IOCTL_IDENT: memcpy(Data, "PTY\0", 4); return 0;
824 case DRV_IOCTL_VERSION: return 0x100;
825 case DRV_IOCTL_LOOKUP: return 0;
827 case PTY_IOCTL_GETMODE:
829 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
831 // TODO: ACK client's SETMODE
833 case PTY_IOCTL_SETMODE:
835 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
836 PTY_SetAttrib(pty, NULL, mode, !is_server);
838 case PTY_IOCTL_GETDIMS:
840 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
843 case PTY_IOCTL_SETDIMS:
845 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
846 PTY_SetAttrib(pty, dims, NULL, !is_server);
848 case PTY_IOCTL_GETID:
851 size_t len = strlen(pty->Name)+1;
854 if( !CheckMem(Data, len) ) { errno = EINVAL; return -1; }
855 strcpy(Data, pty->Name);
860 case PTY_IOCTL_SETID:
861 if( Data && !CheckString(Data) ) { errno = EINVAL; return -1; }
862 if( pty ) return EALREADY;
863 pty = PTY_Create(Data, NULL, NULL,NULL, NULL, NULL,NULL);
867 pty->ServerNode = Node;
869 case PTY_IOCTL_SETPGRP:
870 // TODO: Should this only be done by client?
873 if( !CheckMem(Data, sizeof(tPGID)) ) { errno = EINVAL; return -1; }
874 pty->ControllingProcGroup = *(tPGID*)Data;
875 Log_Debug("PTY", "Set controlling PGID to %i", pty->ControllingProcGroup);
877 return pty->ControllingProcGroup;