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 .Read = PTY_ReadClient,
89 .Write = PTY_WriteClient,
91 .Reference = PTY_ReferenceClient,
92 .Close = PTY_CloseClient
94 tVFS_NodeType gPTY_NodeType_Server = {
95 .TypeName = "PTY-Server",
96 .Read = PTY_ReadServer,
97 .Write = PTY_WriteServer,
99 .Close = PTY_CloseServer
101 tDevFS_Driver gPTY_Driver = {
104 .Flags = VFS_FFLAG_DIRECTORY,
105 .Type = &gPTY_NodeType_Root,
110 tRWLock glPTY_NumPTYs;
111 tPTY *gpPTY_FirstNumPTY;
112 int giPTY_NamedCount;
113 tRWLock glPTY_NamedPTYs;
114 tPTY *gpPTY_FirstNamedPTY;
117 int PTY_Install(char **Arguments)
119 DevFS_AddDevice(&gPTY_Driver);
120 return MODULE_ERR_OK;
123 // --- Management ---
124 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)
126 tPTY **prev_np = NULL;
133 if( Name[0] == '\0' )
135 RWLock_AcquireWrite(&glPTY_NumPTYs);
136 // Get a pty ID if Name==NULL
137 prev_np = &gpPTY_FirstNumPTY;
138 for( tPTY *pty = gpPTY_FirstNumPTY; pty; prev_np = &pty->Next, pty = pty->Next )
140 if( pty->NumericName > idx )
144 namelen = snprintf(NULL,0, "%u", idx);
146 else if( Name[strlen(Name)-1] == '#' )
149 // - "gui#" would translate to "gui0", "gui1", "gui2", ...
151 prev_np = &gpPTY_FirstNamedPTY;
153 RWLock_AcquireWrite(&glPTY_NamedPTYs);
155 namelen = strlen(Name)-1;
156 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
158 int cmp = strncmp(pty->Name, Name, namelen);
165 if( pty->Name[namelen] == '\0' )
168 // Find an unused index
170 int this_idx = strtol(pty->Name+namelen, &name_end, 10);
171 if( *name_end != '\0' )
178 namelen += snprintf(NULL, 0, "%u", idx);
182 prev_np = &gpPTY_FirstNamedPTY;
184 // Check the name isn't decimal
186 if( strtol(Name, &end, 10) != 0 && *end == '\0' ) {
191 RWLock_AcquireWrite(&glPTY_NamedPTYs);
193 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
195 int cmp = strcmp(pty->Name, Name);
199 RWLock_Release(&glPTY_NamedPTYs);
205 namelen = strlen(Name);
209 tPTY *ret = calloc(sizeof(tPTY) + namelen + 1, 1);
215 // - List maintainance
216 ret->Next = *prev_np;
218 // - PTY Name (Used by VT)
219 ret->Name = (char*)(ret + 1);
221 strcpy(ret->Name, Name);
223 sprintf(ret->Name, "%.*s%u", strlen(Name)-1, Name, idx);
225 sprintf(ret->Name, "%u", idx);
226 ret->NumericName = idx;
227 // - Output function and handle (same again)
228 ret->OutputHandle = Handle;
229 ret->OutputFcn = Output;
230 ret->ReqResize = ReqResize;
231 ret->ModeSet = ModeSet;
232 // - Initialise modes
234 ret->Dims = *InitialDims;
236 ret->Mode = *InitialMode;
238 ret->ClientNode.ImplPtr = ret;
239 ret->ClientNode.Type = &gPTY_NodeType_Client;
240 ret->ClientNode.UID = Threads_GetUID();
241 ret->ClientNode.GID = Threads_GetGID();
242 ret->ClientNode.NumACLs = 1;
243 ret->ClientNode.ACLs = &ret->OwnerRW;
244 // - Owner Read-Write ACL
245 ret->OwnerRW.Ent.ID = Threads_GetUID();
246 ret->OwnerRW.Perm.Perms = -1;
250 RWLock_Release(&glPTY_NamedPTYs);
254 RWLock_Release(&glPTY_NumPTYs);
260 int PTY_SetAttrib(tPTY *PTY, const struct ptydims *Dims, const struct ptymode *Mode, int WasClient)
264 // (for now) userland terminals can't be put into framebuffer mode
265 // - Userland PTYs are streams, framebuffer is a block
266 if( !PTY->OutputFcn && (Mode->OutputMode & PTYOMODE_BUFFMT) == PTYBUFFMT_FB ) {
272 if( PTY->ModeSet && PTY->ModeSet(PTY->OutputHandle, Mode) )
277 else if( !PTY->OutputFcn )
279 Log_Warning("PTY", "TODO: Inform server of client SETMODE, halt output");
280 // Block slave write until master ACKs
281 // 0-length read on master indicates need to GETMODE
286 // Should the client be informed that the server just twiddled the modes?
287 Log_Warning("PTY", "Server changed mode, TODO: inform client?");
289 LOG("PTY %p mode set to {0%o, 0%o}", PTY, Mode->InputMode, Mode->OutputMode);
297 if( PTY->ReqResize && PTY->ReqResize(PTY->OutputHandle, Dims) )
302 else if( !PTY->OutputFcn )
304 // Inform server process... somehow
305 Log_Warning("PTY", "TODO: Inform server of client resize request");
310 // SIGWINSZ to client
311 Threads_SignalGroup(PTY->ControllingProcGroup, SIGWINCH);
313 LOG("PTY %p dims set to %ix%i", PTY, Dims->W, Dims->H);
319 void PTY_Close(tPTY *PTY)
324 size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len)
326 size_t space = (*rd - *wr + buflen - 1) % buflen;
327 len = MIN(space, len);
328 if(*wr + len >= buflen) {
329 size_t prelen = buflen - *wr;
330 memcpy((char*)buf + *wr, data, prelen);
331 memcpy(buf, (char*)data + prelen, len - prelen);
335 memcpy((char*)buf + *wr, data, len);
340 size_t _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len)
342 size_t space = (*wr - *rd + buflen) % buflen;
343 len = MIN(space, len);
344 if(*rd + len >= buflen) {
345 size_t prelen = buflen - *rd;
346 memcpy(data, (char*)buf + *rd, prelen);
347 memcpy((char*)data + prelen, buf, len - prelen);
351 memcpy(data, (char*)buf + *rd, len);
357 size_t PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length)
361 Mutex_Acquire(&PTY->InputMutex);
363 ret = _rb_write(PTY->InputData, INPUT_RINGBUFFER_LEN, &PTY->InputReadPos, &PTY->InputWritePos,
366 Mutex_Release(&PTY->InputMutex);
368 VFS_MarkAvaliable(&PTY->ClientNode, 1);
369 if(ret < Length && PTY->ServerNode)
370 VFS_MarkFull(PTY->ServerNode, 1);
375 size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length)
377 size_t ret = 1, print = 1;
379 // Input mode stuff only counts for text output mode
380 // - Any other is Uint32 keypresses
381 if( (PTY->Mode.OutputMode & PTYOMODE_BUFFMT) != PTYBUFFMT_TEXT )
382 return PTY_int_WriteInput(PTY, Input, Length);
383 // If in raw mode, flush directlr
384 if( (PTY->Mode.InputMode & PTYIMODE_RAW) )
385 return PTY_int_WriteInput(PTY, Input, Length);
387 if( PTY->Mode.InputMode & PTYIMODE_CANON )
389 const char char_bs = '\b';
394 Threads_SignalGroup(PTY->ControllingProcGroup, SIGINT);
398 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
399 PTY->HasHitEOF = (PTY->LineLength == 0);
404 if(PTY->LineLength != 0)
407 case 'w'-'a': // Word erase
408 while(PTY->LineLength != 0 && isalnum(PTY->LineData[--PTY->LineLength]))
409 PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
412 case 'u'-'a': // Kill
413 while(PTY->LineLength > 0)
414 PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
424 if(PTY->LineLength == INPUT_LINE_LEN) {
425 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
428 PTY->LineData[PTY->LineLength++] = '\n';
429 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
432 // TODO: Handle ^[[D and ^[[C for in-line editing, also ^[[1~/^[[4~ (home/end)
437 if(PTY->LineLength == INPUT_LINE_LEN) {
438 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
441 PTY->LineData[PTY->LineLength++] = Input[0];
447 ret = PTY_int_WriteInput(PTY, Input, Length);
451 if( PTY->Mode.InputMode & PTYIMODE_ECHO )
453 PTY_WriteClient(&PTY->ClientNode, 0, print, Input, 0);
459 size_t PTY_SendInput(tPTY *PTY, const char *Input, size_t Length)
462 while( ret < Length && !PTY->ClientNode.BufferFull )
464 // TODO: Detect blocking?
465 ret += PTY_int_SendInput(PTY, Input + ret, Length - ret);
471 int PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX])
475 if( idx < giPTY_NumCount )
477 RWLock_AcquireRead(&glPTY_NumPTYs);
478 for( pty = gpPTY_FirstNumPTY; pty && idx; pty = pty->Next )
480 RWLock_Release(&glPTY_NumPTYs);
482 else if( idx < (giPTY_NumCount + giPTY_NamedCount) )
484 idx -= giPTY_NumCount;
485 RWLock_AcquireRead(&glPTY_NamedPTYs);
486 for( pty = gpPTY_FirstNamedPTY; pty && idx; pty = pty->Next )
488 RWLock_Release(&glPTY_NamedPTYs);
495 strncpy(Name, pty->Name, FILENAME_MAX);
499 tVFS_Node *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
502 int num = strtol(Name, &end, 10);
504 if( strcmp(Name, "ptmx") == 0 ) {
505 tVFS_Node *ret = calloc(sizeof(tVFS_Node), 1);
507 ret->Type = &gPTY_NodeType_Server;
511 if( Name[0] == '\0' )
515 if( num && end[0] == '\0' )
518 RWLock_AcquireRead(&glPTY_NumPTYs);
519 for( tPTY *pty = gpPTY_FirstNumPTY; pty; pty = pty->Next )
521 if( pty->NumericName > num )
523 if( pty->NumericName == num ) {
528 RWLock_Release(&glPTY_NumPTYs);
533 RWLock_AcquireRead(&glPTY_NamedPTYs);
534 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; pty = pty->Next )
536 int cmp = strcmp(pty->Name, Name);
544 RWLock_Release(&glPTY_NamedPTYs);
546 // Debug("PTY_FindDir('%s') returned %p", Name, &ret->ClientNode);
548 tVFS_Node *retnode = &ret->ClientNode;
549 retnode->ReferenceCount ++;
556 //\! Read from the client's input
557 size_t PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
559 tPTY *pty = Node->ImplPtr;
561 // Read from flushed queue
562 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
565 // If server has disconnected, return EIO
566 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 ) {
567 //Threads_PostSignal(SIGPIPE);
571 // Wait for data to be ready
572 rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadClient");
574 errno = (timeout ? EWOULDBLOCK : EINTR);
578 Mutex_Acquire(&pty->InputMutex);
579 Length = _rb_read(pty->InputData, INPUT_RINGBUFFER_LEN, &pty->InputReadPos, &pty->InputWritePos,
581 if( Length && pty->ServerNode )
582 VFS_MarkFull(pty->ServerNode, 0);
583 Mutex_Release(&pty->InputMutex);
585 if(pty->InputReadPos == pty->InputWritePos)
586 VFS_MarkAvaliable(Node, 0);
588 if(Length == 0 && !pty->HasHitEOF) {
596 //\! Write to the client's output
597 size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
599 tPTY *pty = Node->ImplPtr;
601 // If the server has terminated, send SIGPIPE
602 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
604 Threads_PostSignal(SIGPIPE);
609 // Write to either FIFO or directly to output function
610 if( pty->OutputFcn ) {
611 pty->OutputFcn(pty->OutputHandle, Length, Buffer);
616 size_t remaining = Length;
619 tTime timeout_z, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
622 rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteClient");
624 errno = (timeout ? EWOULDBLOCK : EINTR);
628 // Write to output ringbuffer
629 size_t written = _rb_write(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
630 &pty->OutputReadPos, &pty->OutputWritePos,
632 LOG("Wrote %i of %i : '%.*s'", written, remaining, written, Buffer);
633 VFS_MarkAvaliable(pty->ServerNode, 1);
634 if( (pty->OutputWritePos + 1) % OUTPUT_RINGBUFFER_LEN == pty->OutputReadPos )
635 VFS_MarkFull(Node, 1);
637 remaining -= written;
638 Buffer = (const char*)Buffer + written;
639 } while( remaining > 0 || (Flags & VFS_IOFLAG_NOBLOCK) );
641 return Length - remaining;
644 void PTY_ReferenceClient(tVFS_Node *Node)
646 Node->ReferenceCount ++;
649 void PTY_CloseClient(tVFS_Node *Node)
651 tPTY *pty = Node->ImplPtr;
652 Node->ReferenceCount --;
654 // Remove PID from list
655 // TODO: Maintain list of client processes
657 // Free structure if this was the last open handle
658 if( Node->ReferenceCount > 0 )
660 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
662 // Free the structure! (Should be off the PTY list now)
663 free(pty->ServerNode);
668 //\! Read from the client's output
669 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
671 tPTY *pty = Node->ImplPtr;
677 // TODO: Prevent two servers fighting over client's output
680 // Kernel-land PTYs can't be read from userland
684 // Read back from fifo
685 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
686 int rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadServer");
688 errno = (timeout ? EWOULDBLOCK : EINTR);
692 Length = _rb_read(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
693 &pty->OutputReadPos, &pty->OutputWritePos,
695 LOG("Read %i '%.*s'", Length, Length, Buffer);
696 if( pty->OutputReadPos == pty->OutputWritePos )
697 VFS_MarkAvaliable(Node, 0);
698 VFS_MarkFull(&pty->ClientNode, 0);
703 //\! Write to the client's input
704 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
706 tPTY *pty = Node->ImplPtr;
712 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
713 int rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteServer");
715 errno = (timeout ? EWOULDBLOCK : EINTR);
720 used += PTY_SendInput(Node->ImplPtr, Buffer, Length);
721 } while( used < Length && !(Flags & VFS_IOFLAG_NOBLOCK) );
723 if( (pty->InputWritePos+1)%INPUT_RINGBUFFER_LEN == pty->InputReadPos )
724 VFS_MarkFull(Node, 1);
728 void PTY_CloseServer(tVFS_Node *Node)
730 tPTY *pty = Node->ImplPtr;
732 Node->ReferenceCount --;
733 // If reference count == 0, remove from main list
734 if( Node->ReferenceCount > 0 )
737 // Locate on list and remove
739 if( pty->NumericName == -1 ) {
740 RWLock_AcquireWrite(&glPTY_NamedPTYs);
741 prev_np = &gpPTY_FirstNamedPTY;
744 RWLock_AcquireWrite(&glPTY_NumPTYs);
745 prev_np = &gpPTY_FirstNumPTY;
748 // Search list until *prev_np is equal to pty
749 for( tPTY *tmp = *prev_np; *prev_np != pty && tmp; prev_np = &tmp->Next, tmp = tmp->Next )
753 if( *prev_np != pty ) {
754 Log_Error("PTY", "PTY %p(%i/%s) not on list at deletion time", pty, pty->NumericName, pty->Name);
757 *prev_np = pty->Next;
761 if( pty->NumericName == -1 ) {
762 RWLock_Release(&glPTY_NamedPTYs);
766 RWLock_Release(&glPTY_NumPTYs);
770 // Send SIGHUP to controling PGID
771 if( pty->ControllingProcGroup > 0 ) {
772 Threads_SignalGroup(pty->ControllingProcGroup, SIGHUP);
775 // If there are no open children, we can safely free this PTY
776 if( pty->ClientNode.ReferenceCount == 0 ) {
782 int PTY_IOCtl(tVFS_Node *Node, int ID, void *Data)
784 tPTY *pty = Node->ImplPtr;
785 struct ptymode *mode = Data;
786 struct ptydims *dims = Data;
788 int is_server = !pty || Node == pty->ServerNode;
792 case DRV_IOCTL_TYPE: return DRV_TYPE_TERMINAL;
793 case DRV_IOCTL_IDENT: memcpy(Data, "PTY\0", 4); return 0;
794 case DRV_IOCTL_VERSION: return 0x100;
795 case DRV_IOCTL_LOOKUP: return 0;
797 case PTY_IOCTL_GETMODE:
799 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
801 // TODO: ACK client's SETMODE
803 case PTY_IOCTL_SETMODE:
805 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
806 PTY_SetAttrib(pty, NULL, mode, !is_server);
808 case PTY_IOCTL_GETDIMS:
810 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
813 case PTY_IOCTL_SETDIMS:
815 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
816 PTY_SetAttrib(pty, dims, NULL, !is_server);
818 case PTY_IOCTL_GETID:
821 size_t len = strlen(pty->Name)+1;
824 if( !CheckMem(Data, len) ) { errno = EINVAL; return -1; }
825 strcpy(Data, pty->Name);
830 case PTY_IOCTL_SETID:
831 if( Data && !CheckString(Data) ) { errno = EINVAL; return -1; }
832 if( pty ) return EALREADY;
833 pty = PTY_Create(Data, NULL, NULL,NULL, NULL, NULL,NULL);
837 pty->ServerNode = Node;
839 case PTY_IOCTL_SETPGRP:
840 // TODO: Should this only be done by client?
843 if( !CheckMem(Data, sizeof(tPGID)) ) { errno = EINVAL; return -1; }
844 pty->ControllingProcGroup = *(tPGID*)Data;
845 Log_Debug("PTY", "Set controlling PGID to %i", pty->ControllingProcGroup);
847 return pty->ControllingProcGroup;