Kernel/VTerm - "Fix" wrapping issue in VTerm (why was old behavior there?)
[tpg/acess2.git] / KernelLand / Kernel / drv / pty.c
1 /*
2  * Acess2 Kernel
3  * - By John Hodge (thePowersGang)
4  *
5  * drv/pty.c
6  * - Pseudo Terminals
7  */
8 #define DEBUG   0
9 #include <acess.h>
10 #include <vfs.h>
11 #include <fs_devfs.h>
12 #include <drv_pty.h>
13 #include <modules.h>
14 #include <rwlock.h>
15 #include <mutex.h>
16 #include <posix_signals.h>
17
18 // === CONSTANTS ===
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
22
23 // === TYPES ===
24 struct sPTY
25 {
26         tPTY    *Next;
27         
28         char    *Name;
29          int    NumericName;
30         
31         void    *OutputHandle;
32         tPTY_OutputFcn  OutputFcn;
33         tPTY_ReqResize  ReqResize;
34         tPTY_ModeSet    ModeSet;
35
36         struct ptymode  Mode;
37         struct ptydims  Dims;
38
39          int    HasHitEOF;      
40         tMutex  InputMutex;
41          int    InputWritePos;
42          int    InputReadPos;
43         char    InputData[INPUT_RINGBUFFER_LEN];
44         
45          int    LineLength;
46         char    LineData[INPUT_LINE_LEN];
47
48         tMutex  OutputMutex;    
49          int    OutputWritePos;
50          int    OutputReadPos;
51         char    OutputData[OUTPUT_RINGBUFFER_LEN];
52         
53         tVFS_Node       *ServerNode;
54         tVFS_Node       ClientNode;
55         tVFS_ACL        OwnerRW;
56
57         tPGID   ControllingProcGroup;
58 };
59
60 // === PROTOTYPES ===
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);
64
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);
69 // PTY_SendInput
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);
78
79 // === GLOBALS ===
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,
85 };
86 tVFS_NodeType   gPTY_NodeType_Client = {
87         .TypeName = "PTY-Client",
88         .Flags = VFS_NODETYPEFLAG_STREAM,
89         .Read = PTY_ReadClient,
90         .Write = PTY_WriteClient,
91         .IOCtl = PTY_IOCtl,
92         .Reference = PTY_ReferenceClient,
93         .Close = PTY_CloseClient
94 };
95 tVFS_NodeType   gPTY_NodeType_Server = {
96         .TypeName = "PTY-Server",
97         .Flags = VFS_NODETYPEFLAG_STREAM,
98         .Read = PTY_ReadServer,
99         .Write = PTY_WriteServer,
100         .IOCtl = PTY_IOCtl,
101         .Close = PTY_CloseServer
102 };
103 tDevFS_Driver   gPTY_Driver = {
104         .Name = "pts",
105         .RootNode = {
106                 .Flags = VFS_FFLAG_DIRECTORY,
107                 .Type = &gPTY_NodeType_Root,
108                 .Size = -1
109         }
110 };
111  int    giPTY_NumCount;
112 tRWLock glPTY_NumPTYs;
113 tPTY    *gpPTY_FirstNumPTY;
114  int    giPTY_NamedCount;
115 tRWLock glPTY_NamedPTYs;
116 tPTY    *gpPTY_FirstNamedPTY;
117
118 // === CODE ===
119 int PTY_Install(char **Arguments)
120 {
121         DevFS_AddDevice(&gPTY_Driver);
122         return MODULE_ERR_OK;
123 }
124
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)
127 {
128         tPTY    **prev_np = NULL;
129         size_t  namelen;
130          int    idx = 1;
131         
132         if( !Name )
133                 Name = "";
134         
135         if( Name[0] == '\0' )
136         {
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 )
141                 {
142                         if( pty->NumericName > idx )
143                                 break;
144                         idx ++;
145                 }
146                 namelen = snprintf(NULL,0, "%u", idx);
147         }
148         else if( Name[strlen(Name)-1] == '#' )
149         {
150                 // Sequenced PTYs
151                 // - "gui#" would translate to "gui0", "gui1", "gui2", ...
152                 //   whichever is free
153                 prev_np = &gpPTY_FirstNamedPTY;
154
155                 RWLock_AcquireWrite(&glPTY_NamedPTYs);
156                 idx = 0;
157                 namelen = strlen(Name)-1;
158                 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
159                 {
160                          int    cmp = strncmp(pty->Name, Name, namelen);
161                         if( cmp < 0 )
162                                 continue ;
163                         if( cmp > 0 )
164                                 break;
165
166                         // Skip non-numbered
167                         if( pty->Name[namelen] == '\0' )
168                                 continue ;                      
169
170                         // Find an unused index
171                         char    *name_end;
172                          int    this_idx = strtol(pty->Name+namelen, &name_end, 10);
173                         if( *name_end != '\0' )
174                                 continue;
175                         if( this_idx > idx )
176                                 break;
177                         idx ++;
178                 }
179                 
180                 namelen += snprintf(NULL, 0, "%u", idx);
181         }
182         else
183         {
184                 prev_np = &gpPTY_FirstNamedPTY;
185                 
186                 // Check the name isn't decimal
187                 char *end;
188                 if( strtol(Name, &end, 10) != 0 && *end == '\0' ) {
189                         errno = EINVAL;
190                         return NULL;
191                 }
192
193                 RWLock_AcquireWrite(&glPTY_NamedPTYs);
194                 // Detect duplicates
195                 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
196                 {
197                          int    cmp = strcmp(pty->Name, Name);
198                         if( cmp < 0 )
199                                 continue;
200                         if( cmp == 0 ) {
201                                 RWLock_Release(&glPTY_NamedPTYs);
202                                 errno = EEXIST;
203                                 return NULL;
204                         }
205                         break;
206                 }
207                 namelen = strlen(Name);
208                 idx = -1;
209         }
210         
211         tPTY *ret = calloc(sizeof(tPTY) + namelen + 1, 1);
212         if(!ret) {
213                 errno = ENOMEM;
214                 return NULL;
215         }
216         
217         // - List maintainance
218         ret->Next = *prev_np;
219         *prev_np = ret;
220         // - PTY Name (Used by VT)
221         ret->Name = (char*)(ret + 1);
222         if( idx == -1 )
223                 strcpy(ret->Name, Name);
224         else if( Name[0] )
225                 sprintf(ret->Name, "%.*s%u", strlen(Name)-1, Name, idx);
226         else
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
235         if( InitialDims )
236                 ret->Dims = *InitialDims;
237         if( InitialMode )
238                 ret->Mode = *InitialMode;
239         // - Client node
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;
250
251         if( Name[0] ) {
252                 giPTY_NamedCount ++;
253                 RWLock_Release(&glPTY_NamedPTYs);
254         }
255         else {
256                 giPTY_NumCount ++;
257                 RWLock_Release(&glPTY_NumPTYs); 
258         }
259
260         return ret;
261 }
262
263 int PTY_SetAttrib(tPTY *PTY, const struct ptydims *Dims, const struct ptymode *Mode, int WasClient)
264 {
265         if( Mode )
266         {
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 ) {
270                         errno = EINVAL;
271                         return -1;
272                 }
273                 if( WasClient )
274                 {
275                         if( PTY->ModeSet && PTY->ModeSet(PTY->OutputHandle, Mode) )
276                         {
277                                 errno = EINVAL;
278                                 return -1;
279                         }
280                         else if( !PTY->OutputFcn )
281                         {
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
285                         }
286                 }
287                 else
288                 {
289                         // Should the client be informed that the server just twiddled the modes?
290                         Log_Warning("PTY", "Server changed mode, TODO: inform client?");
291                 }
292                 LOG("PTY %p mode set to {0%o, 0%o}", PTY, Mode->InputMode, Mode->OutputMode);
293                 PTY->Mode = *Mode;
294         }
295         if( Dims )
296         {
297                 if( WasClient )
298                 {
299                         // Poke the server?
300                         if( PTY->ReqResize && PTY->ReqResize(PTY->OutputHandle, Dims) )
301                         {
302                                 errno = EINVAL;
303                                 return -1;
304                         }
305                         else if( !PTY->OutputFcn )
306                         {
307                                 // Inform server process... somehow
308                                 Log_Warning("PTY", "TODO: Inform server of client resize request");
309                         }
310                 }
311                 else
312                 {
313                         // SIGWINSZ to client
314                         if( PTY->ControllingProcGroup > 0 )
315                                 Threads_SignalGroup(PTY->ControllingProcGroup, SIGWINCH);
316                 }
317                 LOG("PTY %p dims set to %ix%i", PTY, Dims->W, Dims->H);
318                 PTY->Dims = *Dims;
319         }
320         return 0;
321 }
322
323 void PTY_Close(tPTY *PTY)
324 {
325         
326 }
327
328 size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len)
329 {
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);
336                 *wr = len - prelen;
337         }
338         else {
339                 memcpy((char*)buf + *wr, data, len);
340                 *wr += len;
341         }
342         return len;
343 }
344 size_t _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len)
345 {
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);
352                 *rd = len - prelen;
353         }
354         else {
355                 memcpy(data, (char*)buf + *rd, len);
356                 *rd += len;
357         }
358         return len;
359 }
360
361 size_t PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length)
362 {
363         size_t  ret;
364
365         Mutex_Acquire(&PTY->InputMutex);        
366
367         ret = _rb_write(PTY->InputData, INPUT_RINGBUFFER_LEN, &PTY->InputReadPos, &PTY->InputWritePos,
368                 Input, Length);
369         
370         Mutex_Release(&PTY->InputMutex);
371
372         VFS_MarkAvaliable(&PTY->ClientNode, 1);
373         if(ret < Length && PTY->ServerNode)
374                 VFS_MarkFull(PTY->ServerNode, 1);       
375
376         return ret;
377 }
378
379 size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length)
380 {
381         size_t  ret = 1, print = 1;
382         
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);
390         
391         if( PTY->Mode.InputMode & PTYIMODE_CANON )
392         {
393                 
394                 switch(Input[0])
395                 {
396                 case 3: // INTR - ^C
397                         // Send SIGINT
398                         if( PTY->ControllingProcGroup > 0 )
399                                 Threads_SignalGroup(PTY->ControllingProcGroup, SIGINT);
400                         print = 0;
401                         break;
402                 case 4: // EOF - ^D
403                         PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
404                         PTY->HasHitEOF = (PTY->LineLength == 0);
405                         PTY->LineLength = 0;
406                         print = 0;
407                         break;
408                 case 8: // Backspace
409                         if(PTY->LineLength != 0) {
410                                 PTY->LineLength --;
411                                 PTY_WriteClient(&PTY->ClientNode, 0, 3, "\b \b", 0);
412                         }
413                         print = 0;
414                         break;
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);
419                         print = 0;
420                         break;
421                 case 'u'-'a':   // Kill
422                         PTY_WriteClient(&PTY->ClientNode, 0, 8, "\x1b[2K\x1b[0G", 0);
423                         PTY->LineLength = 0;
424                         print = 0;
425                         break;
426                 case 'v'-'a':
427                         Input ++;
428                         Length --;
429                         ret ++;
430                         goto _default;
431                 case '\0':
432                 case '\n':
433                         if(PTY->LineLength == INPUT_LINE_LEN) {
434                                 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
435                                 PTY->LineLength = 0;
436                         }
437                         PTY->LineData[PTY->LineLength++] = '\n';
438                         PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
439                         PTY->LineLength = 0;
440                         break;
441                 // TODO: Handle ^[[D and ^[[C for in-line editing, also ^[[1~/^[[4~ (home/end)
442                 //case 0x1B:
443                 //      break;
444                 default:
445                 _default:
446                         if(PTY->LineLength == INPUT_LINE_LEN) {
447                                 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
448                                 PTY->LineLength = 0;
449                         }
450                         PTY->LineData[PTY->LineLength++] = Input[0];
451                         break;
452                 }
453         }
454         else
455         {
456                 #if 0
457                 if( PTY->Mode.InputMode & PTYIMODE_NLCR )
458                 {
459                         if( Input[0] == '\n' ) {
460                                 char ch = '\r';
461                                 ret = PTY_int_WriteInput(PTY, &ch, 1);
462                         }
463                         else {
464                                  int    i;
465                                 for( i = 0; i < Length && Input[i] != '\n'; i ++ )
466                                         ;
467                                 ret = PTY_int_WriteInput(PTY, Input, i);
468                         }
469                 }
470                 // TODO: CRNL mode?
471                 else
472                 #endif
473                         ret = PTY_int_WriteInput(PTY, Input, Length);
474         }
475         
476         // Echo if requested
477         if( PTY->Mode.InputMode & PTYIMODE_ECHO )
478         {
479                 PTY_WriteClient(&PTY->ClientNode, 0, print, Input, 0);
480         }
481         
482         return ret;
483 }
484
485 size_t PTY_SendInput(tPTY *PTY, const char *Input, size_t Length)
486 {
487         size_t ret = 0;
488         while( ret < Length && !PTY->ClientNode.BufferFull )
489         {
490                 // TODO: Detect blocking?
491                 ret += PTY_int_SendInput(PTY, Input + ret, Length - ret);
492         }
493         return ret;
494 }
495
496 // --- VFS ---
497 int PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX])
498 {
499         tPTY    *pty = NULL;
500          int    idx = Pos;
501         if( idx < giPTY_NumCount )
502         {
503                 RWLock_AcquireRead(&glPTY_NumPTYs);
504                 for( pty = gpPTY_FirstNumPTY; pty && idx; pty = pty->Next )
505                         idx --;
506                 RWLock_Release(&glPTY_NumPTYs);
507         }
508         else if( idx < (giPTY_NumCount + giPTY_NamedCount) )
509         {
510                 idx -= giPTY_NumCount;
511                 RWLock_AcquireRead(&glPTY_NamedPTYs);
512                 for( pty = gpPTY_FirstNamedPTY; pty && idx; pty = pty->Next )
513                         idx --;
514                 RWLock_Release(&glPTY_NamedPTYs);
515         }
516
517         if( !pty ) {
518                 return -1;
519         }
520
521         strncpy(Name, pty->Name, FILENAME_MAX);
522         return 0;
523 }
524
525 tVFS_Node *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
526 {
527         char    *end;
528          int    num = strtol(Name, &end, 10);
529
530         if( strcmp(Name, "ptmx") == 0 ) {
531                 tVFS_Node       *ret = calloc(sizeof(tVFS_Node), 1);
532                 ret->Size = -1;
533                 ret->Type = &gPTY_NodeType_Server;
534                 return ret;
535         } 
536         
537         if( Name[0] == '\0' )
538                 return NULL;
539         
540         tPTY    *ret = NULL;
541         if( num && end[0] == '\0' )
542         {
543                 // Numeric name
544                 RWLock_AcquireRead(&glPTY_NumPTYs);
545                 for( tPTY *pty = gpPTY_FirstNumPTY; pty; pty = pty->Next )
546                 {
547                         if( pty->NumericName > num )
548                                 break;
549                         if( pty->NumericName == num ) {
550                                 ret = pty;
551                                 break;
552                         }
553                 }
554                 RWLock_Release(&glPTY_NumPTYs);
555         }
556         else
557         {
558                 // String name
559                 RWLock_AcquireRead(&glPTY_NamedPTYs);
560                 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; pty = pty->Next )
561                 {
562                         int cmp = strcmp(pty->Name, Name);
563                         if(cmp > 0)
564                                 break;
565                         if(cmp == 0 ) {
566                                 ret = pty;
567                                 break;
568                         }
569                 }
570                 RWLock_Release(&glPTY_NamedPTYs);
571         }
572 //      Debug("PTY_FindDir('%s') returned %p", Name, &ret->ClientNode);
573         if( ret ) {
574                 tVFS_Node       *retnode = &ret->ClientNode;
575                 retnode->ReferenceCount ++;
576                 return retnode;
577         }
578         else
579                 return NULL;
580 }
581
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)
584 {
585         tPTY *pty = Node->ImplPtr;
586         
587         // Read from flushed queue
588         tTime   timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
589          int    rv;
590 _select:
591         // If server has disconnected, return EIO
592         if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 ) {
593                 //Threads_PostSignal(SIGPIPE);
594                 errno = EIO;
595                 return -1;
596         }
597         // Wait for data to be ready
598         rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadClient");
599         if(!rv) {
600                 errno = (timeout ? EWOULDBLOCK : EINTR);
601                 return -1;
602         }
603
604         Mutex_Acquire(&pty->InputMutex);
605         Length = _rb_read(pty->InputData, INPUT_RINGBUFFER_LEN, &pty->InputReadPos, &pty->InputWritePos,
606                 Buffer, Length);
607         if( Length && pty->ServerNode )
608                 VFS_MarkFull(pty->ServerNode, 0);
609         Mutex_Release(&pty->InputMutex);
610
611         if(pty->InputReadPos == pty->InputWritePos)
612                 VFS_MarkAvaliable(Node, 0);
613
614         if(Length == 0 && !pty->HasHitEOF) {
615                 goto _select;
616         }
617         pty->HasHitEOF = 0;
618
619         return Length;
620 }
621
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)
624 {
625         tPTY *pty = Node->ImplPtr;
626
627         // If the server has terminated, send SIGPIPE
628         if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
629         {
630                 LOG("SIGPIPE, server has terminated");
631                 Threads_PostSignal(SIGPIPE);
632                 errno = EIO;
633                 return -1;
634         }       
635
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);
640                 return Length;
641         }
642         
643         // FIFO
644         size_t remaining = Length;
645         do
646         {
647                 tTime   timeout_z, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
648                  int    rv;
649                 
650                 rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteClient");
651                 if(!rv) {
652                         errno = (timeout ? EWOULDBLOCK : EINTR);
653                         return -1;
654                 }
655                 
656                 // Write to output ringbuffer
657                 size_t written = _rb_write(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
658                         &pty->OutputReadPos, &pty->OutputWritePos,
659                         Buffer, remaining);
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);
664                 
665                 remaining -= written;
666                 Buffer = (const char*)Buffer + written;
667         } while( remaining > 0 || (Flags & VFS_IOFLAG_NOBLOCK) );
668         
669         return Length - remaining;
670 }
671
672 void PTY_ReferenceClient(tVFS_Node *Node)
673 {
674         Node->ReferenceCount ++;
675 }
676
677 void PTY_CloseClient(tVFS_Node *Node)
678 {
679         tPTY    *pty = Node->ImplPtr;
680         Node->ReferenceCount --;
681
682         // Remove PID from list
683         // TODO: Maintain list of client processes
684
685         // Free structure if this was the last open handle
686         if( Node->ReferenceCount > 0 )
687                 return ;
688         if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
689         {
690                 // Free the structure! (Should be off the PTY list now)
691                 free(pty->ServerNode);
692                 free(pty);
693         }
694 }
695
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)
698 {
699         tPTY *pty = Node->ImplPtr;
700         if( !pty ) {
701                 errno = EIO;
702                 return -1;
703         }
704
705         // TODO: Prevent two servers fighting over client's output      
706         if( pty->OutputFcn )
707         {
708                 // Kernel-land PTYs can't be read from userland
709                 return 0;
710         }
711         
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");
715         if(!rv) {
716                 errno = (timeout ? EWOULDBLOCK : EINTR);
717                 return -1;
718         }
719         
720         Length = _rb_read(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
721                 &pty->OutputReadPos, &pty->OutputWritePos,
722                 Buffer, Length);
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);
727         
728         return Length;
729 }
730
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)
733 {
734         tPTY    *pty = Node->ImplPtr;
735         if( !pty ) {
736                 errno = EIO;
737                 return -1;
738         }
739
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");
742         if(!rv) {
743                 errno = (timeout ? EWOULDBLOCK : EINTR);
744                 return -1;
745         }
746         size_t  used = 0;
747         do {
748                 used += PTY_SendInput(Node->ImplPtr, Buffer, Length);
749         } while( used < Length && !(Flags & VFS_IOFLAG_NOBLOCK) );
750         
751         if( (pty->InputWritePos+1)%INPUT_RINGBUFFER_LEN == pty->InputReadPos )
752                 VFS_MarkFull(Node, 1);
753         return used;
754 }
755
756 void PTY_CloseServer(tVFS_Node *Node)
757 {
758         tPTY    *pty = Node->ImplPtr;
759         // Dereference node
760         Node->ReferenceCount --;
761         // If reference count == 0, remove from main list
762         if( Node->ReferenceCount > 0 )
763                 return ;
764         
765         // Locate on list and remove
766         tPTY    **prev_np;
767         if( pty->NumericName == -1 ) {
768                 RWLock_AcquireWrite(&glPTY_NamedPTYs);
769                 prev_np = &gpPTY_FirstNamedPTY;
770         }
771         else {
772                 RWLock_AcquireWrite(&glPTY_NumPTYs);
773                 prev_np = &gpPTY_FirstNumPTY;
774         }
775
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 )
778                 ;
779         
780         // Remove
781         if( *prev_np != pty ) {
782                 Log_Error("PTY", "PTY %p(%i/%s) not on list at deletion time", pty, pty->NumericName, pty->Name);
783         }
784         else {
785                 *prev_np = pty->Next;
786         }
787         
788         // Clean up lock
789         if( pty->NumericName == -1 ) {
790                 RWLock_Release(&glPTY_NamedPTYs);
791                 giPTY_NamedCount --;
792         }
793         else {
794                 RWLock_Release(&glPTY_NumPTYs);
795                 giPTY_NumCount --;
796         }
797
798         // Send SIGHUP to controling PGID
799         if( pty->ControllingProcGroup > 0 ) {
800                 Threads_SignalGroup(pty->ControllingProcGroup, SIGHUP);
801         }
802
803         // If there are no open children, we can safely free this PTY
804         if( pty->ClientNode.ReferenceCount == 0 ) {
805                 free(Node);
806                 free(pty);
807         }
808 }
809
810 int PTY_IOCtl(tVFS_Node *Node, int ID, void *Data)
811 {
812         tPTY    *pty = Node->ImplPtr;
813         struct ptymode  *mode = Data;
814         struct ptydims  *dims = Data;
815         
816         int     is_server = !pty || Node == pty->ServerNode;
817
818         LOG("(%i,%p) %s", ID, Data, (is_server?"Server":"Client"));
819
820         switch(ID)
821         {
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;
826         
827         case PTY_IOCTL_GETMODE:
828                 if( !pty )      return 0;
829                 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
830                 *mode = pty->Mode;
831                 // TODO: ACK client's SETMODE
832                 return 0;
833         case PTY_IOCTL_SETMODE:
834                 if( !pty )      return 0;
835                 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
836                 PTY_SetAttrib(pty, NULL, mode, !is_server);
837                 return 0;
838         case PTY_IOCTL_GETDIMS:
839                 if( !pty )      return 0;
840                 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
841                 *dims = pty->Dims;
842                 return 0;
843         case PTY_IOCTL_SETDIMS:
844                 if( !pty )      return 0;
845                 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
846                 PTY_SetAttrib(pty, dims, NULL, !is_server);
847                 return 0;
848         case PTY_IOCTL_GETID:
849                 if( pty )
850                 {
851                         size_t  len = strlen(pty->Name)+1;
852                         if( Data )
853                         {
854                                 if( !CheckMem(Data, len) ) { errno = EINVAL; return -1; }
855                                 strcpy(Data, pty->Name);
856                         }
857                         return len;
858                 }
859                 return 0;
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);
864                 if(pty == NULL)
865                         return 1;
866                 Node->ImplPtr = pty;
867                 pty->ServerNode = Node;
868                 return 0;
869         case PTY_IOCTL_SETPGRP:
870                 // TODO: Should this only be done by client?
871                 if( Data )
872                 {
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);
876                 }
877                 return pty->ControllingProcGroup;
878         }
879         errno = ENOSYS;
880         return -1;
881 }
882

UCC git Repository :: git.ucc.asn.au