CCDciel source review - BUGS AND BAD PRACTICES ================================================ Scope and method ---------------- - Static review of the uploaded ccdciel-master/src (143 Pascal units, ~115,000 lines). The code was NOT compiled or run: no FPC/Lazarus toolchain was available, so every item below comes from reading the source. Line numbers refer to the uploaded files. - Reviewed in depth: cu_fits, cu_tcpserver, the TCP/JSON-RPC parts of pu_main, pu_scriptengine (script launching), u_utils (process, string, time helpers), cu_ascomrest (Get), unit_ricecomp_fits (unpack and header cards), cu_autoguider, cu_autoguider_phd, cu_autoguider_internal (star selection, calibration), cu_tiff (write path), cu_indicamera (image reception, frame), cu_astrometry (engine lifetime), pu_dark, pu_polaralign2, cu_waitthread. - Second round (sections E and F): the mount, focuser and dome drivers for all three interfaces (cu_mount, cu_ascommount, cu_ascomrestmount, cu_indimount, cu_focuser, cu_ascomfocuser, cu_ascomrestfocuser, cu_indifocuser, cu_dome, cu_ascomdome, cu_ascomrestdome, cu_indidome), the sequence engine (cu_targets, cu_plan, cu_sequencefile) and the meridian flip logic in pu_main. - Added later: C16-C18, found when comparing cu_tiff.pas and unit_ricecomp.pas with the same units of ASTAP (the Rice core itself is still not reviewed in depth, only its thread dispatchers and the encoder clamp). - Covered by automated pattern scans only (empty except blocks, loop bounds, self-assignments, Format() argument counts, unreleased locals, async calls): the camera, wheel, rotator, weather, safety, switch and cover drivers, unit_ricecomp (encoder), the ws_* websocket units, fu_sequence/pu_edittargets (GUI) and the rest of pu_main. - The code already contains many "2024 fix (report item N)" comments from an earlier review. Those fixes were re-checked; section A lists the ones that are wrong or incomplete. Status overview (each item below ends with a "Status:" line) ------------------------------------------------------------ implemented (52): A1, A2, A4, A6, A7, B1, B2, B3, B4, B7, B8, B9, B10, B11, B12, B13, B14, B15, B16, C1, C2, C3, C5, C6, C7, C8, C9, C13, C14, C15, C16, C17, C18, D3, D4, D5, D6, E1, E2, E4, E7, E8, E9, E10, E11, F1, F2, F3, F5, F7, F8, F10 implemented differently ( 6): C4, C11, E3, E5, E6, F4 partially implemented ( 9): A3, A5, B6, C10, C12, D8, E12, E13, F6 not implemented ( 8): B5, D1, D2, D7, D9, D10, D11, F9 Severity: HIGH = data corruption, crash, security or wrong result in normal use; MEDIUM = edge cases, races, leaks, robustness; LOW = minor or code hygiene. ===================================================================== A. PROBLEMS IN EARLIER "2024 FIX" CHANGES ===================================================================== A1. [HIGH] 8-bit FITS values change on every save (regression from "item 15f") cu_fits.pas:2706 (TFits.WriteFitsImage, 8-bit branch) The writer now divides by 257, but the reader still stores 8-bit pixels as x8*255 (cu_fits.pas:1217 and 1254). The fix comment assumes Fimage spans 0..65535, but for data loaded from an 8-bit FITS it spans 0..65025. Effect: open + save of an 8-bit file maps 255->253, 128->127, etc. Every re-save darkens the image a little more. Fix: use the same constant in both directions (either revert the writer to 255, or change the reader to *257 and keep 257 in the writer). Add a round-trip test. Status: IMPLEMENTED. A2. [MEDIUM] Overflow fix applied in one place only ("item 5") cu_fits.pas:2456 (TFits.GetFlatLevel) if (FFitsInfo.naxis1*FFitsInfo.naxis2)>(maxl*maxl) is still 32-bit, exactly the pattern that was widened to Int64 in ReadFitsImage. A corrupt header can wrap the product and bypass the size guard. Also: endline := startline+cropsizey (line 2468) makes the loop read cropsizey+1 rows while flatlimit assumes cropsizey rows (off by one). Status: IMPLEMENTED. A3. [MEDIUM] Temporary file race fixed only for tmppack ("item 8") UniqueTempFits is used for the pack/unpack temp file, but other fixed shared names remain: ccdcieltmp.fits, ccdcielsolved.fits, fitstmp.fits, findertmp.fits, finder.fits, findersolved.fits, guidetmp.fits, guidesolved.fits, guidereftmp.fits (cu_astrometry.pas 415-947, cu_autoguider_internal.pas:2756), and tmppack.fits.fz in cu_indicamera.pas:1331. Examples: Tf_main.LoadPictureFile writes ccdcieltmp.fits while an asynchronous plate solve of the main image may still be reading the same file; a guide and a main INDI camera both receiving .fits.fz at the same time share tmppack.fits.fz. The .fits.fz temp file is also not deleted when UnpackFits fails. Status: PARTIALLY IMPLEMENTED. Separate names for picture import, ASTAP menu and INDI .fz; solved-file menu actions refuse while a solve runs; the astrometry module keeps its own fixed names (serialised by its Busy flag). A4. [LOW] Misleading safety claim ("item 1") pu_polaralign2.pas:154 and :186 The comment says nil-ing each slot after Free turns a duplicated pointer into a harmless Free(nil). It does not: if the same object is in slots i and j, slot i is freed and nil'd but slot j still holds the dangling pointer, and freeing it is still a double free. The actual fix (the missing Create) is correct; only the comment is wrong and could mislead a later maintainer. Status: IMPLEMENTED. Correction note added after the original comment. A5. [LOW] Wrong reasoning in StopServer comment ("item 4") pu_main.pas:16666-16676 The comment says a plain WaitFor would deadlock because the daemon uses Synchronize. In current FPC versions TThread.WaitFor called from the main thread services CheckSynchronize while waiting, so it does not deadlock. More important: after the 10-second Wait() loop the code calls TCPDaemon.WaitFor unconditionally, so the "timeout" is not a timeout - if a client never stops, shutdown hangs. The Wait() loop also runs Application.ProcessMessages, so the user can trigger StartServer/StopServer again while TCPDaemon is half torn down. Status: PARTIALLY IMPLEMENTED. Comment corrected, re-entrancy guard and progress message added; the final WaitFor is kept (freeing a running thread is unsafe). A6. [MEDIUM] The worker-thread "join" fixes still ignore thread failures ("item 6") cu_fits.pas:2579, 2596, 2869, 2924, 3481 (and the other WaitFor sites) WaitFor is now correct, but an exception inside TReadFits/TDebayerImage/ TMedianFilter/TGetBgraThread.Execute is stored in TThread.FatalException and never inspected. The caller then uses partially filled image arrays and statistics as if nothing happened. Check FatalException after WaitFor and raise/report it. Status: IMPLEMENTED. ReadFitsImage refuses the image; the other workers report an error message. A7. [HIGH] Program never closes: TCP server thread blocked in Accept (found during testing of the corrections) cu_tcpserver.pas TTCPDaemon.Execute The accept loop called the blocking Accept without waiting for a pending connection first, so the stop request was only checked when a client connected. Since "item 4" made Tf_main.StopServer wait for the thread (WaitFor), closing the program hung forever when no client connected (always on Windows, where the socket timeout does not apply to accept). The review missed this (A5 only noted a hang with a connected client). Fix: CanRead(500) before Accept, the stop request is checked every 500 ms. Status: IMPLEMENTED. ===================================================================== B. HIGH SEVERITY ===================================================================== B1. JSON flattening counts nodes instead of depth cu_tcpserver.pas:553 (TTCPThrd.JsonDataToStringlist) cu_autoguider_phd.pas:178 (T_autoguider_phd.JsonDataToStringlist) JsonRecurseLevel is incremented on every call and never decremented, so it counts all visited values. Any message with about 100 values raises "JSON data recursion > 100" and is dropped, even though it is only 2 levels deep. Fix: dec(JsonRecurseLevel) on exit (try/finally), or pass depth as a parameter. Also: in both units GetJSON's result J leaks when the flattening raises (cu_tcpserver.pas:531, cu_autoguider_phd.pas:~215) - J.Free is not in a finally. Status: IMPLEMENTED. B2. HTTP POST with empty body sends two responses cu_tcpserver.pas:646 (TTCPThrd.ProcessPost) After sending "HTTP/1.0 405 Invalid request" there is no exit, so the code continues, runs ProcessJSON and sends a second "HTTP/1.0 200" response. Status: IMPLEMENTED. B3. POST body reading logic inverted, 413 does not stop processing cu_tcpserver.pas:430 (TTCPThrd.Execute) - The "read until the peer stops" branch runs when cl=0, i.e. when the client sent "Content-Length: 0" (or an unparsable value, because StrToIntDef(...,0)). When the header is absent (cl=-1) nothing is read at all. Intended: cl=0 -> empty body; cl<0 -> read until close (bounded). - Inside that branch the 413 "Request body too large" uses break, which only leaves the inner repeat loop. The truncated body is then still passed to ProcessPost, which sends a second response and executes the request. - The header lines are accumulated in "hdr" without limit and hdr is never used. Status: IMPLEMENTED. B4. HTTP protocol check can never fail cu_tcpserver.pas:599 else if pos('HTTP/',protocol)<0 then Pos never returns a negative value. Should be =0 (or <>1). Status: IMPLEMENTED. B5. (moved to D11 - remote access without authentication is intended) Status: NOT IMPLEMENTED. Moved to D11, remote access is intended. B6. Invalid JSON produced by the JSON-RPC server pu_main.pas:17897 and cu_tcpserver.pas ProcessJSON (error branch) - The request id is inserted unquoted. A string id (allowed by JSON-RPC 2.0, e.g. "id":"abc") produces "id": abc - invalid JSON. - Exception messages and values from the configuration (driver names, paths with backslashes, object names with quotes) are concatenated without escaping. Fix: build replies with fpjson (TJSONObject) instead of string concatenation. Status: PARTIALLY IMPLEMENTED. Ids, error messages and string results are escaped; replies are still built by string concatenation. B7. Use-after-free of asynchronous Python script threads pu_scriptengine.pas:2422 (RunPythonAsync) PythonScr[n].FreeOnTerminate:=true, but the pointer stays in PythonScr[n]. ScriptRunning(), StopPython() and the slot search in RunPython/RunPythonAsync later dereference the freed thread (.Terminated, .FRunning, .PyProcess). This is the same pattern that "item 4" fixed for the TCP threads. Fix: keep FreeOnTerminate=false and free finished threads when the slot is reused, or clear the slot (in ShowOutput, on the main thread) before the thread frees itself. Status: IMPLEMENTED. B8. Successful synchronous script can be reported as failed (race) pu_scriptengine.pas:2585 (TPythonThread.Execute) FRunning:=false is set BEFORE Synchronize(@ShowOutput). RunPython polls ScriptRunning() and can see "not running" and read PythonResult[n] before ShowOutput has stored the exit code, i.e. it reads the initial -1. Fix: set FRunning:=false after the Synchronize call. Status: IMPLEMENTED. B9. Switch lock left on forever after a failed script start pu_scriptengine.pas:390 (RunScriptAsync) LockSwitch is called, but when the script file does not exist, or when RunPythonAsync fails (all 10 slots in use), the function exits without UnLockSwitch. Rate-limited switch status updates then stop permanently. The lock is also not reference-counted: with two scripts running, the first one to finish unlocks the switches while the second is still running. Status: IMPLEMENTED. B10. Forked child keeps running a copy of CCDciel if exec fails (Unix) u_utils.pas:1309 (ExecFork) If fpExecVP returns -1 the child process just returns 0 from ExecFork and continues executing the GUI program as a second instance (duplicate timers, sockets, device connections). The child must call fpExit(127) (or _exit) after a failed exec. The parent never calls fpWaitPid (no waitpid anywhere in the code), so every launched program leaves a zombie process until CCDciel exits. Status: IMPLEMENTED. B11. Stack buffer overflow reading stderr u_utils.pas:1161 and :1196 (ExecProcessMem) cerr is array[0..1024] of char, but P.Stderr.Read(cerr, i) uses i := NumBytesAvailable, which can be much larger than 1025. A noisy external program (astrometry solver, script) overwrites the stack. The buffer is also never re-terminated: after a short read, bytes left over from an earlier longer read are appended to "err". Fix: read into a dynamic buffer of size i, or read min(i, SizeOf(cerr)-1) and terminate. Status: IMPLEMENTED. B12. Buffer overflows and handle leaks in Windows process launchers u_utils.pas:1134 (ExecNoWait, Windows): StrPCopy into a fixed 1025-char buffer with no length check; process and thread handles from CreateProcess are never closed (handle leak per call). u_utils.pas:1320 (ExecuteFile, Windows): three array[0..255] buffers filled by StrPCopy - a file path longer than 255 characters overflows the stack. u_utils.pas:1129 (ExecNoWait, Unix): fpSystem(cmd+' &') runs the string through /bin/sh; any path or object name containing ; & $ ` or quotes is executed as shell syntax. Status: IMPLEMENTED. B13. Alpaca ImageBytes detection is always true cu_ascomrest.pas:423 Result.imagebytes:=pos('application/imagebytes',buf)>=0; Pos returns 0 when not found, so this is true for every Content-Type header. A JSON image reply (from a server without ImageBytes support) is then parsed as binary, fails the MetadataVersion check and the image download aborts with "Unsupported Alpaca ImageBytes MetadataVersion". Should be >0. Same function: - errmsg (line 388) is an uninitialised stack array; Read(errmsg,1024) does not add a terminator, so the error text contains stack garbage. - the "Not implemented Alpaca image array type" raise does not free Result (leak). - dimension1*dimension2*dimension3 is a 32-bit product of device-supplied values and is not validated before SetLength. Status: IMPLEMENTED. B14. Internal guider: frame coordinates multiplied by the binning inside the loop cu_autoguider_internal.pas:794 In the loop that keeps only stars inside the new sub-frame, the INDI-specific conversion frx:=frx*BinX; fry:=fry*BinX; frw:=frw*BinY; frh:=frh*BinY runs once per accepted star. With INDI and binning>1, after the first accepted star the frame bounds used for the following stars and the offsets x1-frx are wrong, and SetFrame finally receives values scaled by bin^N. Also X and Y binning are swapped (fry uses BinX, frw uses BinY). Fix: do the conversion once, after the loop, just before FCamera.SetFrame. Status: IMPLEMENTED. B15. Thread-unsafe GUI and string access from the PHD2 client thread cu_autoguider_phd.pas:128 FonConnect(self) is called directly from the worker thread. The handler Tf_main.AutoguiderConnect (pu_main.pas:8790) changes button and menu captions - LCL controls must only be touched from the main thread (crashes on GTK/Qt). cu_autoguider_phd.pas:147 StarLostTimer.Enabled is changed from the worker thread (TTimer is not thread-safe). cu_autoguider.pas:185 / pu_main.pas:15702 FErrorDesc (an AnsiString) is appended in the worker thread and read and cleared in the main thread with no lock. Concurrent reference-count updates on a managed string can corrupt the heap. cu_autoguider_phd.pas:152 tcpclient.Free in the thread's finally, but the field is not set to nil. Send() (called from the main thread) checks tcpclient<>nil and then uses the freed object. Status: IMPLEMENTED. B16. Dark library dialog: double free and stale callbacks pu_dark.pas:121 (FormClose), :161 (btnStartClick), btnCancelClick - FormClose frees fstack and fdark but does not set them to nil. The form is reused (f_dark.ShowModal is called repeatedly from pu_main), so after a cancelled run the next close frees the same objects again. - Cancel during a run only aborts the exposure; the pending WaitExecute(1000, @NextExposure) still fires. If the user closes the dialog within that second, NextExposure's except branch frees the already-freed fstack/fdark. - btnStartClick creates new fdark/fstack without freeing earlier ones (leak). - nloop:=trunc(LogN(sq2,maxexp))+1 (line 146) raises if MaxExposure is 0. Status: IMPLEMENTED. ===================================================================== C. MEDIUM SEVERITY ===================================================================== C1. FITS header reader: uninitialised variables and 32-bit size arithmetic cu_fits.pas TFitsHeader.ReadHeader / GetExtend (around 560-760) naxis, naxis1..3 and bitpix are not initialised; if the header lacks a keyword, stack garbage decides whether extensions are searched. Data-unit sizes are computed in 32-bit Integer (overflow for large or 3-plane images) and rounded DOWN with trunc(size/2880)*2880 instead of up. It only works because GetExtend then scans block by block; a data block that happens to start with "XTENSION=" would be misread as a header. Status: IMPLEMENTED. C2. NaN pixels poison image statistics cu_fits.pas TReadFits.Execute (-32 and -64 branches) Float FITS files commonly use NaN for blank pixels. NaN is not filtered, so dmin/dmax/sum/sum2 become NaN and the display stretch and statistics break. Status: IMPLEMENTED. C3. Threads that mutate shared object state cu_fits.pas TReadFits.Execute, 8-bit RGBA branch: each worker writes fits.n_plane:=4 and later 3. This is only safe because ReadFitsImage forces 1 thread when n_plane>1; a later change to the thread count would create a race. Pass the plane count to the worker instead of modifying the shared object. Status: IMPLEMENTED. C4. Tile-compressed FITS reader (NativeUnpackFits) loses data unit_ricecomp_fits.pas - :785 every header keyword starting with "Z" is dropped, not only the compression keywords. User keywords such as ZD, ZENITH, ZPOINT are lost. - :770 integer images are always written as BITPIX=16, despite the comment "keep original ZBITPIX". ZBITPIX=8 or 32 data is truncated. - :611 ZNAXIS1=0 (or absent) makes ztile1:=0 and tiles_x:=.../ztile1 divides by zero. ZNAXISn are never range-checked before SetLength(img,...). - tableBytes := bnaxis1*bnaxis2 is a 32-bit product of header values. - :776 k := HdrIndex(hx,'') inside the loop is dead code and makes it O(n^2). - CHECKSUM/DATASUM of the compressed HDU are copied into the uncompressed header, where they are now wrong. Status: IMPLEMENTED DIFFERENTLY. ZBITPIX other than 16 and -32 is refused with a message instead of supporting 8/32-bit output (the decoder supports only 16 and -32). C5. FITS header card writers produce invalid cards unit_ricecomp_fits.pas:283 MakeFloatCard: round(value) raises for |value|>9.2e18 (and for NaN); exponent notation gets ".0" appended ("1E+30.0"). unit_ricecomp_fits.pas:298 MakeStrCard: single quotes in the value are not doubled; values longer than 68 characters lose the closing quote. cu_fits.pas:915 TFitsHeader.Insert: copy(row,1,80) truncates long quoted strings without the closing quote (invalid card). cu_fits.pas:798 TFitsHeader.GetJSON: values are not JSON-escaped. Status: IMPLEMENTED. C6. Header-derived filename parts not sanitised cu_fits.pas:5302 (CapturePath) and :5359 (CaptureFilename) OBJECT goes through SafeFileName, but FILTER and FRAME do not. Filter names come from the wheel driver or user configuration; a filter called "Ha/OIII" or "R:G:B" creates an extra sub-directory or makes the save fail on Windows. DateIso2DateTime (u_utils.pas:1502) raises EConvertError for DATE-OBS values it does not understand (e.g. a trailing "Z"), which would abort filename creation. Status: IMPLEMENTED. Also the sequence step name used as directory name. C7. AstroTIFF export cu_fits.pas:3589 (TFits.SaveAstroTiff) Always calls save_tiff_16, which writes only img[0]. An RGB (3-plane) image is saved as its red plane only. For scaled images (float, 32-bit) it passes Frawimage, whose values are in physical units; clamp16 then flattens most of the image to 0/1. save_tiff_new already selects the right writer and is unused. The "delayed" parameter is unused. cu_tiff.pas:293: height2=0 makes thread_count 0 and the next line divides by zero. Strip-compression thread exceptions are not checked; a nil strip stream would then be written. read_tiff is not called anywhere in CCDciel (dead code). Status: IMPLEMENTED. Read_tiff (dead code) kept on request. C8. INDI image reception cu_indicamera.pas:1311-1324 (NewImageFile) - When the uncompressed size is unknown, a 200 MB buffer (10000*10000*2) is allocated for every compressed frame. - The frame-size estimate assumes 2 bytes per pixel; 32-bit images do not fit and uncompress fails. - If uncompress fails (i<>0) nothing is reported; ".z" is still stripped from the type and the compressed bytes are processed as a FITS file. cu_indicamera.pas:1696 x:=round(x+0.5) "force even values" only works because FPC's Round uses banker's rounding. Use x := x and not 1 for clarity. Status: IMPLEMENTED. C9. TCP daemon socket freed but not cleared cu_tcpserver.pas:331 / :205 Sock.Free in Execute's finally does not set Sock:=nil, but GetIPport tests "if sock=nil". Reading TCPDaemon.IPport after the daemon thread has ended dereferences freed memory (and GetIPport reads the socket from the main thread while the daemon thread owns it). StartServer swallows every exception (empty except). Status: IMPLEMENTED. C10. Queued asynchronous calls can run on freed objects 24 calls to Application.QueueAsyncCall (pu_main 11, pu_devicesetup 3, cu_autoguider_internal 2, pu_polaralign 2, cu_autoguider_phd, cu_camera, cu_targets, fu_finder, pu_polaralign2, pu_scriptengine) and no call to Application.RemoveAsyncCalls anywhere. Concrete case: T_autoguider_phd queues ProcessEventAsync with a TStringStream (cu_autoguider_phd.pas:231). The autoguider thread is FreeOnTerminate and is replaced on disconnect, so events still in the queue run on the freed object and their stream is never freed. Fix: call Application.RemoveAsyncCalls(Self) in every destructor that queued calls. Status: PARTIALLY IMPLEMENTED. RemoveAsyncCalls added everywhere; data passed to a removed call (PHD2 event stream) is not freed. C11. Self-freeing threads referenced after they may have ended cu_astrometry.pas:292 engine.Resolver is read after engine.Resolve started a FreeOnTerminate thread; if the solver fails immediately the object is gone. cu_astrometry.pas:332 StopAstrometry calls engine.Stop when FBusy is true, but FBusy is only cleared when the posted M_AstrometryDone message is processed; in between the engine thread may already have freed itself. cu_autoguider (FreeOnTerminate=true): when AppClose is set, the disconnect handler does not replace the global "autoguider" reference, which then dangles. cu_waitthread.pas:76 WaitExecute calls the target method after sleeping with no check that the target object still exists (e.g. form closed meanwhile). Status: IMPLEMENTED DIFFERENTLY. Engine reference cleared through OnTerminate; WaitExecute skips calls at program close; the autoguider reference at close is replaced by an inactive T_autoguider_none object instead of nil. C12. Internal guider calibration state machine cu_autoguider_internal.pas:2326 When measure_drift fails in direction 6 / step 1, the code switches to direction 7 and recursively calls InternalCalibration, but then falls through and sets InternalguiderCalibrationStep:=1 or 2 afterwards, overwriting the state just set by the recursive call. An exit is missing. cu_autoguider_internal.pas:2344 drift can be 0 (mount did not move) -> floating-point division by zero. Same for pulsegainEast+pulsegainWest (CalPixSize1) and pulsegainEast/pulsegainWest, pulsegainNorth/pulsegainSouth. cu_autoguider_internal.pas:2004 "if Calthecos=0" never triggers because cos(90 deg) is about 6e-17, not 0. Use abs(Calthecos)<1e-6. cu_autoguider_internal.pas:2318, 2333 sleep(500) on the main thread freezes the GUI during the scale measurement (up to 8 times). Status: PARTIALLY IMPLEMENTED. State machine and divisions fixed; the two sleep(500) are kept on purpose (Wait() would allow re-entry). C13. Sequence plan loading leaks configuration objects cu_targets.pas:1129 (CompatLoadPlan) pfile:=TCCDconfig.Create(self) is never freed. Because it is owned by the targets object it is released eventually, but every load of an old-format sequence keeps another parsed XML file in memory until then. Status: IMPLEMENTED. C14. Busy-wait loops u_utils.pas ExecProcessMem / ExecProcess: "while P.Running" without any sleep. Off the main thread (ProcessMessages skipped) this spins a core at 100%. cu_ascomrest.pas:410 and GetImagearrayBase64: sleep(5)+ProcessMessages polling for every Alpaca request. pu_scriptengine RunPython: wait(1) polling. Status: IMPLEMENTED. Process-wait loops; the Alpaca polling loops already had a sleep. C15. Websocket frame length (vendored library) ws_websocket2.pas:1409 The 64-bit payload length is built from signed multiplications; a first byte >=128 makes "len" negative, and there is no upper bound on the frame size before allocating. The peer is the INDI server, so this is low risk, but the library should reject oversized or negative lengths. Status: IMPLEMENTED. C16. [MEDIUM] Float images written as 16-bit TIFF (found when comparing with ASTAP) cu_tiff.pas save_tiff_new "if bitpix<=16" is also true for the negative FITS BITPIX of float images (-32, -64), so a caller that passes the FITS BITPIX gets a 16-bit TIFF. (CCDciel's own SaveAstroTiff passes 32 since C7 and was not affected.) Fix: abs(bitpix)<=16. Status: IMPLEMENTED. C17. [LOW] NaN pixels raise an exception when saving TIFF or .fz (found when comparing with ASTAP) cu_tiff.pas fill_tiff_row/clamp16, unit_ricecomp.pas TRiceEncodeThread round() raises EInvalidOp for NaN (the clamps compare false for NaN), and in the Rice encoder also for values beyond the Int64 range. Since C2 the FITS reader replaces NaN by 0, so this is a safety measure. Fix: NaN written as 0; the Rice encoder clamps to 0..65535 before round(). Status: IMPLEMENTED. C18. [MEDIUM] Failed Rice worker threads not detected (found when comparing with ASTAP; unit_ricecomp.pas had not been reviewed before) unit_ricecomp.pas rice_decode_tiles, rice_encode_rows Same pattern as A6: TRiceTileThread and TRiceEncodeThread use try/finally without except and the dispatchers did not check FatalException. Decoding left the tiles of a failed worker blank without an error; encoding returned ok=true with nil tile_data[] that the caller then wrote. Fix: after WaitFor, a FatalException sets err_decode (decoder) or ok:=false (encoder) with its message. Status: IMPLEMENTED. ===================================================================== D. LOW SEVERITY / CODE HYGIENE ===================================================================== D1. 182 empty "except ... end" blocks silently swallow errors. The largest groups: cu_ascomweather.pas and cu_ascomrestweather.pas (29 each), pu_main.pas (16), cu_ascomcamera / cu_ascomrestcamera (9 each), u_utils.pas (8), cu_autoguider_phd (7). At minimum log the exception message. Status: NOT IMPLEMENTED. On request. D2. Application.ProcessMessages is called in about 100 places, including inside Wait() (u_utils.pas:1343), every Alpaca request and process launch. Each call allows re-entrant event handling (a button can be clicked while its own handler is still running). Several bugs above (A5, C11) depend on this. Status: NOT IMPLEMENTED. On request. D3. Self-assignments with no effect (likely leftover or unfinished code): cu_autoguider_internal.pas:790 xy_array[star_counter2].flux:=...flux fu_starprofile.pas:870 s:=s pu_pause.pas:127 PauseLabel.Caption:=PauseLabel.Caption pu_sensoranalysis.pas:611 minstep:=minstep u_refraction.pas:74, 127 h:=h Status: IMPLEMENTED. D4. u_utils.pas:1408/1414 to360 can return exactly 360.0 for tiny negative inputs (e.g. -1e-14 + 360 rounds to 360). u_utils.pas:401 Splitarg removes one character of a multi-character separator. u_utils.pas:3248 hextostr reads past the end of an odd-length string (range check error in debug builds). u_utils.pas:1353 GetCdCPort: Reset() with I/O checks on and no try/except. Status: IMPLEMENTED. D5. unit_ricecomp_fits.pas MakeLogicalCard computes "s" twice (first assignment is dead); TFormWidthBytes has an unused isP variable. Status: IMPLEMENTED. D6. cu_fits.pas:1301 "ii:=ys-1-i;;" double semicolon; "thread[0]:=nil;" leftovers in Debayer/MedianFilter. Status: IMPLEMENTED. D7. 48 "with" statements. They hide which object a field belongs to and have already caused confusion in this code (e.g. "with sock do" blocks in cu_tcpserver mixing thread and socket members). Status: NOT IMPLEMENTED. On request. D8. Credentials: EncryptStr is obfuscation with a constant key (already noted by the earlier review). In addition, TAscomRest.SetBaseUrl embeds user:password in the URL, which can end up in logs or error messages that print the URL. Status: PARTIALLY IMPLEMENTED. Credentials sent as HTTP Basic authentication instead of in the URL; the obfuscation of stored credentials is unchanged. D9. pu_main.pas is 20,329 lines. Many unrelated responsibilities (UI, TCP server, JSON-RPC dispatcher, sequencing glue, image display) live in one form unit. Status: NOT IMPLEMENTED. On request. D10. Globally mutating DefaultFormatSettings.DecimalSeparator (pu_main.pas:1525) works but affects every unit and any library; prefer a dedicated TFormatSettings for FITS/protocol formatting. Status: NOT IMPLEMENTED. On request. D11. Unauthorized access is possible pu_main.pas StartServer, TCPjsoncmd The TCP/IP server listens on all network interfaces and has no authentication, so anyone who can reach the port can slew the mount, open the dome, run scripts or shut the program down. Remote access is intended (remote clients, the HTML status page), so this is left as designed; restrict the port with a firewall to the hosts that need it. Implemented: SCRIPT_RUN accepts only a plain script name (no path separators, ':' or '..'), so a client can no longer run .script files from outside the configuration directory, and double quotes are removed from script parameters. Status: NOT IMPLEMENTED. Intended, left as designed; only the SCRIPT_RUN script name check is implemented. ===================================================================== E. MOUNT, FOCUSER AND DOME DRIVERS ===================================================================== Common pattern: the drivers report success without checking the outcome ----------------------------------------------------------------------- Almost every "do something" method in these units is a procedure, or a function that returns true as soon as the command was sent. Timeouts and failure states are not propagated to the caller, so the sequence logic (section F) cannot react. The individual items below are the concrete cases. E1. [HIGH] Slew always reports success cu_ascommount.pas:537, cu_ascomrestmount.pas (Slew), cu_indimount.pas (Slew) - ASCOM/Alpaca: WaitMountSlewing(SlewDelay) returns false on timeout, but Slew ignores it and returns true. - INDI: when WaitBusy times out the code only prints rsTimeout, and an IPS_ALERT state on EQUATORIAL_EOD_COORD (slew refused, e.g. below the horizon limit) is not checked at all. Slew still returns true. - cu_targets.pas:3157 (T_Targets.Slew, non-precision branch) does not even look at the return value: "Mount.Slew(ra, de); Wait(delay); result:=true;". Effect: in an unattended sequence a refused or timed-out slew is followed by a full plan of exposures at the wrong position. Status: IMPLEMENTED. E2. [HIGH] Slewing flag stuck after an exception cu_ascommount.pas Slew, cu_ascomrestmount.pas Slew FMountSlewing:=true is set inside the try, but the except branch does not reset it. After one driver exception, GetMountSlewing returns true until the program is restarted. CheckMeridianFlip skips its checks while the mount is "slewing" (pu_main.pas:15848), so the meridian flip is never performed. Fix: reset FMountSlewing in a finally block. Status: IMPLEMENTED. E3. [HIGH] Dome shutter "closed" test treats error and opening states as closed cu_ascomdome.pas:319, cu_ascomrestdome.pas:298 (GetShutter) GetShutter returns true only for ShutterStatus=0 (open). Status 2 (opening), 3 (closing) and 4 (error), and any exception while reading it, all return false, i.e. "closed". Consequences in T_mount.SetParkInterface (cu_mount.pas, dclCloseDome): - a shutter in the ERROR state, or still opening, is reported as "already closed" and the close command is never sent; - a close that fails (ends in status 4) passes the check "if dome.Shutter then abort", so the park sequence reports success. For an unattended end of night this is a weather-safety issue. Fix: expose the full shutter state (open/closed/opening/closing/error/unknown) and test for "closed" explicitly. Status: IMPLEMENTED DIFFERENTLY. New ShutterState property used for the safety-relevant checks; the boolean Shutter property is unchanged elsewhere. E4. [MEDIUM] INDI dome without DOME_SHUTTER (roll-off roofs): shutter state is wrong cu_indidome.pas:419 (GetShutter) / :429 (SetShutter) SetShutter falls back to SetPark(not value) when there is no shutter property, which is how INDI roll-off roof drivers work. GetShutter does not use the same fallback and always returns true ("manual shutter, expect open"). - Open action (dopOpenDome): "if dome.Shutter then already open" is always true, so the roof is never opened by this action. - Close action (dclCloseDome): after the roof has closed, "if dome.Shutter" is still true, so the park sequence prints "dome not closed" and aborts the remaining steps. - InitTarget's check "Dome is not ready" (cu_targets.pas, not dome.Shutter) passes with the roof closed, so the sequence starts imaging the inside of the roof. Fix: when DomeShutterProp=nil, GetShutter should return not GetPark. Status: IMPLEMENTED. E5. [MEDIUM] ASCOM/Alpaca dome cannot be unparked, which aborts the unpark sequence cu_ascomdome.pas:303, cu_ascomrestdome.pas:283 (SetPark) SetPark(false) does nothing (ASCOM has no Unpark). With the "unpark dome" action configured, T_mount.SetParkInterface sets dome.Park:=false, then checks "if dome.Park then abort" - AtPark is still true, so the whole unpark sequence aborts every time. ASCOM clears AtPark on FindHome or SlewToAzimuth; use one of those, or skip the check for ASCOM domes. Status: IMPLEMENTED DIFFERENTLY. CanUnpark property; the "unpark dome" action is skipped for ASCOM/Alpaca domes instead of sending FindHome. E6. [MEDIUM] Mount is not parked when the slaved dome is disconnected cu_mount.pas T_mount.SetParkInterface With SlaveDome enabled and the dome not connected, the method prints "dome not connected / abort mount park" and returns without parking the mount. At the end of an unattended night (RunEndAction, AtEndPark) a lost dome connection therefore leaves the telescope unparked and tracking. Parking the mount alone is normally the safe fallback. Because SetParkInterface is a procedure, the caller does not learn that nothing happened. Status: IMPLEMENTED DIFFERENTLY. Mount is parked alone; SetParkInterface stays a procedure, its result is in the new LastParkOK property. E7. [MEDIUM] INDI park/position checks read the requested state, not the result cu_indimount.pas SetPark/GetPark, cu_indidome.pas SetPark/SetShutter, cu_indifocuser.pas SetPosition The code changes the local switch/number values, sends them, and later reads the same local copy (swpark.s, DomeShutterOpen.s, FocusAbsolutePosition value). The property state (IPS_ALERT) is never checked, and WaitBusy's result is ignored. If the driver rejects the command and does not echo the old values back (driver-dependent), CCDciel believes the mount is parked, the shutter is closed, or the focuser is at the new position. Status: IMPLEMENTED. E8. [MEDIUM] Hard-coded 60 s wait for dome, park and focuser moves cu_ascomdome / cu_ascomrestdome WaitShutter/WaitDomePark(60000), cu_indidome WaitBusy(...,60000), cu_*focuser SetPosition WaitFocuserMoving(60000) Many roll-off roofs and some focusers over their full range take longer than 60 s. The timeout result is ignored: the focuser reports the requested position (FonPositionChange(p)) while it is still moving, so autofocus takes its next image during the move. Make the timeouts configurable and check the result. Status: IMPLEMENTED. Timeouts configurable in the configuration file only (/Dome/ActionTimeout, /Focuser/MoveTimeout), no Options dialog setting. E9. [MEDIUM] Fail-open safety checks cu_dome.pas SetParkInterface/SetShutterInterface, cu_mount.pas unpark branch Opening the dome or unparking is blocked only if the safety monitor is connected AND reports unsafe. If the safety monitor is disconnected, opening is allowed. For an unattended setup "no safety information" should block opening. Status: IMPLEMENTED. E10. [MEDIUM] Focuser backlash compensation silently skipped near the limits cu_focuser.pas:127 (SetPositionInt), cu_ascomfocuser.pas:335 (SetPosition) The overshoot p+FBacklash (or p-FBacklash) is outside MaxStep/0 near the ends of the range; SetPosition rejects it with only a level-1 message and the final move then happens without compensation. Relative moves clamp p+FBacklash to the range, so the compensation amount is also wrong there. Clamp the overshoot to the range instead of rejecting it. Status: IMPLEMENTED. E11. [LOW] Meridian flip success test with unknown pier side cu_ascommount.pas:690 / cu_indimount.pas FlipMeridian result:=(pierside2<>pierside1). Mounts that report pierUnknown return false even when the flip worked. The fallback flip (three slews) ignores the result of each Slew. Status: IMPLEMENTED. E12. [LOW] SlewAsync on a mount without async support blocks the GUI cu_ascommount.pas:502 Falls back to the synchronous SlewToCoordinates COM call, which blocks the main thread for the duration of the slew, and does not set FMountSlewing. Status: PARTIALLY IMPLEMENTED. Slewing flag set during a synchronous slew; the GUI is still blocked during that call (unavoidable). E13. [LOW] Unfinished feature cu_mount.pas SlewToDomeFlatPosition: DomeFlatPositionHome is a "#todo" and does nothing, without telling the user. Status: PARTIALLY IMPLEMENTED. Still not implemented, a message is shown instead of doing nothing. ===================================================================== F. SEQUENCE LOGIC ===================================================================== F1. [HIGH] Wrong pivot time for targets without coordinates cu_targets.pas:2360 (SetTargetTime), used at :2509 and :1729 SetTargetTime returns the pivot in HOURS when the target has coordinates (pivot:=rmod(ht+12+24,24)) but as a FRACTION OF A DAY otherwise (pivot:=frac(middletime)). Both callers divide the pivot by 24. For a target without coordinates (calibration frames, a script target with a time window) the pivot becomes about 00:52 instead of the sequence start time. Example: window 22:00-02:00, sequence started at 21:00. At 01:00 InTimeInterval treats 01:00 as "before 22:00 today", returns -1 and the target waits until the next evening (or is skipped if "skip" is set). Fix: pivot:=frac(middletime)*24. Status: IMPLEMENTED. F2. [HIGH] Meridian flip retries ignore the elapsed time pu_main.pas ~15985 (CheckMeridianFlip, retry loop) When the mount is still on the wrong side after FlipMeridian, the loop retries up to 5 times, each with a 300-second pause. The safety test "if MeridianDelay2<=0 then mount.AbortMotion" uses the value computed before the loop and is never recomputed. If it was positive on entry, the mount keeps tracking for up to ~25 minutes beyond the configured limit without being stopped - a pier collision risk on mounts with a tight limit. Fix: recompute the hour angle (hhmin, MeridianDelay2) in each iteration. Status: IMPLEMENTED. F3. [MEDIUM] Mandatory start time not detected after midnight cu_targets.pas TargetTimerTimer: InTimeInterval(frac(now), t.starttime, nextt.starttime, t.starttime)=1 The pivot is the CURRENT target's start time. When that target has no start time or is circumpolar (starttime -1 / -2), the pivot is negative, times after midnight are not shifted by one day, and a mandatory start of the next target at e.g. 01:00 is never detected; the current target keeps running. Status: IMPLEMENTED. F4. [MEDIUM] Failed guiding start silently skips the light step cu_plan.pas StartStep (capture branch) If guiding cannot be started, the step only logs rsFailedToStar and exits. The plan timer then sees "not running" and moves to the next step, so the light frames of that step are skipped. When the plan ends, TargetTimerTimer increments t.repeatdone, so the target is counted as done even if no frame was taken. Retry, pause, or abort the target instead. Status: IMPLEMENTED DIFFERENTLY. The target is stopped and the sequence goes to the next target without counting it; no retry. F5. [MEDIUM] Script-running flag left set after a failed initialization script cu_targets.pas ~2640-2655 (InitTarget) FScriptRunning:=true is set before seq_scriptengine.RunScript; when the script returns false the code exits without resetting it. GetScriptRunning (cu_targets.pas ~3440) then reports a running script until another script resets the flag. Status: IMPLEMENTED. F6. [MEDIUM] End-of-night actions are not verified and not ordered for safety cu_targets.pas RunEndAction - Mount.Park, Dome.Park and Dome.Shutter are set without checking whether they succeeded; there is no retry and no e-mail/alert on failure, even though e-mail notification exists for other events. - With AtEndCloseDome enabled but AtEndPark disabled, the dome (or roll-off roof) is closed with the telescope in any position. Closing a roll-off roof over an unparked telescope can hit the tube. Check mount.Park (or park first) before closing, or at least warn when the options are combined this way. Status: PARTIALLY IMPLEMENTED. Park and close verified, retried once, reported and e-mailed; closing over an unparked telescope only gives a warning. F7. [MEDIUM] Slew retry and precision-slew results cu_targets.pas T_Targets.Slew - Non-precision slews: see E1 (result always true), so the retry dialog (rsTelescopeSle2) can only ever appear for precision slews. pu_main.pas CheckMeridianFlip: astrometry.PrecisionSlew after the flip is not checked when LastResult is false; imaging resumes uncentered without a message. Status: IMPLEMENTED. F8. [LOW] Moon avoidance checked only once per target cu_targets.pas InitTarget: the moon distance is tested when the target starts. During a long target the moon can move several degrees closer. The check also compares the moon's apparent coordinates of date with the target's J2000 coordinates (about 0.35 deg difference in 2026), which is negligible but worth noting if the limit is small. Status: IMPLEMENTED. Checked every 5 minutes, and the target position is converted to apparent coordinates. F9. [LOW] Blocking waits in the sequence engine InitTarget's weather loop ("while not FWeather.Clear do Wait(5)"), NextStep's wait(2), the dome action waits in SetParkInterface and the 300-second pauses in the meridian flip all run on the main thread through Wait()/ProcessMessages. Timers and user actions are processed re-entrantly during these waits (see D2), which makes the sequence state machine hard to reason about. Status: NOT IMPLEMENTED. Design change needed (state machine with timers). F10. [LOW] Leaked plan configuration (already listed as C13) cu_targets.pas:1129 CompatLoadPlan creates a TCCDconfig that is never freed. Status: IMPLEMENTED. Done as C13. ===================================================================== IMPLEMENTATION STATUS ===================================================================== Every change in the source is marked with a comment "2026 fix (review item Xn)" or "2026 (review item Xn)"; the original comments are kept. The code has not been compiled here; the A-D changes were compiled by the user, the E-F changes still need a compile and a test. NOT IMPLEMENTED --------------- D1 Empty except blocks - on request D2 Application.ProcessMessages re-entrancy - on request (design change) D7 "with" statements - on request D9 Size of pu_main.pas - on request D10 Global DecimalSeparator - on request D11 Remote access without authentication - intended, left as designed (only the SCRIPT_RUN script name check is implemented) F9 Blocking waits in the sequence engine - design change (needs a state machine with timers instead of Wait()); not done cu_tiff.pas read_tiff (dead code) - kept on request PARTIALLY IMPLEMENTED OR IMPLEMENTED DIFFERENTLY ------------------------------------------------ Sections A-D - A7: found while testing (program did not close), implemented. - A3: separate file names for picture import (ccdcielpicture.fits), the ASTAP menu (ccdcielastap.fits) and INDI .fz transfers (unique name); the menu actions that write ccdcielsolved.fits refuse while a solve is running. The astrometry module keeps its fixed names (its solves are serialised by Busy). - A5: the 10 second wait is kept but no longer presented as a timeout; a message is shown when the server is still stopping, and a guard prevents re-entrant StartServer/StopServer. - B6: string ids, error messages and string results are escaped; replies are still built by string concatenation (no full fpjson rewrite). - C4: ZBITPIX other than 16 and -32 is refused with a message (the decoder only supports those two) instead of being written as 16-bit. - C10: RemoveAsyncCalls added everywhere; data passed to a removed call (the PHD2 event TStringStream) is not freed. - C11: the autoguider reference at program close is replaced by an inactive T_autoguider_none object (nil rejected, see Tf_main.AutoguiderDisconnect). - C12: divisions guarded and the state machine fixed; the two sleep(500) calls are kept on purpose (Wait() would allow re-entry of the calibration). - C14: process-wait loops sleep now; the Alpaca polling loops already did. - D8: credentials sent as HTTP Basic authentication instead of in the URL; the obfuscation of stored credentials is unchanged. Sections E-F - E3: a TShutterState (open, closed, opening, closing, error, unknown) and a ShutterState property were added to T_dome and implemented for ASCOM, Alpaca and INDI. It is used where safety matters: the dome actions of the mount park/unpark sequence, the "dome ready" check in InitTarget and the end of sequence verification. The boolean Shutter property is unchanged for the rest of the program (display, scripts). - E5: instead of an unpark command (ASCOM/Alpaca have none), a CanUnpark property was added; the "unpark dome" action is skipped for such a dome with a message (it leaves the park position when it moves). - E6: SetParkInterface stays a procedure (it is the setter of the Park property); its result is available in the new property LastParkOK. - E8: timeouts are configurable only in the configuration file, there is no setting in the Options dialog yet: /Dome/ActionTimeout seconds, default 60 (minimum 10) /Focuser/MoveTimeout seconds, default 60 (minimum 10) - E9: the safety monitor is "configured" when /Devices/Safety is true; opening, unparking the dome and unparking the mount are then refused while it is not connected (unless DomeNoSafetyCheck is set). - E12: the slewing flag is now set during a synchronous slew; the GUI is still blocked during that COM/HTTP call, which cannot be avoided for a mount without asynchronous slew. - E13: "Home" is still not implemented; a message is shown instead of doing nothing silently. - F4: a plan stopped because guiding could not be started goes to the next target without counting the target as done; it is not retried. - F6: park and close are verified, retried once and reported (also by e-mail when end or abort e-mails are enabled). Closing the dome over a telescope that is not parked only gives a warning, because CCDciel cannot tell a roll-off roof from a rotating dome. - F8: the moon distance is checked every 5 minutes while the plan runs; when the moon is too close the target is stopped and the next one starts. - F10: was implemented as C13.