3 * - By John Hodge (thePowersGang)
18 #define OUTPUT_RINGBUFFER_LEN 1024 // Number of bytes in output queue before client blocks
19 #define INPUT_RINGBUFFER_LEN 256 // Number of bytes in input queue before being dropped
20 #define INPUT_LINE_LEN 256
31 tPTY_OutputFcn OutputFcn;
32 tPTY_ReqResize ReqResize;
42 char InputData[INPUT_RINGBUFFER_LEN];
45 char LineData[INPUT_LINE_LEN];
50 char OutputData[OUTPUT_RINGBUFFER_LEN];
52 tVFS_Node *ServerNode;
56 // TODO: Maintain list of client PIDs
60 int PTY_Install(char **Arguments);
61 int PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX]);
62 tVFS_Node *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags);
64 size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len);
65 size_t _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len);
66 size_t PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length);
67 size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length);
69 size_t PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
70 size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
71 void PTY_ReferenceClient(tVFS_Node *Node);
72 void PTY_CloseClient(tVFS_Node *Node);
73 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
74 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
75 void PTY_CloseServer(tVFS_Node *Node);
76 int PTY_IOCtl(tVFS_Node *Node, int ID, void *Arg);
79 MODULE_DEFINE(0, 0x100, PTY, PTY_Install, NULL, NULL);
80 tVFS_NodeType gPTY_NodeType_Root = {
81 .TypeName = "PTY-Root",
82 .ReadDir = PTY_ReadDir,
83 .FindDir = PTY_FindDir,
85 tVFS_NodeType gPTY_NodeType_Client = {
86 .TypeName = "PTY-Client",
87 .Read = PTY_ReadClient,
88 .Write = PTY_WriteClient,
90 .Reference = PTY_ReferenceClient,
91 .Close = PTY_CloseClient
93 tVFS_NodeType gPTY_NodeType_Server = {
94 .TypeName = "PTY-Server",
95 .Read = PTY_ReadServer,
96 .Write = PTY_WriteServer,
98 .Close = PTY_CloseServer
100 tDevFS_Driver gPTY_Driver = {
103 .Flags = VFS_FFLAG_DIRECTORY,
104 .Type = &gPTY_NodeType_Root,
109 tRWLock glPTY_NumPTYs;
110 tPTY *gpPTY_FirstNumPTY;
111 int giPTY_NamedCount;
112 tRWLock glPTY_NamedPTYs;
113 tPTY *gpPTY_FirstNamedPTY;
116 int PTY_Install(char **Arguments)
118 DevFS_AddDevice(&gPTY_Driver);
119 return MODULE_ERR_OK;
122 // --- Management ---
123 tPTY *PTY_Create(const char *Name, void *Handle, tPTY_OutputFcn Output, tPTY_ReqResize ReqResize, tPTY_ModeSet ModeSet)
125 tPTY **prev_np = NULL;
128 if( Name && Name[0] )
130 prev_np = &gpPTY_FirstNamedPTY;
132 // Check the name isn't decimal
134 if( strtol(Name, &end, 10) != 0 && *end == '\0' ) {
139 RWLock_AcquireWrite(&glPTY_NamedPTYs);
141 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
143 int cmp = strcmp(pty->Name, Name);
147 RWLock_Release(&glPTY_NamedPTYs);
153 namelen = strlen(Name);
158 RWLock_AcquireWrite(&glPTY_NumPTYs);
159 // Get a pty ID if Name==NULL
160 prev_np = &gpPTY_FirstNumPTY;
161 for( tPTY *pty = gpPTY_FirstNumPTY; pty; prev_np = &pty->Next, pty = pty->Next )
163 if( pty->NumericName > idx )
167 namelen = snprintf(NULL,0, "%u", idx);
170 tPTY *ret = calloc(sizeof(tPTY) + namelen + 1, 1);
176 // - List maintainance
177 ret->Next = *prev_np;
179 // - PTY Name (Used by VT)
180 ret->Name = (char*)(ret + 1);
182 strcpy(ret->Name, Name);
184 sprintf(ret->Name, "%u", idx);
185 ret->NumericName = idx;
186 // - Output function and handle (same again)
187 ret->OutputHandle = Handle;
188 ret->OutputFcn = Output;
189 ret->ReqResize = ReqResize;
190 ret->ModeSet = ModeSet;
192 ret->ClientNode.ImplPtr = ret;
193 ret->ClientNode.Type = &gPTY_NodeType_Client;
194 ret->ClientNode.UID = Threads_GetUID();
195 ret->ClientNode.GID = Threads_GetGID();
196 ret->ClientNode.NumACLs = 1;
197 ret->ClientNode.ACLs = &ret->OwnerRW;
198 // - Owner Read-Write ACL
199 ret->OwnerRW.Ent.ID = Threads_GetUID();
200 ret->OwnerRW.Perm.Perms = -1;
202 if( Name && Name[0] ) {
204 RWLock_Release(&glPTY_NamedPTYs);
208 RWLock_Release(&glPTY_NumPTYs);
214 int PTY_SetAttrib(tPTY *PTY, const struct ptydims *Dims, const struct ptymode *Mode, int WasClient)
218 // (for now) userland terminals can't be put into framebuffer mode
219 if( !PTY->OutputFcn && (Mode->OutputMode & PTYOMODE_BUFFMT) == PTYBUFFMT_FB ) {
225 if( PTY->ModeSet && PTY->ModeSet(PTY->OutputHandle, Mode) )
230 else if( !PTY->OutputFcn )
232 Log_Warning("PTY", "TODO: Need to stop client output until modeset has been ACKed");
233 // Block write until acked
234 // ACK by server doing GETMODE
239 // Should the client be informed that the server just twiddled the modes?
241 LOG("PTY %p mode set to {0%o, 0%o}", PTY, Mode->InputMode, Mode->OutputMode);
249 if( PTY->ReqResize && PTY->ReqResize(PTY->OutputHandle, Dims) )
254 else if( !PTY->OutputFcn )
256 // Inform server process... somehow
261 // SIGWINSZ to client
263 LOG("PTY %p dims set to %ix%i", PTY, Dims->W, Dims->H);
269 void PTY_Close(tPTY *PTY)
274 size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len)
276 size_t space = (*rd - *wr + buflen - 1) % buflen;
277 ENTER("pbuf ibuflen prd pwr pdata ilen", buf, buflen, rd, wr, data, len);
278 len = MIN(space, len);
279 LOG("space = %i, *rd = %i, *wr = %i", space, *rd, *wr);
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);
293 size_t _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len)
295 size_t space = (*wr - *rd + buflen) % buflen;
296 len = MIN(space, len);
297 if(*rd + len >= buflen) {
298 size_t prelen = buflen - *rd;
299 memcpy(data, (char*)buf + *rd, prelen);
300 memcpy((char*)data + prelen, buf, len - prelen);
304 memcpy(data, (char*)buf + *rd, len);
310 size_t PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length)
314 Mutex_Acquire(&PTY->InputMutex);
316 ret = _rb_write(PTY->InputData, INPUT_RINGBUFFER_LEN, &PTY->InputReadPos, &PTY->InputWritePos,
319 Mutex_Release(&PTY->InputMutex);
321 VFS_MarkAvaliable(&PTY->ClientNode, 1);
323 VFS_MarkFull(PTY->ServerNode, 1);
328 size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length)
330 size_t ret = 1, print = 1;
332 // Input mode stuff only counts for text output mode
333 // - Any other is Uint32 keypresses
334 if( (PTY->Mode.OutputMode & PTYOMODE_BUFFMT) != PTYBUFFMT_TEXT )
335 return PTY_int_WriteInput(PTY, Input, Length);
336 // If in raw mode, flush directlr
337 if( (PTY->Mode.InputMode & PTYIMODE_RAW) )
338 return PTY_int_WriteInput(PTY, Input, Length);
340 if( PTY->Mode.InputMode & PTYIMODE_CANON )
342 const char char_bs = '\b';
347 // Threads_PostSignalExt(PTY->ClientThreads, SIGINT);
351 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
352 PTY->HasHitEOF = (PTY->LineLength == 0);
357 if(PTY->LineLength != 0)
360 case 'w'-'a': // Word erase
361 while(PTY->LineLength != 0 && isalnum(PTY->LineData[--PTY->LineLength]))
362 PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
365 case 'u'-'a': // Kill
366 while(PTY->LineLength > 0)
367 PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
377 if(PTY->LineLength == INPUT_LINE_LEN) {
378 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
381 PTY->LineData[PTY->LineLength++] = '\n';
382 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
385 // TODO: Handle ^[[D and ^[[C for in-line editing, also ^[[1~/^[[4~ (home/end)
390 if(PTY->LineLength == INPUT_LINE_LEN) {
391 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
394 PTY->LineData[PTY->LineLength++] = Input[0];
400 ret = PTY_int_WriteInput(PTY, Input, Length);
404 if( PTY->Mode.InputMode & PTYIMODE_ECHO )
406 PTY_WriteClient(&PTY->ClientNode, 0, print, Input, 0);
412 size_t PTY_SendInput(tPTY *PTY, const char *Input, size_t Length)
415 while( ret < Length && !PTY->ClientNode.BufferFull )
417 // TODO: Detect blocking?
418 ret += PTY_int_SendInput(PTY, Input + ret, Length - ret);
424 int PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX])
428 if( idx < giPTY_NumCount )
430 RWLock_AcquireRead(&glPTY_NumPTYs);
431 for( pty = gpPTY_FirstNumPTY; pty && idx; pty = pty->Next )
433 RWLock_Release(&glPTY_NumPTYs);
435 else if( idx < (giPTY_NumCount + giPTY_NamedCount) )
437 idx -= giPTY_NumCount;
438 RWLock_AcquireRead(&glPTY_NamedPTYs);
439 for( pty = gpPTY_FirstNamedPTY; pty && idx; pty = pty->Next )
441 RWLock_Release(&glPTY_NamedPTYs);
445 LOG("%i out of range", Pos);
449 strncpy(Name, pty->Name, FILENAME_MAX)
450 LOG("Return '%s'", Name);
454 tVFS_Node *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
457 int num = strtol(Name, &end, 10);
459 if( strcmp(Name, "ptmx") == 0 ) {
460 tVFS_Node *ret = calloc(sizeof(tVFS_Node), 1);
462 ret->Type = &gPTY_NodeType_Server;
466 if( Name[0] == '\0' )
470 if( num && end[0] == '\0' )
473 RWLock_AcquireRead(&glPTY_NumPTYs);
474 for( tPTY *pty = gpPTY_FirstNumPTY; pty; pty = pty->Next )
476 if( pty->NumericName > num )
478 if( pty->NumericName == num ) {
483 RWLock_Release(&glPTY_NumPTYs);
488 RWLock_AcquireRead(&glPTY_NamedPTYs);
489 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; pty = pty->Next )
491 int cmp = strcmp(pty->Name, Name);
499 RWLock_Release(&glPTY_NamedPTYs);
502 tVFS_Node *retnode = &ret->ClientNode;
503 retnode->ReferenceCount ++;
510 //\! Read from the client's input
511 size_t PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
513 tPTY *pty = Node->ImplPtr;
515 // Read from flushed queue
516 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
519 // If server has disconnected, return EIO
520 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 ) {
521 //Threads_PostSignal(SIGPIPE);
525 // Wait for data to be ready
526 rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadClient");
528 errno = (timeout ? EWOULDBLOCK : EINTR);
532 Mutex_Acquire(&pty->InputMutex);
533 Length = _rb_read(pty->InputData, INPUT_RINGBUFFER_LEN, &pty->InputReadPos, &pty->InputWritePos,
535 if( Length && pty->ServerNode )
536 VFS_MarkFull(pty->ServerNode, 0);
537 Mutex_Release(&pty->InputMutex);
539 if(pty->InputReadPos == pty->InputWritePos)
540 VFS_MarkAvaliable(Node, 0);
542 if(Length == 0 && !pty->HasHitEOF) {
550 //\! Write to the client's output
551 size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
553 tPTY *pty = Node->ImplPtr;
555 // If the server has terminated, send SIGPIPE
556 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
558 //Threads_PostSignal(SIGPIPE);
563 // Write to either FIFO or directly to output function
564 if( pty->OutputFcn ) {
565 pty->OutputFcn(pty->OutputHandle, Length, Buffer);
570 tTime timeout_z, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
573 rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteClient");
575 errno = (timeout ? EWOULDBLOCK : EINTR);
579 // Write to output ringbuffer
580 Length = _rb_write(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
581 &pty->OutputReadPos, &pty->OutputWritePos,
583 VFS_MarkAvaliable(pty->ServerNode, 1);
584 if( (pty->OutputWritePos + 1) % OUTPUT_RINGBUFFER_LEN == pty->OutputReadPos )
585 VFS_MarkFull(Node, 1);
590 void PTY_ReferenceClient(tVFS_Node *Node)
592 Node->ReferenceCount ++;
593 // TODO: Add PID to list of client PIDs
594 // Log_Notice("PTY", "ReferenceClient: TODO - List of client PIDs");
597 void PTY_CloseClient(tVFS_Node *Node)
599 tPTY *pty = Node->ImplPtr;
600 Node->ReferenceCount --;
602 // Remove PID from list
603 // TODO: Maintain list of client processes
605 // Free structure if this was the last open handle
606 if( Node->ReferenceCount > 0 )
608 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
610 // Free the structure! (Should be off the PTY list now)
611 free(pty->ServerNode);
616 //\! Read from the client's output
617 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
619 tPTY *pty = Node->ImplPtr;
625 // TODO: Prevent two servers fighting over client's output
628 // Kernel-land PTYs can't be read from userland
632 // Read back from fifo
633 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
634 int rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadServer");
636 errno = (timeout ? EWOULDBLOCK : EINTR);
640 Length = _rb_read(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
641 &pty->OutputReadPos, &pty->OutputWritePos,
643 if( pty->OutputReadPos == pty->OutputWritePos )
644 VFS_MarkAvaliable(Node, 0);
645 VFS_MarkFull(&pty->ClientNode, 0);
650 //\! Write to the client's input
651 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
653 tPTY *pty = Node->ImplPtr;
659 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
660 int rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteServer");
662 errno = (timeout ? EWOULDBLOCK : EINTR);
667 used += PTY_SendInput(Node->ImplPtr, Buffer, Length);
668 } while( used < Length && !(Flags & VFS_IOFLAG_NOBLOCK) );
670 if( (pty->InputWritePos+1)%INPUT_RINGBUFFER_LEN == pty->InputReadPos )
671 VFS_MarkFull(Node, 1);
675 void PTY_CloseServer(tVFS_Node *Node)
677 tPTY *pty = Node->ImplPtr;
679 Node->ReferenceCount --;
680 // If reference count == 0, remove from main list
681 if( Node->ReferenceCount > 0 )
684 // Locate on list and remove
686 if( pty->NumericName == 0 ) {
687 RWLock_AcquireWrite(&glPTY_NamedPTYs);
688 prev_np = &gpPTY_FirstNamedPTY;
691 RWLock_AcquireWrite(&glPTY_NumPTYs);
692 prev_np = &gpPTY_FirstNumPTY;
695 // Search list until *prev_np is equal to pty
696 for( tPTY *tmp = *prev_np; *prev_np != pty && tmp; prev_np = &tmp->Next, tmp = tmp->Next )
700 if( *prev_np != pty ) {
701 Log_Error("PTY", "PTY %p(%i/%s) not on list at deletion time", pty, pty->NumericName, pty->Name);
704 *prev_np = pty->Next;
708 if( pty->NumericName == 0 ) {
709 RWLock_Release(&glPTY_NamedPTYs);
713 RWLock_Release(&glPTY_NumPTYs);
717 // If there are no open children, we can safely free this PTY
718 if( pty->ClientNode.ReferenceCount == 0 ) {
724 int PTY_IOCtl(tVFS_Node *Node, int ID, void *Data)
726 tPTY *pty = Node->ImplPtr;
727 struct ptymode *mode = Data;
728 struct ptydims *dims = Data;
730 int is_server = !pty || Node == pty->ServerNode;
734 case DRV_IOCTL_TYPE: return DRV_TYPE_TERMINAL;
735 case DRV_IOCTL_IDENT: memcpy(Data, "PTY\0", 4); return 0;
736 case DRV_IOCTL_VERSION: return 0x100;
737 case DRV_IOCTL_LOOKUP: return 0;
739 case PTY_IOCTL_GETMODE:
741 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
743 // TODO: ACK client's SETMODE
745 case PTY_IOCTL_SETMODE:
747 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
748 PTY_SetAttrib(pty, NULL, mode, !is_server);
750 case PTY_IOCTL_GETDIMS:
752 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
755 case PTY_IOCTL_SETDIMS:
757 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
758 PTY_SetAttrib(pty, dims, NULL, !is_server);
760 case PTY_IOCTL_GETID:
763 size_t len = strlen(pty->Name)+1;
766 if( !CheckMem(Data, len) ) { errno = EINVAL; return -1; }
767 strcpy(Data, pty->Name);
772 case PTY_IOCTL_SETID:
773 if( Data && !CheckString(Data) ) { errno = EINVAL; return -1; }
774 if( pty ) return EALREADY;
775 pty = PTY_Create(Data, NULL, NULL,NULL, NULL);
779 pty->ServerNode = Node;