ebce208518c2598840c82870f9e5f83ddff1694a
[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         .Read = PTY_ReadClient,
89         .Write = PTY_WriteClient,
90         .IOCtl = PTY_IOCtl,
91         .Reference = PTY_ReferenceClient,
92         .Close = PTY_CloseClient
93 };
94 tVFS_NodeType   gPTY_NodeType_Server = {
95         .TypeName = "PTY-Server",
96         .Read = PTY_ReadServer,
97         .Write = PTY_WriteServer,
98         .IOCtl = PTY_IOCtl,
99         .Close = PTY_CloseServer
100 };
101 tDevFS_Driver   gPTY_Driver = {
102         .Name = "pts",
103         .RootNode = {
104                 .Flags = VFS_FFLAG_DIRECTORY,
105                 .Type = &gPTY_NodeType_Root,
106                 .Size = -1
107         }
108 };
109  int    giPTY_NumCount;
110 tRWLock glPTY_NumPTYs;
111 tPTY    *gpPTY_FirstNumPTY;
112  int    giPTY_NamedCount;
113 tRWLock glPTY_NamedPTYs;
114 tPTY    *gpPTY_FirstNamedPTY;
115
116 // === CODE ===
117 int PTY_Install(char **Arguments)
118 {
119         DevFS_AddDevice(&gPTY_Driver);
120         return MODULE_ERR_OK;
121 }
122
123 // --- Management ---
124 tPTY *PTY_Create(const char *Name, void *Handle, tPTY_OutputFcn Output, tPTY_ReqResize ReqResize, tPTY_ModeSet ModeSet)
125 {
126         tPTY    **prev_np = NULL;
127         size_t  namelen;
128          int    idx = 1;
129         
130         if( !Name )
131                 Name = "";
132         
133         if( Name[0] == '\0' )
134         {
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 )
139                 {
140                         if( pty->NumericName > idx )
141                                 break;
142                         idx ++;
143                 }
144                 namelen = snprintf(NULL,0, "%u", idx);
145         }
146         else if( Name[strlen(Name)-1] == '#' )
147         {
148                 // Sequenced PTYs
149                 // - "gui#" would translate to "gui0", "gui1", "gui2", ...
150                 //   whichever is free
151                 prev_np = &gpPTY_FirstNamedPTY;
152
153                 RWLock_AcquireWrite(&glPTY_NamedPTYs);
154                 idx = 0;
155                 namelen = strlen(Name)-1;
156                 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
157                 {
158                          int    cmp = strncmp(pty->Name, Name, namelen);
159                         if( cmp < 0 )
160                                 continue ;
161                         if( cmp > 0 )
162                                 break;
163
164                         // Skip non-numbered
165                         if( pty->Name[namelen] == '\0' )
166                                 continue ;                      
167
168                         // Find an unused index
169                         char    *name_end;
170                          int    this_idx = strtol(pty->Name+namelen, &name_end, 10);
171                         if( *name_end != '\0' )
172                                 continue;
173                         if( this_idx > idx )
174                                 break;
175                         idx ++;
176                 }
177                 
178                 namelen += snprintf(NULL, 0, "%u", idx);
179         }
180         else
181         {
182                 prev_np = &gpPTY_FirstNamedPTY;
183                 
184                 // Check the name isn't decimal
185                 char *end;
186                 if( strtol(Name, &end, 10) != 0 && *end == '\0' ) {
187                         errno = EINVAL;
188                         return NULL;
189                 }
190
191                 RWLock_AcquireWrite(&glPTY_NamedPTYs);
192                 // Detect duplicates
193                 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
194                 {
195                          int    cmp = strcmp(pty->Name, Name);
196                         if( cmp < 0 )
197                                 continue;
198                         if( cmp == 0 ) {
199                                 RWLock_Release(&glPTY_NamedPTYs);
200                                 errno = EEXIST;
201                                 return NULL;
202                         }
203                         break;
204                 }
205                 namelen = strlen(Name);
206                 idx = -1;
207         }
208         
209         tPTY *ret = calloc(sizeof(tPTY) + namelen + 1, 1);
210         if(!ret) {
211                 errno = ENOMEM;
212                 return NULL;
213         }
214         
215         // - List maintainance
216         ret->Next = *prev_np;
217         *prev_np = ret;
218         // - PTY Name (Used by VT)
219         ret->Name = (char*)(ret + 1);
220         if( idx == -1 )
221                 strcpy(ret->Name, Name);
222         else if( Name[0] )
223                 sprintf(ret->Name, "%.*s%u", strlen(Name)-1, Name, idx);
224         else
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         // - Client node
233         ret->ClientNode.ImplPtr = ret;
234         ret->ClientNode.Type = &gPTY_NodeType_Client;
235         ret->ClientNode.UID = Threads_GetUID();
236         ret->ClientNode.GID = Threads_GetGID();
237         ret->ClientNode.NumACLs = 1;
238         ret->ClientNode.ACLs = &ret->OwnerRW;
239         // - Owner Read-Write ACL
240         ret->OwnerRW.Ent.ID = Threads_GetUID();
241         ret->OwnerRW.Perm.Perms = -1;
242
243         if( Name[0] ) {
244                 giPTY_NamedCount ++;
245                 RWLock_Release(&glPTY_NamedPTYs);
246         }
247         else {
248                 giPTY_NumCount ++;
249                 RWLock_Release(&glPTY_NumPTYs); 
250         }
251
252         return ret;
253 }
254
255 int PTY_SetAttrib(tPTY *PTY, const struct ptydims *Dims, const struct ptymode *Mode, int WasClient)
256 {
257         if( Mode )
258         {
259                 // (for now) userland terminals can't be put into framebuffer mode
260                 // - Userland PTYs are streams, framebuffer is a block
261                 if( !PTY->OutputFcn && (Mode->OutputMode & PTYOMODE_BUFFMT) == PTYBUFFMT_FB ) {
262                         errno = EINVAL;
263                         return -1;
264                 }
265                 if( WasClient )
266                 {
267                         if( PTY->ModeSet && PTY->ModeSet(PTY->OutputHandle, Mode) )
268                         {
269                                 errno = EINVAL;
270                                 return -1;
271                         }
272                         else if( !PTY->OutputFcn )
273                         {
274                                 Log_Warning("PTY", "TODO: Inform server of client SETMODE, halt output");
275                                 // Block slave write until master ACKs
276                                 // 0-length read on master indicates need to GETMODE
277                         }
278                 }
279                 else
280                 {
281                         // Should the client be informed that the server just twiddled the modes?
282                         Log_Warning("PTY", "Server changed mode, TODO: inform client?");
283                 }
284                 LOG("PTY %p mode set to {0%o, 0%o}", PTY, Mode->InputMode, Mode->OutputMode);
285                 PTY->Mode = *Mode;
286         }
287         if( Dims )
288         {
289                 if( WasClient )
290                 {
291                         // Poke the server?
292                         if( PTY->ReqResize && PTY->ReqResize(PTY->OutputHandle, Dims) )
293                         {
294                                 errno = EINVAL;
295                                 return -1;
296                         }
297                         else if( !PTY->OutputFcn )
298                         {
299                                 // Inform server process... somehow
300                                 Log_Warning("PTY", "TODO: Inform server of client resize request");
301                         }
302                 }
303                 else
304                 {
305                         // SIGWINSZ to client
306                         Threads_SignalGroup(PTY->ControllingProcGroup, SIGWINCH);
307                 }
308                 LOG("PTY %p dims set to %ix%i", PTY, Dims->W, Dims->H);
309                 PTY->Dims = *Dims;
310         }
311         return 0;
312 }
313
314 void PTY_Close(tPTY *PTY)
315 {
316         
317 }
318
319 size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len)
320 {
321         size_t space = (*rd - *wr + buflen - 1) % buflen;
322         len = MIN(space, len);
323         if(*wr + len >= buflen) {
324                 size_t prelen = buflen - *wr;
325                 memcpy((char*)buf + *wr, data, prelen);
326                 memcpy(buf, (char*)data + prelen, len - prelen);
327                 *wr = len - prelen;
328         }
329         else {
330                 memcpy((char*)buf + *wr, data, len);
331                 *wr += len;
332         }
333         return len;
334 }
335 size_t _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len)
336 {
337         size_t space = (*wr - *rd + buflen) % buflen;
338         len = MIN(space, len);
339         if(*rd + len >= buflen) {
340                 size_t prelen = buflen - *rd;
341                 memcpy(data, (char*)buf + *rd, prelen);
342                 memcpy((char*)data + prelen, buf, len - prelen);
343                 *rd = len - prelen;
344         }
345         else {
346                 memcpy(data, (char*)buf + *rd, len);
347                 *rd += len;
348         }
349         return len;
350 }
351
352 size_t PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length)
353 {
354         size_t  ret;
355
356         Mutex_Acquire(&PTY->InputMutex);        
357
358         ret = _rb_write(PTY->InputData, INPUT_RINGBUFFER_LEN, &PTY->InputReadPos, &PTY->InputWritePos,
359                 Input, Length);
360         
361         Mutex_Release(&PTY->InputMutex);
362
363         VFS_MarkAvaliable(&PTY->ClientNode, 1);
364         if(ret < Length && PTY->ServerNode)
365                 VFS_MarkFull(PTY->ServerNode, 1);       
366
367         return ret;
368 }
369
370 size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length)
371 {
372         size_t  ret = 1, print = 1;
373         
374         // Input mode stuff only counts for text output mode
375         // - Any other is Uint32 keypresses
376         if( (PTY->Mode.OutputMode & PTYOMODE_BUFFMT) != PTYBUFFMT_TEXT )
377                 return PTY_int_WriteInput(PTY, Input, Length);
378         // If in raw mode, flush directlr
379         if( (PTY->Mode.InputMode & PTYIMODE_RAW) )
380                 return PTY_int_WriteInput(PTY, Input, Length);
381         
382         if( PTY->Mode.InputMode & PTYIMODE_CANON )
383         {
384                 const char      char_bs = '\b';
385                 switch(Input[0])
386                 {
387                 case 3: // INTR - ^C
388                         // Send SIGINT
389                         Threads_SignalGroup(PTY->ControllingProcGroup, SIGINT);
390                         print = 0;
391                         break;
392                 case 4: // EOF - ^D
393                         PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
394                         PTY->HasHitEOF = (PTY->LineLength == 0);
395                         PTY->LineLength = 0;
396                         print = 0;
397                         break;
398                 case 8: // Backspace
399                         if(PTY->LineLength != 0)
400                                 PTY->LineLength --;
401                         break;
402                 case 'w'-'a':   // Word erase
403                         while(PTY->LineLength != 0 && isalnum(PTY->LineData[--PTY->LineLength]))
404                                 PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
405                         print = 0;
406                         break;
407                 case 'u'-'a':   // Kill
408                         while(PTY->LineLength > 0)
409                                 PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
410                         print = 0;
411                         break;
412                 case 'v'-'a':
413                         Input ++;
414                         Length --;
415                         ret ++;
416                         goto _default;
417                 case '\0':
418                 case '\n':
419                         if(PTY->LineLength == INPUT_LINE_LEN) {
420                                 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
421                                 PTY->LineLength = 0;
422                         }
423                         PTY->LineData[PTY->LineLength++] = '\n';
424                         PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
425                         PTY->LineLength = 0;
426                         break;
427                 // TODO: Handle ^[[D and ^[[C for in-line editing, also ^[[1~/^[[4~ (home/end)
428                 //case 0x1B:
429                 //      break;
430                 default:
431                 _default:
432                         if(PTY->LineLength == INPUT_LINE_LEN) {
433                                 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
434                                 PTY->LineLength = 0;
435                         }
436                         PTY->LineData[PTY->LineLength++] = Input[0];
437                         break;
438                 }
439         }
440         else
441         {
442                 ret = PTY_int_WriteInput(PTY, Input, Length);
443         }
444         
445         // Echo if requested
446         if( PTY->Mode.InputMode & PTYIMODE_ECHO )
447         {
448                 PTY_WriteClient(&PTY->ClientNode, 0, print, Input, 0);
449         }
450         
451         return ret;
452 }
453
454 size_t PTY_SendInput(tPTY *PTY, const char *Input, size_t Length)
455 {
456         size_t ret = 0;
457         while( ret < Length && !PTY->ClientNode.BufferFull )
458         {
459                 // TODO: Detect blocking?
460                 ret += PTY_int_SendInput(PTY, Input + ret, Length - ret);
461         }
462         return ret;
463 }
464
465 // --- VFS ---
466 int PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX])
467 {
468         tPTY    *pty = NULL;
469          int    idx = Pos;
470         if( idx < giPTY_NumCount )
471         {
472                 RWLock_AcquireRead(&glPTY_NumPTYs);
473                 for( pty = gpPTY_FirstNumPTY; pty && idx; pty = pty->Next )
474                         idx --;
475                 RWLock_Release(&glPTY_NumPTYs);
476         }
477         else if( idx < (giPTY_NumCount + giPTY_NamedCount) )
478         {
479                 idx -= giPTY_NumCount;
480                 RWLock_AcquireRead(&glPTY_NamedPTYs);
481                 for( pty = gpPTY_FirstNamedPTY; pty && idx; pty = pty->Next )
482                         idx --;
483                 RWLock_Release(&glPTY_NamedPTYs);
484         }
485
486         if( !pty ) {
487                 return -1;
488         }
489
490         strncpy(Name, pty->Name, FILENAME_MAX);
491         return 0;
492 }
493
494 tVFS_Node *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
495 {
496         char    *end;
497          int    num = strtol(Name, &end, 10);
498
499         if( strcmp(Name, "ptmx") == 0 ) {
500                 tVFS_Node       *ret = calloc(sizeof(tVFS_Node), 1);
501                 ret->Size = -1;
502                 ret->Type = &gPTY_NodeType_Server;
503                 return ret;
504         } 
505         
506         if( Name[0] == '\0' )
507                 return NULL;
508         
509         tPTY    *ret = NULL;
510         if( num && end[0] == '\0' )
511         {
512                 // Numeric name
513                 RWLock_AcquireRead(&glPTY_NumPTYs);
514                 for( tPTY *pty = gpPTY_FirstNumPTY; pty; pty = pty->Next )
515                 {
516                         if( pty->NumericName > num )
517                                 break;
518                         if( pty->NumericName == num ) {
519                                 ret = pty;
520                                 break;
521                         }
522                 }
523                 RWLock_Release(&glPTY_NumPTYs);
524         }
525         else
526         {
527                 // String name
528                 RWLock_AcquireRead(&glPTY_NamedPTYs);
529                 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; pty = pty->Next )
530                 {
531                         int cmp = strcmp(pty->Name, Name);
532                         if(cmp > 0)
533                                 break;
534                         if(cmp == 0 ) {
535                                 ret = pty;
536                                 break;
537                         }
538                 }
539                 RWLock_Release(&glPTY_NamedPTYs);
540         }
541 //      Debug("PTY_FindDir('%s') returned %p", Name, &ret->ClientNode);
542         if( ret ) {
543                 tVFS_Node       *retnode = &ret->ClientNode;
544                 retnode->ReferenceCount ++;
545                 return retnode;
546         }
547         else
548                 return NULL;
549 }
550
551 //\! Read from the client's input
552 size_t PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
553 {
554         tPTY *pty = Node->ImplPtr;
555         
556         // Read from flushed queue
557         tTime   timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
558          int    rv;
559 _select:
560         // If server has disconnected, return EIO
561         if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 ) {
562                 //Threads_PostSignal(SIGPIPE);
563                 errno = EIO;
564                 return -1;
565         }
566         // Wait for data to be ready
567         rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadClient");
568         if(!rv) {
569                 errno = (timeout ? EWOULDBLOCK : EINTR);
570                 return -1;
571         }
572
573         Mutex_Acquire(&pty->InputMutex);
574         Length = _rb_read(pty->InputData, INPUT_RINGBUFFER_LEN, &pty->InputReadPos, &pty->InputWritePos,
575                 Buffer, Length);
576         if( Length && pty->ServerNode )
577                 VFS_MarkFull(pty->ServerNode, 0);
578         Mutex_Release(&pty->InputMutex);
579
580         if(pty->InputReadPos == pty->InputWritePos)
581                 VFS_MarkAvaliable(Node, 0);
582
583         if(Length == 0 && !pty->HasHitEOF) {
584                 goto _select;
585         }
586         pty->HasHitEOF = 0;
587
588         return Length;
589 }
590
591 //\! Write to the client's output
592 size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
593 {
594         tPTY *pty = Node->ImplPtr;
595
596         // If the server has terminated, send SIGPIPE
597         if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
598         {
599                 Threads_PostSignal(SIGPIPE);
600                 errno = EIO;
601                 return -1;
602         }       
603
604         // Write to either FIFO or directly to output function
605         if( pty->OutputFcn ) {
606                 pty->OutputFcn(pty->OutputHandle, Length, Buffer);
607                 return Length;
608         }
609         
610         // FIFO
611         size_t remaining = Length;
612         do
613         {
614                 tTime   timeout_z, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
615                  int    rv;
616                 
617                 rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteClient");
618                 if(!rv) {
619                         errno = (timeout ? EWOULDBLOCK : EINTR);
620                         return -1;
621                 }
622                 
623                 // Write to output ringbuffer
624                 size_t written = _rb_write(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
625                         &pty->OutputReadPos, &pty->OutputWritePos,
626                         Buffer, remaining);
627                 LOG("Wrote %i of %i : '%.*s'", written, remaining, written, Buffer);
628                 VFS_MarkAvaliable(pty->ServerNode, 1);
629                 if( (pty->OutputWritePos + 1) % OUTPUT_RINGBUFFER_LEN == pty->OutputReadPos )
630                         VFS_MarkFull(Node, 1);
631                 
632                 remaining -= written;
633                 Buffer = (const char*)Buffer + written;
634         } while( remaining > 0 || (Flags & VFS_IOFLAG_NOBLOCK) );
635         
636         return Length - remaining;
637 }
638
639 void PTY_ReferenceClient(tVFS_Node *Node)
640 {
641         Node->ReferenceCount ++;
642 }
643
644 void PTY_CloseClient(tVFS_Node *Node)
645 {
646         tPTY    *pty = Node->ImplPtr;
647         Node->ReferenceCount --;
648
649         // Remove PID from list
650         // TODO: Maintain list of client processes
651
652         // Free structure if this was the last open handle
653         if( Node->ReferenceCount > 0 )
654                 return ;
655         if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
656         {
657                 // Free the structure! (Should be off the PTY list now)
658                 free(pty->ServerNode);
659                 free(pty);
660         }
661 }
662
663 //\! Read from the client's output
664 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
665 {
666         tPTY *pty = Node->ImplPtr;
667         if( !pty ) {
668                 errno = EIO;
669                 return -1;
670         }
671
672         // TODO: Prevent two servers fighting over client's output      
673         if( pty->OutputFcn )
674         {
675                 // Kernel-land PTYs can't be read from userland
676                 return 0;
677         }
678         
679         // Read back from fifo
680         tTime   timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
681         int rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadServer");
682         if(!rv) {
683                 errno = (timeout ? EWOULDBLOCK : EINTR);
684                 return -1;
685         }
686         
687         Length = _rb_read(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
688                 &pty->OutputReadPos, &pty->OutputWritePos,
689                 Buffer, Length);
690         LOG("Read %i '%.*s'", Length, Length, Buffer);
691         if( pty->OutputReadPos == pty->OutputWritePos )
692                 VFS_MarkAvaliable(Node, 0);
693         VFS_MarkFull(&pty->ClientNode, 0);
694         
695         return Length;
696 }
697
698 //\! Write to the client's input
699 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
700 {
701         tPTY    *pty = Node->ImplPtr;
702         if( !pty ) {
703                 errno = EIO;
704                 return -1;
705         }
706
707         tTime   timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
708         int rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteServer");
709         if(!rv) {
710                 errno = (timeout ? EWOULDBLOCK : EINTR);
711                 return -1;
712         }
713         size_t  used = 0;
714         do {
715                 used += PTY_SendInput(Node->ImplPtr, Buffer, Length);
716         } while( used < Length && !(Flags & VFS_IOFLAG_NOBLOCK) );
717         
718         if( (pty->InputWritePos+1)%INPUT_RINGBUFFER_LEN == pty->InputReadPos )
719                 VFS_MarkFull(Node, 1);
720         return used;
721 }
722
723 void PTY_CloseServer(tVFS_Node *Node)
724 {
725         tPTY    *pty = Node->ImplPtr;
726         // Dereference node
727         Node->ReferenceCount --;
728         // If reference count == 0, remove from main list
729         if( Node->ReferenceCount > 0 )
730                 return ;
731         
732         // Locate on list and remove
733         tPTY    **prev_np;
734         if( pty->NumericName == -1 ) {
735                 RWLock_AcquireWrite(&glPTY_NamedPTYs);
736                 prev_np = &gpPTY_FirstNamedPTY;
737         }
738         else {
739                 RWLock_AcquireWrite(&glPTY_NumPTYs);
740                 prev_np = &gpPTY_FirstNumPTY;
741         }
742
743         // Search list until *prev_np is equal to pty   
744         for( tPTY *tmp = *prev_np; *prev_np != pty && tmp; prev_np = &tmp->Next, tmp = tmp->Next )
745                 ;
746         
747         // Remove
748         if( *prev_np != pty ) {
749                 Log_Error("PTY", "PTY %p(%i/%s) not on list at deletion time", pty, pty->NumericName, pty->Name);
750         }
751         else {
752                 *prev_np = pty->Next;
753         }
754         
755         // Clean up lock
756         if( pty->NumericName == -1 ) {
757                 RWLock_Release(&glPTY_NamedPTYs);
758                 giPTY_NamedCount --;
759         }
760         else {
761                 RWLock_Release(&glPTY_NumPTYs);
762                 giPTY_NumCount --;
763         }
764
765         // Send SIGHUP to controling PGID
766         if( pty->ControllingProcGroup > 0 ) {
767                 Threads_SignalGroup(pty->ControllingProcGroup, SIGHUP);
768         }
769
770         // If there are no open children, we can safely free this PTY
771         if( pty->ClientNode.ReferenceCount == 0 ) {
772                 free(Node);
773                 free(pty);
774         }
775 }
776
777 int PTY_IOCtl(tVFS_Node *Node, int ID, void *Data)
778 {
779         tPTY    *pty = Node->ImplPtr;
780         struct ptymode  *mode = Data;
781         struct ptydims  *dims = Data;
782         
783         int     is_server = !pty || Node == pty->ServerNode;
784
785         switch(ID)
786         {
787         case DRV_IOCTL_TYPE:    return DRV_TYPE_TERMINAL;
788         case DRV_IOCTL_IDENT:   memcpy(Data, "PTY\0", 4);       return 0;
789         case DRV_IOCTL_VERSION: return 0x100;
790         case DRV_IOCTL_LOOKUP:  return 0;
791         
792         case PTY_IOCTL_GETMODE:
793                 if( !pty )      return 0;
794                 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
795                 *mode = pty->Mode;
796                 // TODO: ACK client's SETMODE
797                 return 0;
798         case PTY_IOCTL_SETMODE:
799                 if( !pty )      return 0;
800                 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
801                 PTY_SetAttrib(pty, NULL, mode, !is_server);
802                 return 0;
803         case PTY_IOCTL_GETDIMS:
804                 if( !pty )      return 0;
805                 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
806                 *dims = pty->Dims;
807                 return 0;
808         case PTY_IOCTL_SETDIMS:
809                 if( !pty )      return 0;
810                 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
811                 PTY_SetAttrib(pty, dims, NULL, !is_server);
812                 return 0;
813         case PTY_IOCTL_GETID:
814                 if( pty )
815                 {
816                         size_t  len = strlen(pty->Name)+1;
817                         if( Data )
818                         {
819                                 if( !CheckMem(Data, len) ) { errno = EINVAL; return -1; }
820                                 strcpy(Data, pty->Name);
821                         }
822                         return len;
823                 }
824                 return 0;
825         case PTY_IOCTL_SETID:
826                 if( Data && !CheckString(Data) ) { errno = EINVAL; return -1; }
827                 if( pty )       return EALREADY;
828                 pty = PTY_Create(Data, NULL, NULL,NULL, NULL);
829                 if(pty == NULL)
830                         return 1;
831                 Node->ImplPtr = pty;
832                 pty->ServerNode = Node;
833                 return 0;
834         case PTY_IOCTL_SETPGRP:
835                 // TODO: Should this only be done by client?
836                 if( Data )
837                 {
838                         if( !CheckMem(Data, sizeof(tPGID)) ) { errno = EINVAL; return -1; }
839                         pty->ControllingProcGroup = *(tPGID*)Data;
840                         Log_Debug("PTY", "Set controlling PGID to %i", pty->ControllingProcGroup);
841                 }
842                 return pty->ControllingProcGroup;
843         }
844         errno = ENOSYS;
845         return -1;
846 }
847

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