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);
498 // Debug("PTY_FindDir('%s') returned %p", Name, &ret->ClientNode);
500 tVFS_Node *retnode = &ret->ClientNode;
501 retnode->ReferenceCount ++;
508 //\! Read from the client's input
509 size_t PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
511 tPTY *pty = Node->ImplPtr;
513 // Read from flushed queue
514 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
517 // If server has disconnected, return EIO
518 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 ) {
519 //Threads_PostSignal(SIGPIPE);
523 // Wait for data to be ready
524 rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadClient");
526 errno = (timeout ? EWOULDBLOCK : EINTR);
530 Mutex_Acquire(&pty->InputMutex);
531 Length = _rb_read(pty->InputData, INPUT_RINGBUFFER_LEN, &pty->InputReadPos, &pty->InputWritePos,
533 if( Length && pty->ServerNode )
534 VFS_MarkFull(pty->ServerNode, 0);
535 Mutex_Release(&pty->InputMutex);
537 if(pty->InputReadPos == pty->InputWritePos)
538 VFS_MarkAvaliable(Node, 0);
540 if(Length == 0 && !pty->HasHitEOF) {
548 //\! Write to the client's output
549 size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
551 tPTY *pty = Node->ImplPtr;
553 // If the server has terminated, send SIGPIPE
554 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
556 Threads_PostSignal(SIGPIPE);
561 // Write to either FIFO or directly to output function
562 if( pty->OutputFcn ) {
563 pty->OutputFcn(pty->OutputHandle, Length, Buffer);
568 size_t remaining = Length;
571 tTime timeout_z, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
574 rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteClient");
576 errno = (timeout ? EWOULDBLOCK : EINTR);
580 // Write to output ringbuffer
581 size_t written = _rb_write(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
582 &pty->OutputReadPos, &pty->OutputWritePos,
584 LOG("Wrote %i of %i : '%.*s'", written, remaining, written, Buffer);
585 VFS_MarkAvaliable(pty->ServerNode, 1);
586 if( (pty->OutputWritePos + 1) % OUTPUT_RINGBUFFER_LEN == pty->OutputReadPos )
587 VFS_MarkFull(Node, 1);
589 remaining -= written;
590 Buffer = (const char*)Buffer + written;
591 } while( remaining > 0 || (Flags & VFS_IOFLAG_NOBLOCK) );
593 return Length - remaining;
596 void PTY_ReferenceClient(tVFS_Node *Node)
598 Node->ReferenceCount ++;
601 void PTY_CloseClient(tVFS_Node *Node)
603 tPTY *pty = Node->ImplPtr;
604 Node->ReferenceCount --;
606 // Remove PID from list
607 // TODO: Maintain list of client processes
609 // Free structure if this was the last open handle
610 if( Node->ReferenceCount > 0 )
612 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
614 // Free the structure! (Should be off the PTY list now)
615 free(pty->ServerNode);
620 //\! Read from the client's output
621 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
623 tPTY *pty = Node->ImplPtr;
629 // TODO: Prevent two servers fighting over client's output
632 // Kernel-land PTYs can't be read from userland
636 // Read back from fifo
637 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
638 int rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadServer");
640 errno = (timeout ? EWOULDBLOCK : EINTR);
644 Length = _rb_read(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
645 &pty->OutputReadPos, &pty->OutputWritePos,
647 LOG("Read %i '%.*s'", Length, Length, Buffer);
648 if( pty->OutputReadPos == pty->OutputWritePos )
649 VFS_MarkAvaliable(Node, 0);
650 VFS_MarkFull(&pty->ClientNode, 0);
655 //\! Write to the client's input
656 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
658 tPTY *pty = Node->ImplPtr;
664 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
665 int rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteServer");
667 errno = (timeout ? EWOULDBLOCK : EINTR);
672 used += PTY_SendInput(Node->ImplPtr, Buffer, Length);
673 } while( used < Length && !(Flags & VFS_IOFLAG_NOBLOCK) );
675 if( (pty->InputWritePos+1)%INPUT_RINGBUFFER_LEN == pty->InputReadPos )
676 VFS_MarkFull(Node, 1);
680 void PTY_CloseServer(tVFS_Node *Node)
682 tPTY *pty = Node->ImplPtr;
684 Node->ReferenceCount --;
685 // If reference count == 0, remove from main list
686 if( Node->ReferenceCount > 0 )
689 // Locate on list and remove
691 if( pty->NumericName == -1 ) {
692 RWLock_AcquireWrite(&glPTY_NamedPTYs);
693 prev_np = &gpPTY_FirstNamedPTY;
696 RWLock_AcquireWrite(&glPTY_NumPTYs);
697 prev_np = &gpPTY_FirstNumPTY;
700 // Search list until *prev_np is equal to pty
701 for( tPTY *tmp = *prev_np; *prev_np != pty && tmp; prev_np = &tmp->Next, tmp = tmp->Next )
705 if( *prev_np != pty ) {
706 Log_Error("PTY", "PTY %p(%i/%s) not on list at deletion time", pty, pty->NumericName, pty->Name);
709 *prev_np = pty->Next;
713 if( pty->NumericName == -1 ) {
714 RWLock_Release(&glPTY_NamedPTYs);
718 RWLock_Release(&glPTY_NumPTYs);
722 // Send SIGHUP to controling PGID
723 if( pty->ControllingProcGroup > 0 ) {
724 Threads_SignalGroup(pty->ControllingProcGroup, SIGHUP);
727 // If there are no open children, we can safely free this PTY
728 if( pty->ClientNode.ReferenceCount == 0 ) {
734 int PTY_IOCtl(tVFS_Node *Node, int ID, void *Data)
736 tPTY *pty = Node->ImplPtr;
737 struct ptymode *mode = Data;
738 struct ptydims *dims = Data;
740 int is_server = !pty || Node == pty->ServerNode;
744 case DRV_IOCTL_TYPE: return DRV_TYPE_TERMINAL;
745 case DRV_IOCTL_IDENT: memcpy(Data, "PTY\0", 4); return 0;
746 case DRV_IOCTL_VERSION: return 0x100;
747 case DRV_IOCTL_LOOKUP: return 0;
749 case PTY_IOCTL_GETMODE:
751 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
753 // TODO: ACK client's SETMODE
755 case PTY_IOCTL_SETMODE:
757 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
758 PTY_SetAttrib(pty, NULL, mode, !is_server);
760 case PTY_IOCTL_GETDIMS:
762 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
765 case PTY_IOCTL_SETDIMS:
767 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
768 PTY_SetAttrib(pty, dims, NULL, !is_server);
770 case PTY_IOCTL_GETID:
773 size_t len = strlen(pty->Name)+1;
776 if( !CheckMem(Data, len) ) { errno = EINVAL; return -1; }
777 strcpy(Data, pty->Name);
782 case PTY_IOCTL_SETID:
783 if( Data && !CheckString(Data) ) { errno = EINVAL; return -1; }
784 if( pty ) return EALREADY;
785 pty = PTY_Create(Data, NULL, NULL,NULL, NULL);
789 pty->ServerNode = Node;
791 case PTY_IOCTL_SETPGRP:
792 // TODO: Should this only be done by client?
795 if( !CheckMem(Data, sizeof(tPGID)) ) { errno = EINVAL; return -1; }
796 pty->ControllingProcGroup = *(tPGID*)Data;
797 Log_Debug("PTY", "Set controlling PGID to %i", pty->ControllingProcGroup);
799 return pty->ControllingProcGroup;