3 * - By John Hodge (thePowersGang)
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;
58 // TODO: Maintain list of client PIDs
62 int PTY_Install(char **Arguments);
63 int PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX]);
64 tVFS_Node *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags);
66 size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len);
67 size_t _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len);
68 size_t PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length);
69 size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length);
71 size_t PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
72 size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
73 void PTY_ReferenceClient(tVFS_Node *Node);
74 void PTY_CloseClient(tVFS_Node *Node);
75 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
76 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
77 void PTY_CloseServer(tVFS_Node *Node);
78 int PTY_IOCtl(tVFS_Node *Node, int ID, void *Arg);
81 MODULE_DEFINE(0, 0x100, PTY, PTY_Install, NULL, NULL);
82 tVFS_NodeType gPTY_NodeType_Root = {
83 .TypeName = "PTY-Root",
84 .ReadDir = PTY_ReadDir,
85 .FindDir = PTY_FindDir,
87 tVFS_NodeType gPTY_NodeType_Client = {
88 .TypeName = "PTY-Client",
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 .Read = PTY_ReadServer,
98 .Write = PTY_WriteServer,
100 .Close = PTY_CloseServer
102 tDevFS_Driver gPTY_Driver = {
105 .Flags = VFS_FFLAG_DIRECTORY,
106 .Type = &gPTY_NodeType_Root,
111 tRWLock glPTY_NumPTYs;
112 tPTY *gpPTY_FirstNumPTY;
113 int giPTY_NamedCount;
114 tRWLock glPTY_NamedPTYs;
115 tPTY *gpPTY_FirstNamedPTY;
118 int PTY_Install(char **Arguments)
120 DevFS_AddDevice(&gPTY_Driver);
121 return MODULE_ERR_OK;
124 // --- Management ---
125 tPTY *PTY_Create(const char *Name, void *Handle, tPTY_OutputFcn Output, tPTY_ReqResize ReqResize, tPTY_ModeSet ModeSet)
127 tPTY **prev_np = NULL;
130 if( Name && Name[0] )
132 prev_np = &gpPTY_FirstNamedPTY;
134 // Check the name isn't decimal
136 if( strtol(Name, &end, 10) != 0 && *end == '\0' ) {
141 RWLock_AcquireWrite(&glPTY_NamedPTYs);
143 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
145 int cmp = strcmp(pty->Name, Name);
149 RWLock_Release(&glPTY_NamedPTYs);
155 namelen = strlen(Name);
160 RWLock_AcquireWrite(&glPTY_NumPTYs);
161 // Get a pty ID if Name==NULL
162 prev_np = &gpPTY_FirstNumPTY;
163 for( tPTY *pty = gpPTY_FirstNumPTY; pty; prev_np = &pty->Next, pty = pty->Next )
165 if( pty->NumericName > idx )
169 namelen = snprintf(NULL,0, "%u", idx);
172 tPTY *ret = calloc(sizeof(tPTY) + namelen + 1, 1);
178 // - List maintainance
179 ret->Next = *prev_np;
181 // - PTY Name (Used by VT)
182 ret->Name = (char*)(ret + 1);
184 strcpy(ret->Name, Name);
186 sprintf(ret->Name, "%u", idx);
187 ret->NumericName = idx;
188 // - Output function and handle (same again)
189 ret->OutputHandle = Handle;
190 ret->OutputFcn = Output;
191 ret->ReqResize = ReqResize;
192 ret->ModeSet = ModeSet;
194 ret->ClientNode.ImplPtr = ret;
195 ret->ClientNode.Type = &gPTY_NodeType_Client;
196 ret->ClientNode.UID = Threads_GetUID();
197 ret->ClientNode.GID = Threads_GetGID();
198 ret->ClientNode.NumACLs = 1;
199 ret->ClientNode.ACLs = &ret->OwnerRW;
200 // - Owner Read-Write ACL
201 ret->OwnerRW.Ent.ID = Threads_GetUID();
202 ret->OwnerRW.Perm.Perms = -1;
204 if( Name && Name[0] ) {
206 RWLock_Release(&glPTY_NamedPTYs);
210 RWLock_Release(&glPTY_NumPTYs);
216 int PTY_SetAttrib(tPTY *PTY, const struct ptydims *Dims, const struct ptymode *Mode, int WasClient)
220 // (for now) userland terminals can't be put into framebuffer mode
221 if( !PTY->OutputFcn && (Mode->OutputMode & PTYOMODE_BUFFMT) == PTYBUFFMT_FB ) {
227 if( PTY->ModeSet && PTY->ModeSet(PTY->OutputHandle, Mode) )
232 else if( !PTY->OutputFcn )
234 Log_Warning("PTY", "TODO: Need to stop client output until modeset has been ACKed");
235 // Block write until acked
236 // ACK by server doing GETMODE
241 // Should the client be informed that the server just twiddled the modes?
243 LOG("PTY %p mode set to {0%o, 0%o}", PTY, Mode->InputMode, Mode->OutputMode);
251 if( PTY->ReqResize && PTY->ReqResize(PTY->OutputHandle, Dims) )
256 else if( !PTY->OutputFcn )
258 // Inform server process... somehow
263 // SIGWINSZ to client
265 LOG("PTY %p dims set to %ix%i", PTY, Dims->W, Dims->H);
271 void PTY_Close(tPTY *PTY)
276 size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len)
278 size_t space = (*rd - *wr + buflen - 1) % buflen;
279 len = MIN(space, len);
280 if(*wr + len >= buflen) {
281 size_t prelen = buflen - *wr;
282 memcpy((char*)buf + *wr, data, prelen);
283 memcpy(buf, (char*)data + prelen, len - prelen);
287 memcpy((char*)buf + *wr, data, len);
292 size_t _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len)
294 size_t space = (*wr - *rd + buflen) % buflen;
295 len = MIN(space, len);
296 if(*rd + len >= buflen) {
297 size_t prelen = buflen - *rd;
298 memcpy(data, (char*)buf + *rd, prelen);
299 memcpy((char*)data + prelen, buf, len - prelen);
303 memcpy(data, (char*)buf + *rd, len);
309 size_t PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length)
313 Mutex_Acquire(&PTY->InputMutex);
315 ret = _rb_write(PTY->InputData, INPUT_RINGBUFFER_LEN, &PTY->InputReadPos, &PTY->InputWritePos,
318 Mutex_Release(&PTY->InputMutex);
320 VFS_MarkAvaliable(&PTY->ClientNode, 1);
321 if(ret < Length && PTY->ServerNode)
322 VFS_MarkFull(PTY->ServerNode, 1);
327 size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length)
329 size_t ret = 1, print = 1;
331 // Input mode stuff only counts for text output mode
332 // - Any other is Uint32 keypresses
333 if( (PTY->Mode.OutputMode & PTYOMODE_BUFFMT) != PTYBUFFMT_TEXT )
334 return PTY_int_WriteInput(PTY, Input, Length);
335 // If in raw mode, flush directlr
336 if( (PTY->Mode.InputMode & PTYIMODE_RAW) )
337 return PTY_int_WriteInput(PTY, Input, Length);
339 if( PTY->Mode.InputMode & PTYIMODE_CANON )
341 const char char_bs = '\b';
346 // Threads_PostSignalExt(PTY->ClientThreads, SIGINT);
350 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
351 PTY->HasHitEOF = (PTY->LineLength == 0);
356 if(PTY->LineLength != 0)
359 case 'w'-'a': // Word erase
360 while(PTY->LineLength != 0 && isalnum(PTY->LineData[--PTY->LineLength]))
361 PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
364 case 'u'-'a': // Kill
365 while(PTY->LineLength > 0)
366 PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
376 if(PTY->LineLength == INPUT_LINE_LEN) {
377 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
380 PTY->LineData[PTY->LineLength++] = '\n';
381 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
384 // TODO: Handle ^[[D and ^[[C for in-line editing, also ^[[1~/^[[4~ (home/end)
389 if(PTY->LineLength == INPUT_LINE_LEN) {
390 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
393 PTY->LineData[PTY->LineLength++] = Input[0];
399 ret = PTY_int_WriteInput(PTY, Input, Length);
403 if( PTY->Mode.InputMode & PTYIMODE_ECHO )
405 PTY_WriteClient(&PTY->ClientNode, 0, print, Input, 0);
411 size_t PTY_SendInput(tPTY *PTY, const char *Input, size_t Length)
414 while( ret < Length && !PTY->ClientNode.BufferFull )
416 // TODO: Detect blocking?
417 ret += PTY_int_SendInput(PTY, Input + ret, Length - ret);
423 int PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX])
427 if( idx < giPTY_NumCount )
429 RWLock_AcquireRead(&glPTY_NumPTYs);
430 for( pty = gpPTY_FirstNumPTY; pty && idx; pty = pty->Next )
432 RWLock_Release(&glPTY_NumPTYs);
434 else if( idx < (giPTY_NumCount + giPTY_NamedCount) )
436 idx -= giPTY_NumCount;
437 RWLock_AcquireRead(&glPTY_NamedPTYs);
438 for( pty = gpPTY_FirstNamedPTY; pty && idx; pty = pty->Next )
440 RWLock_Release(&glPTY_NamedPTYs);
447 strncpy(Name, pty->Name, FILENAME_MAX);
451 tVFS_Node *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
454 int num = strtol(Name, &end, 10);
456 if( strcmp(Name, "ptmx") == 0 ) {
457 tVFS_Node *ret = calloc(sizeof(tVFS_Node), 1);
459 ret->Type = &gPTY_NodeType_Server;
463 if( Name[0] == '\0' )
467 if( num && end[0] == '\0' )
470 RWLock_AcquireRead(&glPTY_NumPTYs);
471 for( tPTY *pty = gpPTY_FirstNumPTY; pty; pty = pty->Next )
473 if( pty->NumericName > num )
475 if( pty->NumericName == num ) {
480 RWLock_Release(&glPTY_NumPTYs);
485 RWLock_AcquireRead(&glPTY_NamedPTYs);
486 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; pty = pty->Next )
488 int cmp = strcmp(pty->Name, Name);
496 RWLock_Release(&glPTY_NamedPTYs);
499 tVFS_Node *retnode = &ret->ClientNode;
500 retnode->ReferenceCount ++;
507 //\! Read from the client's input
508 size_t PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
510 tPTY *pty = Node->ImplPtr;
512 // Read from flushed queue
513 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
516 // If server has disconnected, return EIO
517 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 ) {
518 //Threads_PostSignal(SIGPIPE);
522 // Wait for data to be ready
523 rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadClient");
525 errno = (timeout ? EWOULDBLOCK : EINTR);
529 Mutex_Acquire(&pty->InputMutex);
530 Length = _rb_read(pty->InputData, INPUT_RINGBUFFER_LEN, &pty->InputReadPos, &pty->InputWritePos,
532 if( Length && pty->ServerNode )
533 VFS_MarkFull(pty->ServerNode, 0);
534 Mutex_Release(&pty->InputMutex);
536 if(pty->InputReadPos == pty->InputWritePos)
537 VFS_MarkAvaliable(Node, 0);
539 if(Length == 0 && !pty->HasHitEOF) {
547 //\! Write to the client's output
548 size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
550 tPTY *pty = Node->ImplPtr;
552 // If the server has terminated, send SIGPIPE
553 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
555 Threads_PostSignal(SIGPIPE);
560 // Write to either FIFO or directly to output function
561 if( pty->OutputFcn ) {
562 pty->OutputFcn(pty->OutputHandle, Length, Buffer);
567 tTime timeout_z, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
570 rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteClient");
572 errno = (timeout ? EWOULDBLOCK : EINTR);
576 // Write to output ringbuffer
577 Length = _rb_write(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
578 &pty->OutputReadPos, &pty->OutputWritePos,
580 VFS_MarkAvaliable(pty->ServerNode, 1);
581 if( (pty->OutputWritePos + 1) % OUTPUT_RINGBUFFER_LEN == pty->OutputReadPos )
582 VFS_MarkFull(Node, 1);
587 void PTY_ReferenceClient(tVFS_Node *Node)
589 Node->ReferenceCount ++;
590 // TODO: Add PID to list of client PIDs
591 // Log_Notice("PTY", "ReferenceClient: TODO - List of client PIDs");
594 void PTY_CloseClient(tVFS_Node *Node)
596 tPTY *pty = Node->ImplPtr;
597 Node->ReferenceCount --;
599 // Remove PID from list
600 // TODO: Maintain list of client processes
602 // Free structure if this was the last open handle
603 if( Node->ReferenceCount > 0 )
605 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
607 // Free the structure! (Should be off the PTY list now)
608 free(pty->ServerNode);
613 //\! Read from the client's output
614 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
616 tPTY *pty = Node->ImplPtr;
622 // TODO: Prevent two servers fighting over client's output
625 // Kernel-land PTYs can't be read from userland
629 // Read back from fifo
630 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
631 int rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadServer");
633 errno = (timeout ? EWOULDBLOCK : EINTR);
637 Length = _rb_read(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
638 &pty->OutputReadPos, &pty->OutputWritePos,
640 if( pty->OutputReadPos == pty->OutputWritePos )
641 VFS_MarkAvaliable(Node, 0);
642 VFS_MarkFull(&pty->ClientNode, 0);
647 //\! Write to the client's input
648 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
650 tPTY *pty = Node->ImplPtr;
656 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
657 int rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteServer");
659 errno = (timeout ? EWOULDBLOCK : EINTR);
664 used += PTY_SendInput(Node->ImplPtr, Buffer, Length);
665 } while( used < Length && !(Flags & VFS_IOFLAG_NOBLOCK) );
667 if( (pty->InputWritePos+1)%INPUT_RINGBUFFER_LEN == pty->InputReadPos )
668 VFS_MarkFull(Node, 1);
672 void PTY_CloseServer(tVFS_Node *Node)
674 tPTY *pty = Node->ImplPtr;
676 Node->ReferenceCount --;
677 // If reference count == 0, remove from main list
678 if( Node->ReferenceCount > 0 )
681 // Locate on list and remove
683 if( pty->NumericName == -1 ) {
684 RWLock_AcquireWrite(&glPTY_NamedPTYs);
685 prev_np = &gpPTY_FirstNamedPTY;
688 RWLock_AcquireWrite(&glPTY_NumPTYs);
689 prev_np = &gpPTY_FirstNumPTY;
692 // Search list until *prev_np is equal to pty
693 for( tPTY *tmp = *prev_np; *prev_np != pty && tmp; prev_np = &tmp->Next, tmp = tmp->Next )
697 if( *prev_np != pty ) {
698 Log_Error("PTY", "PTY %p(%i/%s) not on list at deletion time", pty, pty->NumericName, pty->Name);
701 *prev_np = pty->Next;
705 if( pty->NumericName == -1 ) {
706 RWLock_Release(&glPTY_NamedPTYs);
710 RWLock_Release(&glPTY_NumPTYs);
714 // Send SIGHUP to controling PGID
715 if( pty->ControllingProcGroup > 0 ) {
716 Threads_SignalGroup(pty->ControllingProcGroup, SIGHUP);
719 // If there are no open children, we can safely free this PTY
720 if( pty->ClientNode.ReferenceCount == 0 ) {
726 int PTY_IOCtl(tVFS_Node *Node, int ID, void *Data)
728 tPTY *pty = Node->ImplPtr;
729 struct ptymode *mode = Data;
730 struct ptydims *dims = Data;
732 int is_server = !pty || Node == pty->ServerNode;
736 case DRV_IOCTL_TYPE: return DRV_TYPE_TERMINAL;
737 case DRV_IOCTL_IDENT: memcpy(Data, "PTY\0", 4); return 0;
738 case DRV_IOCTL_VERSION: return 0x100;
739 case DRV_IOCTL_LOOKUP: return 0;
741 case PTY_IOCTL_GETMODE:
743 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
745 // TODO: ACK client's SETMODE
747 case PTY_IOCTL_SETMODE:
749 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
750 PTY_SetAttrib(pty, NULL, mode, !is_server);
752 case PTY_IOCTL_GETDIMS:
754 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
757 case PTY_IOCTL_SETDIMS:
759 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
760 PTY_SetAttrib(pty, dims, NULL, !is_server);
762 case PTY_IOCTL_GETID:
765 size_t len = strlen(pty->Name)+1;
768 if( !CheckMem(Data, len) ) { errno = EINVAL; return -1; }
769 strcpy(Data, pty->Name);
774 case PTY_IOCTL_SETID:
775 if( Data && !CheckString(Data) ) { errno = EINVAL; return -1; }
776 if( pty ) return EALREADY;
777 pty = PTY_Create(Data, NULL, NULL,NULL, NULL);
781 pty->ServerNode = Node;
783 case PTY_IOCTL_SETPGRP:
784 // TODO: Should this only be done by client?
787 if( !CheckMem(Data, sizeof(tPGID)) ) { errno = EINVAL; return -1; }
788 pty->ControllingProcGroup = *(tPGID*)Data;
789 Log_Debug("PTY", "Set controlling PGID to %i", pty->ControllingProcGroup);
791 return pty->ControllingProcGroup;